Module: PWN::AI::Agent::Extrospection
- Defined in:
- lib/pwn/ai/agent/extrospection.rb
Overview
PWN::AI::Agent::Extrospection is the outward-facing counterpart to PWN::AI::Agent::Learning (introspection).
PRIMARY INTENT — on-demand external sensing
Quickly explore external resources when that produces a more informed answer. Call a sense tool only when the question needs it:
"weather in Tokyo" → verify / watch / TransparentBrowser
"what's on 101.1 FM?" → rf_tune(freq: "101.1") → RDS / observe(:rf)
"CVE for openssl 3.0?" → intel(query:) / verify(claim:, kind: :cve)
"did the target change?" → watch(url:) / snapshot(sections: [:web])
Secondary / optional — ambient host baseline
snapshot / drift / correlate can record cheap local posture so the agent can tell "I called the API wrong" from "the world moved" (kernel upgrade, dongle unplugged). This is NEVER the reason to launch GUI / JVM / heavy-REPL binaries — those are presence-only. auto_extrospect, when enabled, uses only side-effect-free sections.
INTROSPECTIVE (self) EXTROSPECTIVE (world)
---------------------- -------------------------------------
Metrics.record Extrospection.intel/verify/watch/rf_tune (sense)
Learning.note_outcome Extrospection.observe (fact)
Learning.reflect Extrospection.snapshot/drift (baseline)
Learning.stats Extrospection.correlate (self×world)
PromptBuilder re-injects Extrospection.to_context on every turn. Persistence: ~/.pwn/extrospection.json across REPL restarts.
Constant Summary collapse
- EXTRO_FILE =
File.join(Dir.home, '.pwn', 'extrospection.json')
- MAX_OBSERVATIONS =
500- SAFE_VERSION_BINS =
CLI tools that accept a cheap, non-interactive --version / -V.
%w[nmap curl git ruby python3 gcc openssl docker].freeze
- PRESENCE_ONLY_BINS =
GUI / JVM / heavy REPL / interactive tools — presence-only. NEVER spawn these from auto-probe (Burp Suite splash, ZAP UI, msfconsole, GQRX).
%w[burpsuite zaproxy msfconsole gqrx sqlmap].freeze
- RF_BINS =
%w[rtl_sdr rtl_test rtl_433 hackrf_info gqrx dump1090 multimon-ng SoapySDRUtil].freeze
- OSINT_BINS =
%w[whois dig host curl jq].freeze
- SERIAL_BINS =
%w[minicom picocom screen cu].freeze
- TELECOMM_BINS =
%w[baresip asterisk linphone sngrep].freeze
- PACKET_BINS =
%w[tshark tcpdump tcpreplay dumpcap].freeze
- VISION_BINS =
%w[tesseract zbarimg qrencode convert identify].freeze
- VOICE_BINS =
%w[sox espeak-ng espeak festival whisper spd-say arecord aplay].freeze
- PROBE_BINS =
( SAFE_VERSION_BINS + PRESENCE_ONLY_BINS + RF_BINS + OSINT_BINS + SERIAL_BINS + TELECOMM_BINS + PACKET_BINS + VISION_BINS + VOICE_BINS ).uniq.freeze
- AUTO_SECTIONS =
Cheap, side-effect-free sections used by auto_extrospect. toolchain / rf / web / osint / serial / telecomm / packet / vision / voice are on-demand only (sense tools or explicit snapshot).
%i[host repo env].freeze
- WEB_SHOT_DIR =
File.join(Dir.home, '.pwn', 'extrospection', 'web')
- DEFAULT_WEB_ANCHORS =
%w[ https://services.nvd.nist.gov/rest/json/cves/2.0 https://www.exploit-db.com/ https://raw.githubusercontent.com/0dayinc/pwn/master/lib/pwn/version.rb ].freeze
- DEFAULT_OSINT_FEEDS =
Public / free OSINT anchors (no key). Keys unlock richer feeds via PWN::Env. Expanded from https://github.com/public-api-lists/public-api-lists (Anti-Malware, Security, Geocoding, Government, Health, Open Data, Vehicle, …).
%i[ ip geo dns whois rdap crtsh bgpview shodan hunter phone fcc_id patent person username github wayback otx urlhaus threatfox urlscan hackertarget openfda nominatim opencorporates courtlistener sec_edgar vital_records ipapi_is iplocate ipwhois abuseipdb virustotal greynoise certspotter epss cisa_kev nhtsa nppes federal_register uk_police callook mac_vendor universities microlink agify genderize nationalize haveibeenpwned securitytrails ].freeze
Class Method Summary collapse
-
.authors ⇒ Object
- Author(s)
0day Inc.
-
.auto_extrospect(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::AI::Agent::Extrospection.auto_extrospect( session_id: 'optional - id of the just-completed session (for tagging)' ).
-
.correlate(opts = {}) ⇒ Object
- Supported Method Parameters
findings = PWN::AI::Agent::Extrospection.correlate( limit: 'optional - max findings returned (default 10)' ).
-
.drift(opts = {}) ⇒ Object
- Supported Method Parameters
delta = PWN::AI::Agent::Extrospection.drift( live: 'optional - probe host NOW and diff vs stored snapshot (default true). When false, diff stored :snapshot vs stored :previous.' ).
-
.help ⇒ Object
Display Usage for this Module.
-
.intel(opts = {}) ⇒ Object
- Supported Method Parameters
hits = PWN::AI::Agent::Extrospection.intel( query: 'required - keyword / product / CVE id to search external threat-intel for', feeds: 'optional - Array subset of [:nvd, :circl, :exploitdb] (default all)', limit: 'optional - max results per feed (default 5)', record: 'optional - also persist each hit as an observation (default false)' ).
-
.load ⇒ Object
- Supported Method Parameters
store = PWN::AI::Agent::Extrospection.load.
-
.observations(opts = {}) ⇒ Object
- Supported Method Parameters
rows = PWN::AI::Agent::Extrospection.observations( limit: 'optional - max entries newest-first (default 50)', source: 'optional - filter by source substring', category: 'optional - filter by category', target: 'optional - filter by target substring', tag: 'optional - filter by tag substring', fresh_only: 'optional - drop entries whose ttl has expired (default false)' ).
-
.observe(opts = {}) ⇒ Object
- Supported Method Parameters
obs = PWN::AI::Agent::Extrospection.observe( source: 'required - where the observation came from (nmap, shodan, burp, cve, human, ...)', data: 'required - the observation payload (String or Hash)', category: 'optional - :recon, :vuln, :intel, :target, :network, :env, :rf, :web, :osint, :serial, :telecomm, :packet, :vision, :voice, :misc (default :misc)', target: 'optional - host/ip/url/asset the observation is about', tags: 'optional - Array of String labels', ttl: 'optional - seconds until this observation is considered stale (default nil = forever)' ).
-
.osint(opts = {}) ⇒ Object
OSINT sense organ ============================================================ Supported Method Parameters:: result = PWN::AI::Agent::Extrospection.osint( query: 'required - phone, IP, domain, email, person name, FCC ID, patent #, username, VIN, MAC, callsign, …', kind: 'optional - auto|:ip|:geo|:dns|:whois|:rdap|:crtsh|:bgp|:shodan|:hunter|:phone|:fcc_id|:patent|:person|:username|:github|:wayback|:url|:company|:cik|:openfda|:vital_records|:threat|:vin|:mac|:callsign|:npi|:cve (default :auto)', feeds: 'optional - Array subset of DEFAULT_OSINT_FEEDS (default: auto-selected from kind)', limit: 'optional - max hits per feed (default 5)', record: 'optional - also observe(category: :osint) (default true)', ttl: 'optional - observation TTL seconds (default 86400)', api_keys: 'optional - Hash of hunter:, abuseipdb:, virustotal:, greynoise:, haveibeenpwned:, securitytrails: overriding PWN::Env / ENV' ).
-
.packet_sense(opts = {}) ⇒ Object
Packet sense organ ============================================================ Supported Method Parameters:: result = PWN::AI::Agent::Extrospection.packet_sense( action: 'optional - :inventory|:capture|:summarize_pcap (default :inventory)', iface: 'optional - capture interface (default first non-lo or "any")', filter: 'optional - BPF filter (e.g. "tcp port 443")', count: 'optional - packets to capture (default 20, max 200)', timeout: 'optional - capture seconds (default 5, max 60)', path: 'optional - pcap path for :summarize_pcap', record: 'optional - observe(category: :packet) (default true)', ttl: 'optional - observation TTL (default 600)' ).
-
.reset ⇒ Object
- Supported Method Parameters
PWN::AI::Agent::Extrospection.reset.
-
.revalidate_memory(opts = {}) ⇒ Object
- Supported Method Parameters
report = PWN::AI::Agent::Extrospection.revalidate_memory( limit: 'optional - max :fact entries to check (default 25)', proxy: 'optional - upstream proxy for TransparentBrowser' ).
-
.rf_tune(opts = {}) ⇒ Object
- Supported Method Parameters
result = PWN::AI::Agent::Extrospection.rf_tune( freq: 'required - frequency: "101.1", "101.1 FM", "101.100.000", 101_100_000, ...', host: 'optional - GQRX remote-control host (default 127.0.0.1)', port: 'optional - GQRX remote-control port (default 7356)', settle_secs: 'optional - seconds to sample RDS after tune (default 8)', rds: 'optional - force RDS on/off (default: auto when FM broadcast / band-plan decoder=:rds)', demodulator_mode: 'optional - e.g. :WFM_ST, :WFM, :FM, :AM (default from band-plan / FM range)', bandwidth: 'optional - passband Hz string, e.g. "200.000" (default from band-plan)', record: 'optional - also observe(category: :rf) so it hits EXTROSPECTION (default true)', ttl: 'optional - observation TTL seconds (default 300 — radio content is ephemeral)' ).
-
.save(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::AI::Agent::Extrospection.save( store: 'required - Hash returned by .load / mutated in place' ).
-
.serial_sense(opts = {}) ⇒ Object
Serial sense organ ============================================================ Supported Method Parameters:: result = PWN::AI::Agent::Extrospection.serial_sense( block_dev: 'optional - device path (default first ttyUSB/ttyACM or config)', baud: 'optional - baud rate (default 9600)', payload: 'optional - String or byte Array to write (e.g. "ATI\r" or [0x41,0x54])', settle_secs:'optional - seconds to read after write (default 1.5)', data_bits: 'optional (default 8)', stop_bits: 'optional (default 1)', parity: 'optional :none|:even|:odd (default :none)', record: 'optional - observe(category: :serial) (default true)', ttl: 'optional - observation TTL (default 600)' ).
-
.snapshot(opts = {}) ⇒ Object
- Supported Method Parameters
snap = PWN::AI::Agent::Extrospection.snapshot( persist: 'optional - Boolean, write snapshot to disk & rotate previous (default true)', sections: 'optional - Array subset of [:host, :net, :toolchain, :repo, :env, :rf, :web, :osint, :serial, :telecomm, :packet, :vision, :voice] (default host/net/toolchain/repo/env/rf)' ).
-
.stats ⇒ Object
- Supported Method Parameters
stats = PWN::AI::Agent::Extrospection.stats.
-
.telecomm(opts = {}) ⇒ Object
Telecomm sense organ (SIP / VoIP / PSTN via BareSIP) ============================================================ Supported Method Parameters:: result = PWN::AI::Agent::Extrospection.telecomm( action: 'optional - :status|:dial|:hangup|:inventory (default :inventory)', target: 'optional - SIP URI / phone number for :dial (e.g. "sip:alice@example.com" or "+13125551212")', host: 'optional - BareSIP HTTP control host (default 127.0.0.1)', port: 'optional - BareSIP HTTP control port (default 8000)', record: 'optional - observe(category: :telecomm) (default true)', ttl: 'optional - observation TTL (default 600)' ).
-
.to_context(opts = {}) ⇒ Object
- Supported Method Parameters
ctx = PWN::AI::Agent::Extrospection.to_context( drift_limit: 'optional - max drift lines (default 4)', obs_limit: 'optional - max observation lines (default 4)' ).
-
.verify(opts = {}) ⇒ Object
- Supported Method Parameters
verdict = PWN::AI::Agent::Extrospection.verify( claim: 'required - factual claim to fact-check against the live web', kind: 'optional - :cve | :version | :doc | :generic (default auto-detect)', url: 'optional - explicit URL the claim cites (forces kind: :doc)', commit: 'optional - write Mistakes/Memory/observe on refute/confirm (default true)', proxy: 'optional - upstream proxy for TransparentBrowser (e.g. "tor")' ).
-
.vision(opts = {}) ⇒ Object
Vision / OCR sense organ ============================================================ Supported Method Parameters:: result = PWN::AI::Agent::Extrospection.vision( file: 'required - path to image / screenshot / PDF-page render', action: 'optional - :ocr|:barcode|:inventory (default :ocr when file given, else :inventory)', lang: 'optional - tesseract language (default eng)', record: 'optional - observe(category: :vision) (default true)', ttl: 'optional - observation TTL (default 86400)' ).
-
.voice_sense(opts = {}) ⇒ Object
Voice sense organ (TTS / STT / inventory) ============================================================ Supported Method Parameters:: result = PWN::AI::Agent::Extrospection.voice_sense( action: 'optional - :inventory|:tts|:stt (default :inventory)', text: 'optional - text to speak for :tts (or text_path:)', text_path: 'optional - path to text file for :tts', audio: 'optional - path to audio file for :stt', out: 'optional - output audio path for :tts (wav)', engine: 'optional - :espeak|:festival|:spd_say|:whisper (auto)', model: 'optional - whisper model (default tiny)', record: 'optional - observe(category: :voice) (default true)', ttl: 'optional - observation TTL (default 3600)' ).
-
.watch(opts = {}) ⇒ Object
- Supported Method Parameters
obs = PWN::AI::Agent::Extrospection.watch( url: 'required - URL to render and fingerprint', selector: 'optional - CSS selector whose innerText to hash (default full body)', ttl: 'optional - seconds until stale (default 7 days)', proxy: 'optional - upstream proxy for TransparentBrowser' ).
Class Method Details
.authors ⇒ Object
- Author(s)
0day Inc. support@0dayinc.com
3541 3542 3543 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 3541 public_class_method def self. "AUTHOR(S):\n 0day Inc. <support@0dayinc.com>\n" end |
.auto_extrospect(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::AI::Agent::Extrospection.auto_extrospect( session_id: 'optional - id of the just-completed session (for tagging)' )
Called by Learning.auto_introspect when PWN::Env[:agent][:auto_extrospect] is truthy. Captures a fresh snapshot and, if drift is non-trivial, records it as an observation and a PWN::Memory :env fact so the NEXT session's system prompt already knows the world moved. Never raises.
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 1344 public_class_method def self.auto_extrospect(opts = {}) sid = opts[:session_id] return unless auto_extrospect_enabled? # Ambient baseline only — never toolchain / rf / web (those spawn # hardware probes or GUI binaries and belong on the *sense* path). res = snapshot(persist: true, sections: AUTO_SECTIONS) delta = res[:drift] moved = Array(delta[:changed]).length + Array(delta[:added]).length + Array(delta[:removed]).length return res if moved.zero? summary = summarise_drift(delta: delta) observe(source: 'auto_extrospect', category: :env, data: summary, tags: ['drift', sid.to_s].reject(&:empty?)) if defined?(PWN::Memory) key = :"extro_drift_#{res[:snapshot][:fingerprint]}" PWN::Memory.remember(key: key, value: "ENV DRIFT #{res[:snapshot][:captured_at]}: #{summary[0, 260]}", category: :env) end res rescue StandardError => e warn "[pwn-ai/extrospection] auto_extrospect swallowed: #{e.class}: #{e.}" nil end |
.correlate(opts = {}) ⇒ Object
- Supported Method Parameters
findings = PWN::AI::Agent::Extrospection.correlate( limit: 'optional - max findings returned (default 10)' )
THE join between introspection and extrospection. Cross-references:
* Metrics tools with success_rate < 50 % vs toolchain drift / missing bins
* Learning failures vs host / net drift on the same day
* Observations tagged :vuln / :intel vs installed package versions
Emits human-readable, actionable findings the model can reason on.
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 1175 public_class_method def self.correlate(opts = {}) limit = opts[:limit] || 10 findings = [] delta = drift(live: false) snap = load[:snapshot] || {} # 1) failing tools whose backing binary vanished / changed version if defined?(Metrics) Metrics.summary(limit: 50).each do |m| next unless m[:success_rate] < 0.5 && m[:calls] > 2 bin = m[:name].to_s.split('_').first tc = Array(delta[:changed]).find { |c| c[:path].to_s.include?("toolchain.#{bin}") } miss = snap.dig(:toolchain, bin.to_sym).to_s.empty? next unless tc || miss findings << { kind: :tool_env_mismatch, tool: m[:name], success_rate: m[:success_rate], evidence: tc || "binary '#{bin}' not found in PATH", advice: "Re-verify `which #{bin}` / reinstall before relying on #{m[:name]}." } end end # 2) introspective failures coinciding with extrospective drift if defined?(Learning) Learning.outcomes(limit: 30, success: false).each do |o| day = o[:timestamp].to_s[0, 10] hit = Array(delta[:changed]).find { |c| c[:after].to_s.include?(day) || c[:path].to_s.match?(/kernel|repo|net/) } findings << { kind: :failure_during_drift, task: o[:task], on: day, drift: hit, advice: 'Environment changed around this failure — re-test under current snapshot before trusting the negative result.' } if hit end end # 3) intel observations matching installed components pkgs = snap[:toolchain] || {} observations(category: 'intel', limit: 100).each do |ob| blob = ob[:data].to_s.downcase pkgs.each do |bin, ver| next if ver.to_s.empty? next unless blob.include?(bin.to_s.downcase) findings << { kind: :intel_matches_host, component: bin, installed: ver, intel: ob[:data], source: ob[:source], advice: "Review #{ob[:source]} advisory for #{bin} #{ver} on this host." } end end # 4) :rf observations vs missing SDR hardware / binaries rf = snap[:rf] || {} hw_present = %i[rtl_sdr hackrf flipper gqrx_sock].any? { |k| rf_present?(val: rf[k]) } observations(category: 'rf', limit: 50).each do |ob| miss = RF_BINS.select { |b| pkgs[b.to_sym].to_s.empty? } if !hw_present findings << { kind: :rf_no_hardware, observation: ob[:data], source: ob[:source], target: ob[:target], advice: 'RF observation recorded but no SDR hardware detected in snapshot — plug in RTL-SDR/HackRF/Flipper or start gqrx (`-r`) before trusting RF results.' } elsif rf[:gqrx_sock] == false && ob[:source].to_s == 'gqrx' findings << { kind: :rf_gqrx_down, observation: ob[:data], target: ob[:target], advice: 'gqrx remote-control socket (127.0.0.1:7356) is closed — start gqrx with remote control enabled before re-running the scan.' } elsif !miss.empty? findings << { kind: :rf_toolchain_gap, missing: miss, observation: ob[:data], advice: "SDR toolchain gap: install #{miss.join(', ')} to decode/act on this RF observation." } end end # 5) :web drift on a target the same day a Learning failure references it — # "your exploit stopped working because the TARGET changed, not your approach" if defined?(Learning) observations(category: 'web', limit: 50).each do |ob| tgt = ob[:target].to_s host = safe_host(url: tgt) Learning.outcomes(limit: 30, success: false).each do |o| next unless o[:task].to_s.include?(host) || o[:details].to_s.include?(host) findings << { kind: :target_web_drift, target: tgt, dom_sha: ob.dig(:data, :dom_sha), task: o[:task], advice: "Target #{host} DOM changed (#{ob[:timestamp]}) around this failure — re-recon before assuming your technique is wrong." } end end end # 6) extro_verify refutations whose claim substring appears in a PWN::Memory :fact -> stale memory if defined?(PWN::Memory) observations(category: 'web', tag: 'stale', limit: 50).each do |ob| findings << { kind: :stale_memory_fact, key: ob[:target], evidence: ob[:data], advice: "PWN::Memory[:#{ob[:target]}] failed browser re-verification — audit or memory_forget it before it poisons future prompts." } end end # 7) :intel observations whose source anchor is currently probe_web-unreachable -> downgrade web = snap[:web] || {} web.each do |host, fp| next unless fp.is_a?(Hash) && (fp[:reachable] == false || fp[:status].to_i >= 500) observations(category: 'intel', limit: 100).each do |ob| next unless ob[:source].to_s.include?(host.to_s) || ob[:data].to_s.include?(host.to_s) findings << { kind: :intel_source_unreachable, source: host, status: fp[:status], intel: ob[:data].to_s[0, 120], advice: "Feed anchor #{host} is currently unreachable (#{fp[:status] || 'down'}) — treat this :intel as stale until probe_web sees it 2xx again." } end end # 8) raw drift as low-priority findings when nothing else matched Array(delta[:added]).first(5).each { |c| findings << { kind: :env_added, detail: c } } if findings.empty? Array(delta[:removed]).first(5).each { |c| findings << { kind: :env_removed, detail: c } } if findings.empty? findings.uniq.first(limit) end |
.drift(opts = {}) ⇒ Object
- Supported Method Parameters
delta = PWN::AI::Agent::Extrospection.drift( live: 'optional - probe host NOW and diff vs stored snapshot (default true). When false, diff stored :snapshot vs stored :previous.' )
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 244 public_class_method def self.drift(opts = {}) live = if opts.key?(:live) opts[:live] ? true : false else true end store = load if live after = snapshot(persist: false)[:snapshot] before = store[:snapshot] || {} else after = store[:snapshot] || {} before = store[:previous] || {} end compute_drift(before: before, after: after) end |
.help ⇒ Object
Display Usage for this Module
3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 3547 public_class_method def self.help puts <<~USAGE USAGE: PWN::AI::Agent::Extrospection.snapshot # probe host, persist, return {snapshot:, drift:} PWN::AI::Agent::Extrospection.drift(live: true) # what changed vs last snapshot PWN::AI::Agent::Extrospection.observe(source: 'nmap', category: :recon, target: '10.0.0.5', data: '22/tcp open ssh 9.6') PWN::AI::Agent::Extrospection.observe(source: 'gqrx', category: :rf, target: '433.920MHz', data: 'peak -34.2 dBFS bw=200k') PWN::AI::Agent::Extrospection.observations(category: 'recon', target: '10.0.0.5') PWN::AI::Agent::Extrospection.intel(query: 'openssl 3.0', record: true) PWN::AI::Agent::Extrospection.correlate # introspection x extrospection findings PWN::AI::Agent::Extrospection.to_context # injected by PromptBuilder PWN::AI::Agent::Extrospection.stats PWN::AI::Agent::Extrospection.auto_extrospect(session_id: sid) # called from Learning.auto_introspect PWN::AI::Agent::Extrospection.snapshot(sections: %i[web]) # opt-in browser probe of web_anchors PWN::AI::Agent::Extrospection.watch(url: 'https://target/api/version') PWN::AI::Agent::Extrospection.rf_tune(freq: '101.1') # tune GQRX + RDS → now_playing PWN::AI::Agent::Extrospection.osint(query: '+13125551212', kind: :phone) PWN::AI::Agent::Extrospection.osint(query: '2ABIP-ESP32', kind: :fcc_id) PWN::AI::Agent::Extrospection.osint(query: 'US10123456', kind: :patent) PWN::AI::Agent::Extrospection.osint(query: '1HGCM82633A004352', kind: :vin) PWN::AI::Agent::Extrospection.osint(query: '00:11:22:33:44:55', kind: :mac) PWN::AI::Agent::Extrospection.osint(query: 'W1AW', kind: :callsign) PWN::AI::Agent::Extrospection.osint(query: 'CVE-2021-44228', kind: :cve) PWN::AI::Agent::Extrospection.serial_sense(payload: "ATI\r") PWN::AI::Agent::Extrospection.telecomm(action: :status) PWN::AI::Agent::Extrospection.packet_sense(action: :capture, filter: 'tcp port 443', count: 10) PWN::AI::Agent::Extrospection.vision(file: '/tmp/shot.png', action: :ocr) PWN::AI::Agent::Extrospection.voice_sense(action: :tts, text: 'hello from pwn') PWN::AI::Agent::Extrospection.verify(claim: 'CVE-2026-12345 affects OpenSSL 3.2.1') PWN::AI::Agent::Extrospection.revalidate_memory # cron: GC stale PWN::Memory :fact entries PWN::AI::Agent::Extrospection.reset PRIMARY use = on-demand sensing (intel / verify / watch / rf_tune / osint / serial_sense / telecomm / packet_sense / vision / voice_sense / observe / rf / web / osint / serial / telecomm / packet / vision / voice). auto_extrospect is OPTIONAL ambient baseline (host/repo/env only — never launches burpsuite/zaproxy/msfconsole/gqrx). Prefer calling sense tools when a question needs the outside world, not after every turn. Enable end-of-run ambient baseline with: PWN::Env[:ai][:agent][:auto_extrospect] = true # sections: AUTO_SECTIONS Configure browser-backed :web probe / verify / watch with: PWN::Env[:ai][:agent][:extrospection][:web] = { anchors: [...], proxy: 'tor', max_anchors: 8, per_page_timeout: 15, screenshot: false, allow_targets: false } Configure RF sense (rf_tune) with: PWN::Env[:ai][:agent][:extrospection][:rf] = { host: '127.0.0.1', port: 7356, settle_secs: 8, ttl: 300 } Configure new limbs: PWN::Env[:ai][:agent][:extrospection][:osint] = { ttl: 86400, api_keys: { shodan: '…', hunter: '…', abuseipdb: '…', virustotal: '…', greynoise: '…', haveibeenpwned: '…', securitytrails: '…' } } PWN::Env[:ai][:agent][:extrospection][:serial] = { block_dev: '/dev/ttyUSB0', baud: 115200, settle_secs: 1.5 } PWN::Env[:ai][:agent][:extrospection][:telecomm] = { host: '127.0.0.1', port: 8000 } PWN::Env[:ai][:agent][:extrospection][:packet] = { iface: 'eth0' } PWN::Env[:ai][:agent][:extrospection][:vision] = { lang: 'eng' } PWN::Env[:ai][:agent][:extrospection][:voice] = { ttl: 3600 } #{self}.authors USAGE end |
.intel(opts = {}) ⇒ Object
- Supported Method Parameters
hits = PWN::AI::Agent::Extrospection.intel( query: 'required - keyword / product / CVE id to search external threat-intel for', feeds: 'optional - Array subset of [:nvd, :circl, :exploitdb] (default all)', limit: 'optional - max results per feed (default 5)', record: 'optional - also persist each hit as an observation (default false)' )
Best-effort external lookups. Network / API failures degrade to an empty result for that feed rather than raising, so learning never breaks the primary loop when offline.
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 273 public_class_method def self.intel(opts = {}) query = opts[:query].to_s.strip raise 'ERROR: query is required' if query.empty? feeds = Array(opts[:feeds]).map(&:to_sym) feeds = %i[nvd circl exploitdb] if feeds.empty? limit = opts[:limit] || 5 record = opts[:record] ? true : false results = {} results[:nvd] = intel_nvd(query: query, limit: limit) if feeds.include?(:nvd) results[:circl] = intel_circl(query: query, limit: limit) if feeds.include?(:circl) results[:exploitdb] = intel_exploitdb(query: query, limit: limit) if feeds.include?(:exploitdb) if record results.each do |feed, hits| Array(hits).each do |h| observe(source: feed.to_s, category: :intel, data: h, tags: ['intel', query], target: h.is_a?(Hash) ? h[:id].to_s : nil) end end end { query: query, feeds: feeds, results: results, total: results.values.flatten.compact.length } end |
.load ⇒ Object
- Supported Method Parameters
store = PWN::AI::Agent::Extrospection.load
97 98 99 100 101 102 103 104 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 97 public_class_method def self.load FileUtils.mkdir_p(File.dirname(EXTRO_FILE)) return { snapshot: {}, previous: {}, observations: [], updated_at: nil } unless File.exist?(EXTRO_FILE) JSON.parse(File.read(EXTRO_FILE), symbolize_names: true) rescue StandardError { snapshot: {}, previous: {}, observations: [], updated_at: nil } end |
.observations(opts = {}) ⇒ Object
- Supported Method Parameters
rows = PWN::AI::Agent::Extrospection.observations( limit: 'optional - max entries newest-first (default 50)', source: 'optional - filter by source substring', category: 'optional - filter by category', target: 'optional - filter by target substring', tag: 'optional - filter by tag substring', fresh_only: 'optional - drop entries whose ttl has expired (default false)' )
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 216 public_class_method def self.observations(opts = {}) limit = opts[:limit] || 50 src = opts[:source].to_s.downcase cat = opts[:category].to_s.downcase tgt = opts[:target].to_s.downcase tag = opts[:tag].to_s.downcase fresh = opts[:fresh_only] ? true : false now = Time.now.utc rows = Array(load[:observations]) rows = rows.reject do |o| next true if fresh && o[:ttl] && (Time.parse(o[:timestamp].to_s) + o[:ttl].to_i) < now (src.empty? ? false : !o[:source].to_s.downcase.include?(src)) || (cat.empty? ? false : o[:category].to_s.downcase != cat) || (tgt.empty? ? false : !o[:target].to_s.downcase.include?(tgt)) || (tag.empty? ? false : Array(o[:tags]).none? { |t| t.to_s.downcase.include?(tag) }) rescue StandardError false end rows.reverse.first(limit) end |
.observe(opts = {}) ⇒ Object
- Supported Method Parameters
obs = PWN::AI::Agent::Extrospection.observe( source: 'required - where the observation came from (nmap, shodan, burp, cve, human, ...)', data: 'required - the observation payload (String or Hash)', category: 'optional - :recon, :vuln, :intel, :target, :network, :env, :rf, :web, :osint, :serial, :telecomm, :packet, :vision, :voice, :misc (default :misc)', target: 'optional - host/ip/url/asset the observation is about', tags: 'optional - Array of String labels', ttl: 'optional - seconds until this observation is considered stale (default nil = forever)' )
Records a fact about the OUTSIDE world (as opposed to Learning.note_outcome which records a fact about the agent's own behaviour). Observations are re-injected via .to_context so recon findings and threat-intel persist across sessions.
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 182 public_class_method def self.observe(opts = {}) source = opts[:source].to_s data = opts[:data] raise 'ERROR: source is required' if source.strip.empty? raise 'ERROR: data is required' if data.to_s.strip.empty? entry = { id: Digest::SHA256.hexdigest("#{source}-#{data}-#{Time.now.to_f}")[0, 12], source: source, category: (opts[:category] || :misc).to_s, target: opts[:target].to_s.empty? ? nil : opts[:target].to_s, data: data.is_a?(String) ? data[0, 4_000] : data, tags: Array(opts[:tags]).map(&:to_s), ttl: opts[:ttl]&.to_i, timestamp: Time.now.utc.iso8601 } store = load store[:observations] ||= [] store[:observations] << entry store[:observations].shift(store[:observations].length - MAX_OBSERVATIONS) if store[:observations].length > MAX_OBSERVATIONS save(store: store) entry end |
.osint(opts = {}) ⇒ Object
============================================================
OSINT sense organ
- Supported Method Parameters
result = PWN::AI::Agent::Extrospection.osint( query: 'required - phone, IP, domain, email, person name, FCC ID, patent #, username, VIN, MAC, callsign, …', kind: 'optional - auto|:ip|:geo|:dns|:whois|:rdap|:crtsh|:bgp|:shodan|:hunter|:phone|:fcc_id|:patent|:person|:username|:github|:wayback|:url|:company|:cik|:openfda|:vital_records|:threat|:vin|:mac|:callsign|:npi|:cve (default :auto)', feeds: 'optional - Array subset of DEFAULT_OSINT_FEEDS (default: auto-selected from kind)', limit: 'optional - max hits per feed (default 5)', record: 'optional - also observe(category: :osint) (default true)', ttl: 'optional - observation TTL seconds (default 86400)', api_keys: 'optional - Hash of hunter:, abuseipdb:, virustotal:, greynoise:, haveibeenpwned:, securitytrails: overriding PWN::Env / ENV' )
Aggregates as many public / free OSINT APIs as possible (sourced in part from public-api-lists/public-api-lists), with optional keyed feeds (Shodan / Hunter / AbuseIPDB / VirusTotal / GreyNoise / HaveIBeenPwned / SecurityTrails) when keys exist in PWN::Env or ENV. Best-effort: any unreachable feed degrades to an error hash rather than raising. First-class kinds cover: reverse phone, person / missing-person, patent, FCC ID, VIN (NHTSA), MAC OUI, ham callsign (Callook), IP/ASN/BGP + threat reputation (ipapi.is / iplocate / ipwho.is / AbuseIPDB / GreyNoise), CT (crt.sh + Cert Spotter), whois/RDAP, GitHub, Wayback, OTX / URLHaus / ThreatFox / urlscan, HackerTarget, openFDA, NPPES NPI, Nominatim, OpenCorporates, CourtListener, SEC EDGAR, Federal Register, UK Police, EPSS + CISA KEV, Microlink unfurl, universities, name demographics (Agify/Genderize/Nationalize), and vital-records public plans.
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 642 public_class_method def self.osint(opts = {}) query = opts[:query].to_s.strip raise 'ERROR: query is required' if query.empty? kind = (opts[:kind] || :auto).to_s.to_sym kind = detect_osint_kind(query: query) if kind == :auto feeds = Array(opts[:feeds]).map(&:to_sym) feeds = osint_feeds_for(kind: kind) if feeds.empty? limit = (opts[:limit] || 5).to_i record = opts.key?(:record) ? !opts[:record].nil? && opts[:record] != false : true ttl = (opts[:ttl] || osint_config[:ttl] || 86_400).to_i keys = osint_api_keys(override: opts[:api_keys]) results = { ok: true, query: query, kind: kind, feeds: {}, captured_at: Time.now.utc.iso8601 } feeds.each do |feed| results[:feeds][feed] = osint_dispatch(feed: feed, query: query, kind: kind, limit: limit, keys: keys) rescue StandardError => e results[:feeds][feed] = { error: "#{e.class}: #{e..to_s[0, 160]}" } end results[:summary] = build_osint_summary(results: results) if record observe( source: 'osint', category: :osint, target: query, data: results[:summary], tags: (['osint', kind.to_s] + feeds.map(&:to_s)).uniq, ttl: ttl ) results[:observed] = true else results[:observed] = false end results end |
.packet_sense(opts = {}) ⇒ Object
============================================================
Packet sense organ
- Supported Method Parameters
result = PWN::AI::Agent::Extrospection.packet_sense( action: 'optional - :inventory|:capture|:summarize_pcap (default :inventory)', iface: 'optional - capture interface (default first non-lo or "any")', filter: 'optional - BPF filter (e.g. "tcp port 443")', count: 'optional - packets to capture (default 20, max 200)', timeout: 'optional - capture seconds (default 5, max 60)', path: 'optional - pcap path for :summarize_pcap', record: 'optional - observe(category: :packet) (default true)', ttl: 'optional - observation TTL (default 600)' )
Passive L2/L3 sense via tshark/tcpdump when present; pcap summarisation via PWN::Plugins::Packet + tshark. Capture is short and bounded so the agent never hangs mid-turn.
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 883 public_class_method def self.packet_sense(opts = {}) action = (opts[:action] || :inventory).to_s.to_sym record = opts.key?(:record) ? !opts[:record].nil? && opts[:record] != false : true ttl = (opts[:ttl] || packet_config[:ttl] || 600).to_i iface = (opts[:iface] || packet_config[:iface] || default_capture_iface).to_s filter = opts[:filter].to_s count = (opts[:count] || 20).to_i.clamp(1, 200) timeout = (opts[:timeout] || 5).to_i.clamp(1, 60) path = opts[:path].to_s inv = probe_packet out = { ok: true, action: action, iface: iface, inventory: inv, captured_at: Time.now.utc.iso8601 } case action when :inventory out[:ifaces] = inv[:ifaces] out[:bins] = inv[:bins] when :capture tshark = sh(cmd: 'which tshark 2>/dev/null') tcpdump = sh(cmd: 'which tcpdump 2>/dev/null') if tshark.empty? && tcpdump.empty? out[:ok] = false out[:error] = 'neither tshark nor tcpdump found in PATH' out[:advice] = 'Install wireshark-common / tcpdump, or summarize an existing pcap with action: :summarize_pcap path:.' else pcap_out = File.join(Dir.home, '.pwn', 'extrospection', 'packet', "cap_#{Time.now.utc.strftime('%Y%m%d_%H%M%S')}.pcap") FileUtils.mkdir_p(File.dirname(pcap_out)) if tshark.empty? bpf = filter.empty? ? '' : filter cmd = "timeout #{timeout + 2} tcpdump -i #{Shellwords.escape(iface)} -c #{count} -w #{Shellwords.escape(pcap_out)} #{Shellwords.escape(bpf)} 2>&1" else bpf = filter.empty? ? '' : "-f #{Shellwords.escape(filter)}" cmd = "timeout #{timeout + 2} tshark -i #{Shellwords.escape(iface)} -c #{count} -a duration:#{timeout} -w #{Shellwords.escape(pcap_out)} #{bpf} 2>&1" end log = sh(cmd: cmd) out[:pcap] = File.exist?(pcap_out) ? pcap_out : nil out[:log] = log.to_s[0, 500] out[:summary] = summarize_pcap_file(path: pcap_out) if out[:pcap] out[:ok] = !out[:pcap].nil? out[:error] = 'capture produced no pcap' unless out[:ok] end when :summarize_pcap if path.empty? || !File.exist?(path) out[:ok] = false out[:error] = "pcap not found: #{path.inspect}" else out[:path] = path out[:summary] = summarize_pcap_file(path: path) end else out[:ok] = false out[:error] = "unsupported action: #{action}" end if record blob = out[:summary].is_a?(Hash) ? out[:summary].to_json[0, 300] : out[:summary].to_s[0, 200] summary = "packet action=#{action} iface=#{iface} #{blob}" observe(source: 'packet', category: :packet, target: iface, data: summary, tags: ['packet', action.to_s], ttl: ttl) out[:observed] = true out[:obs_summary] = summary end out end |
.reset ⇒ Object
- Supported Method Parameters
PWN::AI::Agent::Extrospection.reset
1370 1371 1372 1373 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 1370 public_class_method def self.reset FileUtils.rm_f(EXTRO_FILE) { cleared: true } end |
.revalidate_memory(opts = {}) ⇒ Object
- Supported Method Parameters
report = PWN::AI::Agent::Extrospection.revalidate_memory( limit: 'optional - max :fact entries to check (default 25)', proxy: 'optional - upstream proxy for TransparentBrowser' )
The browser as garbage-collector for PWN::Memory. Walks :fact entries containing a CVE id, version string or URL, runs verify() on each and prefixes stale ones with [UNVERIFIED yyyy-mm-dd] so the injected MEMORY block stops calcifying into confidently-wrong priors. Designed to be scheduled: cron_create(schedule:'0 4 * * 0', ruby:'PWN::AI::Agent::Extrospection.revalidate_memory')
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 1139 public_class_method def self.revalidate_memory(opts = {}) return { checked: 0, refuted: [], confirmed: [], unknown: [] } unless defined?(PWN::Memory) lim = opts[:limit] || 25 proxy = opts[:proxy] || web_config[:proxy] rx = %r{(CVE-\d{4}-\d{4,}|v?\d+\.\d+\.\d+|https?://\S+)}i out = { checked: 0, refuted: [], confirmed: [], unknown: [] } PWN::Memory.load.each do |key, v| break if out[:checked] >= lim next unless v.is_a?(Hash) && v[:category].to_s == 'fact' && v[:value].to_s =~ rx next if v[:value].to_s.start_with?('[UNVERIFIED') res = verify(claim: v[:value].to_s[0, 400], commit: false, proxy: proxy) out[:checked] += 1 out[res[:verdict]] << key next unless res[:verdict] == :refuted && res[:confidence] >= 0.6 stamp = Time.now.utc.strftime('%Y-%m-%d') PWN::Memory.remember(key: key, value: "[UNVERIFIED #{stamp}] #{v[:value]}", category: :fact) observe(source: 'extro_verify', category: :web, target: key.to_s, data: "Memory :fact '#{key}' failed re-validation (#{res[:confidence]})", tags: %w[stale memory]) end out end |
.rf_tune(opts = {}) ⇒ Object
- Supported Method Parameters
result = PWN::AI::Agent::Extrospection.rf_tune( freq: 'required - frequency: "101.1", "101.1 FM", "101.100.000", 101_100_000, ...', host: 'optional - GQRX remote-control host (default 127.0.0.1)', port: 'optional - GQRX remote-control port (default 7356)', settle_secs: 'optional - seconds to sample RDS after tune (default 8)', rds: 'optional - force RDS on/off (default: auto when FM broadcast / band-plan decoder=:rds)', demodulator_mode: 'optional - e.g. :WFM_ST, :WFM, :FM, :AM (default from band-plan / FM range)', bandwidth: 'optional - passband Hz string, e.g. "200.000" (default from band-plan)', record: 'optional - also observe(category: :rf) so it hits EXTROSPECTION (default true)', ttl: 'optional - observation TTL seconds (default 300 — radio content is ephemeral)' )
RF sense organ — the RF analogue of extro_watch / extro_verify. Tunes a running GQRX instance (never launches the GUI), demodulates, measures strength, and when appropriate samples RDS (PI / PS / RadioText) so questions like "what's playing on 101.1?" have a live answer. Requires GQRX remote control already listening (default :7356) and an SDR attached; fails fast with actionable advice otherwise. On success, records observe(category: :rf, source: 'gqrx') so correlate and to_context keep the agent aware of what was last heard.
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 464 public_class_method def self.rf_tune(opts = {}) raw_freq = opts[:freq] raise 'ERROR: freq is required' if raw_freq.nil? || raw_freq.to_s.strip.empty? host = (opts[:host] || rf_config[:host] || '127.0.0.1').to_s port = (opts[:port] || rf_config[:port] || 7356).to_i settle = (opts[:settle_secs] || rf_config[:settle_secs] || 8).to_f settle = 1.0 if settle < 1.0 settle = 30.0 if settle > 30.0 record = opts.key?(:record) ? !opts[:record].nil? && opts[:record] != false : true ttl = (opts[:ttl] || rf_config[:ttl] || 300).to_i force_rds = opts.key?(:rds) ? opts[:rds] : nil hz_i, freq_label = normalize_rf_freq(freq: raw_freq) plan = match_rf_band_plan(hz: hz_i) demod = (opts[:demodulator_mode] || (plan && plan[:demodulator_mode]) || default_rf_demod(hz: hz_i)).to_s.upcase bandwidth = (opts[:bandwidth] || (plan && plan[:bandwidth]) || default_rf_bandwidth(hz: hz_i)).to_s passband_hz = begin require 'pwn/sdr' unless defined?(PWN::SDR) PWN::SDR.hz_to_i(freq: bandwidth) rescue StandardError bandwidth.to_s.gsub(/[^\d]/, '').to_i end passband_hz = 200_000 if passband_hz <= 0 decoder_key = plan && plan[:decoder] band_name = plan && plan[:name] do_rds = if force_rds.nil? decoder_key.to_s == 'rds' || hz_i.between?(87_500_000, 108_100_000) else !force_rds.nil? && force_rds != false end unless tcp_open?(host: host, port: port) advice = 'Start GQRX with remote control enabled (Tools → Remote Control, port 7356) and an SDR attached, then retry extro_rf_tune.' err = { ok: false, error: "gqrx remote control not reachable at #{host}:#{port}", advice: advice, freq: freq_label, hz: hz_i, band_plan: band_name, demodulator_mode: demod, bandwidth: bandwidth } observe(source: 'gqrx', category: :rf, target: freq_label, data: err, tags: %w[rf_tune unreachable], ttl: ttl) if record return err end require 'pwn/sdr/gqrx' unless defined?(PWN::SDR::GQRX) sock = nil begin sock = PWN::SDR::GQRX.connect(target: host, port: port) # Ensure DSP is running so strength/RDS update. begin dsp = PWN::SDR::GQRX.cmd(gqrx_sock: sock, cmd: 'u DSP').to_s.strip PWN::SDR::GQRX.cmd(gqrx_sock: sock, cmd: 'U DSP 1', resp_ok: 'RPRT 0') if dsp == '0' rescue StandardError nil end PWN::SDR::GQRX.cmd( gqrx_sock: sock, cmd: "M #{demod} #{passband_hz}", resp_ok: 'RPRT 0' ) PWN::SDR::GQRX.cmd( gqrx_sock: sock, cmd: "F #{hz_i}", resp_ok: 'RPRT 0' ) sleep 0.4 strength = begin PWN::SDR::GQRX.cmd(gqrx_sock: sock, cmd: 'l STRENGTH').to_f rescue StandardError nil end mode_now = begin PWN::SDR::GQRX.cmd(gqrx_sock: sock, cmd: 'm').to_s.strip rescue StandardError "#{demod} #{passband_hz}" end tuned = begin PWN::SDR::GQRX.cmd(gqrx_sock: sock, cmd: 'f').to_s.strip rescue StandardError freq_label end rds = do_rds ? sample_rds(gqrx_sock: sock, settle_secs: settle) : nil payload = { ok: true, freq: freq_label, hz: hz_i, tuned: tuned, strength_dbfs: strength, demodulator_mode: demod, mode: mode_now, bandwidth: bandwidth, passband_hz: passband_hz, band_plan: band_name, decoder: decoder_key, rds: rds, now_playing: rds && (rds[:radiotext].to_s.strip.empty? ? nil : rds[:radiotext].to_s.strip), station: rds && (rds[:station].to_s.strip.empty? ? nil : rds[:station].to_s.strip), host: host, port: port, captured_at: Time.now.utc.iso8601 } if record summary = build_rf_summary(payload: payload) observe( source: 'gqrx', category: :rf, target: freq_label, data: summary, tags: ['rf_tune', band_name, decoder_key, ('rds' if rds)].compact.map(&:to_s), ttl: ttl ) payload[:observed] = true payload[:summary] = summary else payload[:observed] = false end payload rescue StandardError => e { ok: false, error: "#{e.class}: #{e.}", freq: freq_label, hz: hz_i, band_plan: band_name, advice: 'Confirm GQRX is running with remote control, the SDR is not claimed by another process, and the frequency is in-band for the attached radio.' } ensure begin PWN::SDR::GQRX.cmd(gqrx_sock: sock, cmd: 'U RDS 0') if sock && do_rds rescue StandardError nil end begin PWN::SDR::GQRX.disconnect(gqrx_sock: sock) if sock rescue StandardError nil end end end |
.save(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::AI::Agent::Extrospection.save( store: 'required - Hash returned by .load / mutated in place' )
111 112 113 114 115 116 117 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 111 public_class_method def self.save(opts = {}) store = opts[:store] ||= { snapshot: {}, previous: {}, observations: [] } store[:updated_at] = Time.now.utc.iso8601 FileUtils.mkdir_p(File.dirname(EXTRO_FILE)) File.write(EXTRO_FILE, JSON.pretty_generate(store)) store end |
.serial_sense(opts = {}) ⇒ Object
============================================================
Serial sense organ
- Supported Method Parameters
result = PWN::AI::Agent::Extrospection.serial_sense( block_dev: 'optional - device path (default first ttyUSB/ttyACM or config)', baud: 'optional - baud rate (default 9600)', payload: 'optional - String or byte Array to write (e.g. "ATI\r" or [0x41,0x54])', settle_secs:'optional - seconds to read after write (default 1.5)', data_bits: 'optional (default 8)', stop_bits: 'optional (default 1)', parity: 'optional :none|:even|:odd (default :none)', record: 'optional - observe(category: :serial) (default true)', ttl: 'optional - observation TTL (default 600)' )
Passive inventory via snapshot(sections:[:serial]); this verb is the active serial sense — open a device (PWN::Plugins::Serial), optional payload write, drain response, disconnect. Never keeps the port open across calls so other tools can claim the bus.
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 699 public_class_method def self.serial_sense(opts = {}) cfg = serial_config block_dev = (opts[:block_dev] || cfg[:block_dev] || first_serial_dev).to_s baud = (opts[:baud] || cfg[:baud] || 9600).to_i settle = (opts[:settle_secs] || cfg[:settle_secs] || 1.5).to_f settle = 0.2 if settle < 0.2 settle = 30.0 if settle > 30.0 record = opts.key?(:record) ? !opts[:record].nil? && opts[:record] != false : true ttl = (opts[:ttl] || cfg[:ttl] || 600).to_i payload = opts[:payload] inv = probe_serial if block_dev.empty? || !File.exist?(block_dev) err = { ok: false, error: "serial device not found: #{block_dev.inspect}", advice: 'Plug a USB-UART / modem / Arduino or pass block_dev: "/dev/ttyUSB0". See probe_serial inventory.', inventory: inv } observe(source: 'serial', category: :serial, target: block_dev, data: err, tags: %w[serial_sense unreachable], ttl: ttl) if record return err end require 'pwn/plugins/serial' unless defined?(PWN::Plugins::Serial) serial_obj = nil begin serial_obj = PWN::Plugins::Serial.connect( block_dev: block_dev, baud: baud, data_bits: (opts[:data_bits] || 8).to_i, stop_bits: (opts[:stop_bits] || 1).to_i, parity: (opts[:parity] || :none).to_sym ) PWN::Plugins::Serial.flush_session_data PWN::Plugins::Serial.request(serial_obj: serial_obj, payload: payload) if payload sleep settle raw = Array(PWN::Plugins::Serial.dump_session_data) text = raw.join.force_encoding('UTF-8').scrub hex = raw.map do |b| case b when Integer then format('%02x', b & 0xff) when String then b.bytes.map { |x| format('%02x', x) }.join else b.to_s.unpack1('H*').to_s end end.join(' ') line = begin PWN::Plugins::Serial.get_line_state(serial_obj: serial_obj) rescue StandardError nil end modem = begin PWN::Plugins::Serial.get_modem_params(serial_obj: serial_obj) rescue StandardError nil end payload_out = { ok: true, block_dev: block_dev, baud: baud, bytes: raw.length, text: text[0, 2_000], hex: hex[0, 2_000], line_state: line, modem_params: modem, inventory: inv, captured_at: Time.now.utc.iso8601 } if record summary = "serial #{block_dev}@#{baud} bytes=#{raw.length} text=#{text.to_s.gsub(/\s+/, ' ')[0, 120]}" observe(source: 'serial', category: :serial, target: block_dev, data: summary, tags: %w[serial_sense], ttl: ttl) payload_out[:observed] = true payload_out[:summary] = summary end payload_out rescue StandardError => e { ok: false, error: "#{e.class}: #{e.}", block_dev: block_dev, advice: 'Confirm device path, permissions (dialout group), and that no minicom/screen is holding the port.' } ensure begin PWN::Plugins::Serial.disconnect(serial_obj: serial_obj) if serial_obj rescue StandardError nil end end end |
.snapshot(opts = {}) ⇒ Object
- Supported Method Parameters
snap = PWN::AI::Agent::Extrospection.snapshot( persist: 'optional - Boolean, write snapshot to disk & rotate previous (default true)', sections: 'optional - Array subset of [:host, :net, :toolchain, :repo, :env, :rf, :web, :osint, :serial, :telecomm, :packet, :vision, :voice] (default host/net/toolchain/repo/env/rf)' )
Ambient host baseline (secondary to sense tools like intel/verify/watch). :toolchain never spawns GUI/JVM tools (presence-only). auto_extrospect uses AUTO_SECTIONS (host/repo/env) only. When persist:true the prior snapshot is rotated into :previous so .drift can diff them.
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 130 public_class_method def self.snapshot(opts = {}) persist = if opts.key?(:persist) opts[:persist] ? true : false else true end sections = Array(opts[:sections]).map(&:to_sym) sections = %i[host net toolchain repo env rf] if sections.empty? snap = {} snap[:host] = probe_host if sections.include?(:host) snap[:net] = probe_net if sections.include?(:net) snap[:toolchain] = probe_toolchain if sections.include?(:toolchain) snap[:repo] = probe_repo if sections.include?(:repo) snap[:env] = probe_env if sections.include?(:env) snap[:rf] = probe_rf if sections.include?(:rf) snap[:web] = probe_web if sections.include?(:web) snap[:osint] = probe_osint if sections.include?(:osint) snap[:serial] = probe_serial if sections.include?(:serial) snap[:telecomm] = probe_telecomm if sections.include?(:telecomm) snap[:packet] = probe_packet if sections.include?(:packet) snap[:vision] = probe_vision if sections.include?(:vision) snap[:voice] = probe_voice if sections.include?(:voice) snap[:captured_at] = Time.now.utc.iso8601 snap[:fingerprint] = Digest::SHA256.hexdigest(JSON.generate(snap.except(:captured_at)))[0, 16] if persist store = load store[:previous] = store[:snapshot] || {} store[:snapshot] = snap save(store: store) end drift = compute_drift(before: load[:previous] || {}, after: snap) { snapshot: snap, drift: drift, persisted: persist } end |
.stats ⇒ Object
- Supported Method Parameters
stats = PWN::AI::Agent::Extrospection.stats
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 1309 public_class_method def self.stats store = load snap = store[:snapshot] || {} delta = compute_drift(before: store[:previous] || {}, after: snap) { snapshot_captured_at: snap[:captured_at], snapshot_fingerprint: snap[:fingerprint], observations: Array(store[:observations]).length, drift_changed: Array(delta[:changed]).length, drift_added: Array(delta[:added]).length, drift_removed: Array(delta[:removed]).length, toolchain_bins: (snap[:toolchain] || {}).count { |_, v| !v.to_s.empty? }, listening_ports: Array(snap.dig(:net, :listening)).length, rf_devices: (snap[:rf] || {}).values_at(:rtl_sdr, :hackrf, :flipper, :gqrx_sock).count { |v| rf_present?(val: v) }, web_anchors: (snap[:web] || {}).count { |_, v| v.is_a?(Hash) && v[:reachable] }, serial_devs: Array((snap[:serial] || {})[:devices]).length, packet_bins: ((snap[:packet] || {})[:bins] || {}).count { |_, v| !v.to_s.empty? }, vision_bins: ((snap[:vision] || {})[:bins] || {}).count { |_, v| !v.to_s.empty? }, voice_bins: ((snap[:voice] || {})[:bins] || {}).count { |_, v| !v.to_s.empty? }, telecomm_http: (snap[:telecomm] || {})[:baresip_http] ? true : false, osint_feeds: Array((snap[:osint] || {})[:feeds_available]).length } end |
.telecomm(opts = {}) ⇒ Object
============================================================
Telecomm sense organ (SIP / VoIP / PSTN via BareSIP)
- Supported Method Parameters
result = PWN::AI::Agent::Extrospection.telecomm( action: 'optional - :status|:dial|:hangup|:inventory (default :inventory)', target: 'optional - SIP URI / phone number for :dial (e.g. "sip:alice@example.com" or "+13125551212")', host: 'optional - BareSIP HTTP control host (default 127.0.0.1)', port: 'optional - BareSIP HTTP control port (default 8000)', record: 'optional - observe(category: :telecomm) (default true)', ttl: 'optional - observation TTL (default 600)' )
Telecomm analogue of rf_tune — senses live SIP / VoIP / PSTN state through a running BareSIP instance (never launches it). Status and inventory always; dial/hangup are explicit and OPSEC-sensitive.
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 806 public_class_method def self.telecomm(opts = {}) action = (opts[:action] || :inventory).to_s.to_sym host = (opts[:host] || telecomm_config[:host] || '127.0.0.1').to_s port = (opts[:port] || telecomm_config[:port] || 8000).to_i record = opts.key?(:record) ? !opts[:record].nil? && opts[:record] != false : true ttl = (opts[:ttl] || telecomm_config[:ttl] || 600).to_i target = opts[:target].to_s.strip inv = probe_telecomm http_up = tcp_open?(host: host, port: port) out = { ok: true, action: action, host: host, port: port, baresip_http: http_up, inventory: inv, captured_at: Time.now.utc.iso8601 } case action when :inventory, :status out[:status] = (host: host, port: port, cmd: '/?') if http_up out[:status] ||= inv when :dial if target.empty? out[:ok] = false out[:error] = 'target is required for action: :dial' out[:advice] = 'Pass target: "sip:user@host" or E.164 phone number.' elsif !http_up out[:ok] = false out[:error] = "baresip HTTP control not reachable at #{host}:#{port}" out[:advice] = 'Start baresip with HTTP module enabled (or PWN::Plugins::BareSIP.start) then retry.' else out[:dial] = (host: host, port: port, cmd: "/?dial=#{URI.encode_www_form_component(target)}") end when :hangup if http_up out[:hangup] = (host: host, port: port, cmd: '/?hangup') else out[:ok] = false out[:error] = "baresip HTTP control not reachable at #{host}:#{port}" end else out[:ok] = false out[:error] = "unsupported action: #{action}" out[:advice] = 'Use :inventory, :status, :dial, or :hangup.' end if record summary = "telecomm action=#{action} baresip_http=#{http_up} target=#{target.empty? ? '-' : target}" observe(source: 'telecomm', category: :telecomm, target: (target.empty? ? "#{host}:#{port}" : target), data: summary, tags: ['telecomm', action.to_s], ttl: ttl) out[:observed] = true out[:summary] = summary end out end |
.to_context(opts = {}) ⇒ Object
- Supported Method Parameters
ctx = PWN::AI::Agent::Extrospection.to_context( drift_limit: 'optional - max drift lines (default 4)', obs_limit: 'optional - max observation lines (default 4)' )
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 1276 public_class_method def self.to_context(opts = {}) dlim = opts[:drift_limit] || 4 olim = opts[:obs_limit] || 4 store = load return '' if (store[:snapshot] || {}).empty? && Array(store[:observations]).empty? snap = store[:snapshot] || {} delta = compute_drift(before: store[:previous] || {}, after: snap) lines = [] host = snap[:host] || {} lines << " host_fp : #{snap[:fingerprint]} (#{host[:os]} #{host[:kernel]}, #{host[:arch]})" if snap[:fingerprint] lines << " captured : #{snap[:captured_at]}" if snap[:captured_at] ch = Array(delta[:changed]).first(dlim).map { |c| " ~ #{c[:path]}: #{c[:before].to_s[0, 40]} -> #{c[:after].to_s[0, 40]}" } ad = Array(delta[:added]).first(dlim).map { |c| " + #{c[:path]}: #{c[:after].to_s[0, 60]}" } rm = Array(delta[:removed]).first(dlim).map { |c| " - #{c[:path]}: #{c[:before].to_s[0, 60]}" } unless ch.empty? && ad.empty? && rm.empty? lines << ' drift :' lines.concat(ch).concat(ad).concat(rm) end obs = observations(limit: olim, fresh_only: true) unless obs.empty? lines << ' observed :' obs.each { |o| lines << " * [#{o[:category]}/#{o[:source]}] #{"#{o[:target]} — " if o[:target]}#{o[:data].to_s.gsub(/\s+/, ' ')[0, 120]}" } end "EXTROSPECTION (world-state; correlate with introspective failures)\n#{lines.join("\n")}\n\n" end |
.verify(opts = {}) ⇒ Object
- Supported Method Parameters
verdict = PWN::AI::Agent::Extrospection.verify( claim: 'required - factual claim to fact-check against the live web', kind: 'optional - :cve | :version | :doc | :generic (default auto-detect)', url: 'optional - explicit URL the claim cites (forces kind: :doc)', commit: 'optional - write Mistakes/Memory/observe on refute/confirm (default true)', proxy: 'optional - upstream proxy for TransparentBrowser (e.g. "tor")' )
Browser-backed self fact-checking. Drives PWN::Plugins::TransparentBrowser in :headless mode against a canonical source for the claim class, renders the DOM (JS executed), and returns:
{ claim:, kind:, verdict: :confirmed|:refuted|:unknown,
confidence: 0.0..1.0,
evidence: [{url:, title:, excerpt:, dom_sha:, screenshot:}],
action_taken: :mistakes_record | :extro_observe | :learning_note | nil }
On :refuted -> Mistakes.record(tool:'assumption', error:claim) so the KNOWN MISTAKES block warns every future run. On :confirmed-> observe(category::intel, ttl:30d) reinforces w/ freshness. On :unknown -> Learning.note_outcome(success:false, tags:['needs_human']).
This is the extrospective mirror of Mistakes: a PROACTIVE trigger that catches the model being wrong about the world before a human does.
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 323 public_class_method def self.verify(opts = {}) claim = opts[:claim].to_s.strip raise 'ERROR: claim is required' if claim.empty? kind = (opts[:kind] || detect_claim_kind(claim: claim, url: opts[:url])).to_sym commit = opts.key?(:commit) ? !opts[:commit].nil? && opts[:commit] != false : true proxy = opts[:proxy] || web_config[:proxy] evidence = [] verdict = :unknown conf = 0.0 with_headless_browser(proxy: proxy) do |bo| case kind when :cve cve = claim[/CVE-\d{4}-\d{4,}/i].to_s.upcase %W[https://nvd.nist.gov/vuln/detail/#{cve} https://www.cve.org/CVERecord?id=#{cve}].each do |u| fp = fingerprint_page(browser_obj: bo, url: u) evidence << fp if fp end body = evidence.map { |e| e[:text].to_s }.join(' ') if evidence.empty? || evidence.all? { |e| e[:status].to_i >= 400 } || body =~ /could not be found|does not exist|reserved but/i verdict = :refuted conf = 0.8 else prod = claim.sub(/CVE-\d{4}-\d{4,}/i, '').gsub(/affects?|is|in|the/i, ' ').split.select { |w| w.length > 2 } hit = prod.count { |w| body.downcase.include?(w.downcase) } if prod.empty? || hit.to_f / prod.length >= 0.5 verdict = :confirmed conf = prod.empty? ? 0.6 : [0.5 + (hit.to_f / prod.length * 0.5), 0.95].min else verdict = :refuted conf = 0.6 end end when :doc u = opts[:url] || claim[URI::DEFAULT_PARSER.make_regexp(%w[http https])] fp = fingerprint_page(browser_obj: bo, url: u) evidence << fp if fp if fp.nil? || fp[:status].to_i >= 400 || fp[:reachable] == false verdict = :refuted conf = 0.7 else snippet = claim.sub(u.to_s, '').strip overlap = fuzzy_overlap(needle: snippet, haystack: fp[:text].to_s) if fp[:title].to_s =~ /not found|404|error/i && overlap < 0.2 verdict = :refuted conf = 0.7 else verdict = overlap >= 0.4 ? :confirmed : :unknown conf = overlap end end when :version proj = claim[/[A-Za-z][\w.+-]{2,}/].to_s ver = claim[/v?\d+\.\d+(?:\.\d+)?/].to_s %W[https://rubygems.org/gems/#{proj} https://pypi.org/project/#{proj}/ https://github.com/search?q=#{URI.encode_www_form_component(proj)}&type=repositories].each do |u| fp = fingerprint_page(browser_obj: bo, url: u) evidence << fp if fp end body = evidence.map { |e| e[:text].to_s }.join(' ') if !ver.empty? && body.include?(ver) verdict = :confirmed conf = 0.7 elsif body =~ /\d+\.\d+(?:\.\d+)?/ verdict = :unknown conf = 0.3 end else q = URI.encode_www_form_component(claim) fp = fingerprint_page(browser_obj: bo, url: "https://html.duckduckgo.com/html/?q=#{q}") evidence << fp if fp overlap = fuzzy_overlap(needle: claim, haystack: fp ? fp[:text].to_s : '') verdict = overlap >= 0.5 ? :confirmed : :unknown conf = overlap end end evidence.each { |e| e.delete(:text) } action = commit ? commit_verdict(claim: claim, kind: kind, verdict: verdict, confidence: conf, evidence: evidence) : nil { claim: claim, kind: kind, verdict: verdict, confidence: conf.round(2), evidence: evidence, action_taken: action } rescue StandardError => e { claim: claim, kind: kind, verdict: :unknown, confidence: 0.0, evidence: evidence, error: "#{e.class}: #{e.}", action_taken: nil } end |
.vision(opts = {}) ⇒ Object
============================================================
Vision / OCR sense organ
- Supported Method Parameters
result = PWN::AI::Agent::Extrospection.vision( file: 'required - path to image / screenshot / PDF-page render', action: 'optional - :ocr|:barcode|:inventory (default :ocr when file given, else :inventory)', lang: 'optional - tesseract language (default eng)', record: 'optional - observe(category: :vision) (default true)', ttl: 'optional - observation TTL (default 86400)' )
Eyes on the host: OCR via PWN::Plugins::OCR (RTesseract / tesseract) and barcode/QR decode via zbarimg when present. Inventory only when no file is supplied.
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 968 public_class_method def self.vision(opts = {}) file = opts[:file].to_s.strip action = (opts[:action] || (file.empty? ? :inventory : :ocr)).to_s.to_sym record = opts.key?(:record) ? !opts[:record].nil? && opts[:record] != false : true ttl = (opts[:ttl] || vision_config[:ttl] || 86_400).to_i lang = (opts[:lang] || vision_config[:lang] || 'eng').to_s inv = probe_vision out = { ok: true, action: action, inventory: inv, captured_at: Time.now.utc.iso8601 } case action when :inventory # nothing else when :ocr if file.empty? || !File.exist?(file) out[:ok] = false out[:error] = "image not found: #{file.inspect}" out[:advice] = 'Pass file: "/path/to/image.png" (png/jpg/tiff/webp).' elsif inv.dig(:bins, :tesseract).to_s.empty? && !defined?(RTesseract) out[:ok] = false out[:error] = 'tesseract / rtesseract unavailable' out[:advice] = 'Install tesseract-ocr (+ eng language data) or the rtesseract gem.' else text = vision_ocr(file: file, lang: lang) out[:file] = file out[:text] = text.to_s[0, 8_000] out[:chars] = text.to_s.length out[:preview] = text.to_s.gsub(/\s+/, ' ')[0, 200] end when :barcode if file.empty? || !File.exist?(file) out[:ok] = false out[:error] = "image not found: #{file.inspect}" else codes = (file: file) out[:file] = file out[:codes] = codes end else out[:ok] = false out[:error] = "unsupported action: #{action}" end if record summary = if out[:preview] "vision ocr file=#{File.basename(file)} chars=#{out[:chars]} preview=#{out[:preview]}" elsif out[:codes] "vision barcode file=#{File.basename(file)} codes=#{Array(out[:codes]).length}" else "vision action=#{action} tesseract=#{!inv.dig(:bins, :tesseract).to_s.empty?}" end observe(source: 'vision', category: :vision, target: (file.empty? ? 'inventory' : file), data: summary, tags: ['vision', action.to_s], ttl: ttl) out[:observed] = true out[:summary] = summary end out end |
.voice_sense(opts = {}) ⇒ Object
============================================================
Voice sense organ (TTS / STT / inventory)
- Supported Method Parameters
result = PWN::AI::Agent::Extrospection.voice_sense( action: 'optional - :inventory|:tts|:stt (default :inventory)', text: 'optional - text to speak for :tts (or text_path:)', text_path: 'optional - path to text file for :tts', audio: 'optional - path to audio file for :stt', out: 'optional - output audio path for :tts (wav)', engine: 'optional - :espeak|:festival|:spd_say|:whisper (auto)', model: 'optional - whisper model (default tiny)', record: 'optional - observe(category: :voice) (default true)', ttl: 'optional - observation TTL (default 3600)' )
Wraps PWN::Plugins::Voice + system TTS/STT binaries (espeak-ng, festival, spd-say, whisper, sox). Inventory is always free; TTS/STT are on-demand and persist optional artefacts under ~/.pwn/extrospection/voice/.
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 1051 public_class_method def self.voice_sense(opts = {}) action = (opts[:action] || :inventory).to_s.to_sym record = opts.key?(:record) ? !opts[:record].nil? && opts[:record] != false : true ttl = (opts[:ttl] || voice_config[:ttl] || 3_600).to_i inv = probe_voice out = { ok: true, action: action, inventory: inv, captured_at: Time.now.utc.iso8601 } case action when :inventory # nothing else when :tts text = opts[:text].to_s if text.empty? && opts[:text_path] text = begin File.read(opts[:text_path].to_s) rescue StandardError '' end end if text.strip.empty? out[:ok] = false out[:error] = 'text or text_path is required for action: :tts' else engine = (opts[:engine] || pick_tts_engine(inv: inv)).to_s.to_sym art = File.join(Dir.home, '.pwn', 'extrospection', 'voice') FileUtils.mkdir_p(art) wav = (opts[:out] || File.join(art, "tts_#{Time.now.utc.strftime('%Y%m%d_%H%M%S')}.wav")).to_s ok, log = voice_tts(text: text, engine: engine, out: wav, inv: inv) out[:engine] = engine out[:audio] = File.exist?(wav) ? wav : nil out[:log] = log.to_s[0, 400] out[:chars] = text.length out[:ok] = ok out[:error] = 'TTS engine failed' unless ok end when :stt audio = opts[:audio].to_s if audio.empty? || !File.exist?(audio) out[:ok] = false out[:error] = "audio not found: #{audio.inspect}" out[:advice] = 'Pass audio: "/path/to/recording.wav". Requires whisper binary or plugin path.' else engine = (opts[:engine] || pick_stt_engine(inv: inv)).to_s.to_sym text, log = voice_stt(audio: audio, engine: engine, model: opts[:model] || 'tiny', inv: inv) out[:engine] = engine out[:audio] = audio out[:text] = text.to_s[0, 8_000] out[:log] = log.to_s[0, 400] out[:ok] = !text.to_s.strip.empty? out[:error] = 'STT produced empty transcript' unless out[:ok] end else out[:ok] = false out[:error] = "unsupported action: #{action}" end if record summary = case action when :tts then "voice tts engine=#{out[:engine]} chars=#{out[:chars]} audio=#{out[:audio]}" when :stt then "voice stt engine=#{out[:engine]} text=#{out[:text].to_s.gsub(/\s+/, ' ')[0, 120]}" else "voice inventory espeak=#{!inv.dig(:bins, :'espeak-ng').to_s.empty? && inv.dig(:bins, :'espeak-ng') != ''} sox=#{!inv.dig(:bins, :sox).to_s.empty?}" end observe(source: 'voice', category: :voice, target: action.to_s, data: summary, tags: ['voice', action.to_s], ttl: ttl) out[:observed] = true out[:summary] = summary end out end |
.watch(opts = {}) ⇒ Object
- Supported Method Parameters
obs = PWN::AI::Agent::Extrospection.watch( url: 'required - URL to render and fingerprint', selector: 'optional - CSS selector whose innerText to hash (default full body)', ttl: 'optional - seconds until stale (default 7 days)', proxy: 'optional - upstream proxy for TransparentBrowser' )
Passive change-detection on an external artefact you care about
(target /api/version, vendor changelog, bounty scope page).
Renders headless, hashes the DOM text, screenshots, and persists as
observe(category: :web). On subsequent snapshot(sections:[:web]) or
watch of the same URL, a hash mismatch surfaces in drift() as
~web.
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 |
# File 'lib/pwn/ai/agent/extrospection.rb', line 423 public_class_method def self.watch(opts = {}) url = opts[:url].to_s raise 'ERROR: url is required' if url.empty? ttl = opts[:ttl] || (7 * 24 * 3600) proxy = opts[:proxy] || web_config[:proxy] fp = nil with_headless_browser(proxy: proxy) do |bo| fp = fingerprint_page(browser_obj: bo, url: url, selector: opts[:selector], screenshot: true) end raise "unreachable: #{url}" unless fp prior = observations(category: 'web', target: url, limit: 1).first changed = prior && prior.dig(:data, :dom_sha) && prior.dig(:data, :dom_sha) != fp[:dom_sha] data = fp.slice(:status, :final_url, :title, :dom_sha, :cert_fp, :cert_not_after, :screenshot).merge(excerpt: fp[:text].to_s[0, 200]) observe(source: 'transparent_browser', category: :web, target: url, data: data, tags: (['watch'] + Array(opts[:tags])).compact, ttl: ttl) { url: url, changed: changed, prior_sha: prior && prior.dig(:data, :dom_sha), current: data } end |