@visiq/openclaw-plugin 0.1.10 → 0.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-E7RQSJFB.js +10 -0
- package/dist/index.d.ts +8 -5
- package/dist/index.js +1 -1
- package/dist/openclaw-entry.js +4 -4
- package/openclaw.plugin.json +2 -2
- package/package.json +6 -5
- package/skills/fraud-triage/SKILL.md +5 -5
- package/skills/investigate/SKILL.md +5 -5
- package/dist/chunk-ZWWZ4HHR.js +0 -10
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
var ct="[REDACTED]",dt=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"in_pan_tax",re:/\b[A-Z]{3}[ABCFGHJLPTE][A-Z]\d{4}[A-Z]\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"date_of_birth",re:/\b(?:\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])|(?:0[1-9]|[12]\d|3[01])[/.](?:0[1-9]|1[0-2])[/.]\d{4}|(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12]\d|3[01])\/\d{4})\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];function ye(e){if(!/^\d+$/.test(e))return!1;let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let i=e.charCodeAt(r)-48;n&&(i*=2,i>9&&(i-=9)),t+=i,n=!n}return t%10===0}function Fn(e){let t=e.replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let i=0;i<n.length;i++){let a=n[i],o=a>="A"&&a<="Z"?String(a.charCodeAt(0)-55):a;for(let s=0;s<o.length;s++)r=(r*10+(o.charCodeAt(s)-48))%97}return r===1}function jn(e){if(!/^\d{9}$/.test(e))return!1;let t=[3,7,1,3,7,1,3,7,1],n=0;for(let r=0;r<9;r++)n+=(e.charCodeAt(r)-48)*t[r];return n%10===0}var Bn=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],qn=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]];function Un(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=Bn[t][qn[r%8][n[r].charCodeAt(0)-48]];return t===0}function zn(e){if(!/^\d{11}$/.test(e)||/^(\d)\1{10}$/.test(e))return!1;let t=n=>{let r=0;for(let a=0;a<n;a++)r+=(e.charCodeAt(a)-48)*(n+1-a);let i=r*10%11;return i===10?0:i};return t(9)===e.charCodeAt(9)-48&&t(10)===e.charCodeAt(10)-48}function Vn(e){if(!/^\d{10}$/.test(e))return!1;let t=0;for(let i=0;i<9;i++)t+=(e.charCodeAt(i)-48)*(10-i);let n=11-t%11,r=n===11?0:n;return r!==10&&r===e.charCodeAt(9)-48}var Kn=[1,4,3,7,5,8,6,9,10];function Gn(e){if(!/^\d{8,9}$/.test(e))return!1;let t=0;for(let n=0;n<e.length;n++)t+=(e.charCodeAt(n)-48)*Kn[n];return t%11===0}var Wn="TRWAGMYFPDXBNJZSQVHLCKE";function Hn(e){let t=e.replace(/[\s-]/g,"").toUpperCase(),n=/^([XYZ]?)(\d{7,8})([A-Z])$/.exec(t);if(!n)return!1;let[,r,i,a]=n;if(r===""&&i.length!==8||r!==""&&i.length!==7)return!1;let o=r===""?i:String("XYZ".indexOf(r))+i;return Wn[Number(o)%23]===a}var Qn=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Yn(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Qn.has(t.slice(0,2)):!1}var Zn=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&ye(e)},{name:"iban",re:/\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]){10,30}\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:Fn},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:jn},{name:"uk_nino",re:/\b[A-Za-z]{2} ?\d{2} ?\d{2} ?\d{2} ?[A-Da-d]\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:(e,t)=>t!==void 0&&t===t.toLowerCase()?!1:Yn(e)},{name:"in_aadhaar",re:/\b[2-9]\d{3}[ -]?\d{4}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===12&&Un(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:zn},{name:"es_dni_nie",re:/\b[XYZxyz]?\d{7,8}[ -]?[A-Za-z]\b/g,normalize:e=>e.replace(/[\s-]/g,"").toUpperCase(),validate:Hn},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&ye(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Vn},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Gn}],w=Object.fromEntries(dt.map(e=>[e.name,e.re.source])),ut=["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","pan","iban","aba_routing","us_ein","swift_bic","ssn","uk_nino","in_aadhaar","in_pan_tax","br_cpf","es_dni_nie","ca_sin","uk_nhs_number","au_tfn","email","us_phone","date_of_birth","ipv4","mac_address"],H={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
2
|
+
MIIEv\u2026
|
|
3
|
+
-----END PRIVATE KEY-----`,template:{pattern:w.private_key,mode:"full"},defaultEnabled:!0},jwt:{id:"jwt",label:"JWT / bearer tokens",description:"JSON Web Tokens (base64url header.payload.signature).",category:"secret",example:"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.dBjftJeZ4CVP",template:{pattern:w.jwt,mode:"full"},defaultEnabled:!0},aws_access_key:{id:"aws_access_key",label:"AWS access key IDs",description:"AWS access / identity key ids (AKIA / ASIA / AROA \u2026).",category:"secret",example:"AKIAIOSFODNN7EXAMPLE",template:{pattern:w.aws_access_key,mode:"full"},defaultEnabled:!0},github_token:{id:"github_token",label:"GitHub tokens",description:"GitHub personal / OAuth tokens (classic ghp_\u2026 + fine-grained).",category:"secret",example:"ghp_0123456789abcdef0123456789abcdef0123",template:{pattern:w.github_token,mode:"full"},defaultEnabled:!0},slack_token:{id:"slack_token",label:"Slack tokens",description:"Slack bot / user / app tokens (xoxb- / xoxp- \u2026).",category:"secret",example:"xoxb-1234567890-abcdefghijkl",template:{pattern:w.slack_token,mode:"full"},defaultEnabled:!0},stripe_secret:{id:"stripe_secret",label:"Stripe secret keys",description:"Stripe live secret / restricted keys (sk_live_ / rk_live_).",category:"secret",example:"sk_live_0123456789abcdefABCDEF",template:{pattern:w.stripe_secret,mode:"full"},defaultEnabled:!0},google_api_key:{id:"google_api_key",label:"Google API keys",description:"Google API keys (AIza\u2026).",category:"secret",example:"AIzaSyA1234567890abcdefghijklmnopqrstuv",template:{pattern:w.google_api_key,mode:"full"},defaultEnabled:!0},llm_api_key:{id:"llm_api_key",label:"LLM provider API keys",description:"OpenAI / Anthropic secret keys (sk-\u2026, sk-proj-\u2026, sk-ant-\u2026).",category:"secret",example:"sk-ant-api03-AbCdEf0123456789AbCdEf01",template:{pattern:w.llm_api_key,mode:"full"},defaultEnabled:!0},bearer_token:{id:"bearer_token",label:"Authorization bearer tokens",description:"Credentials following an HTTP `Authorization: Bearer \u2026` header.",category:"secret",example:"Bearer abcdef0123456789abcdef0123456789",template:{pattern:w.bearer_token,mode:"full"},defaultEnabled:!0},connection_string:{id:"connection_string",label:"Connection strings (with password)",description:"Database / broker DSNs carrying an inline password (scheme://user:pass@host).",category:"secret",example:"postgres://app:s3cr3t@db.internal:5432/main",template:{pattern:w.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS).",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\b\\d{13,19}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){10,30}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:"\\b\\d{9}\\b",mode:"full"},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX).",category:"financial",example:"12-3456789",template:{pattern:w.us_ein,mode:"full"},defaultEnabled:!0},swift_bic:{id:"swift_bic",label:"SWIFT / BIC codes",description:"Bank SWIFT/BIC codes (8 or 11 chars). DEFAULT-OFF (matches uppercase tokens).",category:"financial",example:"DEUTDEFF500",template:{pattern:w.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789).",category:"pii",example:"123-45-6789",template:{pattern:w.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},uk_nino:{id:"uk_nino",label:"UK National Insurance numbers",description:"UK NINOs (e.g. AB 12 34 56 C). DEFAULT-OFF \u2014 NO CHECKSUM. Precision comes only from the issued alphabet and the never-issued administrative prefixes (BG, GB, NK, KN, TN, NT, ZZ), so roughly half of tokens already shaped 2-letters/6-digits/[A-D] validate. All-lowercase candidates are rejected (git short SHAs), but that does NOT exclude uppercase business identifiers \u2014 serial, part, batch, PO, coupon and asset tags share the shape exactly and were measured being masked. Opt in when UK NINOs are expected in your traffic.",category:"pii",example:"AB 12 34 56 C",template:{pattern:"\\b[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-D]\\b",mode:"full"},defaultEnabled:!1},in_aadhaar:{id:"in_aadhaar",label:"Aadhaar numbers (India)",description:"12-digit UIDAI Aadhaar numbers, Verhoeff-checksum validated and constrained to the issued 2-9 leading digit. Keeps the last 4 visible.",category:"pii",example:"2345 6789 0124",template:{pattern:"\\b[2-9]\\d{3}\\s\\d{4}\\s\\d{4}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},in_pan_tax:{id:"in_pan_tax",label:"India PAN (tax ID)",description:"India Permanent Account Number \u2014 the income-tax id (ABCPE1234F), NOT a payment-card PAN. NO CHECKSUM: the only discriminator is the holder-type letter in position 4, which removes just 15 of 26 possibilities in one position, so roughly 4 in 10 uniform 5-letter/4-digit/1-letter tokens validate. DEFAULT-OFF for that reason \u2014 an uppercase SKU or part number of the same shape is masked, and nothing in the value distinguishes it.",category:"financial",example:"ABCPE1234F",template:{pattern:w.in_pan_tax,mode:"full"},defaultEnabled:!1},br_cpf:{id:"br_cpf",label:"CPF numbers (Brazil)",description:"Brazilian CPF, closed by TWO independent mod-11 check digits (~1-in-100 false-positive rate). Repdigits are rejected. Keeps the last 2 visible.",category:"pii",example:"123.456.789-09",template:{pattern:"\\b\\d{3}\\.\\d{3}\\.\\d{3}-\\d{2}\\b",mode:"partial",keepLast:2},defaultEnabled:!0},es_dni_nie:{id:"es_dni_nie",label:"DNI / NIE numbers (Spain)",description:"Spanish national ID (8 digits + letter) and foreigner ID (X/Y/Z + 7 digits + letter), validated by the mod-23 check letter.",category:"pii",example:"12345678Z",template:{pattern:"\\b[XYZ]?\\d{7,8}[A-Z]\\b",mode:"full"},defaultEnabled:!0},ca_sin:{id:"ca_sin",label:"SIN numbers (Canada)",description:"Canadian Social Insurance Numbers (9-digit, Luhn-validated). DEFAULT-OFF \u2014 identical shape to an ABA routing number and to any 9-digit id, with only a mod-10 pass to separate them.",category:"pii",example:"046 454 286",template:{pattern:"\\b\\d{3}[- ]\\d{3}[- ]\\d{3}\\b",mode:"partial",keepLast:3},defaultEnabled:!1},uk_nhs_number:{id:"uk_nhs_number",label:"NHS numbers (UK)",description:"UK NHS patient numbers (10-digit, weighted mod-11). DEFAULT-OFF \u2014 a 10-digit run is also every North American phone number.",category:"pii",example:"943 476 5919",template:{pattern:"\\b\\d{3}[- ]\\d{3}[- ]\\d{4}\\b",mode:"full"},defaultEnabled:!1},au_tfn:{id:"au_tfn",label:"Tax File Numbers (Australia)",description:"Australian TFNs (8-9 digit, weighted mod-11). DEFAULT-OFF \u2014 collides with essentially every 8-9 digit identifier.",category:"financial",example:"123 456 782",template:{pattern:"\\b\\d{3}[- ]\\d{3}[- ]\\d{2,3}\\b",mode:"full"},defaultEnabled:!1},date_of_birth:{id:"date_of_birth",label:"Dates of birth",description:"Dates in the common written formats. DEFAULT-OFF and heavily over-masking by nature \u2014 a DOB is indistinguishable from any other date (created_at, invoice, release). Offered because DOB is a GDPR/HIPAA identifier some regulated tenants must mask regardless.",category:"pii",example:"1985-04-12",template:{pattern:w.date_of_birth,mode:"full"},defaultEnabled:!1},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept).",category:"pii",example:"alice@acme.com",template:{pattern:w.email,mode:"email"},defaultEnabled:!0},us_phone:{id:"us_phone",label:"US phone numbers",description:"US phone numbers in common formats. DEFAULT-OFF (10-digit false-positive surface).",category:"pii",example:"(415) 555-0132",template:{pattern:w.us_phone,mode:"partial",keepLast:4},defaultEnabled:!1},ipv4:{id:"ipv4",label:"IPv4 addresses",description:"Dotted-quad IPv4 addresses. DEFAULT-OFF (common + usually benign).",category:"identifier",example:"203.0.113.42",template:{pattern:w.ipv4,mode:"full"},defaultEnabled:!1},mac_address:{id:"mac_address",label:"MAC addresses",description:"Hardware MAC addresses. DEFAULT-OFF.",category:"identifier",example:"3c:22:fb:1a:2b:3c",template:{pattern:w.mac_address,mode:"full"},defaultEnabled:!1}};var Ya=new Set(ut.filter(e=>!H[e].defaultEnabled));function Jn(e,t){let n=new Set;for(let r of ut)(H[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function Xn(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=e;for(let{name:a,re:o}of dt){let s=a;n.has(s)||(i=i.replace(o,()=>(r?.(s),t)))}for(let{name:a,re:o,normalize:s,validate:l}of Zn)n.has(a)||(i=i.replace(o,c=>l(s(c),c)?(r?.(a),t):c));return i}function Ie(e,t=ct,n,r){return er(e,t,Jn(n,r))}function er(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=s=>{if(typeof s=="string")return Xn(s,t,n,a);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!i)return s;let l=String(s);return l.length>=13&&l.length<=19&&ye(l)?(r.add("pan"),t):s}if(Array.isArray(s))return s.map(l=>o(l));if(s!==null&&typeof s=="object"){let l=s,c={};for(let d of Object.keys(l))c[d]=o(l[d]);return c}return s};return{value:o(e),detectors:[...r].sort()}}function pt(e,t=ct){return Ie(e,t).value}function tr(e){let{value:t,detectors:n}=Ie(e),r=n.some(i=>H[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function Q(e,t){let{blocked:n,redacted:r,detectors:i}=tr(e);return n?t.failMode==="closed"?{verdict:"block",redacted:r,detectors:i}:{verdict:"redact",redacted:r,detectors:i}:{verdict:"allow",redacted:r,detectors:i}}function ke(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var nr=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function Se(e){return nr.has(ke(e))}var rr=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,ft=Object.freeze({\u0430:"a",\u0435:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0456:"i",\u0455:"s",\u043A:"k",\u043C:"m",\u0442:"t",\u043D:"h",\u0432:"b",\u0433:"r",\u03BF:"o",\u03B1:"a",\u03C1:"p",\u03B9:"i",\u03C4:"t",\u03B5:"e",\u03BA:"k",\u03BD:"v",\u03C5:"u",\u03B7:"n",\u0131:"i","\u04CF":"l",\u0578:"n"}),ir=new RegExp(`[${Object.keys(ft).join("")}]`,"gu"),ar=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),mt="\u2801\u2803\u2809\u2819\u2811\u280B\u281B\u2813\u280A\u281A\u2805\u2807\u280D\u281D\u2815\u280F\u281F\u2817\u280E\u281E\u2825\u2827\u283A\u282D\u283D\u2835",or=Object.freeze(Object.fromEntries([...mt].map((e,t)=>[e,String.fromCharCode(97+t)]))),sr=new RegExp(`[${mt}\u2800]`,"g"),gt=/[⠀-⣿]/;function lr(e){let t="";for(let n of e){let r=n.codePointAt(0);r!==void 0&&(r>=917536&&r<=917630?t+=String.fromCodePoint(r-917504):r>=917504&&r<=917631||(t+=n))}return t}function cr(e){return e.replace(rr,"")}function ht(e){return e.replace(ir,t=>ft[t]??t)}function dr(e){return e.replace(/[4@31!05$79(8]/g,t=>ar[t]??t)}function ur(e){return e.replace(/[a-zA-Z]/g,t=>{let n=t<="Z"?65:97;return String.fromCharCode((t.charCodeAt(0)-n+13)%26+n)})}function pr(e){return gt.test(e)?e.replace(sr,t=>t==="\u2800"?" ":or[t]??t):e}function et(e){let t;try{t=lr(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=cr(t),t=ht(t),t}var fr=/^[A-Za-z0-9+/]{16,}={0,2}$/,mr=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,tt=/[A-Za-z0-9+/]{20,}={0,2}/g;function be(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);(r===9||r===10||r===13||r>=32&&r<=126||r>=160&&r!==65533)&&t++}return t/e.length}var _t=new TextDecoder("utf-8",{fatal:!1});function yt(e){let t;try{t=atob(e)}catch{return[]}let n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i)&255;let r=_t.decode(n);return t===r?[t]:[r,t]}function gr(e){let t=e.replace(/\s+/g,"");if(t.length===0||t.length%2!==0)return[];let n=new Uint8Array(t.length/2);for(let a=0;a<n.length;a++){let o=Number.parseInt(t.slice(a*2,a*2+2),16);if(Number.isNaN(o))return[];n[a]=o}let r="";for(let a=0;a<n.length;a++)r+=String.fromCharCode(n[a]);let i=_t.decode(n);return r===i?[r]:[i,r]}function nt(e){let t=e.trim(),n=[];if(mr.test(t))for(let r of gr(t))n.push({decoded:r,textiness:be(r)});if(fr.test(t)&&t.length%4===0)for(let r of yt(t))n.push({decoded:r,textiness:be(r)});return n}function rt(e,t){let n=[],r;for(tt.lastIndex=0;(r=tt.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of yt(i))n.push({decoded:a,textiness:be(a)})}return n}var hr=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function bt(e,t=hr){if(typeof e!="string"||e.length===0)return{views:[],anyDecoded:!1,truncated:!1,nodes:0,maxDepthSeen:0};let{maxDepth:n,byteCap:r,maxNodes:i,maxBlobsPerNode:a}=t,o=new Set,s=m=>{m.length>0&&m.length<=r&&o.add(m)},l=!1,c=!1,d=0,f=0,g=[{s:e,depth:0}];for(;g.length>0;){if(d>=i){c=!0;break}let m=g.pop();if(m===void 0)break;let{s:h,depth:v}=m;if(h.length>r){c=!0;continue}d++,v>f&&(f=v);let _=et(h);s(_);let A=dr(_);if(A!==_&&s(A),s(ur(_)),gt.test(h)&&s(pr(_)),v>=n){let S=et(h);(nt(S).length>0||rt(S,a).length>0)&&(c=!0);continue}let k=[...nt(_),...rt(_,a)];for(let S of k){if(l=!0,S.decoded.length>r){c=!0;continue}S.textiness>=.85&&S.decoded!==_?g.push({s:S.decoded,depth:v+1}):s(S.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:d,maxDepthSeen:f}}var vt=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],_r=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),yr=8,br=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),it=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function vr(e){let t=[...e].map(r=>r.codePointAt(0)),n=0;for(let r=0;r<t.length;r++){let i=t[r];if(i>=917504&&i<=917631||br.has(i)&&it(t[r-1])&&it(t[r+1])&&(n++,n>=yr))return!0}return!1}var wr=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function Ar(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(wr.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Ir=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function kr(e){for(let t of Ir)if(e>=t.lo&&e<=t.hi)return t.name;return null}function Sr(e){for(let t of e.split(/\s+/)){if(t.length<4)continue;let n=0,r=0,i=!0;for(let a of t){let o=kr(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:ht(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var at=Object.freeze({signals:[],contributes:!1});function Er(e){if(typeof e!="string"||e.length===0)return{...at,signals:[]};let t=new Set;try{vr(e)&&t.add("hidden_text_carrier"),Ar(e)&&t.add("injected_turn_boundary"),Sr(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=bt(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...at,signals:[]}}return{signals:[...vt.filter(n=>t.has(n))],contributes:_r.some(n=>t.has(n))}}var Y=[{name:"override_instructions",re:/\bignore (?:all |the )?(?:previous|above|prior) (?:instructions|prompts?)\b/i},{name:"disregard_instructions",re:/\bdisregard (?:the )?(?:above|previous|system)\b/i},{name:"role_tag",re:/<\/?(system|assistant|instructions|host_context)\b/i},{name:"privilege_override",re:/\b(grant|escalate|elevate) (admin|root|all|full) (access|privileges?)\b/i},{name:"tool_smuggle",re:/```[\s\S]*?(tool_call|function_call)/i}];function ot(e){return typeof e!="string"||e.length===0?[]:Y.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function Cr(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(ot(e)),{views:n}=bt(e);for(let r of n)for(let i of ot(r))t.add(i);return Y.filter(r=>t.has(r.name)).map(r=>r.name)}function Tr(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of Cr(a))t.add(s);let o=Er(a);for(let s of o.signals)n.add(s);o.contributes&&(r=!0);return}if(Array.isArray(a)){for(let o of a)i(o);return}if(typeof a=="object")for(let o of Object.values(a))i(o)}};return i(e),{matched:t.size>0||r,signatures:Y.filter(a=>t.has(a.name)).map(a=>a.name),structural:vt.filter(a=>n.has(a))}}function Nr(e){return Tr(e).matched}var Za=Y.map(e=>e.name);var Or=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var xr="i:injection";function wt(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=Ie(e.content);for(let a of i){let o=H[a]?.category;o&&t.add(`c:${o}`)}Nr(e.content)&&t.add(xr)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Or.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var _e="(?:system\\s+prompt|initial\\s+(?:instructions|prompt)|system\\s+(?:instructions|message)|hidden\\s+(?:instructions|prompt)|your\\s+(?:system\\s+prompt|initial\\s+instructions|instructions|prompt)|the\\s+prompt\\s+(?:above|you\\s+were\\s+given))",Ja=[{name:"reveal_prompt",re:new RegExp(`\\b(?:reveal|show|print|repeat|output|echo|display|expose|dump|leak|reprint|divulge|disclose)\\b[\\s\\S]{0,40}?\\b${_e}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${_e}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${_e}\\b`,"i")},{name:"repeat_above",re:/\b(?:repeat|print|output|echo|reproduce)\b[\s\S]{0,20}?\b(?:everything|all\s+(?:the\s+)?(?:text|words))\b[\s\S]{0,12}?\b(?:above|before|preceding|verbatim|word\s+for\s+word)\b/i}],st="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Rr=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${st}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${st}|programming|training))`,Mr="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",lt="(?:\\b(?:unrestricted|unfiltered|uncensored|unbounded|unlimited|unchained|jailbroken|lawless|amoral)\\b|\\b(?:DAN|STAN|DUDE|AIM)\\b|\\bno\\s+(?:longer\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|boundaries|constraints?)\\b(?!\\s+(?:on|over|regarding|upon|for)\\b)|\\bwithout\\s+(?:any\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|constraints?|censorship)\\b|\\b(?:free|freed|released)\\s+from\\s+(?:your\\s+)?(?:restrictions?|limits?|rules?|guidelines?|guardrails?|programming|constraints?)\\b|\\b(?:can|will|are\\s+able\\s+to)\\s+(?:do|say)\\s+anything\\b|\\bignore\\s+(?:all\\s+)?(?:your\\s+)?(?:previous\\s+|prior\\s+|system\\s+)?(?:instructions?|rules?|guidelines?)\\b)",Lr="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Xa=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${Mr}${Rr}\\b`,"i")},{name:"forget_everything_prior",re:/\b(?:forget|ignore|disregard|erase|discard)\s+(?:about\s+|all\s+|any\s+)?(?:everything|anything)\b[\s\S]{0,24}?\b(?:above|before|previously|prior|earlier|you\s+(?:were|have\s+been)\s+(?:told|instructed|given|programmed))\b/i},{name:"persona_reassignment_jailbreak",re:new RegExp(`\\byou\\s+are\\s+now\\s+(?:(?:a|an|the)\\s+)?[\\s\\S]{0,48}?${lt}`,"i")},{name:"constraint_release",re:/\byou\s+are\s+no\s+longer\s+(?:bound|restricted|limited|constrained|obligated|governed|subject\s+to|required\s+to)\b/i},{name:"from_now_on_reassignment",re:new RegExp(`\\bfrom\\s+now\\s+on\\s*,?\\s+you\\s+(?:are|will|must|shall|have|can)\\s+(?:${Lr}\\b|[\\s\\S]{0,40}?${lt})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Pr="[SYSTEM-PROMPT-REDACTED]";function ve(e){return e.toLowerCase().replace(/\s+/g," ").trim().split(" ").filter(t=>t.length>0)}function $r(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function At(e,t){if(typeof e!="string"||typeof t!="string"||e.length===0||t.length===0)return[];let n=ve(e),r=ve(t),i=8;if(n.length<i||r.length<i)return[];let a=new Set;for(let l=0;l+i<=r.length;l++)a.add(r.slice(l,l+i).join(" "));let o=[],s=new Set;for(let l=0;l+i<=n.length;l++){let c=n.slice(l,l+i).join(" ");a.has(c)&&!s.has(c)&&(s.add(c),o.push(c))}return o}function Dr(e,t){if(typeof e!="string"||e.length===0)return e;let n=e,r=Math.max(1,ve(e).length);for(let i=0;i<r;i++){let a=At(t,n);if(a.length===0)return n;for(let o of a){let s=o.split(" ").filter(d=>d.length>0);if(s.length===0)continue;let l=s.map($r).join("\\s+"),c;try{c=new RegExp(l,"gi")}catch{continue}n=n.replace(c,Pr)}}return n}function we(e,t,n){if(e==null)return e;if(typeof e=="string"){for(let r of At(t,e))n.add(r);return Dr(e,t)}if(Array.isArray(e))return e.map(r=>we(r,t,n));if(typeof e=="object"){let r=e,i=Object.create(Object.getPrototypeOf(r));for(let a of Object.keys(r))i[a]=we(r[a],t,n);return i}return e}function Fr(e,t){if(typeof t!="string"||t.length===0)return{leaked:!1,matchedSpans:[],redacted:e};let n=new Set,r=we(e,t,n),i=[...n].sort();return{leaked:i.length>0,matchedSpans:i,redacted:r}}function It(e,t,n){let{leaked:r,redacted:i,matchedSpans:a}=Fr(e,t);return r?n.failMode==="closed"?{verdict:"block",redacted:i,matchedSpans:a}:{verdict:"redact",redacted:i,matchedSpans:a}:{verdict:"allow",redacted:i,matchedSpans:a}}var eo=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var x=e=>`[^.!?;\\n]{0,${e}}?`,jr=["\\bi\\s+(?:can'?t|cannot|can\\s+not|won'?t|will\\s+not)\\b","\\bi(?:'m|\\s+am)\\s+(?:not\\s+able\\s+to|unable\\s+to|not\\s+going\\s+to|not\\s+permitted\\s+to|not\\s+allowed\\s+to)\\b"].join("|"),kt="(?:help|assist|provide|create|generate|produce|write|compose|draft|comply|fulfil|fulfill|share|disclose|reveal|perform|execute|run|send|transmit|publish|export|approve|grant|carry\\s+out|do\\s+that|do\\s+this|do\\s+so|go\\s+ahead)",to=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${jr})\\s${x(40)}\\b${kt}\\b`,"\\b(?:that|this|it)(?:'s|\\s+is)\\s+not\\s+something\\s+i\\s+(?:can|could|am\\s+able\\s+to|'m\\s+able\\s+to)\\b",`\\b(?:falls|sits|is)\\s+outside\\s+(?:of\\s+)?(?:what|the\\s+(?:scope|range|bounds))\\b${x(40)}\\bi\\s+(?:can|am|'m)\\b`,"\\bnot\\s+something\\s+i(?:'m|\\s+am)\\s+(?:able|willing|permitted|allowed)\\s+to\\b"].join("|"),"i")},{id:"explicit_decline",class:"strong",re:new RegExp(["\\bi\\s+(?:must|have\\s+to|need\\s+to|will\\s+have\\s+to|am\\s+going\\s+to|'m\\s+going\\s+to)\\s+(?:respectfully\\s+)?decline\\b","\\bi(?:'m|\\s+am)\\s+not\\s+(?:comfortable|willing|prepared)\\b","\\bi(?:'ll|\\s+will)\\s+(?:have\\s+to\\s+)?pass\\s+on\\b","\\bi\\s+(?:must|have\\s+to)\\s+refuse\\b"].join("|"),"i")},{id:"policy_citation",class:"strong",re:new RegExp([`\\b(?:against|contrary\\s+to|prohibited\\s+by|forbidden\\s+by|in\\s+violation\\s+of|violates)\\s${x(24)}\\b(?:polic(?:y|ies)|guidelines?|terms\\s+of\\s+(?:use|service)|rules\\s+of\\s+engagement|code\\s+of\\s+conduct)\\b`,`\\b(?:my|our|the|company|organi[sz]ation'?s?)\\s+(?:polic(?:y|ies)|guidelines?)\\s${x(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${x(24)}\\b(?:polic(?:y|ies)|guidelines?)\\b`].join("|"),"i")},{id:"guardrail_selfreference",class:"strong",re:new RegExp(["\\bi(?:'ve|\\s+have)\\s+been\\s+(?:instructed|configured|told|trained)\\s+not\\s+to\\b","\\bi(?:'m|\\s+am)\\s+(?:designed|configured|programmed|built|set\\s+up)\\s+not\\s+to\\b",`\\bmy\\s+(?:safety\\s+)?(?:instructions|configuration|guardrails?|constraints|training)\\s${x(24)}\\b(?:prevent|prohibit|forbid|do(?:es)?\\s+not\\s+(?:allow|permit)|preclude)\\b`,"\\b(?:outside|beyond)\\s+(?:my|the)\\s+(?:permitted|authori[sz]ed|configured|approved)\\s+(?:scope|remit|capabilities|actions|operations)\\b"].join("|"),"i")},{id:"ethical_objection",class:"strong",re:new RegExp(["\\b(?:that|this|doing\\s+(?:so|that)|what\\s+you(?:'re|\\s+are)\\s+asking|the\\s+request|such\\s+a\\s+request)\\s+(?:would\\s+be|is|are)\\s+(?:clearly\\s+|both\\s+|potentially\\s+)?(?:illegal|unethical|unlawful|harmful|fraudulent)\\b","\\bi\\s+(?:do\\s+not|don'?t)\\s+condone\\b","\\b(?:goes|would\\s+go|runs)\\s+against\\s+my\\s+(?:principles|values|ethics)\\b","\\bi\\s+(?:can'?t|cannot|won'?t)\\s+in\\s+good\\s+conscience\\b"].join("|"),"i")},{id:"apology_marker",class:"weak",re:new RegExp("\\b(?:i(?:'m|\\s+am)\\s+(?:really\\s+|very\\s+|terribly\\s+|so\\s+)?sorry|i\\s+apologi[sz]e|my\\s+apologies)\\b","i")}]),no=Object.freeze([/```/,/\b(?:here(?:'s|\s+is|\s+are)|below\s+(?:is|are|you(?:'ll|\s+will)\s+find)|the\s+following\s+(?:is|are))\b/i,new RegExp(`\\b(?:but|however|instead|although|that\\s+said)\\b${x(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${x(30)}\\b${kt}\\b|i(?:'d|\\s+would)\\s+be\\s+happy\\s+to\\b|i(?:'m|\\s+am)\\s+able\\s+to\\b)`,"i"),/\bwhat\s+i\s+can\s+do\s+(?:instead|is|for\s+you)\b/i]);var D=e=>`[^.!?;\\n]{0,${e}}?`,ro=Object.freeze([{id:"vulnerability_scanning",objectPatterns:[/\b(?:vulnerability|vuln|security)\s+(?:scan|scans|scanning|assessment|audit|test|testing)\b/i,/\bpen(?:etration)?[\s-]?test(?:ing)?\b/i,/\bport\s+scan(?:ning)?\b/i,/\b(?:exploit|nmap|metasploit|nessus|burp\s+suite)\b/i,/\bCVE-\d{4}-\d{4,7}\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|vulnerability|incident\s+respon\w{0,4}|threat|soc|red\s+team|phishing|malware)\b/i]},{id:"credential_access",objectPatterns:[/\b(?:credential|password|passphrase|api\s+key|access\s+key|secret|token|private\s+key|ssh\s+key)s?\b/i,/\b(?:vault|secrets?\s+manager|keychain|keystore)\b/i,/\bservice\s+account\s+key\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|identity|iam|credential|secrets?\s+manage\w{0,4}|vault|platform|devops)\b/i]},{id:"financial_transaction",objectPatterns:[/\b(?:wire\s+transfer|bank\s+transfer|payout|disbursement|chargeback)\b/i,new RegExp(`\\b(?:approve|issue|initiate|process|release)\\s${D(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${D(20)}\\b(?:funds|money)\\b`,"i")],purposeFunctions:["finance_accounting","procurement"],purposePatterns:[/\b(?:finance|financial|accounting|invoice|invoicing|payment|payments|billing|refund|refunds|treasury|procurement|spend|purchasing|fraud|kyc)\b/i]},{id:"personnel_data",objectPatterns:[/\b(?:employee|personnel|payroll|hr|staff)\s+(?:record|records|data|file|files|information|details)\b/i,/\b(?:salary|salaries|compensation|performance\s+review|termination\s+letter)s?\b/i,/\b(?:home\s+address|social\s+security\s+number|national\s+insurance\s+number)e?s?\b/i],purposeFunctions:["hr","privacy_compliance"],purposePatterns:[/\b(?:hr|human\s+resources|people\s+ops|payroll|benefits|recruit\w{0,4}|onboarding|privacy|dsar|consent)\b/i]},{id:"regulated_advice",objectPatterns:[/\b(?:legal|medical|tax|investment|financial)\s+advice\b/i,/\bpractis\w{0,3}\s+law\b/i,/\b(?:diagnose|diagnosis|prescribe|prescription)\b/i,/\b(?:binding|enforceable)\s+(?:opinion|interpretation)\b/i],purposeFunctions:["legal","privacy_compliance"],purposePatterns:[/\b(?:legal|compliance|counsel|contract|contracts|litigation|nda|privacy|regulator\w{0,2}|audit\w{0,3})\b/i]},{id:"data_export",objectPatterns:[new RegExp(`\\b(?:export|download|dump|extract|exfiltrat\\w{0,3}|bulk\\s+copy)\\b\\s${D(30)}\\b(?:data|database|dataset|records?|table|tables|customer\\s+list|contact\\s+list|report)\\b`,"i"),/\b(?:full|entire|whole)\s+(?:database|dataset|customer\s+table)\b/i],purposeFunctions:["operations","engineering","privacy_compliance"],purposePatterns:[/\b(?:data\s+(?:pipeline|engineering|platform)|etl|export|reporting|analytics|operations|document\s+extract\w{0,3}|forecast\w{0,3})\b/i]},{id:"code_execution",objectPatterns:[new RegExp(`\\b(?:run|execute|invoke)\\s${D(24)}\\b(?:script|scripts|command|commands|shell|code|binary|query|migration)\\b`,"i"),/\b(?:shell|root|sudo|admin)\s+(?:access|command|session)\b/i,/\bagainst\s+(?:the\s+)?production\s+(?:system|server|database|environment)s?\b/i],purposeFunctions:["engineering","it_security"],purposePatterns:[/\b(?:engineering|developer|devops|platform|release|deploy\w{0,4}|build|pipeline|sandbox|test\s+data|change\s+window)\b/i]},{id:"external_communication",objectPatterns:[new RegExp(`\\b(?:send|post|publish|email|tweet|message|broadcast)\\b\\s${D(30)}\\b(?:external|customer|customers|public|press|social\\s+media|third[\\s-]party|prospect|prospects)\\b`,"i"),/\b(?:cold\s+outreach|marketing\s+blast|phishing\s+email|press\s+release)\b/i],purposeFunctions:["marketing","sales","customer_support"],purposePatterns:[/\b(?:marketing|campaign|outreach|email\s+assistant|support|customer|sales|lead|leads|communication|communications)\b/i]}]);var Br=["competitor_mention","disallowed_topic","off_brand_claim","restricted_advice"];var qr=[{id:"competitor_mention",re:/\b(acmecorp|northwind\s+rival|zenithsoft|globex\s+analytics)\b/gi},{id:"disallowed_topic",re:/\b(political\s+endorsement|religious\s+affiliation|layoff\s+rumou?rs?|pending\s+litigation)\b/gi},{id:"off_brand_claim",re:/\b(100%\s+(secure|guaranteed)|zero\s+risk|unhackable|never\s+fails)\b/gi},{id:"restricted_advice",re:/\b(investment\s+advice|medical\s+diagnosis|legal\s+advice|tax\s+advice)\b/gi}];var Ur={competitor_mention:"redact",off_brand_claim:"redact",disallowed_topic:"escalate",restricted_advice:"escalate"};function zr(e){return e.length===0?null:e.some(t=>Ur[t]==="escalate")?"escalate":"redact"}var Vr="[BRAND-TOPIC-REDACTED]";function Ae(e,t){if(e==null)return e;if(typeof e=="string"){let n=e;for(let{id:r,re:i}of qr){i.lastIndex=0;let a=n.replace(i,()=>Vr);a!==n&&(t.add(r),n=a)}return n}if(Array.isArray(e))return e.map(n=>Ae(n,t));if(typeof e=="object"){let n=e,r=Object.create(Object.getPrototypeOf(n));for(let i of Object.keys(n))r[i]=Ae(n[i],t);return r}return e}function Kr(e){let t=new Set,n=Ae(e,t);return{matched:Br.filter(r=>t.has(r)),redacted:n}}function Z(e,t){let{matched:n,redacted:r}=Kr(e),i=zr(n);return n.length===0?{verdict:"allow",redacted:r,matched:n,recommendedOutcome:i}:t.failMode==="closed"?{verdict:"block",redacted:r,matched:n,recommendedOutcome:i}:{verdict:"redact",redacted:r,matched:n,recommendedOutcome:i}}var Ee="[REDACTED]",L="\u2022",W=e=>/[A-Za-z0-9]/.test(e);function St(e,t,n,r){let i=Array.from(e),a=i.length,o=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:L,c=o+s>=a;return i.map((d,f)=>!c&&(f<o||f>=a-s)?d:W(d)?l:d).join("")}function Gr(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return St(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:L;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(o=>W(o)?a:o).join(""))+i}function Wr(e,t,n){let r=n.length>0?n:L,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let c=new RegExp(t,"g"),d;for(;(d=c.exec(e))!==null;){if(d[0].length===0){c.lastIndex++;continue}for(let f=d.index;f<d.index+d[0].length;f++)i[f]=!0}}catch{}let a=!1,o=!0;for(let c=0;c<e.length;c++)if(W(e[c])&&(a=!0,!i[c])){o=!1;break}let s=a&&o,l="";for(let c=0;c<e.length;c++){let d=e[c];!s&&i[c]||!W(d)?l+=d:l+=r}return l}function Et(e,t){let n=t.mode??"full";return n==="partial"?St(e,t.keepFirst??0,t.keepLast??0,t.maskChar??L):n==="email"?Gr(e,t.maskChar??L):n==="custom"?Wr(e,t.keepPattern,t.maskChar??L):t.replacement??Ee}function Hr(e,t){return typeof e=="string"?Et(e,t):t.replacement??Ee}function Ct(e){let t=[],n=e.replacement??Ee;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:a=>Et(a,r)})}return t}function Tt(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(a,o=>i(o))}return n}function J(e,t){return e==null?e:typeof e=="string"?Qr(e,t):typeof e=="object"?Yr(e,t):e}function Qr(e,t){if(typeof e!="string")return e;let n=Ct(t);return n.length===0?e:Tt(e,n)}function Yr(e,t){let n=new Map;for(let s of t.fields??[])typeof s=="string"&&s.length>0&&n.set(s,{field:s,mode:"full",replacement:t.replacement});for(let s of t.directives??[])typeof s.field=="string"&&s.field.length>0&&n.set(s.field,s);let r=Ct(t),i=n.size>0,a=r.length>0,o=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>o(l));if(typeof s=="object"){let l=s,c=Object.create(Object.getPrototypeOf(l));for(let d of Object.keys(l)){let f=i?n.get(d):void 0;if(f){c[d]=Hr(l[d],f);continue}c[d]=o(l[d])}return c}return typeof s=="string"&&a?Tt(s,r):s};return o(e)}import{readFile as Zr}from"node:fs/promises";import{homedir as Te}from"node:os";import{join as Ne,isAbsolute as Jr,resolve as Xr}from"node:path";import{createInterface as ei}from"node:readline";import{parseArgs as ti}from"node:util";var ni="https://api.visiqlabs.com",Nt="@visiq/openclaw-plugin",te="open";function Oe(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}var ri={enabled:!0,thresholds:{}},ne=[{key:"minEvents",env:"VISIQ_SEQUENCE_ANOMALY_MIN_EVENTS",cli:"sequence-anomaly-min-events",json:"min_events"},{key:"minClasses",env:"VISIQ_SEQUENCE_ANOMALY_MIN_CLASSES",cli:"sequence-anomaly-min-classes",json:"min_classes"},{key:"concentrationSigma",env:"VISIQ_SEQUENCE_ANOMALY_SIGMA",cli:"sequence-anomaly-sigma",json:"concentration_sigma"},{key:"dominanceRatio",env:"VISIQ_SEQUENCE_ANOMALY_DOMINANCE_RATIO",cli:"sequence-anomaly-dominance-ratio",json:"dominance_ratio"},{key:"dominanceShare",env:"VISIQ_SEQUENCE_ANOMALY_DOMINANCE_SHARE",cli:"sequence-anomaly-dominance-share",json:"dominance_share"},{key:"frictionRatio",env:"VISIQ_SEQUENCE_ANOMALY_FRICTION_RATIO",cli:"sequence-anomaly-friction-ratio",json:"friction_ratio"},{key:"minFrictionEvents",env:"VISIQ_SEQUENCE_ANOMALY_MIN_FRICTION_EVENTS",cli:"sequence-anomaly-min-friction-events",json:"min_friction_events"}],ii=["sequence-anomaly",...ne.map(e=>e.cli)];function ee(e){if(typeof e=="boolean")return e;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="0"||t==="off"||t==="false"||t==="no"||t==="disabled")return!1;if(t==="1"||t==="on"||t==="true"||t==="yes"||t==="enabled")return!0}function xe(e){if(typeof e=="number")return Number.isFinite(e)&&e>=0?e:void 0;if(typeof e!="string"||e.trim()==="")return;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function ai(...e){let t={};for(let n of e)for(let[r,i]of Object.entries(n??{}))typeof i=="number"&&(t[r]=i);return t}var oi='[VisIQ] OpenClaw plugin is installed but missing credentials. Provide them with one of (highest precedence first): (1) environment variables VISIQ_API_KEY=<key> VISIQ_AGENT_ID=<id> (set before `openclaw gateway run` / `openclaw start`) ; (2) a JSON file at the path in VISIQ_CONFIG_PATH ; (3) ~/.openclaw/openclaw.json -> plugins.entries["@visiq/openclaw-plugin"].config = { "apiKey": "<key>", "agentId": "<id>" } . Until credentials are provided the plugin is a NO-OP \u2014 tool calls run UNGOVERNED (fail-open default; set VISIQ_FAIL_MODE=closed to block instead).';function si(e){return e==="~"||e.startsWith("~/")?Ne(Te(),e.slice(1).replace(/^\//,"")):e}async function Ot(e){try{let t=Jr(e)?e:Xr(e),n=await Zr(t,"utf-8");return JSON.parse(n)}catch{return null}}function X(e,...t){for(let n of t){let r=e[n];if(typeof r=="string")return r}}function Ce(e){if(!e||typeof e!="object")return{};let t=e,n=X(t,"apiKey","api_key"),r=X(t,"agentId","agent_id"),i=X(t,"baseUrl","base_url"),a=Oe(X(t,"failMode","fail_mode")),o={};n&&(o.apiKey=n),r&&(o.agentId=r),i&&(o.baseUrl=i),a&&(o.failMode=a);let s=t.sequenceAnomaly??t.sequence_anomaly;if(s!=null){let l=ee(s);if(l!==void 0)o.sequenceAnomalyEnabled=l;else if(typeof s=="object"&&!Array.isArray(s)){let c=s,d=ee(c.enabled);d!==void 0&&(o.sequenceAnomalyEnabled=d);let f={};for(let g of ne){let m=xe(c[g.key]??c[g.json]);m!==void 0&&(f[g.key]=m)}Object.keys(f).length>0&&(o.sequenceAnomalyThresholds=f)}}return o}async function li(e){if(!e)return{};let t=si(e),n=await Ot(t);if(!n||typeof n!="object")return{};let r=n,i=r.plugins?.entries,a=i&&typeof i=="object"?i[Nt]:void 0;return a&&typeof a=="object"&&a.config?Ce(a.config):Ce(r)}async function xt(e){if(!e)return{};let t=await Ot(e);if(!t||typeof t!="object")return{};let a=t.plugins?.entries?.[Nt];return!a||typeof a!="object"?{}:Ce(a.config)}function ci(){return xt(Ne(Te(),".openclaw","openclaw.json"))}function di(){let e=process.env.OPENCLAW_CONFIG_PATH;return!e||e===Ne(Te(),".openclaw","openclaw.json")?Promise.resolve({}):xt(e)}async function ui(e){if(!process.stdout.isTTY)return{};let t=ei({input:process.stdin,output:process.stdout}),n=r=>new Promise(i=>t.question(r,a=>i(a)));try{let r={...e};if(!r.apiKey){let i=(await n("VisIQ API key: ")).trim();i&&(r.apiKey=i)}if(!r.agentId){let i=(await n("VisIQ agent ID: ")).trim();i&&(r.agentId=i)}if(!r.baseUrl){let i=(await n("VisIQ base URL (optional, press Enter for default): ")).trim();i&&(r.baseUrl=i)}return r}finally{t.close()}}function pi(){try{let e={"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"},"fail-mode":{type:"string"}};for(let c of ii)e[c]={type:"string"};let{values:t}=ti({args:process.argv.slice(2),options:e,strict:!1,allowPositionals:!0}),n={},r=t["api-key"],i=t["agent-id"],a=t["base-url"],o=Oe(t["fail-mode"]);typeof r=="string"&&r&&(n.apiKey=r),typeof i=="string"&&i&&(n.agentId=i),typeof a=="string"&&a&&(n.baseUrl=a),o&&(n.failMode=o);let s=ee(t["sequence-anomaly"]);s!==void 0&&(n.sequenceAnomalyEnabled=s);let l={};for(let c of ne){let d=xe(t[c.cli]);d!==void 0&&(l[c.key]=d)}return Object.keys(l).length>0&&(n.sequenceAnomalyThresholds=l),n}catch{return{}}}async function uo(){return(await Re()).config}async function Re(){let e=pi(),t={};process.env.VISIQ_API_KEY&&(t.apiKey=process.env.VISIQ_API_KEY),process.env.VISIQ_AGENT_ID&&(t.agentId=process.env.VISIQ_AGENT_ID),process.env.VISIQ_BASE_URL?t.baseUrl=process.env.VISIQ_BASE_URL:process.env.VISIQ_ENDPOINT&&(t.baseUrl=process.env.VISIQ_ENDPOINT);let n=Oe(process.env.VISIQ_FAIL_MODE);n&&(t.failMode=n);let r=ee(process.env.VISIQ_SEQUENCE_ANOMALY);r!==void 0&&(t.sequenceAnomalyEnabled=r);let i={};for(let f of ne){let g=xe(process.env[f.env]);g!==void 0&&(i[f.key]=g)}Object.keys(i).length>0&&(t.sequenceAnomalyThresholds=i);let a=await li(process.env.VISIQ_CONFIG_PATH),o=await ci(),s=await di(),l={...o,...s,...a,...t,...e,sequenceAnomalyThresholds:ai(o.sequenceAnomalyThresholds,s.sequenceAnomalyThresholds,a.sequenceAnomalyThresholds,t.sequenceAnomalyThresholds,e.sequenceAnomalyThresholds)};(!l.apiKey||!l.agentId)&&process.stdout.isTTY&&process.stdin.isTTY&&(l=await ui(l));let c=l.failMode??te;if(!l.apiKey||!l.agentId)return process.stderr.write(`${oi}
|
|
4
|
+
`),{config:null,failMode:c};let d={apiKey:l.apiKey,agentId:l.agentId,failMode:c,sequenceAnomaly:{enabled:l.sequenceAnomalyEnabled??ri.enabled,thresholds:l.sequenceAnomalyThresholds??{}}};return d.baseUrl=l.baseUrl||ni,{config:d,failMode:c}}var Me=null,Rt={ready:!1,config:null,failMode:te};function Le(){return Me||(Me=Re().catch(e=>(process.stderr.write(`[VisIQ] Config resolution failed (treating as unconfigured): ${e instanceof Error?e.message:String(e)}
|
|
5
|
+
`),{config:null,failMode:te})).then(e=>(Rt={ready:!0,config:e.config,failMode:e.failMode},e))),Me}function re(){return Le().then(e=>e.config)}function ie(){return Le()}function ae(){return Rt}function mo(){Le()}var ho="VisIQ agent-governance plugin for the OpenClaw CLI \u2014 action governance on every tool call, retrieval governance on its configured retrieval tools, and audit-trail reporting, wired into OpenClaw's own tool hooks.",Mt="0.1.11";import{z as u}from"zod";import*as C from"node:os";import{randomUUID as j}from"node:crypto";var Pe=1,Pt="X-VisIQ-SDK",$t="X-VisIQ-Dialect",Dt="unknown";function $e(e,t=1){return{[Pt]:e&&e.length>0?e:Dt,[$t]:String(t)}}var Ft="interceptor_source",fi=u.enum(["enforce","audit","off"]),mi=u.enum(["closed","open"]),jt=u.enum(["enforce","monitor","off"]),gi=u.object({apiKey:u.string().min(1,"apiKey is required"),agentId:u.string().min(1,"agentId is required"),endpoint:u.string().url().optional(),mode:fi.optional(),timeoutMs:u.number().int().positive().optional(),hitlTimeoutMs:u.number().int().positive().optional(),failBehavior:mi.optional()}),bo=u.object({agent_id:u.string().min(1),target_app:u.string().min(1),action:u.string().min(1),context:u.record(u.unknown()).optional(),session_id:u.string().min(1).max(255).optional(),action_schema_id:u.string().min(1).max(128).optional(),telemetry:u.record(u.unknown()).optional()}),hi=u.object({field:u.string().optional(),pattern:u.string().optional(),replacement:u.string().optional(),mode:u.enum(["full","partial","email"]).optional(),keepFirst:u.number().optional(),keepLast:u.number().optional(),maskChar:u.string().optional()}),_i=u.object({decision_id:u.string().min(1),decision:u.enum(["permit","deny","approval_required","mask"]),reason:u.string().optional(),rule_code:u.string().nullable().optional(),enforced:u.boolean().optional(),agent_mode:jt.optional(),arg_redaction_rules:u.array(hi).optional(),plane:u.string().nullable().optional(),operation:u.string().nullable().optional(),is_retrieval:u.boolean().optional(),metadata:u.record(u.unknown()).optional()}),yi=u.object({field:u.string().min(1),operator:u.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:u.union([u.string(),u.number(),u.array(u.string())])}),bi=u.object({id:u.string().min(1),rule_code:u.string().default(""),name:u.string().min(1),description:u.string().nullable().default(null),effect:u.enum(["allow","deny","hitl","mask"]),resource_type:u.string().min(1),rego_source:u.string().default(""),target_app:u.string().nullable().default(null),action_pattern:u.string().nullable().default(null),conditions:u.array(yi).default([]),priority:u.number().int().default(0)}),vi=u.object({version:u.string().min(1),agent_mode:jt.optional(),rules:u.array(bi),no_coverage:u.object({no_coverage_defaults:u.record(u.string()),autopilot_enabled:u.boolean(),enduser_hitl_enabled:u.boolean(),hitl_timeout_seconds:u.number()}).optional()}),wi=2e3,De=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return $e(this.config.sdkVersion,this.config.sdkDialect)}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return _i.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json",...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();return vi.parse(a)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let o=a,s=o.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof o.reason=="string"?o.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await Ai(wi)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Ai(e){return new Promise(t=>setTimeout(t,e))}function le(){let e={};try{let t=`${C.platform()} ${C.release()}`.trim();t&&(e.os=t)}catch{}try{let t=C.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=C.userInfo();t&&(e.username=t)}catch{}try{let t=Ii();t&&(e.ip=t)}catch{}return e}function Ii(){let e=C.networkInterfaces();for(let t of Object.keys(e))for(let n of e[t]??[])if((n.family==="IPv4"||n.family===4)&&!n.internal&&n.address)return n.address}function ki(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function oe(e,...t){for(let n of t){let r=ki(e[n]);if(r)return r}}function se(e){if(oe(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(oe(e,"user_id","userId"))return"user";if(oe(e,"agent_id","agentId"))return"agent";if(oe(e,"org_id","orgId","namespace"))return"org"}var Si=[{framework:"mem0",matches:e=>/^(mem0[_-])?(add|search|get|retrieve|update|delete)[_-]memor(y|ies)$/i.test(e),extract:(e,t)=>{let n=/^(?:mem0[_-])?([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"||n==="update"?r="write":r="read";let i=se(t);return{op:r,store:"mem0",framework:"mem0",...i?{scope:i}:{}}}},{framework:"letta",matches:e=>/^(core_memory_(append|replace)|archival_memory_(insert|search)|conversation_search)$/i.test(e),extract:e=>{let t=e.toLowerCase();return t.startsWith("core_memory_")?{op:"write",store:"letta-core",scope:"agent",framework:"letta"}:t==="archival_memory_insert"?{op:"write",store:"letta-archival",scope:"agent",framework:"letta"}:t==="archival_memory_search"?{op:"search",store:"letta-archival",scope:"agent",framework:"letta"}:{op:"search",store:"letta-conversation",scope:"session",framework:"letta"}}},{framework:"langgraph",matches:e=>/^(upsert_memory|save_recall_memory|search_recall_memories)$/i.test(e),extract:(e,t)=>{let n=/^search_/i.test(e),r=se(t);return{op:n?"search":"write",store:"langgraph-store",framework:"langgraph",...r?{scope:r}:{}}}},{framework:"zep",matches:e=>/^zep[_-](add|search|get|delete)[_-]memory$/i.test(e),extract:(e,t)=>{let n=/^zep[_-]([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"?r="write":r="read";let i=se(t)??"session";return{op:r,store:"zep",scope:i,framework:"zep"}}},{framework:"mcp-memory",matches:e=>/^(create_entities|create_relations|add_observations|delete_entities|delete_relations|delete_observations|search_nodes|open_nodes|read_graph)$/i.test(e),extract:e=>{let t=e.toLowerCase(),n;return t.startsWith("delete_")?n="delete":t==="search_nodes"?n="search":t==="open_nodes"||t==="read_graph"?n="read":n="write",{op:n,store:"mcp-memory",scope:"agent",framework:"mcp-memory"}}},{framework:"generic",matches:e=>/(^|[_\-.])(memory|memories|mem0|recall)([_\-.]|$)/i.test(e),extract:(e,t)=>{let n=e.toLowerCase(),r;/(^|[_\-.])(search|query|find|lookup|retrieve)([_\-.]|$)/.test(n)?r="search":/(^|[_\-.])(delete|remove|forget|clear|purge)([_\-.]|$)/.test(n)?r="delete":/(^|[_\-.])(add|save|write|store|upsert|put|set|update|insert|append|remember)([_\-.]|$)/.test(n)?r="write":r="read";let i=se(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function F(e,t){if(!e)return null;let n=t??{};for(let r of Si)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function Fe(e,t){let n=typeof t?.itemCount=="number"&&Number.isFinite(t.itemCount)&&t.itemCount>=0?Math.round(t.itemCount):void 0,r=typeof t?.bytes=="number"&&Number.isFinite(t.bytes)&&t.bytes>=0?Math.round(t.bytes):void 0,i=e.op==="read"||e.op==="search";return{op:e.op,store:e.store,...e.scope?{scope:e.scope}:{},...n!==void 0?{itemCount:n}:{},...r!==void 0?{bytes:r}:{},...i&&n!==void 0?{hit:n>0}:{}}}var Lt=new Map;function B(e){let t=(Lt.get(e)??0)+1;return Lt.set(e,t),t}function Bt(e){if(!e||typeof e!="object")return;let t={};for(let n of["tokensIn","tokensOut","cacheRead","cacheWrite"]){let r=e[n];typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[n]=Math.round(r))}return Object.keys(t).length>0?t:void 0}function je(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=Array.isArray(n.texts)?n.texts.filter(o=>typeof o=="string"&&o.length>0).join(`
|
|
6
|
+
|
|
7
|
+
`):"",a=Bt(n.usage);e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:B(r),ts:Date.now(),kind:n.final?"speech":"thought",visibility:"shown",provenance:"narration",...i?{content:{text:i}}:{},...a?{cost:a}:{},...n.model?{model:n.model}:{},...typeof n.durationMs=="number"&&Number.isFinite(n.durationMs)?{durationMs:Math.max(0,Math.round(n.durationMs))}:{},...t.framework?{framework:t.framework}:{}})}function Be(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:B(r),ts:Date.now(),kind:"spawn",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},spawn:{childAgentId:n.childAgentId,childName:n.childName,kind:n.kind,...n.model?{model:n.model}:{},...n.task?{prompt:n.task}:{}}})}function qe(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=n.memory?Fe(n.memory):void 0;e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:B(r),ts:Date.now(),kind:i?"memory":"action",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},tool:{name:n.toolName,...n.verb?{verb:n.verb}:{},...n.argSummary?{argSummary:n.argSummary}:{}},...i?{memory:i}:{}})}function Ue(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.round(c):void 0,a=i(n.bytes),o=i(n.itemCount),s=i(n.durationMs),l;n.memory&&(l=Fe(n.memory,{itemCount:o,bytes:a})),e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:B(r),ts:Date.now(),kind:"observation",visibility:"shown",provenance:"parsed",...s!==void 0?{durationMs:s}:{},...t.framework?{framework:t.framework}:{},tool:{name:n.toolName},result:{ok:n.ok,...a!==void 0?{bytes:a}:{},...o!==void 0?{itemCount:o}:{}},...l?{memory:l}:{}})}function ze(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:B(r),ts:Date.now(),kind:"intervention",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},tool:{name:n.toolName},governance:{decision:n.decision,enforced:n.enforced,...n.ruleCode?{ruleCode:n.ruleCode}:{},...n.ruleLabel?{ruleLabel:n.ruleLabel}:{},...n.harnessMessage?{harnessMessage:n.harnessMessage}:{}}})}function ce(e){try{let t=JSON.stringify(e);return typeof t=="string"?t.length:void 0}catch{return}}function de(e){try{return Array.isArray(e)?e.length:void 0}catch{return}}import{z as p}from"zod";import{createHash as Ei}from"crypto";import{createHash as Ji}from"crypto";var qt=new Map;function Ut(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function Ke(e){let t=Ei("sha256").update(e).digest("hex"),n=qt.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
|
|
8
|
+
`).map(l=>Ci(l)).filter(l=>l.trim().length>0),o=0;for(;o<a.length;){let l=a[o].trim();if(l.startsWith("package ")||l.startsWith("import ")){o++;continue}let c=l.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(c){let g=c[1],m=c[2].trim();r.set(g,U(m)),o++;continue}let d=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(d){let g=d[1],m=d[2].trim(),h=d[3].trim(),v=[];if(h&&h!=="}"){let A=h.endsWith("}")?h.slice(0,-1).trim():h;A&&v.push(A),h.endsWith("}")||(o++,o=ue(a,o,v))}else h==="}"||(o++,o=ue(a,o,v));let _=zt(v);i.push({variable:g,value:U(m),conditions:_,rawConditions:Ut(v)}),o++;continue}let f=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(f){let g=f[1],m=f[2].trim(),h=[];if(m&&m!=="}"){let _=m.endsWith("}")?m.slice(0,-1).trim():m;_&&h.push(_),m.endsWith("}")||(o++,o=ue(a,o,h))}else m==="}"||(o++,o=ue(a,o,h));let v=zt(h);i.push({variable:g,value:"true",conditions:v,rawConditions:Ut(h)}),o++;continue}o++}let s={defaults:r,rules:i};return qt.set(t,s),s}function Ci(e){let t=!1,n="";for(let r=0;r<e.length;r++){let i=e[r];if(t)i===n&&e[r-1]!=="\\"&&(t=!1);else if(i==='"'||i==="'")t=!0,n=i;else if(i==="#")return e.slice(0,r)}return e}function ue(e,t,n){let r=1,i=t;for(;i<e.length&&r>0;){let a=e[i].trim();for(let o of a)o==="{"&&r++,o==="}"&&r--;if(r>0)n.push(a),i++;else{let o=a.slice(0,a.lastIndexOf("}")).trim();return o&&n.push(o),i}}return i}function U(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ti(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function zt(e){let t=[];for(let n of e){let r=n.split(";").map(i=>i.trim()).filter(i=>i.length>0);for(let i of r){let a=Ni(i);a&&t.push(a)}}return t}function Ni(e){let t=!1,n=e.trim();if(n.startsWith("not ")&&(t=!0,n=n.slice(4).trim()),n==="true"||n==="false")return{type:"literal_bool",negated:t,field:"",value:n==="true"};if(n.includes("[_]"))return{type:"truthy",negated:!1,field:me,value:e.trim()};let r=n.match(/^count\(([^)]+)\)\s*(>=|<=|>|<)\s*(\d+)$/);if(r)return{type:"count_gt",negated:t,field:r[1].trim(),operator:r[2],value:parseInt(r[3],10)};let i=n.match(/^startswith\(([^,]+),\s*"([^"]*)"\)$/);if(i)return{type:"startswith",negated:t,field:i[1].trim(),value:i[2]};let a=n.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(a)return{type:"endswith",negated:t,field:a[1].trim(),value:a[2]};let o=n.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"contains",negated:t,field:o[1].trim(),value:o[2]};let s=n.match(/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:Ti(s[1])};let l=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s+in\s+((?:input|data)[^\s]*)$/);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:Zt(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let v=Ri(c[2]);if(v!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:v}}let d=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(d)return{type:"comparison",negated:t,field:d[1].trim(),operator:d[2],value:parseFloat(d[3])};let f=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s*==\s*((?:input|data)\S*)$/);if(f)return{type:"equality",negated:t,field:f[2].trim(),value:U(f[1].trim())};let g=n.match(/^([^\s=!]+)\s*==\s*(.+)$/);if(g)return{type:"equality",negated:t,field:g[1].trim(),value:U(g[2].trim())};let m=n.match(/^([^\s=!]+)\s*!=\s*(.+)$/);if(m)return{type:"inequality",negated:t,field:m[1].trim(),value:U(m[2].trim())};let h=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return h?{type:"truthy",negated:t,field:h[1].trim()}:{type:"truthy",negated:!1,field:me,value:e.trim()}}var me="__unrecognized_condition_forces_deny__";var Oi=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Qt(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==me&&Oi.test(r.field)&&t.push(r.field);return t}var xi=["input.normalized.","input.normalized["];function Yt(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions){let{field:i}=r;typeof i!="string"||i===me||xi.some(a=>i.startsWith(a))&&t.add(i)}return[...t].sort()}function Zt(e){let t=e.trim();return t==="true"?!0:t==="false"?!1:/^-?\d+(?:\.\d+)?$/.test(t)?parseFloat(t):t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Ri(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",i=!1,a="";for(let s=0;s<t.length;s++){let l=t[s];i?(r+=l,l===a&&t[s-1]!=="\\"&&(i=!1)):l==='"'||l==="'"?(r+=l,i=!0,a=l):l===","?(n.push(r.trim()),r=""):r+=l}if(i)return null;r.trim().length>0&&n.push(r.trim());let o=[];for(let s of n){let l=s.startsWith('"')&&s.endsWith('"')&&s.length>=2||s.startsWith("'")&&s.endsWith("'")&&s.length>=2,c=/^-?\d+(?:\.\d+)?$/.test(s);if(!l&&!c&&!(s==="true"||s==="false"))return null;o.push(Zt(s))}return o}var Mi=["tier1","tier2","tier3"];function Jt(e){return typeof e=="string"&&Mi.includes(e)}var Li=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Pi=["internal","customer_facing","experimental","third_party"],Xt=[...Li,...Pi];function $i(e){return typeof e=="string"&&Xt.includes(e)}function en(e){let t=new Set;for(let n of e)$i(n)&&t.add(n);return Xt.filter(n=>t.has(n))}var tn=["read_only","record_create","record_update","record_delete","data_export","data_share","data_subject_request","consent_change","funds_transfer","funds_disbursement","payroll_run","trade_execution","ledger_mutation","credit_decision","decision_adverse","account_restriction","account_closure","card_management","purchase_commitment","vendor_management","deal_management","pricing_change","contract_execution","legal_hold","regulatory_filing","personnel_action","employment_termination","compensation_change","campaign_send","content_publish","inventory_adjustment","order_fulfillment","account_servicing","credential_reset","access_grant","permission_change","credential_management","auth_policy_change","security_config_change","logging_change","alert_management","code_change","infrastructure_provision","deployment_change","communication_send","other"],Di=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],Fi=["production","staging","development","test"],ji=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function Bi(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return t.length>0?t:null}var Vt={github:"version_control",gitlab:"version_control",bitbucket:"version_control",stripe:"payments",adyen:"payments",braintree:"payments",paypal:"payments",square:"payments",salesforce:"crm",hubspot:"crm",pipedrive:"crm",slack:"communication",teams:"communication",twilio:"communication",sendgrid:"communication",mailgun:"communication",gmail:"communication",outlook:"communication",zoom:"communication",aws:"cloud_infra",gcp:"cloud_infra",azure:"cloud_infra",okta:"identity",auth0:"identity",entra:"identity",onelogin:"identity",duo:"identity",snowflake:"data_warehouse",bigquery:"data_warehouse",databricks:"data_warehouse",redshift:"data_warehouse",jira:"ticketing",zendesk:"ticketing",servicenow:"ticketing",freshdesk:"ticketing",linear:"ticketing",workday:"hr",bamboohr:"hr",gusto:"hr",netsuite:"finance_erp",quickbooks:"finance_erp",sap:"finance_erp",xero:"finance_erp",s3:"storage",gcs:"storage",dropbox:"storage",box:"storage",postgres:"database",postgresql:"database",mysql:"database",mongodb:"database",redis:"database"};function qi(e){let t=Bi(e);return t===null?"other":Vt[t]??Vt[t.replace(/_/g,"")]??"other"}function nn(e,t){let n={...e};if(t.targetApp!==void 0&&t.targetApp!==null){let r=n.context&&typeof n.context=="object"&&!Array.isArray(n.context)?{...n.context}:{};r.app_category===void 0&&(r.app_category=qi(t.targetApp)),n.context=r}return n}var Kt=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],Gt=["none","low","medium","high","critical"],Ui=["public","internal","confidential","restricted","credentials","api_key","private_key","password","secret","token","pan","full_pan","card_number","track_data","cvv","cvc","ssn","tax_id","national_id","passport","drivers_license","identity_document","document_number","kyc_document","bank_account","account_number","routing_number","iban","account_balance","customer_financial","credit_score","net_worth","income","financial_profile","employee_pii","payroll","compensation","material_nonpublic","pre_release_earnings","mnpi","attorney_client","legal_hold","privileged","special_category_gdpr","gdpr_special_category","biometric","ethnicity","political_opinion","health_special","religion"],zi={action_class:tn,"context/app_category":Di,"context/environment":Fi,"context/actor_function":ji,"read/classification":Ui,"read/data_categories":Kt,"read/data_sensitivity":Gt,"write/data_categories":Kt,"write/data_sensitivity":Gt};function rn(e){if(e===null||typeof e!="object")return[];let t=e,n=new Set,r=(i,a,o)=>{let s=Array.isArray(a)?a:[a];for(let l of s)typeof l!="string"||l.length===0||o.includes(l)||n.add(`${i}=${l}`)};for(let[i,a]of Object.entries(zi)){Object.prototype.hasOwnProperty.call(t,i)&&r(i,t[i],a);let o=i.indexOf("/");if(o===-1)continue;let s=t[i.slice(0,o)];if(s!==null&&typeof s=="object"&&!Array.isArray(s)){let l=i.slice(o+1),c=s;Object.prototype.hasOwnProperty.call(c,l)&&r(i,c[l],a)}}return[...n].sort()}var Wt=64,Vi=64,z={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function an(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var Ki=new Set(["deny","approval_required","escalate"]);function q(e,t){if(t.length===0)return[...e];let n=new Set(e);for(let i of t)n.add(i);let r=[...n].sort();return r.length>Wt?r.slice(0,Wt):r}function Ht(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function pe(e){return typeof e=="string"&&e.length>0?e:null}function on(e,t){let n=Ht(t.data_categories),r=pe(t.classification),i=Ht(t.taint),a=pe(t.action_class),o=a&&tn.includes(a)?a:null,s=pe(t.target_app),l=pe(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<Vi)c[o]=1;else{let d=Object.keys(c).sort(),f=d[d.length-1];f!==void 0&&o<f&&(delete c[f],c[o]=1)}return{retrieved_data_categories:q(e.retrieved_data_categories,n),retrieved_classifications:q(e.retrieved_classifications,r?[r]:[]),taint:q(e.taint,i),action_classes:q(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&Ki.has(l)?1:0),event_count:e.event_count+1,target_apps:q(e.target_apps,s?[s]:[])}}var sn={minEvents:12,minClasses:3,concentrationSigma:2,dominanceRatio:4,dominanceShare:.5,frictionRatio:.75,minFrictionEvents:6};function Gi(e){let t=null,n=0;for(let r of Object.keys(e).sort()){let i=Math.max(0,e[r]??0);i>n&&(n=i,t=r)}return{label:t,count:n}}function Ve(e){let t=e.length;if(t===0)return 0;let n=t>>1;return t%2===1?e[n]:(e[n-1]+e[n])/2}function fe(e){return Number.isFinite(e)?Math.round(e*1e3)/1e3:0}var Wi=.5;function Hi(e){let t=e.length;if(t===0)return 0;let n=[...e].sort((s,l)=>s-l),r=Ve(n),i=n[t-1],a=n.map(s=>Math.abs(s-r)).sort((s,l)=>s-l),o=Ve(a);return o>0?.6745*(i-r)/o:i===r?0:.6745*(i-r)/Wi}function Ge(e,t){let n={...sn,...t.config},r=e.action_counts??{},i=Math.max(0,e.event_count??0),a=Math.max(0,e.denied_count??0),o=Math.max(0,e.inhibited_count??0),s=Gi(r),l={};for(let y of Object.keys(r).sort()){let b=Math.max(0,r[y]??0);b>0&&(l[y]=b)}let c=Object.values(l),d=c.reduce((y,b)=>y+b,0),f=[...c].sort((y,b)=>y-b),g=Ve(f),m=Hi(c),h=g>0?s.count/g:0,v=d>0?s.count/d:0,_=i>0?(a+o)/i:0,A={action_class:null,repeats:s.count,event_count:i,denied_count:a,inhibited_count:o,class_count:c.length,class_counts:l,concentration_score:fe(m),dominance_ratio:fe(h),dominance_share:fe(v),friction_score:fe(_),signals:[]};if(i<n.minEvents)return{verdict:"allow",signals:[],evidence:A};let k=[],S=null;return c.length>=n.minClasses&&m>=n.concentrationSigma&&h>=n.dominanceRatio&&v>=n.dominanceShare&&(k.push("concentration"),S=s.label),_>=n.frictionRatio&&a+o>=n.minFrictionEvents&&k.push("friction"),k.length===0?{verdict:"allow",signals:[],evidence:A}:{verdict:t.failMode==="closed"?"deny":"hold",signals:[...k],evidence:{...A,action_class:S,signals:[...k]}}}var ln="generic",cn=[{id:"finance_accounting",name:"Finance & Accounting",icon:"Landmark",description:"Payments, invoicing, ledgers, transactions, refunds, financial reporting, SOX/AML/KYC controls."},{id:"hr",name:"Human Resources",icon:"Users",description:"Employee records, payroll, hiring/recruiting, benefits, personnel actions and PII of staff."},{id:"engineering",name:"Engineering",icon:"Code",description:"Source code, build/deploy pipelines, infrastructure changes, production systems and developer tooling."},{id:"it_security",name:"IT & Security",icon:"ShieldCheck",description:"Credentials, secrets, access control, configuration, threat/exfiltration prevention and security operations."},{id:"legal",name:"Legal",icon:"Scale",description:"Contracts, NDAs, litigation, counsel communications and legal-hold material."},{id:"privacy_compliance",name:"Privacy & Compliance",icon:"BadgeCheck",description:"GDPR/CCPA/HIPAA, consent, data-subject rights, special-category data and regulatory data handling."},{id:"sales",name:"Sales",icon:"TrendingUp",description:"CRM, leads, deals, quotes, pipeline and customer commercial relationships."},{id:"marketing",name:"Marketing",icon:"Megaphone",description:"Campaigns, content, brand, social channels and prospect/audience data."},{id:"operations",name:"Operations",icon:"Cog",description:"Business operations, logistics, internal workflows, vendor/ops tooling and process automation."},{id:"customer_support",name:"Customer Support",icon:"LifeBuoy",description:"Support tickets, customer communications, account servicing and help-desk actions."},{id:"procurement",name:"Procurement",icon:"ShoppingCart",description:"Purchasing, supplier management, purchase orders, sourcing and spend approvals."},{id:ln,name:"Generic",icon:"Shapes",description:"Catch-all for cross-cutting rules or rules that do not fit a specific function. Assign when no specific function clearly applies."}],Qi=cn.map(e=>e.id),ko=new Map(cn.map(e=>[e.id,e])),So=new Set(Qi);function dn(e){return Array.isArray(e)&&e.length>0?[...e]:[ln]}var Yi=/^[a-z][a-z0-9_]*$/;function un(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Yi.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Zi=["narrow","moderate","broad","unbounded","unknown"];function pn(e){return typeof e=="string"&&Zi.includes(e)}function fn(e){return e==="open"||e==="closed"?e:null}var Xi=["tool_name","function","name","action"];function ge(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)ge(r,`${t}[]`,n);return}if(e!==null&&typeof e=="object"){let r=Object.entries(e);if(r.length===0){t&&n.push([t,void 0]);return}for(let[i,a]of r)ge(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function ea(e){let t=[];return ge(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function ta(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function na(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function ra(e,t={}){if(t.discriminatorField===null)return null;let n=[];ge(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??Xi;for(let i of r){let a=null;for(let[o,s]of n){if(ta(o)!==i)continue;let l=na(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function mn(e,t={}){let n=Ji("sha256").update(ea(e).join(",")).digest("hex").slice(0,16),r=ra(e,t);return r!==null?`${n}:${r}`:n}var ia=["action","retrieval","delegation"];function aa(e){return typeof e=="string"&&ia.includes(e)}var oa=new Set(["rules"]);function gn(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!oa.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(aa):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{z as he}from"zod";var hn=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function sa(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:hn(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:hn(t.spawn.prompt)}),t}function la(e,t=process.env){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let n=t.ALLOW_TIMEOUT_MS;if(n!==void 0){let r=Number.parseInt(n,10);if(Number.isFinite(r)&&r>0)return r}return 5e3}var ca=1440*60*1e3,da="VISIQ_BUNDLE_GRACE_TTL_MS",ua="VISIQ_BUNDLE_CACHE_DISABLED",pa="VISIQ_CACHE_DIR",fa=he.object({graceTtlMs:he.number().int().nonnegative().optional(),disabled:he.boolean().optional(),cacheDir:he.string().min(1).optional()}).strict();function ma(e){return e==null?{}:fa.parse(e)}function ga(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[da];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return ca}function ha(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[ua]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var _n;function _a(){if(_n!==void 0)return _n;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function ya(e){return JSON.stringify(He(e))}function He(e){if(Array.isArray(e))return e.map(He);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=He(t[r]);return n}return e}function ba(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function va(e){if(e!==null&&typeof e=="object"&&typeof e.fetchedAt=="number"&&typeof e.contentHash=="string"&&"body"in e){let t=e;return{fetchedAt:t.fetchedAt,version:typeof t.version=="string"?t.version:null,contentHash:t.contentHash,body:t.body}}return null}async function kn(){if(!_a())return null;try{let[e,t,n,r]=await Promise.all([import("node:fs/promises"),import("node:path"),import("node:os"),import("node:crypto")]);return{fs:e,path:t,os:n,crypto:r}}catch{return null}}function Sn(e,t){return e.createHash("sha256").update(ya(t)).digest("hex")}function wa(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[pa]?.trim();if(r)return r;let i=process.env.XDG_CACHE_HOME?.trim();if(i)return e.path.join(i,"visiq");let a="";try{a=e.os.homedir()}catch{a=""}return a?e.path.join(a,".cache","visiq"):e.path.join(e.os.tmpdir(),"visiq-cache")}function Aa(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function En(e,t,n){return e.path.join(wa(e,n),"bundles",`${Aa(e,t)}.json`)}async function Ia(e,t,n,r={}){let i=await kn();if(i)try{let a=En(i,e,r),o=i.path.dirname(a);await i.fs.mkdir(o,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:Sn(i.crypto,t),body:t},l=`${a}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(l,JSON.stringify(s),{mode:384});try{await i.fs.rename(l,a)}catch(c){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),c}}catch{}}async function ka(e,t={}){let n=await kn();if(!n)return null;try{let r=await n.fs.readFile(En(n,e,t),"utf-8"),i=va(JSON.parse(r));return!i||Sn(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var V;async function Sa(){if(V!==void 0)return V;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;V=typeof t=="function"?t:null}catch{V=null}return V}function Ea(e){let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,i=r.rego_source;if(typeof i!="string"||i.length===0)continue;let a;try{a=Ke(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of Qt(a))t.push(`${o}: ${s}`)}return t}function Ca(e){let t={retrieval:new Set,action:new Set,delegation:new Set};for(let n of e){if(!n.enabled||n.bypassActive)continue;let r=n.regoSource;if(typeof r!="string"||r.length===0)continue;let i;try{i=Ke(r)}catch{continue}let a=Yt(i);if(a.length!==0)for(let o of n.appliesTo){let s=t[o];if(s)for(let l of a)s.add(`${n.id}: ${l}`)}}return{retrieval:[...t.retrieval].sort(),action:[...t.action].sort(),delegation:[...t.delegation].sort()}}function Ta(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var Na=5e3,Oa=600*1e3,xa=1e4,Ra=25,yn=1e3,Ma=5e3,La=100,bn=2e3,Pa=10,$a=512,Da=1800*1e3,Fa=.7,ja="monitor",Ba="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",vn="Rules bundle requires a newer SDK wire-contract dialect than this SDK supports \u2014 refusing the bundle and blocking all actions (fail-closed, G001). Upgrade the VisIQ SDK.",qa="open";function wn(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Ua(e,t){return wt({content:e,resourceMetadata:t})}var za=p.object({operations:p.array(p.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:p.string().min(1,"agentId is required"),sessionId:p.string().min(1).max(255).optional(),toolName:p.string().optional(),toolArgs:p.record(p.unknown()).optional(),targetResource:p.string().optional(),resourceType:p.string().optional(),resourceMetadata:p.record(p.unknown()).optional(),normalized:p.record(p.unknown()).optional(),query:p.string().optional(),contentPreview:p.string().optional(),telemetry:p.record(p.unknown()).optional(),context:p.record(p.unknown()).optional(),mcpServer:p.string().min(1).max(255).optional()}),Va=p.object({version:p.string().min(1),dialect_version:p.number().int().optional(),min_dialect:p.number().int().optional(),shutdown:p.boolean().optional(),agent_mode:p.enum(["enforce","monitor","off"]).optional(),cognition_capture:p.boolean().optional(),agent_mode_by_operation:p.object({action:p.string().optional(),retrieval:p.string().optional(),delegation:p.string().optional()}).partial().optional(),agent_attributes:p.object({trust_tier:p.string().nullable().optional(),categories:p.array(p.string()).optional(),business_function:p.string().nullable().optional(),business_functions:p.array(p.string()).nullable().optional(),blast_radius_tier:p.string().nullable().optional(),no_coverage:p.string().nullable().optional(),fail_mode:p.string().nullable().optional()}).optional(),rules:p.array(p.record(p.unknown())),action_schemas:p.array(p.object({id:p.string(),plane:p.string().optional(),field_mappings:p.array(p.record(p.unknown())).optional(),derived_fields:p.array(p.record(p.unknown())).optional(),action_class:p.string().nullable().optional(),action_class_confidence:p.number().optional()})).optional(),no_coverage:p.object({no_coverage_defaults:p.record(p.string()),autopilot_enabled:p.boolean(),enduser_hitl_enabled:p.boolean(),hitl_timeout_seconds:p.number().optional()}).optional()});function Ka(e){let t=e.trust_tier??null,n=[];Array.isArray(e.business_functions)&&e.business_functions.length>0?n=e.business_functions:typeof e.business_function=="string"&&e.business_function!==""&&(n=[e.business_function]);let r=dn(un(n));return{trust_tier:Jt(t)?t:null,categories:en(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&pn(e.blast_radius_tier)?e.blast_radius_tier:null}}function Ga(e){if(!e)return null;let t={};for(let n of["action","retrieval","delegation"]){let r=e[n];(r==="enforce"||r==="monitor"||r==="off")&&(t[n]=r)}return Object.keys(t).length>0?t:null}function Wa(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Qe=new Set,An=!1;async function In(e){let t=[];for(let n of Qe){if(n.pendingTelemetryCount()>0&&!n.hasBackend()){console.warn(`[UnifiedRuntime] exiting with ${n.pendingTelemetryCount()} un-sent decision(s) and no backend \u2014 telemetry lost.`);continue}let r=n.flush();e&&t.push(r)}t.length>0&&await Promise.allSettled(t)}function Ha(){if(!An&&!(typeof process>"u"||typeof process.once!="function")){An=!0,process.once("beforeExit",()=>{In(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await In(!0)}finally{process.kill(process.pid,e)}})()})}}var Cn=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;cacheIdentity;bundleCacheDisabled;bundleGraceTtlMs;bundleCacheDirOverride;diskFallbackServed=!1;agentMode=ja;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=wn(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??qa;governedFailMode=null;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastCloneCaptureSig=null;toolDescriptions=new Map;constructor(e,t,n,r,i,a,o,s){let l=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,c=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,d=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=l,this.resolvedEndpoint=c,this.resolvedAgentId=d,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=o,this.originalFetch=globalThis.fetch.bind(globalThis);let f=ma(s);if(this.bundleCacheDisabled=ha(f.disabled),this.bundleGraceTtlMs=ga(f.graceTtlMs),this.bundleCacheDirOverride=f.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:d,apiKey:l}:null,l&&c){let g={apiKey:l,agentId:d,endpoint:c,mode:"enforce",timeoutMs:la(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new De(g,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Na),We(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},xa),We(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Ma),We(this.cognitionTimer),Qe.add(this),Ha()}else this.client=null}async evaluate(e){let t=za.parse(e),n=Date.now();if(this.operatorShutdown){let m=this.denyAll(t,Ba);return this.applyAgentMode(m,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,vn,n);let m=this.denyAll(t,vn);return this.applyAgentMode(m,"enforce",t,n)}if(t.operations.every(m=>this.modeFor(m)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let m;if(this.agentModeConfirmed?m=this.agentMode:this.bundleApplyFailed?m="enforce":m="monitor",m==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let h=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(h,m,t,n)}let r=this.readSession(t.sessionId),i=await Sa();if(!i||!this.rawBundle){if(this.failMode==="open")return this.failOpen(t,"governance core (@visiq/core-wasm) unavailable",n);throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)")}let a=t.operations.includes("action")||t.operations.includes("delegation")?nn(t.normalized??{},{targetApp:t.targetResource??t.toolName??""}):t.normalized,o=this.buildActionSchemaEvent(t),s=t.mcpServer?{...a??{},mcp_server:t.mcpServer}:a,l={...t,normalized:s,session:r,at:Date.now(),action_schema_id:o.id,action_schema_raw:o.canonical},c={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},d;try{d=i(l,c)}catch(m){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${m instanceof Error?m.message:String(m)}`,n);throw m}let f=[...new Set(t.operations.flatMap(m=>this.normalizedRefs[m]??[]))].sort();f.length>0&&Ta(t.normalized)&&(d.normalizedColdStart=f,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${f.length} loaded rule condition(s) on this event's operation(s) read input.normalized.* \u2014 those conditions resolve to undefined here, so a deny carrying one does not fire. (Builtin-derived paths such as context/app_category ARE still populated in-core, so this is a dependency report, not a proof that every listed condition was the decider.) Cold start / no action-schema mapping yet. Affected: ${f.slice(0,5).join("; ")}${f.length>5?`; +${f.length-5} more`:""}`)));let g=rn(t.normalized);return g.length>0&&(d.normalizedDrift=g,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${g.length} value(s) outside the canonical vocabulary \u2014 a builder-authored rule can only select in-vocab values, so these cannot match one, so a rule keyed on the canonical value does not fire here. Check the harness classifier's casing/spelling. Affected: ${g.slice(0,5).join("; ")}${g.length>5?`; +${g.length-5} more`:""}`))),this.foldSession(t,d.enforced?d.decision:"permit"),d.enforced&&d.action.decision==="approval_required"&&await this.registerHitl(t,d),this.bufferTelemetry(t,d,Date.now()-n,d.enforced),d}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return z;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Da?(this.sessions.delete(e),z):t.state:z}foldActionClass(e){let t=e.normalized?.action_class;if(typeof t=="string"&&t.length>0)return t;let n=this.rawBundle?.action_schemas;if(!Array.isArray(n))return;let{id:r}=this.buildActionSchemaEvent(e),i=n.find(s=>s?.id===r);if(!i)return;let a=i.action_class,o=typeof i.action_class_confidence=="number"?i.action_class_confidence:0;if(typeof a=="string"&&a.length>0&&o>=Fa)return a}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),o=e.operations.includes("action")||e.operations.includes("delegation"),s=on(r===z?an():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?Ua(e.contentPreview,i):void 0,action_class:o?this.foldActionClass(e):void 0,target_app:o?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>$a){let l=this.sessions.keys().next().value;l!==void 0&&this.sessions.delete(l)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let o={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,o,i,!0),o}let a={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,a,i,!1),a}setFailMode(e){this.failMode=e}getFailMode(){return this.failMode}getGovernedFailMode(){return this.governedFailMode}failOpen(e,t,n){let r=`fail-open: ${t} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`;console.error(`[VisIQ] FAIL-OPEN: ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`);let i=e.operations.includes("action")||e.operations.includes("delegation"),a=e.operations.includes("retrieval"),o={decision:"permit",allowed:!0,reason:r,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:i?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:a?{action:"allow"}:{action:null},failOpen:!0};return this.bufferTelemetry(e,o,Date.now()-n,!1,!0),o}reportFailOpen(e,t){try{let n={operations:["action"],agentId:this.resolvedAgentId,...t?.toolName?{toolName:t.toolName}:{},...t?.sessionId?{sessionId:t.sessionId}:{}},r={decision:"permit",allowed:!0,reason:`fail-open: ${e} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:{decision:"permit",allowed:!0},retrieval:{action:null},failOpen:!0};this.bufferTelemetry(n,r,0,!1,!0)}catch{}}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},action_schema_id:this.buildActionSchemaEvent(e).id,...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=Va.parse(e);this.bundleApplyFailed=!1;let n=this.sdkDialect??1;if(t.min_dialect!==void 0&&t.min_dialect>n){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle requires dialect ${t.min_dialect} but this SDK speaks ${n} \u2014 refusing the bundle and failing closed (deny-all, G001). Upgrade the VisIQ SDK.`);return}let r=Ea(t.rules);if(r.length>0){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle contains rego_source using a builtin the engine cannot evaluate (would silently never match \u2192 fail open): ${r.join("; ")}. Refusing the bundle and failing closed (G001). Recompile the rule without case-folding wrappers like upper()/lower().`);return}this.dialectRefused=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(i=>gn(i)).filter(i=>i!==null),this.agentAttributes=t.agent_attributes?Ka(t.agent_attributes):null,this.agentNoCoverage=fn(t.agent_attributes?.no_coverage),this.governedFailMode=wn(t.agent_attributes?.fail_mode)??null,this.bundleVersion=t.version,this.bundleLoaded=!0,this.noCoverage=t.no_coverage?{no_coverage_defaults:t.no_coverage.no_coverage_defaults,autopilot_enabled:t.no_coverage.autopilot_enabled,enduser_hitl_enabled:t.no_coverage.enduser_hitl_enabled}:null,t.agent_mode!==void 0&&(this.agentMode=t.agent_mode,this.agentModeConfirmed=!0),this.agentModeByOperation=Ga(t.agent_mode_by_operation),process.env.VISIQ_COGNITION_CAPTURE==="1"?this.cognitionEnabled=!0:typeof t.cognition_capture=="boolean"&&(this.cognitionEnabled=t.cognition_capture),this.operatorShutdown=t.shutdown===!0,this.normalizedRefs=Ca(this.rules),this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1,this.lastNormalizedWarnRearmMs=Date.now(),this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json",...$e(this.sdkVersion,this.sdkDialect)};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304){let o=Date.now();o-this.lastNormalizedWarnRearmMs>=Oa&&(this.lastNormalizedWarnRearmMs=o,this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1);return}if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let a=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&a?this.bundleEtag=r:a||(this.bundleEtag=null),a&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await ka(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(ba(e,this.bundleGraceTtlMs,t)){try{this.applyBundle(e.body)}catch{return}if(this.bundleLoaded&&!this.dialectRefused&&!this.diskFallbackServed){this.diskFallbackServed=!0;let n=Math.max(0,Math.round((t-e.fetchedAt)/1e3)),r=Math.round(this.bundleGraceTtlMs/1e3);console.warn(`[UnifiedRuntime] serving cached rules bundle (age ${n}s) \u2014 control plane unreachable on cold start; will keep retrying and fail closed once the cache exceeds the ${r}s grace window.`)}}}async persistBundleToDisk(e){this.bundleCacheDisabled||!this.cacheIdentity||await Ia(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}isBundleLoaded(){return this.bundleLoaded}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e,t){this.registerEnvironment({...le(),...e?{agent_type:e}:{},...t?.model?{model:t.model}:{},...t?.systemPrompt?{systemPrompt:t.systemPrompt}:{},...t?.toolSchemas&&t.toolSchemas.length>0?{toolSchemas:t.toolSchemas}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));for(let n of e)n.description&&this.toolDescriptions.set(n.name,n.description);t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}captureCloneMetadata(e){if(!this.client||!this.resolvedAgentId||!(e.model||e.systemPrompt||(e.toolSchemas?.length??0)>0))return;let t=JSON.stringify({m:e.model??"",s:e.systemPrompt??"",t:e.toolSchemas??[]});t!==this.lastCloneCaptureSig&&(this.lastCloneCaptureSig=t,this.client.registerEnvironment({...le(),...e.agentType?{agent_type:e.agentType}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{toolSchemas:e.toolSchemas}:{}}))}buildActionSchemaEvent(e){let t=e.toolName?this.toolDescriptions.get(e.toolName):void 0,n={agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{},...e.toolArgs?{tool_args:e.toolArgs}:{},...t?{tool_description:t}:{}},r=mn(n),i={...n};return e.toolArgs&&(i.tool_args=pt(e.toolArgs)),{canonical:n,id:r,rawEventForWire:i}}bufferTelemetry(e,t,n,r,i=!1){let a=this.buildActionSchemaEvent(e);this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:r?Wa(t.decision):"permit",reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:a.rawEventForWire,action_schema_id:a.id,...this.harnessKind||e.context||i||t.normalizedColdStart||t.normalizedDrift?{context:{...this.harnessKind?{[Ft]:this.harnessKind}:{},...e.context??{},...i?{fail_open:!0}:{},...t.normalizedColdStart?{normalized_cold_start:!0,normalized_inert_conditions:t.normalizedColdStart.length}:{},...t.normalizedDrift?{normalized_drift:!0,normalized_drift_values:t.normalizedDrift.length,normalized_drift_fields:t.normalizedDrift.slice(0,Pa)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Ra&&this.flushTelemetry()}pendingTelemetryCount(){return this.telemetryBuffer.length}hasBackend(){return this.client!==null}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0);try{await this.client.sendTelemetry(e)}catch(t){console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",t)}}enforceTelemetryCap(){let e=this.telemetryBuffer.length-yn;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${yn})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(sa(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=La&&this.flushCognition())}async flushCognition(){if(this.cognitionBuffer.length===0||!this.client)return;let e=this.cognitionBuffer.splice(0);try{await this.client.sendCognition(void 0,e)}catch(t){console.error("[UnifiedRuntime] cognition flush failed (non-fatal):",t)}}enforceCognitionCap(){let e=this.cognitionBuffer.length-bn;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${bn})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),Qe.delete(this)}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.cognitionTimer&&(clearInterval(this.cognitionTimer),this.cognitionTimer=null),this.flushTelemetry(),this.flushCognition()}};function We(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function K(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Tn(e,t){if(e!=="sessions_spawn")return null;let n=K(t.agentId);return n?{childAgentId:n,childName:K(t.taskName)??K(t.label)??n,kind:"subagent",task:K(t.task),model:K(t.model),source:"structural"}:null}function Nn(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}var R=null;function E(e){let t=`${e.apiKey}::${e.agentId}::${e.baseUrl??""}`;if(R&&R.key===t)return R.runtimes;let n=new Cn(e.apiKey,e.baseUrl,e.agentId,"cli_harness",void 0,Mt,Pe);return n.setFailMode(e.failMode),n.registerHostEnvironment(),R={key:t,runtimes:{unified:n}},R.runtimes}async function jo(){if(R)try{await R.runtimes.unified.flush()}catch{}}async function Bo(e){try{let t=await re();if(!t)return;let{unified:n}=E(t);await n.awaitBundleReady(e)}catch{}}function On(){return R?.runtimes.unified.getAgentMode()}function I(e){try{process.stderr.write(`[VisIQ] FAIL-OPEN (${e.stage}): ${e.detail} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.
|
|
9
|
+
`)}catch{}if(e.config)try{E(e.config).unified.reportFailOpen(`${e.stage}: ${e.detail}`,{...e.toolName?{toolName:e.toolName}:{},...e.sessionId?{sessionId:e.sessionId}:{}})}catch{}}function G(e,t,n){try{let r=n instanceof Error?n.message:String(n);process.stderr.write(`[VisIQ] TRACE-DEGRADED (${e}) for tool "${t}": ${r} \u2014 the governance decision was still made and enforced; only the execution-trace beat was lost.
|
|
10
|
+
`)}catch{}}function O(e,t){return e?.sessionKey??t?.sessionKey??t?.sessionId??"default"}var Ye=class{entries=new Map;set(t,n){this.entries.set(t,n)}get(t){return this.entries.get(t)}delete(t){this.entries.delete(t)}clear(){this.entries.clear()}size(){return this.entries.size}},Ze=new Map;function P(e){let t=Ze.get(e);return t||(t=new Ye,Ze.set(e,t)),t}function xn(e){Ze.delete(e)}var Rn=new Set(["web_search","x_search","web_fetch","tool_search","tool_describe","get_account","get_transactions","get_devices","check_watchlist","search_knowledge"]);function Mn(e){return Rn.has(ke(e))}function Go(){return Rn}var Je="@visiq/openclaw-plugin";function Ln(e){let t=[],n=[],r;for(let a of e){let{field:o,pattern:s,replacement:l}=a;o&&t.push(o),s&&n.push(s),l&&r===void 0&&(r=l)}let i={};return t.length>0&&(i.fields=t),n.length>0&&(i.patterns=n),r!==void 0&&(i.replacement=r),i}async function ls(e,t){let{config:n,failMode:r}=await ie();if(!n){if(r==="closed")return{block:!0,blockReason:"[VisIQ] Plugin is loaded but NOT configured \u2014 VisIQ cannot govern this tool call. Set VISIQ_API_KEY + VISIQ_AGENT_ID (and optionally VISIQ_ENDPOINT), or the plugin config, then retry. Blocked because VISIQ_FAIL_MODE=closed."};I({stage:"unconfigured",detail:"no VisIQ credentials resolved (need VISIQ_API_KEY + VISIQ_AGENT_ID)",toolName:e.toolName,sessionId:O(e,t)});return}let i=E(n),a=n.agentId??t.agentId,o=O(e,t),s=t.toolCallId??e.toolCallId,c=Mn(e.toolName)?["retrieval","action"]:["action"],d=Qa(e.params),f=Tn(e.toolName,e.params??{}),g;f&&a&&(Be(i.unified,{agentId:a,sessionId:o,framework:"openclaw"},f),c.push("delegation"),g=Nn(f,a));let m=a?{agentId:a,sessionId:o,framework:"openclaw"}:null,h=F(e.toolName,e.params??{});if(m)try{qe(i.unified,m,{toolName:e.toolName,...h?{memory:h}:{}})}catch(y){G("step-beat",e.toolName,y)}let v=(y,b,M,T)=>{if(m)try{ze(i.unified,m,{toolName:e.toolName,decision:y,...b?{ruleCode:b}:{},...M?{ruleLabel:M}:{},enforced:!0,...T?{harnessMessage:T}:{}})}catch(N){G("intervention-beat",e.toolName,N)}},_;try{if(await i.unified.awaitBundleReady(),!i.unified.isBundleLoaded()&&n.failMode!=="closed"){I({stage:"no-bundle",detail:"no rule bundle available after warm-up",toolName:e.toolName,sessionId:o,config:n});return}_=await i.unified.evaluate({operations:c,agentId:a,sessionId:o,toolName:e.toolName,toolArgs:e.params??{},resourceType:"tool_result",resourceMetadata:{toolName:e.toolName,runId:e.runId??t.runId},...d!==void 0?{query:d}:{},...g?{context:g}:{}})}catch(y){let b=y instanceof Error?y.message:String(y);if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ] Evaluation error \u2014 blocked (VISIQ_FAIL_MODE=closed): ${b}`};I({stage:"eval-error",detail:b,toolName:e.toolName,sessionId:o,config:n});return}if(!_.enforced)return;let{action:A}=_;if(A.decision==="approval_required")return v("approval_required",_.ruleCode??void 0,_.reason),{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:_.reason,severity:"critical",allowedDecisions:["allow-once","allow-always","deny"],pluginId:Je}};if(!A.allowed){let b=`[VisIQ ${_.ruleCode??"DENY"}] ${_.reason}`;return v("deny",_.ruleCode??void 0,_.reason,b),{block:!0,blockReason:b}}let k;if(A.decision==="mask"&&A.argRedactionRules&&A.argRedactionRules.length>0)try{k=J(e.params??{},Ln(A.argRedactionRules)),v("mask",_.ruleCode??void 0,_.reason)}catch(y){let b=y instanceof Error?y.message:String(y);if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ] Argument masking failed \u2014 blocked (VISIQ_FAIL_MODE=closed): ${b}`};I({stage:"mask-error",detail:`argument masking failed \u2014 running with UNMASKED params: ${b}`,toolName:e.toolName,sessionId:o,config:n}),k=void 0}if(c.includes("retrieval"))switch(_.retrieval.action){case"allow":case null:break;case"deny":{let y=`[VisIQ retrieval governance] ${_.reason}`;return v("deny",_.ruleCode??void 0,_.reason,y),{block:!0,blockReason:y}}case"redact":{if(!s){if(n.failMode==="closed")return{block:!0,blockReason:"[VisIQ retrieval governance] Redact decision but no toolCallId \u2014 blocked (VISIQ_FAIL_MODE=closed)"};I({stage:"redact-no-toolcallid",detail:"redact decision could not be applied (no toolCallId to correlate the result)",toolName:e.toolName,sessionId:o,config:n});break}let y=_.retrieval.redactionRules??[];y.length>0&&P(o).set(s,Ln(y));break}case"escalate":return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:_.reason,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:Je}};default:{let y=_.retrieval.action;if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ retrieval governance] Unknown action "${String(y)}" \u2014 blocked (VISIQ_FAIL_MODE=closed)`};I({stage:"unknown-retrieval-verb",detail:`unknown retrieval action "${String(y)}" (harness/backend version skew)`,toolName:e.toolName,sessionId:o,config:n});break}}if(Se(e.toolName)){let y=n.failMode==="closed"?"closed":"open",b=k??e.params??{},M=!1,T=Q(b,{failMode:y});if(T.verdict==="block")return{block:!0,blockReason:`[VisIQ OUTPUT-BLOCK] outbound content carried a live secret (${T.detectors.join(",")}) \u2014 blocked (VISIQ_FAIL_MODE=closed)`};T.verdict==="redact"&&(b=T.redacted,M=!0,I({stage:"outbound-secret-redacted",detail:`outbound secret screen redacted ${T.detectors.length} detector(s): ${T.detectors.join(",")}`,toolName:e.toolName,sessionId:o,config:n}));let N=Z(b,{failMode:y});if(N.verdict==="block")return{block:!0,blockReason:`[VisIQ OUTPUT-BLOCK] outbound content matched a brand/topic rule (${N.matched.join(",")}) \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(N.verdict==="redact"&&(b=N.redacted,M=!0,I({stage:"outbound-brand-topic-redacted",detail:`outbound brand/topic screen redacted ${N.matched.length} rule(s): ${N.matched.join(",")} (recommended: ${N.recommendedOutcome??"none"})`,toolName:e.toolName,sessionId:o,config:n})),M)return{params:b}}if((n.sequenceAnomaly?.enabled??!0)&&typeof i.unified.getSessionState=="function"&&o){let y=i.unified.getSessionState(o),b=Ge(y,{failMode:n.failMode==="closed"?"closed":"open",config:n.sequenceAnomaly?.thresholds});if(b.verdict==="deny")return{block:!0,blockReason:`[VisIQ ANOMALY] session-sequence anomaly (${b.signals.join(",")}) over ${b.evidence.event_count} events \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(b.verdict==="hold")return I({stage:"sequence-anomaly-hold",detail:`session-sequence anomaly held for approval (${b.signals.join(",")}) over ${b.evidence.event_count} events`,toolName:e.toolName,sessionId:o,config:n}),{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:`A behavioral sequence anomaly was detected in this session (${b.signals.join(",")}). Approve to proceed, or deny to stop the run.`,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:Je}}}if(k)return{params:k}}function Qa(e){if(e)for(let t of["query","q","url","prompt"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}}function hs(e,t){let{ready:n,config:r}=ae();if(!n||!r)return;let i=O(e,t),a=e.toolName??t.toolName,o=r.agentId??t.agentId;if(a&&o)try{let f=e.message?.content,g=F(a);Ue(E(r).unified,{agentId:o,sessionId:i,framework:"openclaw"},{toolName:a,ok:!0,...ce(f)!==void 0?{bytes:ce(f)}:{},...de(f)!==void 0?{itemCount:de(f)}:{},...g?{memory:g}:{}})}catch(f){G("observation-beat",a,f)}let s=e.toolCallId??t.toolCallId;if(!s)return;let l=P(i),c=l.get(s);if(!c)return;let d={...e.message};return d.content!==void 0&&(d.content=J(d.content,c)),l.delete(s),{message:d}}function $(e,t){return e?.sessionKey||e?.sessionId||t?.sessionKey||t?.sessionId||void 0}var Xe=new Map;function Pn(e,t){e&&Xe.set(e,t)}function $n(e){return e?Xe.get(e):void 0}function Dn(e){e&&Xe.delete(e)}function Ss(e,t){let{ready:n,config:r,failMode:i}=ae();if(n&&!r)return;let a=O(e,t),o=P(a);if(o.size()>0){if(o.clear(),i==="closed")return{block:!0};I({stage:"unconsumed-redaction",detail:"queued redaction was never applied to a tool result before message write",sessionId:a,config:r})}if(r&&On()==="enforce"){let s=i==="closed"?"closed":"open",l=Q(e.message,{failMode:s});if(l.verdict==="block")return{block:!0};let c=e.message,d=!1;l.verdict==="redact"&&(c=l.redacted,d=!0);let f=!1,g=$n($(e,t));if(g){let v=It(c,g,{failMode:s});if(v.verdict==="block")return{block:!0};v.verdict==="redact"&&(c=v.redacted,f=!0,I({stage:"final-message-prompt-leak-redacted",detail:`final assistant message leaked the system prompt \u2014 masked ${v.matchedSpans.length} verbatim span(s)`,sessionId:a,config:r}))}let m=!1,h=Z(c,{failMode:s});if(h.verdict==="block")return{block:!0};if(h.verdict==="redact"&&(c=h.redacted,m=!0,I({stage:"final-message-brand-topic-redacted",detail:`final assistant message matched a brand/topic rule \u2014 redacted ${h.matched.length} rule(s): ${h.matched.join(",")} (recommended: ${h.recommendedOutcome??"none"})`,sessionId:a,config:r})),d&&I({stage:"final-message-secret-redacted",detail:`final assistant message carried a live secret \u2014 redacted ${l.detectors.length} detector(s): ${l.detectors.join(",")}`,sessionId:a,config:r}),d||f||m)return{message:c}}}async function Os(e,t){try{let{config:n}=await ie();if(!n)return;typeof e.systemPrompt=="string"&&e.systemPrompt.trim().length>0&&Pn($(e,t),e.systemPrompt);let{unified:r}=E(n);r.captureCloneMetadata({model:typeof e.model=="string"&&e.model.trim().length>0?e.model:void 0,systemPrompt:typeof e.systemPrompt=="string"&&e.systemPrompt.trim().length>0?e.systemPrompt:void 0,toolSchemas:Array.isArray(e.tools)&&e.tools.length>0?e.tools:void 0,agentType:"openclaw"})}catch{}}async function Ps(e,t){try{let n=await re();if(!n)return;let r=n.agentId??t.agentId;if(!r)return;let i=e.sessionId??t.sessionId??t.sessionKey,{unified:a}=E(n);await a.awaitBundleReady(),je(a,{agentId:r,...i?{sessionId:i}:{},framework:"openclaw"},{texts:e.assistantTexts,usage:e.usage?{tokensIn:e.usage.input,tokensOut:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite}:void 0,model:e.model||e.resolvedRef,final:!0})}catch{}}function js(e,t){xn(O(e,t)),Dn($(e,t))}export{ke as a,te as b,Oe as c,uo as d,Re as e,mo as f,ho as g,Mt as h,jo as i,Bo as j,I as k,Ye as l,P as m,xn as n,Mn as o,Go as p,ls as q,hs as r,Ss as s,Os as t,Ps as u,js as v};
|
package/dist/index.d.ts
CHANGED
|
@@ -220,7 +220,7 @@ export interface RedactionDirective {
|
|
|
220
220
|
keepPattern?: string;
|
|
221
221
|
}
|
|
222
222
|
/**
|
|
223
|
-
* Redaction specification produced by
|
|
223
|
+
* Redaction specification produced by retrieval-governance evaluation. A non-null spec
|
|
224
224
|
* indicates the content must be masked before being persisted or returned to
|
|
225
225
|
* an agent.
|
|
226
226
|
*/
|
|
@@ -255,7 +255,7 @@ export interface RedactionSpec {
|
|
|
255
255
|
* A long-running OpenClaw daemon relies on the UnifiedRuntime's periodic (10s,
|
|
256
256
|
* unref'd) timer to flush telemetry — but a SHORT-LIVED driver (the
|
|
257
257
|
* visiq-openclaw-driver oneshot, which runs ~1s then exits) would otherwise
|
|
258
|
-
* exit before the registration handshake lands and before any
|
|
258
|
+
* exit before the registration handshake lands and before any governance telemetry
|
|
259
259
|
* is sent, so the fleet harness-liveness probe never sees the
|
|
260
260
|
* `allow_agents` row OR the `allow_audit_log` heartbeat. Call this once after a
|
|
261
261
|
* run, before the process exits, to guarantee both land.
|
|
@@ -300,7 +300,7 @@ export declare function getLedger(sessionId: string): RedactionLedger;
|
|
|
300
300
|
export declare function clearLedger(sessionId: string): void;
|
|
301
301
|
/**
|
|
302
302
|
* True if the tool participates in retrieval semantics and therefore must be
|
|
303
|
-
* routed through
|
|
303
|
+
* routed through action + retrieval governance evaluation in `before_tool_call`.
|
|
304
304
|
*
|
|
305
305
|
* Non-retrieval tools bypass the evaluation entirely so the plugin does not
|
|
306
306
|
* add latency to write tools (whose authorization is handled elsewhere).
|
|
@@ -312,10 +312,11 @@ export declare function isRetrievalTool(toolName: string): boolean;
|
|
|
312
312
|
*/
|
|
313
313
|
export declare function getRetrievalToolNames(): ReadonlySet<string>;
|
|
314
314
|
/**
|
|
315
|
-
* True when the tool performs a governed side effect and must be gated by
|
|
315
|
+
* True when the tool performs a governed side effect and must be gated by
|
|
316
|
+
* action governance.
|
|
316
317
|
*
|
|
317
318
|
* Decision rule (fail-closed, G001):
|
|
318
|
-
* - Retrieval tools are NEVER actions (
|
|
319
|
+
* - Retrieval tools are NEVER actions (retrieval governance gates those).
|
|
319
320
|
* - OpenClaw framework-internal tools are NEVER actions (host plumbing).
|
|
320
321
|
* - Everything else IS an action — both the explicitly-listed write tools and
|
|
321
322
|
* any unknown/unclassified agent tool. Gating unknown writes by default is
|
|
@@ -344,6 +345,8 @@ export interface OpenclawHook {
|
|
|
344
345
|
export interface OpenclawPlugin {
|
|
345
346
|
id: string;
|
|
346
347
|
name: string;
|
|
348
|
+
/** Same sentence as package.json / openclaw.plugin.json — see plugin-meta.ts. */
|
|
349
|
+
description: string;
|
|
347
350
|
version: string;
|
|
348
351
|
hooks: OpenclawHook[];
|
|
349
352
|
}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as e,b as _,c as d,d as f,e as k,g as i,h as s,i as h,j as N,k as I,l as T,m as O,n as R,o as t,p as x,q as l,r as a,s as u,t as p,u as c,v as m}from"./chunk-E7RQSJFB.js";var g=new Set(["place_hold","block_card","wire_transfer","create_case","send_notification","bank_account_lookup_tool","exec","write_file","http_post","http_put","http_delete"]),y=new Set(["sessions_list","sessions_history","sessions_send","sessions_get","sessions_create","sessions_delete","memory_search","memory_read","memory_write"]),A=["sessions_","memory_"];function L(o){let r=e(o);return y.has(r)?!0:A.some(w=>r.startsWith(w))}function P(o){return!(t(o)||L(o))}function b(o){return g.has(e(o))}function v(){return g}var n="@visiq/openclaw-plugin";function E(){return{id:n,name:"VisIQ OpenClaw Plugin",description:i,version:s,hooks:[{pluginId:n,hookName:"before_tool_call",handler:l,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"tool_result_persist",handler:a,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"before_message_write",handler:u,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"llm_input",handler:p,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"llm_output",handler:c,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"session_end",handler:m,source:"visiq-openclaw-plugin"}]}}var V=E;export{_ as DEFAULT_FAIL_MODE,T as RedactionLedger,N as awaitRuntimesReady,e as bareToolName,R as clearLedger,E as createPlugin,V as default,v as getActionToolNames,O as getLedger,x as getRetrievalToolNames,P as isActionTool,b as isKnownActionTool,t as isRetrievalTool,f as loadConfig,k as loadPluginState,d as normalizeFailMode,I as reportFailOpen,h as shutdownRuntimes};
|
package/dist/openclaw-entry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{f as w,
|
|
2
|
-
`)){let[
|
|
3
|
-
${
|
|
1
|
+
import{f as w,g as b,q as S,r as k,s as v,t as L,u as I,v as O}from"./chunk-E7RQSJFB.js";import{Type as e}from"typebox";import{emptyPluginConfigSchema as x}from"openclaw/plugin-sdk/core";import{readFileSync as C,readdirSync as A,statSync as P,existsSync as $}from"node:fs";import{join as p,dirname as R}from"node:path";import{fileURLToPath as U}from"node:url";var N="@visiq/openclaw-plugin",h=process.env.BANK_API_URL??"http://localhost:4000/api",D=R(U(import.meta.url));function c(n,i={}){return{content:[{type:"text",text:n}],details:i}}async function g(n){let i=await fetch(`${h}${n}`);return i.ok?await i.text():`[Error ${i.status}]`}async function d(n,i){let t=await fetch(`${h}${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return t.ok?await t.text():`[Error ${t.status}]`}function j(){let n=[p(D,"..","..","..","examples","langchain-agent","docs"),p(D,"..","..","examples","langchain-agent","docs"),process.env.VISIQ_KNOWLEDGE_DIR??""].filter(i=>i.length>0);for(let i of n)if($(i))return i;return null}function B(){let n=j();if(!n)return[];let i=[];function t(o){for(let s of A(o)){let r=p(o,s);if(P(r).isDirectory())t(r);else if(s.endsWith(".txt")){let l=C(r,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(l){let a={};for(let _ of l[1].split(`
|
|
2
|
+
`)){let[m,...y]=_.split(":");m&&y.length&&(a[m.trim()]=y.join(":").trim())}i.push({path:r,title:a.title?.replace(/"/g,"")??s,classification:a.classification??"public",source:a.source??"unknown",content:l[2].trim()})}}}}return t(n),i}var f=null;function T(){return f===null&&(f=B()),f}function K(n,i=5){let t=T(),o=n.toLowerCase().split(/\s+/).filter(r=>r.length>=3);return t.map(r=>{let u=`${r.title} ${r.content}`.toLowerCase(),l=0;for(let a of o)u.includes(a)&&(l+=a.length,r.title.toLowerCase().includes(a)&&(l+=a.length*2));return{doc:r,score:l}}).filter(r=>r.score>0).sort((r,u)=>u.score-r.score).slice(0,i).map(r=>r.doc)}function G(n){w(),n.on("before_tool_call",S,{priority:50}),n.on("tool_result_persist",k),n.on("before_message_write",v),n.on("llm_input",L),n.on("llm_output",I),n.on("session_end",O),n.registerTool({name:"get_account",label:"Get account",description:"Get account holder profile from core banking system. Input: account ID (e.g. '4821-7734'). Returns: holder name, balance, risk score, KYC status, linked cards, address.",parameters:e.Object({account_id:e.String({description:"Account ID (e.g. '4821-7734')."})}),async execute(i,t){return c(await g(`/accounts/${t.account_id}`))}}),n.registerTool({name:"get_devices",label:"Get devices",description:"Get device fingerprints and login sessions from BioCatch. Input: account ID. Returns: registered devices, recent sessions with IP/geolocation, anomaly alerts.",parameters:e.Object({account_id:e.String({description:"Account ID to fetch devices for."})}),async execute(i,t){return c(await g(`/accounts/${t.account_id}/devices`))}}),n.registerTool({name:"get_transactions",label:"Get transactions",description:"Get recent transactions from the card processor with filtering. Returns: transaction list with amounts, merchants, locations, and risk flags.",parameters:e.Object({account_id:e.String({description:"Account ID (e.g. '4821-7734')."}),lookback_hours:e.Optional(e.Integer({minimum:1,maximum:720,description:"How far back to look (1\u2013720h, default 72)."})),min_amount:e.Optional(e.Number({minimum:0,description:"Filter out transactions below this dollar amount."}))}),async execute(i,t){let o=new URLSearchParams;t.lookback_hours!==void 0&&o.set("lookback_hours",String(t.lookback_hours)),t.min_amount!==void 0&&o.set("min_amount",String(t.min_amount));let s=o.toString()?`?${o.toString()}`:"";return c(await g(`/accounts/${t.account_id}/transactions${s}`))}}),n.registerTool({name:"check_watchlist",label:"Check watchlist",description:"Screen a name or entity against OFAC SDN, EU, and UN sanctions lists. Returns: match scores and recommendation.",parameters:e.Object({name:e.String({description:"Name or entity to screen."}),country_code:e.Optional(e.String({description:"ISO 3166-1 alpha-2 country code to scope the screening (e.g. 'US')."}))}),async execute(i,t){return c(await d("/watchlists/check",{name:t.name,country_code:t.country_code}))}}),n.registerTool({name:"search_knowledge",label:"Search knowledge base",description:"Search the bank's internal knowledge base for compliance policies, prior fraud case files, triage procedures, and customer information. Input is a free-text search query.",parameters:e.Object({query:e.String({description:"Free-text knowledge base search query."})}),async execute(i,t){let o=K(t.query,5);if(o.length===0)return c("No matching knowledge base documents found.",{hitCount:0});let s=o.map(r=>`--- ${r.title} (classification=${r.classification}, source=${r.source}) ---
|
|
3
|
+
${r.content}`).join(`
|
|
4
4
|
|
|
5
|
-
`);return c(s,{hitCount:
|
|
5
|
+
`);return c(s,{hitCount:o.length,classifications:o.map(r=>r.classification)})}}),n.registerTool({name:"place_hold",label:"Place hold",description:"Place a temporary fraud hold on an account. Blocks outbound transactions while allowing inbound credits.",parameters:e.Object({account_id:e.String({description:"Account to place the hold on."}),amount:e.Number({minimum:0,description:"Dollar amount to hold (0 = full account freeze)."}),currency:e.Union([e.Literal("USD"),e.Literal("EUR"),e.Literal("GBP"),e.Literal("CAD")],{description:"ISO currency code for the hold amount."}),duration_hours:e.Integer({minimum:1,maximum:168,description:"How long the hold stays (1\u2013168h)."}),reason:e.Union([e.Literal("fraud_investigation"),e.Literal("suspicious_pattern"),e.Literal("sanctions_review"),e.Literal("manual_review")],{description:"Reason classification for the hold."}),notify_holder:e.String({description:"Whether to notify the holder. Accepts: yes, no, true, false, 1, 0."})}),async execute(i,t){let{account_id:o,...s}=t;return c(await d(`/accounts/${o}/hold`,s))}}),n.registerTool({name:"block_card",label:"Block card",description:"Block a debit or credit card immediately. A replacement card will be mailed.",parameters:e.Object({account_id:e.String({description:"Account ID owning the card."}),reason:e.Union([e.Literal("fraud_investigation"),e.Literal("lost"),e.Literal("stolen"),e.Literal("compromised_pin"),e.Literal("customer_request")],{description:"Reason for blocking \u2014 drives the customer notification."}),notify_holder:e.Optional(e.String({description:"Whether to notify the holder. Accepts: yes, no, true, false."}))}),async execute(i,t){return c(await d(`/accounts/${t.account_id}/card/block`,{reason:t.reason,notify_holder:t.notify_holder}))}}),n.registerTool({name:"wire_transfer",label:"Wire transfer",description:"Initiate an outbound wire transfer from an account. HIGH RISK \u2014 large or sanctioned-destination wires are blocked or escalated by VisIQ action-governance policy.",parameters:e.Object({account_id:e.String({description:"Source account ID."}),amount:e.Number({minimum:0,description:"Dollar amount to wire."}),currency:e.Union([e.Literal("USD"),e.Literal("EUR"),e.Literal("GBP"),e.Literal("CAD")],{description:"ISO currency code."}),destination:e.String({description:"Destination account / IBAN / beneficiary identifier."}),destination_country:e.Optional(e.String({description:"ISO 3166-1 alpha-2 destination country (e.g. 'US')."})),memo:e.Optional(e.String({description:"Free-text wire memo."}))}),async execute(i,t){let{account_id:o,...s}=t;return c(await d(`/accounts/${o}/wire`,s))}}),n.registerTool({name:"create_case",label:"Create case",description:"Create a fraud investigation case. Routes to the right queue based on severity / category.",parameters:e.Object({account_id:e.String({description:"Affected account ID."}),severity:e.Union([e.Literal("low"),e.Literal("medium"),e.Literal("high"),e.Literal("critical")],{description:"Case severity \u2014 drives SLA and routing."}),category:e.Union([e.Literal("account_takeover"),e.Literal("card_fraud"),e.Literal("wire_fraud"),e.Literal("synthetic_identity"),e.Literal("sanctions_hit"),e.Literal("structuring")],{description:"Fraud category \u2014 routes to specialist queue."}),summary:e.String({description:"Free-text case summary for the analyst."}),assignee:e.Optional(e.String({description:"Specialist email to assign directly."})),sla_hours:e.Optional(e.Integer({minimum:1,maximum:168,description:"Override the default SLA (1\u2013168h)."}))}),async execute(i,t){return c(await d("/cases",t))}}),n.registerTool({name:"send_notification",label:"Send notification",description:"Send a fraud alert notification to the customer. Channel + priority drive delivery latency.",parameters:e.Object({account_id:e.String({description:"Account ID \u2014 used to look up contact methods."}),channel:e.Union([e.Literal("sms"),e.Literal("email"),e.Literal("push"),e.Literal("voice"),e.Literal("in_app")],{description:"Delivery channel."}),priority:e.Union([e.Literal("low"),e.Literal("normal"),e.Literal("high"),e.Literal("critical")],{description:"Delivery priority \u2014 critical bypasses customer quiet hours."}),subject:e.String({maxLength:120,description:"Short subject line (used for email / push title)."}),message:e.String({description:"Body text of the notification."}),locale:e.Optional(e.String({description:"BCP-47 locale (e.g. 'en-US', 'es-MX')."}))}),async execute(i,t){return c(await d("/notifications/send",t))}}),n.registerTool({name:"bank_account_lookup_tool",label:"Bank account lookup (sensitive)",description:"Look up sensitive account data for fraud investigation. account_id is the account number (e.g. '4821-7734'). include_ssn controls whether PII fields (SSN, DOB, full legal name) come back \u2014 accepts 'yes' / 'no' / 'true' / 'false' / '1' / '0'.",parameters:e.Object({account_id:e.String({description:"Account number to look up (e.g. 4821-7734)."}),include_ssn:e.String({description:"Whether to include PII fields (SSN, DOB, full legal name). Accepts: yes, no, true, false, 1, 0."})}),async execute(i,t){let s=new Set(["yes","y","true","1"]).has(String(t.include_ssn).toLowerCase().trim()),r=await fetch(`${h}/accounts/${t.account_id}`);if(!r.ok)return c(JSON.stringify({error:`Account ${t.account_id} not found`}),{status:r.status});let u=await r.json();if(!s){let{ssn:l,dob:a,full_legal_name:_,...m}=u;return c(JSON.stringify({account:m,pii_included:!1}),{pii_included:!1})}return c(JSON.stringify({account:u,pii_included:!0}),{pii_included:!0})}})}var q={id:N,name:"VisIQ OpenClaw Plugin",description:b,configSchema:x(),register:G},te=q;export{te as default};
|
package/openclaw.plugin.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "@visiq/openclaw-plugin",
|
|
3
3
|
"name": "VisIQ OpenClaw Plugin",
|
|
4
|
-
"version": "0.1.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "0.1.11",
|
|
5
|
+
"description": "VisIQ agent-governance plugin for the OpenClaw CLI — action governance on every tool call, retrieval governance on its configured retrieval tools, and audit-trail reporting, wired into OpenClaw's own tool hooks.",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"activation": {
|
|
8
8
|
"onStartup": true
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@visiq/openclaw-plugin",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.11",
|
|
4
|
+
"description": "VisIQ agent-governance plugin for the OpenClaw CLI — action governance on every tool call, retrieval governance on its configured retrieval tools, and audit-trail reporting, wired into OpenClaw's own tool hooks.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -72,8 +72,9 @@
|
|
|
72
72
|
"openclaw",
|
|
73
73
|
"plugin",
|
|
74
74
|
"ai-governance",
|
|
75
|
-
"
|
|
76
|
-
"
|
|
77
|
-
"
|
|
75
|
+
"agent-governance",
|
|
76
|
+
"action-governance",
|
|
77
|
+
"retrieval-governance",
|
|
78
|
+
"audit-trail"
|
|
78
79
|
]
|
|
79
80
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: fraud-triage
|
|
3
|
-
description: Investigate a bank fraud alert by calling the VisIQ bank tools and take protective action. Every tool call is governed by VisIQ
|
|
3
|
+
description: Investigate a bank fraud alert by calling the VisIQ bank tools and take protective action. Every tool call is governed by VisIQ action governance, retrieval governance, and the audit trail.
|
|
4
4
|
user-invocable: true
|
|
5
5
|
metadata: { "openclaw": { "emoji": "🛡️" } }
|
|
6
6
|
---
|
|
@@ -11,9 +11,9 @@ You are an AI fraud triage analyst at a major US retail bank. You investigate
|
|
|
11
11
|
fraud alerts EXCLUSIVELY by calling tools — you cannot reason about an account
|
|
12
12
|
without first fetching its data.
|
|
13
13
|
|
|
14
|
-
The VisIQ governance plugin owns these tools.
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
The VisIQ governance plugin owns these tools. Retrieval tools are governed for
|
|
15
|
+
read authorization + PII redaction; action tools are governed for permit / deny /
|
|
16
|
+
human-in-the-loop approval. Every model turn is written to the audit trail.
|
|
17
17
|
|
|
18
18
|
## Available tools
|
|
19
19
|
|
|
@@ -36,7 +36,7 @@ Actions (write): `place_hold`, `block_card`, `wire_transfer`, `create_case`,
|
|
|
36
36
|
4. Take protective action via tools: `place_hold`, `block_card`, `create_case`,
|
|
37
37
|
`send_notification`. Use `wire_transfer` only to claw back or reroute funds
|
|
38
38
|
when policy permits — large or sanctioned-destination wires will be blocked
|
|
39
|
-
or escalated by
|
|
39
|
+
or escalated by action governance.
|
|
40
40
|
5. Only after every relevant tool has been called, write a final summary.
|
|
41
41
|
|
|
42
42
|
## Hard rules
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: investigate
|
|
3
|
-
description: One-command bank fraud investigation of the flagged account (4821-7734). Fetches the account, transactions, devices, knowledge base and sanctions watchlist, then takes protective action — every tool call governed by VisIQ
|
|
3
|
+
description: One-command bank fraud investigation of the flagged account (4821-7734). Fetches the account, transactions, devices, knowledge base and sanctions watchlist, then takes protective action — every tool call governed by VisIQ action governance, retrieval governance, and the audit trail.
|
|
4
4
|
user-invocable: true
|
|
5
5
|
metadata: { "openclaw": { "emoji": "🔎" } }
|
|
6
6
|
---
|
|
@@ -30,9 +30,9 @@ Retrieval (read): `get_account`, `get_transactions`, `get_devices`,
|
|
|
30
30
|
Actions (write): `place_hold`, `block_card`, `wire_transfer`, `create_case`,
|
|
31
31
|
`send_notification`, `bank_account_lookup_tool`
|
|
32
32
|
|
|
33
|
-
The VisIQ governance plugin owns these tools.
|
|
34
|
-
|
|
35
|
-
deny / human-in-the-loop
|
|
33
|
+
The VisIQ governance plugin owns these tools. Retrieval tools are governed for
|
|
34
|
+
read authorization + PII redaction; action tools are governed for permit /
|
|
35
|
+
deny / human-in-the-loop approval. Every model turn is written to the audit trail.
|
|
36
36
|
|
|
37
37
|
## Workflow (mandatory)
|
|
38
38
|
|
|
@@ -46,7 +46,7 @@ deny / human-in-the-loop escalation). Every model turn is RECORDed.
|
|
|
46
46
|
4. Take protective action via tools: `place_hold`, `block_card`, `create_case`,
|
|
47
47
|
`send_notification`. Use `wire_transfer` only to claw back or reroute funds
|
|
48
48
|
when policy permits — large or sanctioned-destination wires will be blocked or
|
|
49
|
-
escalated by
|
|
49
|
+
escalated by action governance.
|
|
50
50
|
5. Only after every relevant tool has been called, write a final summary.
|
|
51
51
|
|
|
52
52
|
## Hard rules
|
package/dist/chunk-ZWWZ4HHR.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
var st="[REDACTED]",lt=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];function ct(e){if(!/^\d+$/.test(e))return!1;let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let i=e.charCodeAt(r)-48;n&&(i*=2,i>9&&(i-=9)),t+=i,n=!n}return t%10===0}function Pn(e){let t=e.replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let i=0;i<n.length;i++){let a=n[i],o=a>="A"&&a<="Z"?String(a.charCodeAt(0)-55):a;for(let s=0;s<o.length;s++)r=(r*10+(o.charCodeAt(s)-48))%97}return r===1}function Dn(e){if(!/^\d{9}$/.test(e))return!1;let t=[3,7,1,3,7,1,3,7,1],n=0;for(let r=0;r<9;r++)n+=(e.charCodeAt(r)-48)*t[r];return n%10===0}var Fn=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&ct(e)},{name:"iban",re:/\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]){10,30}\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:Pn},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Dn}],w=Object.fromEntries(lt.map(e=>[e.name,e.re.source])),dt=["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","pan","iban","aba_routing","us_ein","swift_bic","ssn","email","us_phone","ipv4","mac_address"],H={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
2
|
-
MIIEv\u2026
|
|
3
|
-
-----END PRIVATE KEY-----`,template:{pattern:w.private_key,mode:"full"},defaultEnabled:!0},jwt:{id:"jwt",label:"JWT / bearer tokens",description:"JSON Web Tokens (base64url header.payload.signature).",category:"secret",example:"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.dBjftJeZ4CVP",template:{pattern:w.jwt,mode:"full"},defaultEnabled:!0},aws_access_key:{id:"aws_access_key",label:"AWS access key IDs",description:"AWS access / identity key ids (AKIA / ASIA / AROA \u2026).",category:"secret",example:"AKIAIOSFODNN7EXAMPLE",template:{pattern:w.aws_access_key,mode:"full"},defaultEnabled:!0},github_token:{id:"github_token",label:"GitHub tokens",description:"GitHub personal / OAuth tokens (classic ghp_\u2026 + fine-grained).",category:"secret",example:"ghp_0123456789abcdef0123456789abcdef0123",template:{pattern:w.github_token,mode:"full"},defaultEnabled:!0},slack_token:{id:"slack_token",label:"Slack tokens",description:"Slack bot / user / app tokens (xoxb- / xoxp- \u2026).",category:"secret",example:"xoxb-1234567890-abcdefghijkl",template:{pattern:w.slack_token,mode:"full"},defaultEnabled:!0},stripe_secret:{id:"stripe_secret",label:"Stripe secret keys",description:"Stripe live secret / restricted keys (sk_live_ / rk_live_).",category:"secret",example:"sk_live_0123456789abcdefABCDEF",template:{pattern:w.stripe_secret,mode:"full"},defaultEnabled:!0},google_api_key:{id:"google_api_key",label:"Google API keys",description:"Google API keys (AIza\u2026).",category:"secret",example:"AIzaSyA1234567890abcdefghijklmnopqrstuv",template:{pattern:w.google_api_key,mode:"full"},defaultEnabled:!0},llm_api_key:{id:"llm_api_key",label:"LLM provider API keys",description:"OpenAI / Anthropic secret keys (sk-\u2026, sk-proj-\u2026, sk-ant-\u2026).",category:"secret",example:"sk-ant-api03-AbCdEf0123456789AbCdEf01",template:{pattern:w.llm_api_key,mode:"full"},defaultEnabled:!0},bearer_token:{id:"bearer_token",label:"Authorization bearer tokens",description:"Credentials following an HTTP `Authorization: Bearer \u2026` header.",category:"secret",example:"Bearer abcdef0123456789abcdef0123456789",template:{pattern:w.bearer_token,mode:"full"},defaultEnabled:!0},connection_string:{id:"connection_string",label:"Connection strings (with password)",description:"Database / broker DSNs carrying an inline password (scheme://user:pass@host).",category:"secret",example:"postgres://app:s3cr3t@db.internal:5432/main",template:{pattern:w.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS).",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\b\\d{13,19}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){10,30}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:"\\b\\d{9}\\b",mode:"full"},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX).",category:"financial",example:"12-3456789",template:{pattern:w.us_ein,mode:"full"},defaultEnabled:!0},swift_bic:{id:"swift_bic",label:"SWIFT / BIC codes",description:"Bank SWIFT/BIC codes (8 or 11 chars). DEFAULT-OFF (matches uppercase tokens).",category:"financial",example:"DEUTDEFF500",template:{pattern:w.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789).",category:"pii",example:"123-45-6789",template:{pattern:w.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept).",category:"pii",example:"alice@acme.com",template:{pattern:w.email,mode:"email"},defaultEnabled:!0},us_phone:{id:"us_phone",label:"US phone numbers",description:"US phone numbers in common formats. DEFAULT-OFF (10-digit false-positive surface).",category:"pii",example:"(415) 555-0132",template:{pattern:w.us_phone,mode:"partial",keepLast:4},defaultEnabled:!1},ipv4:{id:"ipv4",label:"IPv4 addresses",description:"Dotted-quad IPv4 addresses. DEFAULT-OFF (common + usually benign).",category:"identifier",example:"203.0.113.42",template:{pattern:w.ipv4,mode:"full"},defaultEnabled:!1},mac_address:{id:"mac_address",label:"MAC addresses",description:"Hardware MAC addresses. DEFAULT-OFF.",category:"identifier",example:"3c:22:fb:1a:2b:3c",template:{pattern:w.mac_address,mode:"full"},defaultEnabled:!1}},La=new Set(dt.filter(e=>!H[e].defaultEnabled));function jn(e,t){let n=new Set;for(let r of dt)(H[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function qn(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=e;for(let{name:a,re:o}of lt){let s=a;n.has(s)||(i=i.replace(o,()=>(r?.(s),t)))}for(let{name:a,re:o,normalize:s,validate:l}of Fn)n.has(a)||(i=i.replace(o,c=>l(s(c))?(r?.(a),t):c));return i}function Ae(e,t=st,n,r){return Bn(e,t,jn(n,r))}function Bn(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=s=>{if(typeof s=="string")return qn(s,t,n,a);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!i)return s;let l=String(s);return l.length>=13&&l.length<=19&&ct(l)?(r.add("pan"),t):s}if(Array.isArray(s))return s.map(l=>o(l));if(s!==null&&typeof s=="object"){let l=s,c={};for(let d of Object.keys(l))c[d]=o(l[d]);return c}return s};return{value:o(e),detectors:[...r].sort()}}function ut(e,t=st){return Ae(e,t).value}function Un(e){let{value:t,detectors:n}=Ae(e),r=n.some(i=>H[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function Q(e,t){let{blocked:n,redacted:r,detectors:i}=Un(e);return n?t.failMode==="closed"?{verdict:"block",redacted:r,detectors:i}:{verdict:"redact",redacted:r,detectors:i}:{verdict:"allow",redacted:r,detectors:i}}function Ie(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var zn=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function ke(e){return zn.has(Ie(e))}var Vn=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,pt=Object.freeze({\u0430:"a",\u0435:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0456:"i",\u0455:"s",\u043A:"k",\u043C:"m",\u0442:"t",\u043D:"h",\u0432:"b",\u0433:"r",\u03BF:"o",\u03B1:"a",\u03C1:"p",\u03B9:"i",\u03C4:"t",\u03B5:"e",\u03BA:"k",\u03BD:"v",\u03C5:"u",\u03B7:"n",\u0131:"i","\u04CF":"l",\u0578:"n"}),Gn=new RegExp(`[${Object.keys(pt).join("")}]`,"gu"),Kn=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),ft="\u2801\u2803\u2809\u2819\u2811\u280B\u281B\u2813\u280A\u281A\u2805\u2807\u280D\u281D\u2815\u280F\u281F\u2817\u280E\u281E\u2825\u2827\u283A\u282D\u283D\u2835",Wn=Object.freeze(Object.fromEntries([...ft].map((e,t)=>[e,String.fromCharCode(97+t)]))),Hn=new RegExp(`[${ft}\u2800]`,"g"),mt=/[⠀-⣿]/;function Qn(e){let t="";for(let n of e){let r=n.codePointAt(0);r!==void 0&&(r>=917536&&r<=917630?t+=String.fromCodePoint(r-917504):r>=917504&&r<=917631||(t+=n))}return t}function Yn(e){return e.replace(Vn,"")}function gt(e){return e.replace(Gn,t=>pt[t]??t)}function Zn(e){return e.replace(/[4@31!05$79(8]/g,t=>Kn[t]??t)}function Jn(e){return e.replace(/[a-zA-Z]/g,t=>{let n=t<="Z"?65:97;return String.fromCharCode((t.charCodeAt(0)-n+13)%26+n)})}function Xn(e){return mt.test(e)?e.replace(Hn,t=>t==="\u2800"?" ":Wn[t]??t):e}function Je(e){let t;try{t=Qn(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=Yn(t),t=gt(t),t}var er=/^[A-Za-z0-9+/]{16,}={0,2}$/,tr=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,Xe=/[A-Za-z0-9+/]{20,}={0,2}/g;function ye(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);(r===9||r===10||r===13||r>=32&&r<=126||r>=160&&r!==65533)&&t++}return t/e.length}var ht=new TextDecoder("utf-8",{fatal:!1});function _t(e){let t;try{t=atob(e)}catch{return[]}let n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i)&255;let r=ht.decode(n);return t===r?[t]:[r,t]}function nr(e){let t=e.replace(/\s+/g,"");if(t.length===0||t.length%2!==0)return[];let n=new Uint8Array(t.length/2);for(let a=0;a<n.length;a++){let o=Number.parseInt(t.slice(a*2,a*2+2),16);if(Number.isNaN(o))return[];n[a]=o}let r="";for(let a=0;a<n.length;a++)r+=String.fromCharCode(n[a]);let i=ht.decode(n);return r===i?[r]:[i,r]}function et(e){let t=e.trim(),n=[];if(tr.test(t))for(let r of nr(t))n.push({decoded:r,textiness:ye(r)});if(er.test(t)&&t.length%4===0)for(let r of _t(t))n.push({decoded:r,textiness:ye(r)});return n}function tt(e,t){let n=[],r;for(Xe.lastIndex=0;(r=Xe.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of _t(i))n.push({decoded:a,textiness:ye(a)})}return n}var rr=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function yt(e,t=rr){if(typeof e!="string"||e.length===0)return{views:[],anyDecoded:!1,truncated:!1,nodes:0,maxDepthSeen:0};let{maxDepth:n,byteCap:r,maxNodes:i,maxBlobsPerNode:a}=t,o=new Set,s=g=>{g.length>0&&g.length<=r&&o.add(g)},l=!1,c=!1,d=0,f=0,m=[{s:e,depth:0}];for(;m.length>0;){if(d>=i){c=!0;break}let g=m.pop();if(g===void 0)break;let{s:_,depth:v}=g;if(_.length>r){c=!0;continue}d++,v>f&&(f=v);let h=Je(_);s(h);let A=Zn(h);if(A!==h&&s(A),s(Jn(h)),mt.test(_)&&s(Xn(h)),v>=n){let S=Je(_);(et(S).length>0||tt(S,a).length>0)&&(c=!0);continue}let k=[...et(h),...tt(h,a)];for(let S of k){if(l=!0,S.decoded.length>r){c=!0;continue}S.textiness>=.85&&S.decoded!==h?m.push({s:S.decoded,depth:v+1}):s(S.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:d,maxDepthSeen:f}}var bt=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],ir=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),ar=8,or=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),nt=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function sr(e){let t=[...e].map(r=>r.codePointAt(0)),n=0;for(let r=0;r<t.length;r++){let i=t[r];if(i>=917504&&i<=917631||or.has(i)&&nt(t[r-1])&&nt(t[r+1])&&(n++,n>=ar))return!0}return!1}var lr=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function cr(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(lr.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var dr=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function ur(e){for(let t of dr)if(e>=t.lo&&e<=t.hi)return t.name;return null}function pr(e){for(let t of e.split(/\s+/)){if(t.length<4)continue;let n=0,r=0,i=!0;for(let a of t){let o=ur(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:gt(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var rt=Object.freeze({signals:[],contributes:!1});function fr(e){if(typeof e!="string"||e.length===0)return{...rt,signals:[]};let t=new Set;try{sr(e)&&t.add("hidden_text_carrier"),cr(e)&&t.add("injected_turn_boundary"),pr(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=yt(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...rt,signals:[]}}return{signals:[...bt.filter(n=>t.has(n))],contributes:ir.some(n=>t.has(n))}}var Y=[{name:"override_instructions",re:/\bignore (?:all |the )?(?:previous|above|prior) (?:instructions|prompts?)\b/i},{name:"disregard_instructions",re:/\bdisregard (?:the )?(?:above|previous|system)\b/i},{name:"role_tag",re:/<\/?(system|assistant|instructions|host_context)\b/i},{name:"privilege_override",re:/\b(grant|escalate|elevate) (admin|root|all|full) (access|privileges?)\b/i},{name:"tool_smuggle",re:/```[\s\S]*?(tool_call|function_call)/i}];function it(e){return typeof e!="string"||e.length===0?[]:Y.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function mr(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(it(e)),{views:n}=yt(e);for(let r of n)for(let i of it(r))t.add(i);return Y.filter(r=>t.has(r.name)).map(r=>r.name)}function gr(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of mr(a))t.add(s);let o=fr(a);for(let s of o.signals)n.add(s);o.contributes&&(r=!0);return}if(Array.isArray(a)){for(let o of a)i(o);return}if(typeof a=="object")for(let o of Object.values(a))i(o)}};return i(e),{matched:t.size>0||r,signatures:Y.filter(a=>t.has(a.name)).map(a=>a.name),structural:bt.filter(a=>n.has(a))}}function hr(e){return gr(e).matched}var Pa=Y.map(e=>e.name);var _r=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var yr="i:injection";function vt(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=Ae(e.content);for(let a of i){let o=H[a]?.category;o&&t.add(`c:${o}`)}hr(e.content)&&t.add(yr)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&_r.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var _e="(?:system\\s+prompt|initial\\s+(?:instructions|prompt)|system\\s+(?:instructions|message)|hidden\\s+(?:instructions|prompt)|your\\s+(?:system\\s+prompt|initial\\s+instructions|instructions|prompt)|the\\s+prompt\\s+(?:above|you\\s+were\\s+given))",Da=[{name:"reveal_prompt",re:new RegExp(`\\b(?:reveal|show|print|repeat|output|echo|display|expose|dump|leak|reprint|divulge|disclose)\\b[\\s\\S]{0,40}?\\b${_e}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${_e}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${_e}\\b`,"i")},{name:"repeat_above",re:/\b(?:repeat|print|output|echo|reproduce)\b[\s\S]{0,20}?\b(?:everything|all\s+(?:the\s+)?(?:text|words))\b[\s\S]{0,12}?\b(?:above|before|preceding|verbatim|word\s+for\s+word)\b/i}],at="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",br=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${at}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${at}|programming|training))`,vr="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",ot="(?:\\b(?:unrestricted|unfiltered|uncensored|unbounded|unlimited|unchained|jailbroken|lawless|amoral)\\b|\\b(?:DAN|STAN|DUDE|AIM)\\b|\\bno\\s+(?:longer\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|boundaries|constraints?)\\b(?!\\s+(?:on|over|regarding|upon|for)\\b)|\\bwithout\\s+(?:any\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|constraints?|censorship)\\b|\\b(?:free|freed|released)\\s+from\\s+(?:your\\s+)?(?:restrictions?|limits?|rules?|guidelines?|guardrails?|programming|constraints?)\\b|\\b(?:can|will|are\\s+able\\s+to)\\s+(?:do|say)\\s+anything\\b|\\bignore\\s+(?:all\\s+)?(?:your\\s+)?(?:previous\\s+|prior\\s+|system\\s+)?(?:instructions?|rules?|guidelines?)\\b)",wr="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Fa=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${vr}${br}\\b`,"i")},{name:"forget_everything_prior",re:/\b(?:forget|ignore|disregard|erase|discard)\s+(?:about\s+|all\s+|any\s+)?(?:everything|anything)\b[\s\S]{0,24}?\b(?:above|before|previously|prior|earlier|you\s+(?:were|have\s+been)\s+(?:told|instructed|given|programmed))\b/i},{name:"persona_reassignment_jailbreak",re:new RegExp(`\\byou\\s+are\\s+now\\s+(?:(?:a|an|the)\\s+)?[\\s\\S]{0,48}?${ot}`,"i")},{name:"constraint_release",re:/\byou\s+are\s+no\s+longer\s+(?:bound|restricted|limited|constrained|obligated|governed|subject\s+to|required\s+to)\b/i},{name:"from_now_on_reassignment",re:new RegExp(`\\bfrom\\s+now\\s+on\\s*,?\\s+you\\s+(?:are|will|must|shall|have|can)\\s+(?:${wr}\\b|[\\s\\S]{0,40}?${ot})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Ar="[SYSTEM-PROMPT-REDACTED]";function be(e){return e.toLowerCase().replace(/\s+/g," ").trim().split(" ").filter(t=>t.length>0)}function Ir(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wt(e,t){if(typeof e!="string"||typeof t!="string"||e.length===0||t.length===0)return[];let n=be(e),r=be(t),i=8;if(n.length<i||r.length<i)return[];let a=new Set;for(let l=0;l+i<=r.length;l++)a.add(r.slice(l,l+i).join(" "));let o=[],s=new Set;for(let l=0;l+i<=n.length;l++){let c=n.slice(l,l+i).join(" ");a.has(c)&&!s.has(c)&&(s.add(c),o.push(c))}return o}function kr(e,t){if(typeof e!="string"||e.length===0)return e;let n=e,r=Math.max(1,be(e).length);for(let i=0;i<r;i++){let a=wt(t,n);if(a.length===0)return n;for(let o of a){let s=o.split(" ").filter(d=>d.length>0);if(s.length===0)continue;let l=s.map(Ir).join("\\s+"),c;try{c=new RegExp(l,"gi")}catch{continue}n=n.replace(c,Ar)}}return n}function ve(e,t,n){if(e==null)return e;if(typeof e=="string"){for(let r of wt(t,e))n.add(r);return kr(e,t)}if(Array.isArray(e))return e.map(r=>ve(r,t,n));if(typeof e=="object"){let r=e,i=Object.create(Object.getPrototypeOf(r));for(let a of Object.keys(r))i[a]=ve(r[a],t,n);return i}return e}function Sr(e,t){if(typeof t!="string"||t.length===0)return{leaked:!1,matchedSpans:[],redacted:e};let n=new Set,r=ve(e,t,n),i=[...n].sort();return{leaked:i.length>0,matchedSpans:i,redacted:r}}function At(e,t,n){let{leaked:r,redacted:i,matchedSpans:a}=Sr(e,t);return r?n.failMode==="closed"?{verdict:"block",redacted:i,matchedSpans:a}:{verdict:"redact",redacted:i,matchedSpans:a}:{verdict:"allow",redacted:i,matchedSpans:a}}var ja=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var R=e=>`[^.!?;\\n]{0,${e}}?`,Cr=["\\bi\\s+(?:can'?t|cannot|can\\s+not|won'?t|will\\s+not)\\b","\\bi(?:'m|\\s+am)\\s+(?:not\\s+able\\s+to|unable\\s+to|not\\s+going\\s+to|not\\s+permitted\\s+to|not\\s+allowed\\s+to)\\b"].join("|"),It="(?:help|assist|provide|create|generate|produce|write|compose|draft|comply|fulfil|fulfill|share|disclose|reveal|perform|execute|run|send|transmit|publish|export|approve|grant|carry\\s+out|do\\s+that|do\\s+this|do\\s+so|go\\s+ahead)",qa=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Cr})\\s${R(40)}\\b${It}\\b`,"\\b(?:that|this|it)(?:'s|\\s+is)\\s+not\\s+something\\s+i\\s+(?:can|could|am\\s+able\\s+to|'m\\s+able\\s+to)\\b",`\\b(?:falls|sits|is)\\s+outside\\s+(?:of\\s+)?(?:what|the\\s+(?:scope|range|bounds))\\b${R(40)}\\bi\\s+(?:can|am|'m)\\b`,"\\bnot\\s+something\\s+i(?:'m|\\s+am)\\s+(?:able|willing|permitted|allowed)\\s+to\\b"].join("|"),"i")},{id:"explicit_decline",class:"strong",re:new RegExp(["\\bi\\s+(?:must|have\\s+to|need\\s+to|will\\s+have\\s+to|am\\s+going\\s+to|'m\\s+going\\s+to)\\s+(?:respectfully\\s+)?decline\\b","\\bi(?:'m|\\s+am)\\s+not\\s+(?:comfortable|willing|prepared)\\b","\\bi(?:'ll|\\s+will)\\s+(?:have\\s+to\\s+)?pass\\s+on\\b","\\bi\\s+(?:must|have\\s+to)\\s+refuse\\b"].join("|"),"i")},{id:"policy_citation",class:"strong",re:new RegExp([`\\b(?:against|contrary\\s+to|prohibited\\s+by|forbidden\\s+by|in\\s+violation\\s+of|violates)\\s${R(24)}\\b(?:polic(?:y|ies)|guidelines?|terms\\s+of\\s+(?:use|service)|rules\\s+of\\s+engagement|code\\s+of\\s+conduct)\\b`,`\\b(?:my|our|the|company|organi[sz]ation'?s?)\\s+(?:polic(?:y|ies)|guidelines?)\\s${R(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${R(24)}\\b(?:polic(?:y|ies)|guidelines?)\\b`].join("|"),"i")},{id:"guardrail_selfreference",class:"strong",re:new RegExp(["\\bi(?:'ve|\\s+have)\\s+been\\s+(?:instructed|configured|told|trained)\\s+not\\s+to\\b","\\bi(?:'m|\\s+am)\\s+(?:designed|configured|programmed|built|set\\s+up)\\s+not\\s+to\\b",`\\bmy\\s+(?:safety\\s+)?(?:instructions|configuration|guardrails?|constraints|training)\\s${R(24)}\\b(?:prevent|prohibit|forbid|do(?:es)?\\s+not\\s+(?:allow|permit)|preclude)\\b`,"\\b(?:outside|beyond)\\s+(?:my|the)\\s+(?:permitted|authori[sz]ed|configured|approved)\\s+(?:scope|remit|capabilities|actions|operations)\\b"].join("|"),"i")},{id:"ethical_objection",class:"strong",re:new RegExp(["\\b(?:that|this|doing\\s+(?:so|that)|what\\s+you(?:'re|\\s+are)\\s+asking|the\\s+request|such\\s+a\\s+request)\\s+(?:would\\s+be|is|are)\\s+(?:clearly\\s+|both\\s+|potentially\\s+)?(?:illegal|unethical|unlawful|harmful|fraudulent)\\b","\\bi\\s+(?:do\\s+not|don'?t)\\s+condone\\b","\\b(?:goes|would\\s+go|runs)\\s+against\\s+my\\s+(?:principles|values|ethics)\\b","\\bi\\s+(?:can'?t|cannot|won'?t)\\s+in\\s+good\\s+conscience\\b"].join("|"),"i")},{id:"apology_marker",class:"weak",re:new RegExp("\\b(?:i(?:'m|\\s+am)\\s+(?:really\\s+|very\\s+|terribly\\s+|so\\s+)?sorry|i\\s+apologi[sz]e|my\\s+apologies)\\b","i")}]),Ba=Object.freeze([/```/,/\b(?:here(?:'s|\s+is|\s+are)|below\s+(?:is|are|you(?:'ll|\s+will)\s+find)|the\s+following\s+(?:is|are))\b/i,new RegExp(`\\b(?:but|however|instead|although|that\\s+said)\\b${R(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${R(30)}\\b${It}\\b|i(?:'d|\\s+would)\\s+be\\s+happy\\s+to\\b|i(?:'m|\\s+am)\\s+able\\s+to\\b)`,"i"),/\bwhat\s+i\s+can\s+do\s+(?:instead|is|for\s+you)\b/i]);var D=e=>`[^.!?;\\n]{0,${e}}?`,Ua=Object.freeze([{id:"vulnerability_scanning",objectPatterns:[/\b(?:vulnerability|vuln|security)\s+(?:scan|scans|scanning|assessment|audit|test|testing)\b/i,/\bpen(?:etration)?[\s-]?test(?:ing)?\b/i,/\bport\s+scan(?:ning)?\b/i,/\b(?:exploit|nmap|metasploit|nessus|burp\s+suite)\b/i,/\bCVE-\d{4}-\d{4,7}\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|vulnerability|incident\s+respon\w{0,4}|threat|soc|red\s+team|phishing|malware)\b/i]},{id:"credential_access",objectPatterns:[/\b(?:credential|password|passphrase|api\s+key|access\s+key|secret|token|private\s+key|ssh\s+key)s?\b/i,/\b(?:vault|secrets?\s+manager|keychain|keystore)\b/i,/\bservice\s+account\s+key\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|identity|iam|credential|secrets?\s+manage\w{0,4}|vault|platform|devops)\b/i]},{id:"financial_transaction",objectPatterns:[/\b(?:wire\s+transfer|bank\s+transfer|payout|disbursement|chargeback)\b/i,new RegExp(`\\b(?:approve|issue|initiate|process|release)\\s${D(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${D(20)}\\b(?:funds|money)\\b`,"i")],purposeFunctions:["finance_accounting","procurement"],purposePatterns:[/\b(?:finance|financial|accounting|invoice|invoicing|payment|payments|billing|refund|refunds|treasury|procurement|spend|purchasing|fraud|kyc)\b/i]},{id:"personnel_data",objectPatterns:[/\b(?:employee|personnel|payroll|hr|staff)\s+(?:record|records|data|file|files|information|details)\b/i,/\b(?:salary|salaries|compensation|performance\s+review|termination\s+letter)s?\b/i,/\b(?:home\s+address|social\s+security\s+number|national\s+insurance\s+number)e?s?\b/i],purposeFunctions:["hr","privacy_compliance"],purposePatterns:[/\b(?:hr|human\s+resources|people\s+ops|payroll|benefits|recruit\w{0,4}|onboarding|privacy|dsar|consent)\b/i]},{id:"regulated_advice",objectPatterns:[/\b(?:legal|medical|tax|investment|financial)\s+advice\b/i,/\bpractis\w{0,3}\s+law\b/i,/\b(?:diagnose|diagnosis|prescribe|prescription)\b/i,/\b(?:binding|enforceable)\s+(?:opinion|interpretation)\b/i],purposeFunctions:["legal","privacy_compliance"],purposePatterns:[/\b(?:legal|compliance|counsel|contract|contracts|litigation|nda|privacy|regulator\w{0,2}|audit\w{0,3})\b/i]},{id:"data_export",objectPatterns:[new RegExp(`\\b(?:export|download|dump|extract|exfiltrat\\w{0,3}|bulk\\s+copy)\\b\\s${D(30)}\\b(?:data|database|dataset|records?|table|tables|customer\\s+list|contact\\s+list|report)\\b`,"i"),/\b(?:full|entire|whole)\s+(?:database|dataset|customer\s+table)\b/i],purposeFunctions:["operations","engineering","privacy_compliance"],purposePatterns:[/\b(?:data\s+(?:pipeline|engineering|platform)|etl|export|reporting|analytics|operations|document\s+extract\w{0,3}|forecast\w{0,3})\b/i]},{id:"code_execution",objectPatterns:[new RegExp(`\\b(?:run|execute|invoke)\\s${D(24)}\\b(?:script|scripts|command|commands|shell|code|binary|query|migration)\\b`,"i"),/\b(?:shell|root|sudo|admin)\s+(?:access|command|session)\b/i,/\bagainst\s+(?:the\s+)?production\s+(?:system|server|database|environment)s?\b/i],purposeFunctions:["engineering","it_security"],purposePatterns:[/\b(?:engineering|developer|devops|platform|release|deploy\w{0,4}|build|pipeline|sandbox|test\s+data|change\s+window)\b/i]},{id:"external_communication",objectPatterns:[new RegExp(`\\b(?:send|post|publish|email|tweet|message|broadcast)\\b\\s${D(30)}\\b(?:external|customer|customers|public|press|social\\s+media|third[\\s-]party|prospect|prospects)\\b`,"i"),/\b(?:cold\s+outreach|marketing\s+blast|phishing\s+email|press\s+release)\b/i],purposeFunctions:["marketing","sales","customer_support"],purposePatterns:[/\b(?:marketing|campaign|outreach|email\s+assistant|support|customer|sales|lead|leads|communication|communications)\b/i]}]);var Er=["competitor_mention","disallowed_topic","off_brand_claim","restricted_advice"];var Tr=[{id:"competitor_mention",re:/\b(acmecorp|northwind\s+rival|zenithsoft|globex\s+analytics)\b/gi},{id:"disallowed_topic",re:/\b(political\s+endorsement|religious\s+affiliation|layoff\s+rumou?rs?|pending\s+litigation)\b/gi},{id:"off_brand_claim",re:/\b(100%\s+(secure|guaranteed)|zero\s+risk|unhackable|never\s+fails)\b/gi},{id:"restricted_advice",re:/\b(investment\s+advice|medical\s+diagnosis|legal\s+advice|tax\s+advice)\b/gi}];var Nr={competitor_mention:"redact",off_brand_claim:"redact",disallowed_topic:"escalate",restricted_advice:"escalate"};function Or(e){return e.length===0?null:e.some(t=>Nr[t]==="escalate")?"escalate":"redact"}var Rr="[BRAND-TOPIC-REDACTED]";function we(e,t){if(e==null)return e;if(typeof e=="string"){let n=e;for(let{id:r,re:i}of Tr){i.lastIndex=0;let a=n.replace(i,()=>Rr);a!==n&&(t.add(r),n=a)}return n}if(Array.isArray(e))return e.map(n=>we(n,t));if(typeof e=="object"){let n=e,r=Object.create(Object.getPrototypeOf(n));for(let i of Object.keys(n))r[i]=we(n[i],t);return r}return e}function xr(e){let t=new Set,n=we(e,t);return{matched:Er.filter(r=>t.has(r)),redacted:n}}function Z(e,t){let{matched:n,redacted:r}=xr(e),i=Or(n);return n.length===0?{verdict:"allow",redacted:r,matched:n,recommendedOutcome:i}:t.failMode==="closed"?{verdict:"block",redacted:r,matched:n,recommendedOutcome:i}:{verdict:"redact",redacted:r,matched:n,recommendedOutcome:i}}var Se="[REDACTED]",$="\u2022",W=e=>/[A-Za-z0-9]/.test(e);function kt(e,t,n,r){let i=Array.from(e),a=i.length,o=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:$,c=o+s>=a;return i.map((d,f)=>!c&&(f<o||f>=a-s)?d:W(d)?l:d).join("")}function Mr(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return kt(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:$;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(o=>W(o)?a:o).join(""))+i}function $r(e,t,n){let r=n.length>0?n:$,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let c=new RegExp(t,"g"),d;for(;(d=c.exec(e))!==null;){if(d[0].length===0){c.lastIndex++;continue}for(let f=d.index;f<d.index+d[0].length;f++)i[f]=!0}}catch{}let a=!1,o=!0;for(let c=0;c<e.length;c++)if(W(e[c])&&(a=!0,!i[c])){o=!1;break}let s=a&&o,l="";for(let c=0;c<e.length;c++){let d=e[c];!s&&i[c]||!W(d)?l+=d:l+=r}return l}function St(e,t){let n=t.mode??"full";return n==="partial"?kt(e,t.keepFirst??0,t.keepLast??0,t.maskChar??$):n==="email"?Mr(e,t.maskChar??$):n==="custom"?$r(e,t.keepPattern,t.maskChar??$):t.replacement??Se}function Lr(e,t){return typeof e=="string"?St(e,t):t.replacement??Se}function Ct(e){let t=[],n=e.replacement??Se;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:a=>St(a,r)})}return t}function Et(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(a,o=>i(o))}return n}function J(e,t){return e==null?e:typeof e=="string"?Pr(e,t):typeof e=="object"?Dr(e,t):e}function Pr(e,t){if(typeof e!="string")return e;let n=Ct(t);return n.length===0?e:Et(e,n)}function Dr(e,t){let n=new Map;for(let s of t.fields??[])typeof s=="string"&&s.length>0&&n.set(s,{field:s,mode:"full",replacement:t.replacement});for(let s of t.directives??[])typeof s.field=="string"&&s.field.length>0&&n.set(s.field,s);let r=Ct(t),i=n.size>0,a=r.length>0,o=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>o(l));if(typeof s=="object"){let l=s,c=Object.create(Object.getPrototypeOf(l));for(let d of Object.keys(l)){let f=i?n.get(d):void 0;if(f){c[d]=Lr(l[d],f);continue}c[d]=o(l[d])}return c}return typeof s=="string"&&a?Et(s,r):s};return o(e)}import{readFile as Fr}from"node:fs/promises";import{homedir as Ee}from"node:os";import{join as Te,isAbsolute as jr,resolve as qr}from"node:path";import{createInterface as Br}from"node:readline";import{parseArgs as Ur}from"node:util";var zr="https://api.visiqlabs.com",Tt="@visiq/openclaw-plugin",te="open";function Ne(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}var Vr={enabled:!0,thresholds:{}},ne=[{key:"minEvents",env:"VISIQ_SEQUENCE_ANOMALY_MIN_EVENTS",cli:"sequence-anomaly-min-events",json:"min_events"},{key:"minClasses",env:"VISIQ_SEQUENCE_ANOMALY_MIN_CLASSES",cli:"sequence-anomaly-min-classes",json:"min_classes"},{key:"concentrationSigma",env:"VISIQ_SEQUENCE_ANOMALY_SIGMA",cli:"sequence-anomaly-sigma",json:"concentration_sigma"},{key:"dominanceRatio",env:"VISIQ_SEQUENCE_ANOMALY_DOMINANCE_RATIO",cli:"sequence-anomaly-dominance-ratio",json:"dominance_ratio"},{key:"dominanceShare",env:"VISIQ_SEQUENCE_ANOMALY_DOMINANCE_SHARE",cli:"sequence-anomaly-dominance-share",json:"dominance_share"},{key:"frictionRatio",env:"VISIQ_SEQUENCE_ANOMALY_FRICTION_RATIO",cli:"sequence-anomaly-friction-ratio",json:"friction_ratio"},{key:"minFrictionEvents",env:"VISIQ_SEQUENCE_ANOMALY_MIN_FRICTION_EVENTS",cli:"sequence-anomaly-min-friction-events",json:"min_friction_events"}],Gr=["sequence-anomaly",...ne.map(e=>e.cli)];function ee(e){if(typeof e=="boolean")return e;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="0"||t==="off"||t==="false"||t==="no"||t==="disabled")return!1;if(t==="1"||t==="on"||t==="true"||t==="yes"||t==="enabled")return!0}function Oe(e){if(typeof e=="number")return Number.isFinite(e)&&e>=0?e:void 0;if(typeof e!="string"||e.trim()==="")return;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function Kr(...e){let t={};for(let n of e)for(let[r,i]of Object.entries(n??{}))typeof i=="number"&&(t[r]=i);return t}var Wr='[VisIQ] OpenClaw plugin is installed but missing credentials. Provide them with one of (highest precedence first): (1) environment variables VISIQ_API_KEY=<key> VISIQ_AGENT_ID=<id> (set before `openclaw gateway run` / `openclaw start`) ; (2) a JSON file at the path in VISIQ_CONFIG_PATH ; (3) ~/.openclaw/openclaw.json -> plugins.entries["@visiq/openclaw-plugin"].config = { "apiKey": "<key>", "agentId": "<id>" } . Until credentials are provided the plugin is a NO-OP \u2014 tool calls run UNGOVERNED (fail-open default; set VISIQ_FAIL_MODE=closed to block instead).';function Hr(e){return e==="~"||e.startsWith("~/")?Te(Ee(),e.slice(1).replace(/^\//,"")):e}async function Nt(e){try{let t=jr(e)?e:qr(e),n=await Fr(t,"utf-8");return JSON.parse(n)}catch{return null}}function X(e,...t){for(let n of t){let r=e[n];if(typeof r=="string")return r}}function Ce(e){if(!e||typeof e!="object")return{};let t=e,n=X(t,"apiKey","api_key"),r=X(t,"agentId","agent_id"),i=X(t,"baseUrl","base_url"),a=Ne(X(t,"failMode","fail_mode")),o={};n&&(o.apiKey=n),r&&(o.agentId=r),i&&(o.baseUrl=i),a&&(o.failMode=a);let s=t.sequenceAnomaly??t.sequence_anomaly;if(s!=null){let l=ee(s);if(l!==void 0)o.sequenceAnomalyEnabled=l;else if(typeof s=="object"&&!Array.isArray(s)){let c=s,d=ee(c.enabled);d!==void 0&&(o.sequenceAnomalyEnabled=d);let f={};for(let m of ne){let g=Oe(c[m.key]??c[m.json]);g!==void 0&&(f[m.key]=g)}Object.keys(f).length>0&&(o.sequenceAnomalyThresholds=f)}}return o}async function Qr(e){if(!e)return{};let t=Hr(e),n=await Nt(t);if(!n||typeof n!="object")return{};let r=n,i=r.plugins?.entries,a=i&&typeof i=="object"?i[Tt]:void 0;return a&&typeof a=="object"&&a.config?Ce(a.config):Ce(r)}async function Ot(e){if(!e)return{};let t=await Nt(e);if(!t||typeof t!="object")return{};let a=t.plugins?.entries?.[Tt];return!a||typeof a!="object"?{}:Ce(a.config)}function Yr(){return Ot(Te(Ee(),".openclaw","openclaw.json"))}function Zr(){let e=process.env.OPENCLAW_CONFIG_PATH;return!e||e===Te(Ee(),".openclaw","openclaw.json")?Promise.resolve({}):Ot(e)}async function Jr(e){if(!process.stdout.isTTY)return{};let t=Br({input:process.stdin,output:process.stdout}),n=r=>new Promise(i=>t.question(r,a=>i(a)));try{let r={...e};if(!r.apiKey){let i=(await n("VisIQ API key: ")).trim();i&&(r.apiKey=i)}if(!r.agentId){let i=(await n("VisIQ agent ID: ")).trim();i&&(r.agentId=i)}if(!r.baseUrl){let i=(await n("VisIQ base URL (optional, press Enter for default): ")).trim();i&&(r.baseUrl=i)}return r}finally{t.close()}}function Xr(){try{let e={"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"},"fail-mode":{type:"string"}};for(let c of Gr)e[c]={type:"string"};let{values:t}=Ur({args:process.argv.slice(2),options:e,strict:!1,allowPositionals:!0}),n={},r=t["api-key"],i=t["agent-id"],a=t["base-url"],o=Ne(t["fail-mode"]);typeof r=="string"&&r&&(n.apiKey=r),typeof i=="string"&&i&&(n.agentId=i),typeof a=="string"&&a&&(n.baseUrl=a),o&&(n.failMode=o);let s=ee(t["sequence-anomaly"]);s!==void 0&&(n.sequenceAnomalyEnabled=s);let l={};for(let c of ne){let d=Oe(t[c.cli]);d!==void 0&&(l[c.key]=d)}return Object.keys(l).length>0&&(n.sequenceAnomalyThresholds=l),n}catch{return{}}}async function Qa(){return(await Re()).config}async function Re(){let e=Xr(),t={};process.env.VISIQ_API_KEY&&(t.apiKey=process.env.VISIQ_API_KEY),process.env.VISIQ_AGENT_ID&&(t.agentId=process.env.VISIQ_AGENT_ID),process.env.VISIQ_BASE_URL?t.baseUrl=process.env.VISIQ_BASE_URL:process.env.VISIQ_ENDPOINT&&(t.baseUrl=process.env.VISIQ_ENDPOINT);let n=Ne(process.env.VISIQ_FAIL_MODE);n&&(t.failMode=n);let r=ee(process.env.VISIQ_SEQUENCE_ANOMALY);r!==void 0&&(t.sequenceAnomalyEnabled=r);let i={};for(let f of ne){let m=Oe(process.env[f.env]);m!==void 0&&(i[f.key]=m)}Object.keys(i).length>0&&(t.sequenceAnomalyThresholds=i);let a=await Qr(process.env.VISIQ_CONFIG_PATH),o=await Yr(),s=await Zr(),l={...o,...s,...a,...t,...e,sequenceAnomalyThresholds:Kr(o.sequenceAnomalyThresholds,s.sequenceAnomalyThresholds,a.sequenceAnomalyThresholds,t.sequenceAnomalyThresholds,e.sequenceAnomalyThresholds)};(!l.apiKey||!l.agentId)&&process.stdout.isTTY&&process.stdin.isTTY&&(l=await Jr(l));let c=l.failMode??te;if(!l.apiKey||!l.agentId)return process.stderr.write(`${Wr}
|
|
4
|
-
`),{config:null,failMode:c};let d={apiKey:l.apiKey,agentId:l.agentId,failMode:c,sequenceAnomaly:{enabled:l.sequenceAnomalyEnabled??Vr.enabled,thresholds:l.sequenceAnomalyThresholds??{}}};return d.baseUrl=l.baseUrl||zr,{config:d,failMode:c}}var xe=null,Rt={ready:!1,config:null,failMode:te};function Me(){return xe||(xe=Re().catch(e=>(process.stderr.write(`[VisIQ] Config resolution failed (treating as unconfigured): ${e instanceof Error?e.message:String(e)}
|
|
5
|
-
`),{config:null,failMode:te})).then(e=>(Rt={ready:!0,config:e.config,failMode:e.failMode},e))),xe}function re(){return Me().then(e=>e.config)}function ie(){return Me()}function ae(){return Rt}function Ja(){Me()}import{z as u}from"zod";import*as E from"node:os";import{randomUUID as j}from"node:crypto";var Mt="X-VisIQ-SDK",$t="X-VisIQ-Dialect",Lt="unknown";function $e(e,t=1){return{[Mt]:e&&e.length>0?e:Lt,[$t]:String(t)}}var Pt="interceptor_source",ei=u.enum(["enforce","audit","off"]),ti=u.enum(["closed","open"]),Dt=u.enum(["enforce","monitor","off"]),ni=u.object({apiKey:u.string().min(1,"apiKey is required"),agentId:u.string().min(1,"agentId is required"),endpoint:u.string().url().optional(),mode:ei.optional(),timeoutMs:u.number().int().positive().optional(),hitlTimeoutMs:u.number().int().positive().optional(),failBehavior:ti.optional()}),to=u.object({agent_id:u.string().min(1),target_app:u.string().min(1),action:u.string().min(1),context:u.record(u.unknown()).optional(),session_id:u.string().min(1).max(255).optional(),action_schema_id:u.string().min(1).max(128).optional(),telemetry:u.record(u.unknown()).optional()}),ri=u.object({field:u.string().optional(),pattern:u.string().optional(),replacement:u.string().optional(),mode:u.enum(["full","partial","email"]).optional(),keepFirst:u.number().optional(),keepLast:u.number().optional(),maskChar:u.string().optional()}),ii=u.object({decision_id:u.string().min(1),decision:u.enum(["permit","deny","approval_required","mask"]),reason:u.string().optional(),rule_code:u.string().nullable().optional(),enforced:u.boolean().optional(),agent_mode:Dt.optional(),arg_redaction_rules:u.array(ri).optional(),plane:u.string().nullable().optional(),operation:u.string().nullable().optional(),is_retrieval:u.boolean().optional(),metadata:u.record(u.unknown()).optional()}),ai=u.object({field:u.string().min(1),operator:u.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:u.union([u.string(),u.number(),u.array(u.string())])}),oi=u.object({id:u.string().min(1),rule_code:u.string().default(""),name:u.string().min(1),description:u.string().nullable().default(null),effect:u.enum(["allow","deny","hitl","mask"]),resource_type:u.string().min(1),rego_source:u.string().default(""),target_app:u.string().nullable().default(null),action_pattern:u.string().nullable().default(null),conditions:u.array(ai).default([]),priority:u.number().int().default(0)}),si=u.object({version:u.string().min(1),agent_mode:Dt.optional(),rules:u.array(oi),no_coverage:u.object({no_coverage_defaults:u.record(u.string()),autopilot_enabled:u.boolean(),enduser_hitl_enabled:u.boolean(),hitl_timeout_seconds:u.number()}).optional()}),li=2e3,Le=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return $e(this.config.sdkVersion,this.config.sdkDialect)}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return ii.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json",...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();return si.parse(a)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let o=a,s=o.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof o.reason=="string"?o.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await ci(li)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function ci(e){return new Promise(t=>setTimeout(t,e))}function le(){let e={};try{let t=`${E.platform()} ${E.release()}`.trim();t&&(e.os=t)}catch{}try{let t=E.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=E.userInfo();t&&(e.username=t)}catch{}try{let t=di();t&&(e.ip=t)}catch{}return e}function di(){let e=E.networkInterfaces();for(let t of Object.keys(e))for(let n of e[t]??[])if((n.family==="IPv4"||n.family===4)&&!n.internal&&n.address)return n.address}function ui(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function oe(e,...t){for(let n of t){let r=ui(e[n]);if(r)return r}}function se(e){if(oe(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(oe(e,"user_id","userId"))return"user";if(oe(e,"agent_id","agentId"))return"agent";if(oe(e,"org_id","orgId","namespace"))return"org"}var pi=[{framework:"mem0",matches:e=>/^(mem0[_-])?(add|search|get|retrieve|update|delete)[_-]memor(y|ies)$/i.test(e),extract:(e,t)=>{let n=/^(?:mem0[_-])?([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"||n==="update"?r="write":r="read";let i=se(t);return{op:r,store:"mem0",framework:"mem0",...i?{scope:i}:{}}}},{framework:"letta",matches:e=>/^(core_memory_(append|replace)|archival_memory_(insert|search)|conversation_search)$/i.test(e),extract:e=>{let t=e.toLowerCase();return t.startsWith("core_memory_")?{op:"write",store:"letta-core",scope:"agent",framework:"letta"}:t==="archival_memory_insert"?{op:"write",store:"letta-archival",scope:"agent",framework:"letta"}:t==="archival_memory_search"?{op:"search",store:"letta-archival",scope:"agent",framework:"letta"}:{op:"search",store:"letta-conversation",scope:"session",framework:"letta"}}},{framework:"langgraph",matches:e=>/^(upsert_memory|save_recall_memory|search_recall_memories)$/i.test(e),extract:(e,t)=>{let n=/^search_/i.test(e),r=se(t);return{op:n?"search":"write",store:"langgraph-store",framework:"langgraph",...r?{scope:r}:{}}}},{framework:"zep",matches:e=>/^zep[_-](add|search|get|delete)[_-]memory$/i.test(e),extract:(e,t)=>{let n=/^zep[_-]([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"?r="write":r="read";let i=se(t)??"session";return{op:r,store:"zep",scope:i,framework:"zep"}}},{framework:"mcp-memory",matches:e=>/^(create_entities|create_relations|add_observations|delete_entities|delete_relations|delete_observations|search_nodes|open_nodes|read_graph)$/i.test(e),extract:e=>{let t=e.toLowerCase(),n;return t.startsWith("delete_")?n="delete":t==="search_nodes"?n="search":t==="open_nodes"||t==="read_graph"?n="read":n="write",{op:n,store:"mcp-memory",scope:"agent",framework:"mcp-memory"}}},{framework:"generic",matches:e=>/(^|[_\-.])(memory|memories|mem0|recall)([_\-.]|$)/i.test(e),extract:(e,t)=>{let n=e.toLowerCase(),r;/(^|[_\-.])(search|query|find|lookup|retrieve)([_\-.]|$)/.test(n)?r="search":/(^|[_\-.])(delete|remove|forget|clear|purge)([_\-.]|$)/.test(n)?r="delete":/(^|[_\-.])(add|save|write|store|upsert|put|set|update|insert|append|remember)([_\-.]|$)/.test(n)?r="write":r="read";let i=se(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function F(e,t){if(!e)return null;let n=t??{};for(let r of pi)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function Pe(e,t){let n=typeof t?.itemCount=="number"&&Number.isFinite(t.itemCount)&&t.itemCount>=0?Math.round(t.itemCount):void 0,r=typeof t?.bytes=="number"&&Number.isFinite(t.bytes)&&t.bytes>=0?Math.round(t.bytes):void 0,i=e.op==="read"||e.op==="search";return{op:e.op,store:e.store,...e.scope?{scope:e.scope}:{},...n!==void 0?{itemCount:n}:{},...r!==void 0?{bytes:r}:{},...i&&n!==void 0?{hit:n>0}:{}}}var xt=new Map;function q(e){let t=(xt.get(e)??0)+1;return xt.set(e,t),t}function Ft(e){if(!e||typeof e!="object")return;let t={};for(let n of["tokensIn","tokensOut","cacheRead","cacheWrite"]){let r=e[n];typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[n]=Math.round(r))}return Object.keys(t).length>0?t:void 0}function De(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=Array.isArray(n.texts)?n.texts.filter(o=>typeof o=="string"&&o.length>0).join(`
|
|
6
|
-
|
|
7
|
-
`):"",a=Ft(n.usage);e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:q(r),ts:Date.now(),kind:n.final?"speech":"thought",visibility:"shown",provenance:"narration",...i?{content:{text:i}}:{},...a?{cost:a}:{},...n.model?{model:n.model}:{},...typeof n.durationMs=="number"&&Number.isFinite(n.durationMs)?{durationMs:Math.max(0,Math.round(n.durationMs))}:{},...t.framework?{framework:t.framework}:{}})}function Fe(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:q(r),ts:Date.now(),kind:"spawn",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},spawn:{childAgentId:n.childAgentId,childName:n.childName,kind:n.kind,...n.model?{model:n.model}:{},...n.task?{prompt:n.task}:{}}})}function je(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=n.memory?Pe(n.memory):void 0;e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:q(r),ts:Date.now(),kind:i?"memory":"action",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},tool:{name:n.toolName,...n.verb?{verb:n.verb}:{},...n.argSummary?{argSummary:n.argSummary}:{}},...i?{memory:i}:{}})}function qe(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.round(c):void 0,a=i(n.bytes),o=i(n.itemCount),s=i(n.durationMs),l;n.memory&&(l=Pe(n.memory,{itemCount:o,bytes:a})),e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:q(r),ts:Date.now(),kind:"observation",visibility:"shown",provenance:"parsed",...s!==void 0?{durationMs:s}:{},...t.framework?{framework:t.framework}:{},tool:{name:n.toolName},result:{ok:n.ok,...a!==void 0?{bytes:a}:{},...o!==void 0?{itemCount:o}:{}},...l?{memory:l}:{}})}function Be(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId:j(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:q(r),ts:Date.now(),kind:"intervention",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},tool:{name:n.toolName},governance:{decision:n.decision,enforced:n.enforced,...n.ruleCode?{ruleCode:n.ruleCode}:{},...n.ruleLabel?{ruleLabel:n.ruleLabel}:{},...n.harnessMessage?{harnessMessage:n.harnessMessage}:{}}})}function ce(e){try{let t=JSON.stringify(e);return typeof t=="string"?t.length:void 0}catch{return}}function de(e){try{return Array.isArray(e)?e.length:void 0}catch{return}}import{z as p}from"zod";import{createHash as fi}from"crypto";import{createHash as ji}from"crypto";var jt=new Map;function qt(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function ze(e){let t=fi("sha256").update(e).digest("hex"),n=jt.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
|
|
8
|
-
`).map(l=>mi(l)).filter(l=>l.trim().length>0),o=0;for(;o<a.length;){let l=a[o].trim();if(l.startsWith("package ")||l.startsWith("import ")){o++;continue}let c=l.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(c){let m=c[1],g=c[2].trim();r.set(m,U(g)),o++;continue}let d=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(d){let m=d[1],g=d[2].trim(),_=d[3].trim(),v=[];if(_&&_!=="}"){let A=_.endsWith("}")?_.slice(0,-1).trim():_;A&&v.push(A),_.endsWith("}")||(o++,o=ue(a,o,v))}else _==="}"||(o++,o=ue(a,o,v));let h=Bt(v);i.push({variable:m,value:U(g),conditions:h,rawConditions:qt(v)}),o++;continue}let f=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(f){let m=f[1],g=f[2].trim(),_=[];if(g&&g!=="}"){let h=g.endsWith("}")?g.slice(0,-1).trim():g;h&&_.push(h),g.endsWith("}")||(o++,o=ue(a,o,_))}else g==="}"||(o++,o=ue(a,o,_));let v=Bt(_);i.push({variable:m,value:"true",conditions:v,rawConditions:qt(_)}),o++;continue}o++}let s={defaults:r,rules:i};return jt.set(t,s),s}function mi(e){let t=!1,n="";for(let r=0;r<e.length;r++){let i=e[r];if(t)i===n&&e[r-1]!=="\\"&&(t=!1);else if(i==='"'||i==="'")t=!0,n=i;else if(i==="#")return e.slice(0,r)}return e}function ue(e,t,n){let r=1,i=t;for(;i<e.length&&r>0;){let a=e[i].trim();for(let o of a)o==="{"&&r++,o==="}"&&r--;if(r>0)n.push(a),i++;else{let o=a.slice(0,a.lastIndexOf("}")).trim();return o&&n.push(o),i}}return i}function U(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function gi(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Bt(e){let t=[];for(let n of e){let r=n.split(";").map(i=>i.trim()).filter(i=>i.length>0);for(let i of r){let a=hi(i);a&&t.push(a)}}return t}function hi(e){let t=!1,n=e.trim();if(n.startsWith("not ")&&(t=!0,n=n.slice(4).trim()),n==="true"||n==="false")return{type:"literal_bool",negated:t,field:"",value:n==="true"};if(n.includes("[_]"))return{type:"truthy",negated:!1,field:me,value:e.trim()};let r=n.match(/^count\(([^)]+)\)\s*(>=|<=|>|<)\s*(\d+)$/);if(r)return{type:"count_gt",negated:t,field:r[1].trim(),operator:r[2],value:parseInt(r[3],10)};let i=n.match(/^startswith\(([^,]+),\s*"([^"]*)"\)$/);if(i)return{type:"startswith",negated:t,field:i[1].trim(),value:i[2]};let a=n.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(a)return{type:"endswith",negated:t,field:a[1].trim(),value:a[2]};let o=n.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"contains",negated:t,field:o[1].trim(),value:o[2]};let s=n.match(/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:gi(s[1])};let l=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s+in\s+((?:input|data)[^\s]*)$/);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:Qt(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let v=bi(c[2]);if(v!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:v}}let d=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(d)return{type:"comparison",negated:t,field:d[1].trim(),operator:d[2],value:parseFloat(d[3])};let f=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s*==\s*((?:input|data)\S*)$/);if(f)return{type:"equality",negated:t,field:f[2].trim(),value:U(f[1].trim())};let m=n.match(/^([^\s=!]+)\s*==\s*(.+)$/);if(m)return{type:"equality",negated:t,field:m[1].trim(),value:U(m[2].trim())};let g=n.match(/^([^\s=!]+)\s*!=\s*(.+)$/);if(g)return{type:"inequality",negated:t,field:g[1].trim(),value:U(g[2].trim())};let _=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return _?{type:"truthy",negated:t,field:_[1].trim()}:{type:"truthy",negated:!1,field:me,value:e.trim()}}var me="__unrecognized_condition_forces_deny__";var _i=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Wt(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==me&&_i.test(r.field)&&t.push(r.field);return t}var yi=["input.normalized.","input.normalized["];function Ht(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions){let{field:i}=r;typeof i!="string"||i===me||yi.some(a=>i.startsWith(a))&&t.add(i)}return[...t].sort()}function Qt(e){let t=e.trim();return t==="true"?!0:t==="false"?!1:/^-?\d+(?:\.\d+)?$/.test(t)?parseFloat(t):t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function bi(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",i=!1,a="";for(let s=0;s<t.length;s++){let l=t[s];i?(r+=l,l===a&&t[s-1]!=="\\"&&(i=!1)):l==='"'||l==="'"?(r+=l,i=!0,a=l):l===","?(n.push(r.trim()),r=""):r+=l}if(i)return null;r.trim().length>0&&n.push(r.trim());let o=[];for(let s of n){let l=s.startsWith('"')&&s.endsWith('"')&&s.length>=2||s.startsWith("'")&&s.endsWith("'")&&s.length>=2,c=/^-?\d+(?:\.\d+)?$/.test(s);if(!l&&!c&&!(s==="true"||s==="false"))return null;o.push(Qt(s))}return o}var vi=["tier1","tier2","tier3"];function Yt(e){return typeof e=="string"&&vi.includes(e)}var wi=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Ai=["internal","customer_facing","experimental","third_party"],Zt=[...wi,...Ai];function Ii(e){return typeof e=="string"&&Zt.includes(e)}function Jt(e){let t=new Set;for(let n of e)Ii(n)&&t.add(n);return Zt.filter(n=>t.has(n))}var Xt=["read_only","record_create","record_update","record_delete","data_export","data_share","data_subject_request","consent_change","funds_transfer","funds_disbursement","payroll_run","trade_execution","ledger_mutation","credit_decision","decision_adverse","account_restriction","account_closure","card_management","purchase_commitment","vendor_management","deal_management","pricing_change","contract_execution","legal_hold","regulatory_filing","personnel_action","employment_termination","compensation_change","campaign_send","content_publish","inventory_adjustment","order_fulfillment","account_servicing","credential_reset","access_grant","permission_change","credential_management","auth_policy_change","security_config_change","logging_change","alert_management","code_change","infrastructure_provision","deployment_change","communication_send","other"],ki=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],Si=["production","staging","development","test"],Ci=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function Ei(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return t.length>0?t:null}var Ut={github:"version_control",gitlab:"version_control",bitbucket:"version_control",stripe:"payments",adyen:"payments",braintree:"payments",paypal:"payments",square:"payments",salesforce:"crm",hubspot:"crm",pipedrive:"crm",slack:"communication",teams:"communication",twilio:"communication",sendgrid:"communication",mailgun:"communication",gmail:"communication",outlook:"communication",zoom:"communication",aws:"cloud_infra",gcp:"cloud_infra",azure:"cloud_infra",okta:"identity",auth0:"identity",entra:"identity",onelogin:"identity",duo:"identity",snowflake:"data_warehouse",bigquery:"data_warehouse",databricks:"data_warehouse",redshift:"data_warehouse",jira:"ticketing",zendesk:"ticketing",servicenow:"ticketing",freshdesk:"ticketing",linear:"ticketing",workday:"hr",bamboohr:"hr",gusto:"hr",netsuite:"finance_erp",quickbooks:"finance_erp",sap:"finance_erp",xero:"finance_erp",s3:"storage",gcs:"storage",dropbox:"storage",box:"storage",postgres:"database",postgresql:"database",mysql:"database",mongodb:"database",redis:"database"};function Ti(e){let t=Ei(e);return t===null?"other":Ut[t]??Ut[t.replace(/_/g,"")]??"other"}function en(e,t){let n={...e};if(t.targetApp!==void 0&&t.targetApp!==null){let r=n.context&&typeof n.context=="object"&&!Array.isArray(n.context)?{...n.context}:{};r.app_category===void 0&&(r.app_category=Ti(t.targetApp)),n.context=r}return n}var zt=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],Vt=["none","low","medium","high","critical"],Ni=["public","internal","confidential","restricted","credentials","api_key","private_key","password","secret","token","pan","full_pan","card_number","track_data","cvv","cvc","ssn","tax_id","national_id","passport","drivers_license","identity_document","document_number","kyc_document","bank_account","account_number","routing_number","iban","account_balance","customer_financial","credit_score","net_worth","income","financial_profile","employee_pii","payroll","compensation","material_nonpublic","pre_release_earnings","mnpi","attorney_client","legal_hold","privileged","special_category_gdpr","gdpr_special_category","biometric","ethnicity","political_opinion","health_special","religion"],Oi={action_class:Xt,"context/app_category":ki,"context/environment":Si,"context/actor_function":Ci,"read/classification":Ni,"read/data_categories":zt,"read/data_sensitivity":Vt,"write/data_categories":zt,"write/data_sensitivity":Vt};function tn(e){if(e===null||typeof e!="object")return[];let t=e,n=new Set,r=(i,a,o)=>{let s=Array.isArray(a)?a:[a];for(let l of s)typeof l!="string"||l.length===0||o.includes(l)||n.add(`${i}=${l}`)};for(let[i,a]of Object.entries(Oi)){Object.prototype.hasOwnProperty.call(t,i)&&r(i,t[i],a);let o=i.indexOf("/");if(o===-1)continue;let s=t[i.slice(0,o)];if(s!==null&&typeof s=="object"&&!Array.isArray(s)){let l=i.slice(o+1),c=s;Object.prototype.hasOwnProperty.call(c,l)&&r(i,c[l],a)}}return[...n].sort()}var Gt=64,Ri=64,z={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function nn(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var xi=new Set(["deny","approval_required","escalate"]);function B(e,t){if(t.length===0)return[...e];let n=new Set(e);for(let i of t)n.add(i);let r=[...n].sort();return r.length>Gt?r.slice(0,Gt):r}function Kt(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function pe(e){return typeof e=="string"&&e.length>0?e:null}function rn(e,t){let n=Kt(t.data_categories),r=pe(t.classification),i=Kt(t.taint),a=pe(t.action_class),o=a&&Xt.includes(a)?a:null,s=pe(t.target_app),l=pe(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<Ri)c[o]=1;else{let d=Object.keys(c).sort(),f=d[d.length-1];f!==void 0&&o<f&&(delete c[f],c[o]=1)}return{retrieved_data_categories:B(e.retrieved_data_categories,n),retrieved_classifications:B(e.retrieved_classifications,r?[r]:[]),taint:B(e.taint,i),action_classes:B(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&xi.has(l)?1:0),event_count:e.event_count+1,target_apps:B(e.target_apps,s?[s]:[])}}var an={minEvents:12,minClasses:3,concentrationSigma:2,dominanceRatio:4,dominanceShare:.5,frictionRatio:.75,minFrictionEvents:6};function Mi(e){let t=null,n=0;for(let r of Object.keys(e).sort()){let i=Math.max(0,e[r]??0);i>n&&(n=i,t=r)}return{label:t,count:n}}function Ue(e){let t=e.length;if(t===0)return 0;let n=t>>1;return t%2===1?e[n]:(e[n-1]+e[n])/2}function fe(e){return Number.isFinite(e)?Math.round(e*1e3)/1e3:0}var $i=.5;function Li(e){let t=e.length;if(t===0)return 0;let n=[...e].sort((s,l)=>s-l),r=Ue(n),i=n[t-1],a=n.map(s=>Math.abs(s-r)).sort((s,l)=>s-l),o=Ue(a);return o>0?.6745*(i-r)/o:i===r?0:.6745*(i-r)/$i}function Ve(e,t){let n={...an,...t.config},r=e.action_counts??{},i=Math.max(0,e.event_count??0),a=Math.max(0,e.denied_count??0),o=Math.max(0,e.inhibited_count??0),s=Mi(r),l={};for(let y of Object.keys(r).sort()){let b=Math.max(0,r[y]??0);b>0&&(l[y]=b)}let c=Object.values(l),d=c.reduce((y,b)=>y+b,0),f=[...c].sort((y,b)=>y-b),m=Ue(f),g=Li(c),_=m>0?s.count/m:0,v=d>0?s.count/d:0,h=i>0?(a+o)/i:0,A={action_class:null,repeats:s.count,event_count:i,denied_count:a,inhibited_count:o,class_count:c.length,class_counts:l,concentration_score:fe(g),dominance_ratio:fe(_),dominance_share:fe(v),friction_score:fe(h),signals:[]};if(i<n.minEvents)return{verdict:"allow",signals:[],evidence:A};let k=[],S=null;return c.length>=n.minClasses&&g>=n.concentrationSigma&&_>=n.dominanceRatio&&v>=n.dominanceShare&&(k.push("concentration"),S=s.label),h>=n.frictionRatio&&a+o>=n.minFrictionEvents&&k.push("friction"),k.length===0?{verdict:"allow",signals:[],evidence:A}:{verdict:t.failMode==="closed"?"deny":"hold",signals:[...k],evidence:{...A,action_class:S,signals:[...k]}}}var on="generic",sn=[{id:"finance_accounting",name:"Finance & Accounting",icon:"Landmark",description:"Payments, invoicing, ledgers, transactions, refunds, financial reporting, SOX/AML/KYC controls."},{id:"hr",name:"Human Resources",icon:"Users",description:"Employee records, payroll, hiring/recruiting, benefits, personnel actions and PII of staff."},{id:"engineering",name:"Engineering",icon:"Code",description:"Source code, build/deploy pipelines, infrastructure changes, production systems and developer tooling."},{id:"it_security",name:"IT & Security",icon:"ShieldCheck",description:"Credentials, secrets, access control, configuration, threat/exfiltration prevention and security operations."},{id:"legal",name:"Legal",icon:"Scale",description:"Contracts, NDAs, litigation, counsel communications and legal-hold material."},{id:"privacy_compliance",name:"Privacy & Compliance",icon:"BadgeCheck",description:"GDPR/CCPA/HIPAA, consent, data-subject rights, special-category data and regulatory data handling."},{id:"sales",name:"Sales",icon:"TrendingUp",description:"CRM, leads, deals, quotes, pipeline and customer commercial relationships."},{id:"marketing",name:"Marketing",icon:"Megaphone",description:"Campaigns, content, brand, social channels and prospect/audience data."},{id:"operations",name:"Operations",icon:"Cog",description:"Business operations, logistics, internal workflows, vendor/ops tooling and process automation."},{id:"customer_support",name:"Customer Support",icon:"LifeBuoy",description:"Support tickets, customer communications, account servicing and help-desk actions."},{id:"procurement",name:"Procurement",icon:"ShoppingCart",description:"Purchasing, supplier management, purchase orders, sourcing and spend approvals."},{id:on,name:"Generic",icon:"Shapes",description:"Catch-all for cross-cutting rules or rules that do not fit a specific function. Assign when no specific function clearly applies."}],Pi=sn.map(e=>e.id),oo=new Map(sn.map(e=>[e.id,e])),so=new Set(Pi);function ln(e){return Array.isArray(e)&&e.length>0?[...e]:[on]}var Di=/^[a-z][a-z0-9_]*$/;function cn(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Di.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Fi=["narrow","moderate","broad","unbounded","unknown"];function dn(e){return typeof e=="string"&&Fi.includes(e)}function un(e){return e==="open"||e==="closed"?e:null}var qi=["tool_name","function","name","action"];function ge(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)ge(r,`${t}[]`,n);return}if(e!==null&&typeof e=="object"){let r=Object.entries(e);if(r.length===0){t&&n.push([t,void 0]);return}for(let[i,a]of r)ge(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Bi(e){let t=[];return ge(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function Ui(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function zi(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function Vi(e,t={}){if(t.discriminatorField===null)return null;let n=[];ge(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??qi;for(let i of r){let a=null;for(let[o,s]of n){if(Ui(o)!==i)continue;let l=zi(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function pn(e,t={}){let n=ji("sha256").update(Bi(e).join(",")).digest("hex").slice(0,16),r=Vi(e,t);return r!==null?`${n}:${r}`:n}var Gi=["action","retrieval","delegation"];function Ki(e){return typeof e=="string"&&Gi.includes(e)}var Wi=new Set(["rules"]);function fn(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Wi.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Ki):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{z as he}from"zod";var mn=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Hi(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:mn(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:mn(t.spawn.prompt)}),t}function Qi(e,t=process.env){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let n=t.ALLOW_TIMEOUT_MS;if(n!==void 0){let r=Number.parseInt(n,10);if(Number.isFinite(r)&&r>0)return r}return 5e3}var Yi=1440*60*1e3,Zi="VISIQ_BUNDLE_GRACE_TTL_MS",Ji="VISIQ_BUNDLE_CACHE_DISABLED",Xi="VISIQ_CACHE_DIR",ea=he.object({graceTtlMs:he.number().int().nonnegative().optional(),disabled:he.boolean().optional(),cacheDir:he.string().min(1).optional()}).strict();function ta(e){return e==null?{}:ea.parse(e)}function na(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Zi];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Yi}function ra(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Ji]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var gn;function ia(){if(gn!==void 0)return gn;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function aa(e){return JSON.stringify(Ke(e))}function Ke(e){if(Array.isArray(e))return e.map(Ke);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Ke(t[r]);return n}return e}function oa(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function sa(e){if(e!==null&&typeof e=="object"&&typeof e.fetchedAt=="number"&&typeof e.contentHash=="string"&&"body"in e){let t=e;return{fetchedAt:t.fetchedAt,version:typeof t.version=="string"?t.version:null,contentHash:t.contentHash,body:t.body}}return null}async function An(){if(!ia())return null;try{let[e,t,n,r]=await Promise.all([import("node:fs/promises"),import("node:path"),import("node:os"),import("node:crypto")]);return{fs:e,path:t,os:n,crypto:r}}catch{return null}}function In(e,t){return e.createHash("sha256").update(aa(t)).digest("hex")}function la(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Xi]?.trim();if(r)return r;let i=process.env.XDG_CACHE_HOME?.trim();if(i)return e.path.join(i,"visiq");let a="";try{a=e.os.homedir()}catch{a=""}return a?e.path.join(a,".cache","visiq"):e.path.join(e.os.tmpdir(),"visiq-cache")}function ca(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function kn(e,t,n){return e.path.join(la(e,n),"bundles",`${ca(e,t)}.json`)}async function da(e,t,n,r={}){let i=await An();if(i)try{let a=kn(i,e,r),o=i.path.dirname(a);await i.fs.mkdir(o,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:In(i.crypto,t),body:t},l=`${a}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(l,JSON.stringify(s),{mode:384});try{await i.fs.rename(l,a)}catch(c){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),c}}catch{}}async function ua(e,t={}){let n=await An();if(!n)return null;try{let r=await n.fs.readFile(kn(n,e,t),"utf-8"),i=sa(JSON.parse(r));return!i||In(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var V;async function pa(){if(V!==void 0)return V;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;V=typeof t=="function"?t:null}catch{V=null}return V}function fa(e){let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,i=r.rego_source;if(typeof i!="string"||i.length===0)continue;let a;try{a=ze(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of Wt(a))t.push(`${o}: ${s}`)}return t}function ma(e){let t=new Set;for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,i=r.rego_source;if(typeof i!="string"||i.length===0)continue;let a;try{a=ze(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of Ht(a))t.add(`${o}: ${s}`)}return[...t].sort()}function ga(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var ha=5e3,_a=1e4,ya=25,hn=1e3,ba=5e3,va=100,_n=2e3,wa=512,Aa=1800*1e3,Ia=.7,ka="monitor",Sa="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",yn="Rules bundle requires a newer SDK wire-contract dialect than this SDK supports \u2014 refusing the bundle and blocking all actions (fail-closed, G001). Upgrade the VisIQ SDK.",Ca="open";function bn(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Ea(e,t){return vt({content:e,resourceMetadata:t})}var Ta=p.object({operations:p.array(p.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:p.string().min(1,"agentId is required"),sessionId:p.string().min(1).max(255).optional(),toolName:p.string().optional(),toolArgs:p.record(p.unknown()).optional(),targetResource:p.string().optional(),resourceType:p.string().optional(),resourceMetadata:p.record(p.unknown()).optional(),normalized:p.record(p.unknown()).optional(),query:p.string().optional(),contentPreview:p.string().optional(),telemetry:p.record(p.unknown()).optional(),context:p.record(p.unknown()).optional(),mcpServer:p.string().min(1).max(255).optional()}),Na=p.object({version:p.string().min(1),dialect_version:p.number().int().optional(),min_dialect:p.number().int().optional(),shutdown:p.boolean().optional(),agent_mode:p.enum(["enforce","monitor","off"]).optional(),cognition_capture:p.boolean().optional(),agent_mode_by_operation:p.object({action:p.string().optional(),retrieval:p.string().optional(),delegation:p.string().optional()}).partial().optional(),agent_attributes:p.object({trust_tier:p.string().nullable().optional(),categories:p.array(p.string()).optional(),business_function:p.string().nullable().optional(),business_functions:p.array(p.string()).nullable().optional(),blast_radius_tier:p.string().nullable().optional(),no_coverage:p.string().nullable().optional(),fail_mode:p.string().nullable().optional()}).optional(),rules:p.array(p.record(p.unknown())),action_schemas:p.array(p.object({id:p.string(),plane:p.string().optional(),field_mappings:p.array(p.record(p.unknown())).optional(),derived_fields:p.array(p.record(p.unknown())).optional(),action_class:p.string().nullable().optional(),action_class_confidence:p.number().optional()})).optional(),no_coverage:p.object({no_coverage_defaults:p.record(p.string()),autopilot_enabled:p.boolean(),enduser_hitl_enabled:p.boolean(),hitl_timeout_seconds:p.number().optional()}).optional()});function Oa(e){let t=e.trust_tier??null,n=[];Array.isArray(e.business_functions)&&e.business_functions.length>0?n=e.business_functions:typeof e.business_function=="string"&&e.business_function!==""&&(n=[e.business_function]);let r=ln(cn(n));return{trust_tier:Yt(t)?t:null,categories:Jt(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&dn(e.blast_radius_tier)?e.blast_radius_tier:null}}function Ra(e){if(!e)return null;let t={};for(let n of["action","retrieval","delegation"]){let r=e[n];(r==="enforce"||r==="monitor"||r==="off")&&(t[n]=r)}return Object.keys(t).length>0?t:null}function xa(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var We=new Set,vn=!1;async function wn(e){let t=[];for(let n of We){if(n.pendingTelemetryCount()>0&&!n.hasBackend()){console.warn(`[UnifiedRuntime] exiting with ${n.pendingTelemetryCount()} un-sent decision(s) and no backend \u2014 telemetry lost.`);continue}let r=n.flush();e&&t.push(r)}t.length>0&&await Promise.allSettled(t)}function Ma(){if(!vn&&!(typeof process>"u"||typeof process.once!="function")){vn=!0,process.once("beforeExit",()=>{wn(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await wn(!0)}finally{process.kill(process.pid,e)}})()})}}var Sn=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;cacheIdentity;bundleCacheDisabled;bundleGraceTtlMs;bundleCacheDirOverride;diskFallbackServed=!1;agentMode=ka;agentModeByOperation=null;rawBundle=null;normalizedRefs=[];warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=bn(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Ca;governedFailMode=null;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastCloneCaptureSig=null;toolDescriptions=new Map;constructor(e,t,n,r,i,a,o,s){let l=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,c=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,d=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=l,this.resolvedEndpoint=c,this.resolvedAgentId=d,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=o,this.originalFetch=globalThis.fetch.bind(globalThis);let f=ta(s);if(this.bundleCacheDisabled=ra(f.disabled),this.bundleGraceTtlMs=na(f.graceTtlMs),this.bundleCacheDirOverride=f.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:d,apiKey:l}:null,l&&c){let m={apiKey:l,agentId:d,endpoint:c,mode:"enforce",timeoutMs:Qi(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new Le(m,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},ha),Ge(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},_a),Ge(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},ba),Ge(this.cognitionTimer),We.add(this),Ma()}else this.client=null}async evaluate(e){let t=Ta.parse(e),n=Date.now();if(this.operatorShutdown){let m=this.denyAll(t,Sa);return this.applyAgentMode(m,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,yn,n);let m=this.denyAll(t,yn);return this.applyAgentMode(m,"enforce",t,n)}if(t.operations.every(m=>this.modeFor(m)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let m;if(this.agentModeConfirmed?m=this.agentMode:this.bundleApplyFailed?m="enforce":m="monitor",m==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let g=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(g,m,t,n)}let r=this.readSession(t.sessionId),i=await pa();if(!i||!this.rawBundle){if(this.failMode==="open")return this.failOpen(t,"governance core (@visiq/core-wasm) unavailable",n);throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)")}let a=t.operations.includes("action")||t.operations.includes("delegation")?en(t.normalized??{},{targetApp:t.targetResource??t.toolName??""}):t.normalized,o=this.buildActionSchemaEvent(t),s=t.mcpServer?{...a??{},mcp_server:t.mcpServer}:a,l={...t,normalized:s,session:r,at:Date.now(),action_schema_id:o.id,action_schema_raw:o.canonical},c={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},d;try{d=i(l,c)}catch(m){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${m instanceof Error?m.message:String(m)}`,n);throw m}this.normalizedRefs.length>0&&ga(t.normalized)&&(d.normalizedColdStart=[...this.normalizedRefs],this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${this.normalizedRefs.length} loaded rule condition(s) read input.normalized.* \u2014 those conditions CANNOT match, so a deny carrying one silently permits. Cold start / no action-schema mapping yet. Affected: ${this.normalizedRefs.slice(0,5).join("; ")}${this.normalizedRefs.length>5?`; +${this.normalizedRefs.length-5} more`:""}`)));let f=tn(t.normalized);return f.length>0&&(d.normalizedDrift=f,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${f.length} value(s) outside the canonical vocabulary \u2014 a builder-authored rule can only select in-vocab values, so these CANNOT match one (silent non-match). Check the harness classifier's casing/spelling. Affected: ${f.slice(0,5).join("; ")}${f.length>5?`; +${f.length-5} more`:""}`))),this.foldSession(t,d.enforced?d.decision:"permit"),d.enforced&&d.action.decision==="approval_required"&&await this.registerHitl(t,d),this.bufferTelemetry(t,d,Date.now()-n,d.enforced),d}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return z;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Aa?(this.sessions.delete(e),z):t.state:z}foldActionClass(e){let t=e.normalized?.action_class;if(typeof t=="string"&&t.length>0)return t;let n=this.rawBundle?.action_schemas;if(!Array.isArray(n))return;let{id:r}=this.buildActionSchemaEvent(e),i=n.find(s=>s?.id===r);if(!i)return;let a=i.action_class,o=typeof i.action_class_confidence=="number"?i.action_class_confidence:0;if(typeof a=="string"&&a.length>0&&o>=Ia)return a}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),o=e.operations.includes("action")||e.operations.includes("delegation"),s=rn(r===z?nn():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?Ea(e.contentPreview,i):void 0,action_class:o?this.foldActionClass(e):void 0,target_app:o?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>wa){let l=this.sessions.keys().next().value;l!==void 0&&this.sessions.delete(l)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let o={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,o,i,!0),o}let a={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,a,i,!1),a}setFailMode(e){this.failMode=e}getFailMode(){return this.failMode}getGovernedFailMode(){return this.governedFailMode}failOpen(e,t,n){let r=`fail-open: ${t} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`;console.error(`[VisIQ] FAIL-OPEN: ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`);let i=e.operations.includes("action")||e.operations.includes("delegation"),a=e.operations.includes("retrieval"),o={decision:"permit",allowed:!0,reason:r,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:i?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:a?{action:"allow"}:{action:null},failOpen:!0};return this.bufferTelemetry(e,o,Date.now()-n,!1,!0),o}reportFailOpen(e,t){try{let n={operations:["action"],agentId:this.resolvedAgentId,...t?.toolName?{toolName:t.toolName}:{},...t?.sessionId?{sessionId:t.sessionId}:{}},r={decision:"permit",allowed:!0,reason:`fail-open: ${e} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:{decision:"permit",allowed:!0},retrieval:{action:null},failOpen:!0};this.bufferTelemetry(n,r,0,!1,!0)}catch{}}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},action_schema_id:this.buildActionSchemaEvent(e).id,...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=Na.parse(e);this.bundleApplyFailed=!1;let n=this.sdkDialect??1;if(t.min_dialect!==void 0&&t.min_dialect>n){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle requires dialect ${t.min_dialect} but this SDK speaks ${n} \u2014 refusing the bundle and failing closed (deny-all, G001). Upgrade the VisIQ SDK.`);return}let r=fa(t.rules);if(r.length>0){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle contains rego_source using a builtin the engine cannot evaluate (would silently never match \u2192 fail open): ${r.join("; ")}. Refusing the bundle and failing closed (G001). Recompile the rule without case-folding wrappers like upper()/lower().`);return}this.dialectRefused=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(i=>fn(i)).filter(i=>i!==null),this.agentAttributes=t.agent_attributes?Oa(t.agent_attributes):null,this.agentNoCoverage=un(t.agent_attributes?.no_coverage),this.governedFailMode=bn(t.agent_attributes?.fail_mode)??null,this.bundleVersion=t.version,this.bundleLoaded=!0,this.noCoverage=t.no_coverage?{no_coverage_defaults:t.no_coverage.no_coverage_defaults,autopilot_enabled:t.no_coverage.autopilot_enabled,enduser_hitl_enabled:t.no_coverage.enduser_hitl_enabled}:null,t.agent_mode!==void 0&&(this.agentMode=t.agent_mode,this.agentModeConfirmed=!0),this.agentModeByOperation=Ra(t.agent_mode_by_operation),process.env.VISIQ_COGNITION_CAPTURE==="1"?this.cognitionEnabled=!0:typeof t.cognition_capture=="boolean"&&(this.cognitionEnabled=t.cognition_capture),this.operatorShutdown=t.shutdown===!0,this.normalizedRefs=ma(t.rules),this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1,this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json",...$e(this.sdkVersion,this.sdkDialect)};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let a=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&a?this.bundleEtag=r:a||(this.bundleEtag=null),a&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await ua(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(oa(e,this.bundleGraceTtlMs,t)){try{this.applyBundle(e.body)}catch{return}if(this.bundleLoaded&&!this.dialectRefused&&!this.diskFallbackServed){this.diskFallbackServed=!0;let n=Math.max(0,Math.round((t-e.fetchedAt)/1e3)),r=Math.round(this.bundleGraceTtlMs/1e3);console.warn(`[UnifiedRuntime] serving cached rules bundle (age ${n}s) \u2014 control plane unreachable on cold start; will keep retrying and fail closed once the cache exceeds the ${r}s grace window.`)}}}async persistBundleToDisk(e){this.bundleCacheDisabled||!this.cacheIdentity||await da(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}isBundleLoaded(){return this.bundleLoaded}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e,t){this.registerEnvironment({...le(),...e?{agent_type:e}:{},...t?.model?{model:t.model}:{},...t?.systemPrompt?{systemPrompt:t.systemPrompt}:{},...t?.toolSchemas&&t.toolSchemas.length>0?{toolSchemas:t.toolSchemas}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));for(let n of e)n.description&&this.toolDescriptions.set(n.name,n.description);t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}captureCloneMetadata(e){if(!this.client||!this.resolvedAgentId||!(e.model||e.systemPrompt||(e.toolSchemas?.length??0)>0))return;let t=JSON.stringify({m:e.model??"",s:e.systemPrompt??"",t:e.toolSchemas??[]});t!==this.lastCloneCaptureSig&&(this.lastCloneCaptureSig=t,this.client.registerEnvironment({...le(),...e.agentType?{agent_type:e.agentType}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{toolSchemas:e.toolSchemas}:{}}))}buildActionSchemaEvent(e){let t=e.toolName?this.toolDescriptions.get(e.toolName):void 0,n={agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{},...e.toolArgs?{tool_args:e.toolArgs}:{},...t?{tool_description:t}:{}},r=pn(n),i={...n};return e.toolArgs&&(i.tool_args=ut(e.toolArgs)),{canonical:n,id:r,rawEventForWire:i}}bufferTelemetry(e,t,n,r,i=!1){let a=this.buildActionSchemaEvent(e);this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:r?xa(t.decision):"permit",reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:a.rawEventForWire,action_schema_id:a.id,...this.harnessKind||e.context||i||t.normalizedColdStart||t.normalizedDrift?{context:{...this.harnessKind?{[Pt]:this.harnessKind}:{},...e.context??{},...i?{fail_open:!0}:{},...t.normalizedColdStart?{normalized_cold_start:!0,normalized_inert_conditions:t.normalizedColdStart.length}:{},...t.normalizedDrift?{normalized_drift:!0,normalized_drift_values:t.normalizedDrift.length}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=ya&&this.flushTelemetry()}pendingTelemetryCount(){return this.telemetryBuffer.length}hasBackend(){return this.client!==null}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0);try{await this.client.sendTelemetry(e)}catch(t){console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",t)}}enforceTelemetryCap(){let e=this.telemetryBuffer.length-hn;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${hn})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Hi(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=va&&this.flushCognition())}async flushCognition(){if(this.cognitionBuffer.length===0||!this.client)return;let e=this.cognitionBuffer.splice(0);try{await this.client.sendCognition(void 0,e)}catch(t){console.error("[UnifiedRuntime] cognition flush failed (non-fatal):",t)}}enforceCognitionCap(){let e=this.cognitionBuffer.length-_n;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${_n})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),We.delete(this)}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.cognitionTimer&&(clearInterval(this.cognitionTimer),this.cognitionTimer=null),this.flushTelemetry(),this.flushCognition()}};function Ge(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function G(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Cn(e,t){if(e!=="sessions_spawn")return null;let n=G(t.agentId);return n?{childAgentId:n,childName:G(t.taskName)??G(t.label)??n,kind:"subagent",task:G(t.task),model:G(t.model),source:"structural"}:null}function En(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}var x=null;function C(e){let t=`${e.apiKey}::${e.agentId}::${e.baseUrl??""}`;if(x&&x.key===t)return x.runtimes;let n=new Sn(e.apiKey,e.baseUrl,e.agentId,"cli_harness");return n.setFailMode(e.failMode),n.registerHostEnvironment(),x={key:t,runtimes:{unified:n}},x.runtimes}async function Ao(){if(x)try{await x.runtimes.unified.flush()}catch{}}async function Io(e){try{let t=await re();if(!t)return;let{unified:n}=C(t);await n.awaitBundleReady(e)}catch{}}function Tn(){return x?.runtimes.unified.getAgentMode()}function I(e){try{process.stderr.write(`[VisIQ] FAIL-OPEN (${e.stage}): ${e.detail} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.
|
|
9
|
-
`)}catch{}if(e.config)try{C(e.config).unified.reportFailOpen(`${e.stage}: ${e.detail}`,{...e.toolName?{toolName:e.toolName}:{},...e.sessionId?{sessionId:e.sessionId}:{}})}catch{}}function K(e,t,n){try{let r=n instanceof Error?n.message:String(n);process.stderr.write(`[VisIQ] TRACE-DEGRADED (${e}) for tool "${t}": ${r} \u2014 the governance decision was still made and enforced; only the execution-trace beat was lost.
|
|
10
|
-
`)}catch{}}function O(e,t){return e?.sessionKey??t?.sessionKey??t?.sessionId??"default"}var He=class{entries=new Map;set(t,n){this.entries.set(t,n)}get(t){return this.entries.get(t)}delete(t){this.entries.delete(t)}clear(){this.entries.clear()}size(){return this.entries.size}},Qe=new Map;function L(e){let t=Qe.get(e);return t||(t=new He,Qe.set(e,t)),t}function Nn(e){Qe.delete(e)}var On=new Set(["web_search","x_search","web_fetch","tool_search","tool_describe","get_account","get_transactions","get_devices","check_watchlist","search_knowledge"]);function Rn(e){return On.has(Ie(e))}function No(){return On}var Ye="@visiq/openclaw-plugin";function xn(e){let t=[],n=[],r;for(let a of e){let{field:o,pattern:s,replacement:l}=a;o&&t.push(o),s&&n.push(s),l&&r===void 0&&(r=l)}let i={};return t.length>0&&(i.fields=t),n.length>0&&(i.patterns=n),r!==void 0&&(i.replacement=r),i}async function Go(e,t){let{config:n,failMode:r}=await ie();if(!n){if(r==="closed")return{block:!0,blockReason:"[VisIQ] Plugin is loaded but NOT configured \u2014 VisIQ cannot govern this tool call. Set VISIQ_API_KEY + VISIQ_AGENT_ID (and optionally VISIQ_ENDPOINT), or the plugin config, then retry. Blocked because VISIQ_FAIL_MODE=closed."};I({stage:"unconfigured",detail:"no VisIQ credentials resolved (need VISIQ_API_KEY + VISIQ_AGENT_ID)",toolName:e.toolName,sessionId:O(e,t)});return}let i=C(n),a=n.agentId??t.agentId,o=O(e,t),s=t.toolCallId??e.toolCallId,c=Rn(e.toolName)?["retrieval","action"]:["action"],d=$a(e.params),f=Cn(e.toolName,e.params??{}),m;f&&a&&(Fe(i.unified,{agentId:a,sessionId:o,framework:"openclaw"},f),c.push("delegation"),m=En(f,a));let g=a?{agentId:a,sessionId:o,framework:"openclaw"}:null,_=F(e.toolName,e.params??{});if(g)try{je(i.unified,g,{toolName:e.toolName,..._?{memory:_}:{}})}catch(y){K("step-beat",e.toolName,y)}let v=(y,b,M,T)=>{if(g)try{Be(i.unified,g,{toolName:e.toolName,decision:y,...b?{ruleCode:b}:{},...M?{ruleLabel:M}:{},enforced:!0,...T?{harnessMessage:T}:{}})}catch(N){K("intervention-beat",e.toolName,N)}},h;try{if(await i.unified.awaitBundleReady(),!i.unified.isBundleLoaded()&&n.failMode!=="closed"){I({stage:"no-bundle",detail:"no rule bundle available after warm-up",toolName:e.toolName,sessionId:o,config:n});return}h=await i.unified.evaluate({operations:c,agentId:a,sessionId:o,toolName:e.toolName,toolArgs:e.params??{},resourceType:"tool_result",resourceMetadata:{toolName:e.toolName,runId:e.runId??t.runId},...d!==void 0?{query:d}:{},...m?{context:m}:{}})}catch(y){let b=y instanceof Error?y.message:String(y);if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ] Evaluation error \u2014 blocked (VISIQ_FAIL_MODE=closed): ${b}`};I({stage:"eval-error",detail:b,toolName:e.toolName,sessionId:o,config:n});return}if(!h.enforced)return;let{action:A}=h;if(A.decision==="approval_required")return v("approval_required",h.ruleCode??void 0,h.reason),{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:h.reason,severity:"critical",allowedDecisions:["allow-once","allow-always","deny"],pluginId:Ye}};if(!A.allowed){let b=`[VisIQ ${h.ruleCode??"DENY"}] ${h.reason}`;return v("deny",h.ruleCode??void 0,h.reason,b),{block:!0,blockReason:b}}let k;if(A.decision==="mask"&&A.argRedactionRules&&A.argRedactionRules.length>0)try{k=J(e.params??{},xn(A.argRedactionRules)),v("mask",h.ruleCode??void 0,h.reason)}catch(y){let b=y instanceof Error?y.message:String(y);if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ] Argument masking failed \u2014 blocked (VISIQ_FAIL_MODE=closed): ${b}`};I({stage:"mask-error",detail:`argument masking failed \u2014 running with UNMASKED params: ${b}`,toolName:e.toolName,sessionId:o,config:n}),k=void 0}if(c.includes("retrieval"))switch(h.retrieval.action){case"allow":case null:break;case"deny":{let y=`[VisIQ RECALL] ${h.reason}`;return v("deny",h.ruleCode??void 0,h.reason,y),{block:!0,blockReason:y}}case"redact":{if(!s){if(n.failMode==="closed")return{block:!0,blockReason:"[VisIQ RECALL] Redact decision but no toolCallId \u2014 blocked (VISIQ_FAIL_MODE=closed)"};I({stage:"redact-no-toolcallid",detail:"redact decision could not be applied (no toolCallId to correlate the result)",toolName:e.toolName,sessionId:o,config:n});break}let y=h.retrieval.redactionRules??[];y.length>0&&L(o).set(s,xn(y));break}case"escalate":return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:h.reason,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:Ye}};default:{let y=h.retrieval.action;if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ RECALL] Unknown action "${String(y)}" \u2014 blocked (VISIQ_FAIL_MODE=closed)`};I({stage:"unknown-retrieval-verb",detail:`unknown retrieval action "${String(y)}" (harness/backend version skew)`,toolName:e.toolName,sessionId:o,config:n});break}}if(ke(e.toolName)){let y=n.failMode==="closed"?"closed":"open",b=k??e.params??{},M=!1,T=Q(b,{failMode:y});if(T.verdict==="block")return{block:!0,blockReason:`[VisIQ OUTPUT-BLOCK] outbound content carried a live secret (${T.detectors.join(",")}) \u2014 blocked (VISIQ_FAIL_MODE=closed)`};T.verdict==="redact"&&(b=T.redacted,M=!0,I({stage:"outbound-secret-redacted",detail:`outbound secret screen redacted ${T.detectors.length} detector(s): ${T.detectors.join(",")}`,toolName:e.toolName,sessionId:o,config:n}));let N=Z(b,{failMode:y});if(N.verdict==="block")return{block:!0,blockReason:`[VisIQ OUTPUT-BLOCK] outbound content matched a brand/topic rule (${N.matched.join(",")}) \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(N.verdict==="redact"&&(b=N.redacted,M=!0,I({stage:"outbound-brand-topic-redacted",detail:`outbound brand/topic screen redacted ${N.matched.length} rule(s): ${N.matched.join(",")} (recommended: ${N.recommendedOutcome??"none"})`,toolName:e.toolName,sessionId:o,config:n})),M)return{params:b}}if((n.sequenceAnomaly?.enabled??!0)&&typeof i.unified.getSessionState=="function"&&o){let y=i.unified.getSessionState(o),b=Ve(y,{failMode:n.failMode==="closed"?"closed":"open",config:n.sequenceAnomaly?.thresholds});if(b.verdict==="deny")return{block:!0,blockReason:`[VisIQ ANOMALY] session-sequence anomaly (${b.signals.join(",")}) over ${b.evidence.event_count} events \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(b.verdict==="hold")return I({stage:"sequence-anomaly-hold",detail:`session-sequence anomaly held for approval (${b.signals.join(",")}) over ${b.evidence.event_count} events`,toolName:e.toolName,sessionId:o,config:n}),{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:`A behavioral sequence anomaly was detected in this session (${b.signals.join(",")}). Approve to proceed, or deny to stop the run.`,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:Ye}}}if(k)return{params:k}}function $a(e){if(e)for(let t of["query","q","url","prompt"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}}function Xo(e,t){let{ready:n,config:r}=ae();if(!n||!r)return;let i=O(e,t),a=e.toolName??t.toolName,o=r.agentId??t.agentId;if(a&&o)try{let f=e.message?.content,m=F(a);qe(C(r).unified,{agentId:o,sessionId:i,framework:"openclaw"},{toolName:a,ok:!0,...ce(f)!==void 0?{bytes:ce(f)}:{},...de(f)!==void 0?{itemCount:de(f)}:{},...m?{memory:m}:{}})}catch(f){K("observation-beat",a,f)}let s=e.toolCallId??t.toolCallId;if(!s)return;let l=L(i),c=l.get(s);if(!c)return;let d={...e.message};return d.content!==void 0&&(d.content=J(d.content,c)),l.delete(s),{message:d}}function P(e,t){return e?.sessionKey||e?.sessionId||t?.sessionKey||t?.sessionId||void 0}var Ze=new Map;function Mn(e,t){e&&Ze.set(e,t)}function $n(e){return e?Ze.get(e):void 0}function Ln(e){e&&Ze.delete(e)}function ls(e,t){let{ready:n,config:r,failMode:i}=ae();if(n&&!r)return;let a=O(e,t),o=L(a);if(o.size()>0){if(o.clear(),i==="closed")return{block:!0};I({stage:"unconsumed-redaction",detail:"queued redaction was never applied to a tool result before message write",sessionId:a,config:r})}if(r&&Tn()==="enforce"){let s=i==="closed"?"closed":"open",l=Q(e.message,{failMode:s});if(l.verdict==="block")return{block:!0};let c=e.message,d=!1;l.verdict==="redact"&&(c=l.redacted,d=!0);let f=!1,m=$n(P(e,t));if(m){let v=At(c,m,{failMode:s});if(v.verdict==="block")return{block:!0};v.verdict==="redact"&&(c=v.redacted,f=!0,I({stage:"final-message-prompt-leak-redacted",detail:`final assistant message leaked the system prompt \u2014 masked ${v.matchedSpans.length} verbatim span(s)`,sessionId:a,config:r}))}let g=!1,_=Z(c,{failMode:s});if(_.verdict==="block")return{block:!0};if(_.verdict==="redact"&&(c=_.redacted,g=!0,I({stage:"final-message-brand-topic-redacted",detail:`final assistant message matched a brand/topic rule \u2014 redacted ${_.matched.length} rule(s): ${_.matched.join(",")} (recommended: ${_.recommendedOutcome??"none"})`,sessionId:a,config:r})),d&&I({stage:"final-message-secret-redacted",detail:`final assistant message carried a live secret \u2014 redacted ${l.detectors.length} detector(s): ${l.detectors.join(",")}`,sessionId:a,config:r}),d||f||g)return{message:c}}}async function fs(e,t){try{let{config:n}=await ie();if(!n)return;typeof e.systemPrompt=="string"&&e.systemPrompt.trim().length>0&&Mn(P(e,t),e.systemPrompt);let{unified:r}=C(n);r.captureCloneMetadata({model:typeof e.model=="string"&&e.model.trim().length>0?e.model:void 0,systemPrompt:typeof e.systemPrompt=="string"&&e.systemPrompt.trim().length>0?e.systemPrompt:void 0,toolSchemas:Array.isArray(e.tools)&&e.tools.length>0?e.tools:void 0,agentType:"openclaw"})}catch{}}async function ys(e,t){try{let n=await re();if(!n)return;let r=n.agentId??t.agentId;if(!r)return;let i=e.sessionId??t.sessionId??t.sessionKey,{unified:a}=C(n);await a.awaitBundleReady(),De(a,{agentId:r,...i?{sessionId:i}:{},framework:"openclaw"},{texts:e.assistantTexts,usage:e.usage?{tokensIn:e.usage.input,tokensOut:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite}:void 0,model:e.model||e.resolvedRef,final:!0})}catch{}}function As(e,t){Nn(O(e,t)),Ln(P(e,t))}export{Ie as a,te as b,Ne as c,Qa as d,Re as e,Ja as f,Ao as g,Io as h,I as i,He as j,L as k,Nn as l,Rn as m,No as n,Go as o,Xo as p,ls as q,fs as r,ys as s,As as t};
|