@visiq/openclaw-plugin 0.1.19 → 0.1.21

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.
@@ -0,0 +1,12 @@
1
+ var Er=/[^\u0000-\u007F]/,Mt=new RegExp("^\\p{Nd}$","u"),Cr=new RegExp("^\\p{Pd}$","u"),Nr=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,Tr=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,xr=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),$t="<invisible>",ht=new Map;function Rr(e){let t=String.fromCodePoint(e).normalize("NFKC");if(t.length===1&&t>="0"&&t<="9")return t;let n=e;for(let i=0;i<256&&n>0&&Mt.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function Or(e){if(e<128)return null;let t=ht.get(e);if(t!==void 0)return t;let n=(()=>{if(e>=65281&&e<=65374)return String.fromCharCode(e-65248);let r=String.fromCodePoint(e);return Mt.test(r)?Rr(e):Cr.test(r)||xr.has(e)?"-":Nr.test(r)?" ":Tr.test(r)?$t:null})();return ht.set(e,n),n}function $e(e){if(typeof e!="string"||e.length===0||!Er.test(e))return[];let t=_t(e,"as-separator");if(t===null)return[];let n=_t(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function _t(e,t){let n=[],r=[],i=!1;for(let a=0;a<e.length;){let o=e.codePointAt(a),s=o>65535?2:1,l=Or(o);if(l===null){for(let c=0;c<s;c++)n.push(e[a+c]),r.push(a+c);a+=s;continue}if(i=!0,l===$t){t==="as-separator"&&(n.push(" "),r.push(a)),a+=s;continue}n.push(l),r.push(a),a+=s}return i?(r.push(e.length),{label:t,text:n.join(""),offsets:Int32Array.from(r)}):null}function Mr(e,t){return{start:e.offsets[t.start],end:e.offsets[t.end]}}function $r(e){if(e.length<=1)return[...e];let t=[...e].sort((i,a)=>i.start-a.start||i.end-a.end),n=[],r={start:t[0].start,end:t[0].end};for(let i=1;i<t.length;i++){let a=t[i];a.start<=r.end?a.end>r.end&&(r={start:r.start,end:a.end}):(n.push(r),r={start:a.start,end:a.end})}return n.push(r),n}function yt(e,t){let n=[];e.lastIndex=0;let r;for(;(r=e.exec(t))!==null;){if(r[0].length===0){e.lastIndex++;continue}n.push({start:r.index,end:r.index+r[0].length})}return n}var Pt="[REDACTED]",Pe=[{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:/(?<![A-Za-z0-9._%+-])[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}],Ys=Pe.map(({name:e,re:t})=>({name:e,source:t.source})),Pr="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function Lr(e){return Lt(e,Pr)}function Lt(e,t){let n="",r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a==="\\"){if(!r&&e[i+1]==="b"){n+=t,i++;continue}n+=a+(e[i+1]??""),i++;continue}a==="["?r=!0:a==="]"&&(r=!1),n+=a}return n}function Dt(e){return new RegExp(Lr(e.source),e.flags)}var Dr="(?:\\b|_)";function Ne(e){return Lt(e,Dr)}var Fr=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function jr(e){let t=Fr.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function Te(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 Br(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 Ur(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 qr=[[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]],zr=[[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 Vr(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=qr[t][zr[r%8][n[r].charCodeAt(0)-48]];return t===0}function Gr(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 Kr(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 Wr=[1,4,3,7,5,8,6,9,10];function Hr(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)*Wr[n];return t%11===0}var Qr="TRWAGMYFPDXBNJZSQVHLCKE";function Yr(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 Qr[Number(o)%23]===a}var Zr=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Jr(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Zr.has(t.slice(0,2)):!1}var Le=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&Te(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:Br},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Ur},{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:Jr(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&&Vr(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:Gr},{name:"es_dni_nie",re:/\b(?:[XYZxyz]-?)?(?:\d{7,8}|\d{1,2}[. ]\d{3}[. ]\d{3})[ -]?[A-Za-z]\b/g,normalize:e=>e.replace(/[\s.-]/g,"").toUpperCase(),validate:Yr},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&Te(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Kr},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Hr}],Xr=Object.fromEntries([...Pe,...Le].map(e=>[e.name,e.re.source])),A=Xr,Zs=Le.map(e=>e.name),Ft=Pe.map(({name:e,re:t})=>({name:e,re:Dt(t)})),jt=Le.map(e=>({...e,re:Dt(e.re)})),Js=[...Ft,...jt].map(({name:e,re:t})=>({name:String(e),source:t.source})),De=["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"],ei={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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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). Collision rate: MEASURED 9.8% of benign 16-digit runs \u2014 Luhn leaves ~1 in 10. Default-ON because PCI-DSS makes masking mandatory; note in_aadhaar sits at the same rate and is often proposed for removal on that basis.",category:"financial",example:"4242 4242 4242 4242",template:{pattern:A.pan,mode:"partial",keepLast:4,templateOnly:{reason:"A rego rule cannot run Luhn, so the rule masks EVERY 13-19 digit run (grouped or not) \u2014 the floor's regex without the checksum that makes it precise. ~9 in 10 of those are not card numbers.",examples:["4242 4242 4242 4243","4242424242424241"],measuredOverMaskRate:.531}},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible. Collision rate: MEASURED 1.0% \u2014 mod-97 leaves ~1 in 97, the most precise detector on this floor alongside br_cpf.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:A.iban,mode:"partial",keepLast:4,templateOnly:{reason:"A rego rule cannot run mod-97, so the rule masks EVERY IBAN-SHAPED token (2 letters, 2 digits, 10-30 alphanumerics) \u2014 and mod-97 is what makes this the most precise detector on the floor, so almost all of those are not IBANs.",examples:["DE89 3704 0044 0532 0130 01","GB00 NWBK 6016 1331 9268 19"],measuredOverMaskRate:.934}},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:A.aba_routing,mode:"full",templateOnly:{reason:"A rego rule cannot run the weighted 3-7-1 mod-10, so the rule masks EVERY bare 9-digit run \u2014 which is why this detector is default-OFF on the floor and why its rule form is broader still.",examples:["021000022","123456789"],measuredOverMaskRate:.899}},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX). Collision rate: MEASURED 100% \u2014 no checksum, so every 2-then-7 dashed digit run matches. Same trade as ssn: the punctuated shape is rare in benign traffic, not precise.",category:"financial",example:"12-3456789",template:{pattern:A.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:A.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789). Collision rate: MEASURED 100% \u2014 there is NO checksum, so every dashed 3-2-4 digit run matches. Default-ON regardless, because that punctuated shape is essentially absent from benign agent traffic; if your traffic carries 3-2-4 dashed reference codes, opt out.",category:"pii",example:"123-45-6789",template:{pattern:A.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-Za-ceghj-npr-tw-z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-Da-d]|[A-CEGHJ-PR-TW-Za-ceghj-pr-tw-z][A-CEGHJ-NPR-TW-Z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-Da-d]|[A-CEGHJ-PR-TW-Za-ceghj-pr-tw-z][A-CEGHJ-NPR-TW-Za-ceghj-npr-tw-z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-D])\\b",mode:"full",templateOnly:{reason:"uk_nino has no checksum, but the floor still rejects the seven NEVER-ISSUED administrative prefixes (BG GB NK KN TN NT ZZ). A rego rule cannot express that exclusion without enumerating hundreds of letter pairs (RE2 has no lookahead), so the rule masks those too.",examples:["NK 12 34 56 A","ZZ 12 34 56 C"],measuredOverMaskRate:.019}},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. Collision rate: MEASURED 10.0% of benign 12-digit ids starting 2-9 (order/transaction numbers) \u2014 Verhoeff leaves ~1 in 10. Comparable to the long-shipped pan (10.0%) and well behind iban (1.0%); it stays default-ON because the two US identifiers this floor has always shipped, ssn and us_ein, collide at 100%.",category:"pii",example:"2345 6789 0124",template:{pattern:"\\b[2-9]\\d{3}(?:[ -]\\d{4}[ -]?\\d{4}|\\d{4}[ -]\\d{4})\\b",mode:"partial",keepLast:4,floorOnly:{reason:"The floor accepts the entirely UNPUNCTUATED 12-digit form because Verhoeff gates it (~1 in 10 survive). A rego rule cannot run Verhoeff, so a bare \\d{12} in a rule would mask every 12-digit order id and E.164 Indian mobile number in the tenant. The rule requires at least one printed separator \u2014 every half-punctuated form is covered; only the bare digit run stays floor-only.",examples:["234567890124","id=234567890124"]},templateOnly:{reason:"A rego rule cannot run the Verhoeff checksum, so the rule masks EVERY 4-4-4 grouping that starts 2-9 \u2014 including the ~9 in 10 that are not Aadhaar numbers at all.",examples:["2345 6789 0125","2345-6789-0123"],measuredOverMaskRate:.903}},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:A.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. Collision rate: MEASURED 1.0% of benign 11-digit runs (~1-in-100) \u2014 the most precise detector on this floor, alongside iban. 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}|\\d{3}(?:\\.\\d{3}-?\\d{2}|\\d{3}-\\d{2}))\\b",mode:"partial",keepLast:2,floorOnly:{reason:"The floor accepts the entirely bare 11-digit form because TWO mod-11 check digits gate it (~1 in 100 survive). A rego rule cannot run mod-11, so a bare \\d{11} in a rule would mask every 11-digit identifier in the tenant. The rule requires at least one printed separator; the bare form stays floor-only.",examples:["11144477735","ref 11144477735","12345678909"]},templateOnly:{reason:"A rego rule cannot run the two mod-11 check digits, so the rule masks EVERY punctuated 3-3-3-2 digit grouping \u2014 including the ~99 in 100 that are not CPFs.",examples:["123.456.789-10","111.444.777-34"],measuredOverMaskRate:.995}},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. Collision rate: MEASURED 4.0% of benign 8-digit-plus-letter tokens (invoice/order numbers with a suffix letter) \u2014 mod-23 leaves ~1 in 23. More precise than in_aadhaar (10.0%) and pan (10.0%); behind br_cpf (1.0%) and iban (1.0%).",category:"pii",example:"12345678Z",template:{pattern:A.es_dni_nie,mode:"full",templateOnly:{reason:"A rego rule cannot run the mod-23 check letter, so the rule masks EVERY 7-8 digit run followed by a letter \u2014 invoice and order numbers with a suffix letter included. mod-23 admits ~1 in 23; the rule admits all of them. Re-measured 0.973 \u2192 0.981 when the floor learned the printed forms (dotted DNI, hyphenated NIE): the rule now also matches those written forms, and ~22 in 23 of them are not DNI/NIEs. The FLOOR's own rate is unchanged \u2014 mod-23, not punctuation, gates it.",examples:["12345678A","X1234567H"],measuredOverMaskRate:.976}},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}|\\d{3}[- ]\\d{3})\\b",mode:"partial",keepLast:3,floorOnly:{reason:"The floor accepts the entirely bare 9-digit form because Luhn gates it. A rego rule cannot run Luhn, and a bare \\d{9} in a rule is also every ABA routing number and every 9-digit identifier, so the rule requires at least one printed separator in the 3-3-3 grouping.",examples:["046454286"]},templateOnly:{reason:"A rego rule cannot run Luhn, so the rule masks EVERY printed 3-3-3 digit grouping \u2014 including the ~9 in 10 that are not SINs.",examples:["046 454 287","123 456 789"],measuredOverMaskRate:.914}},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}|\\d{3}[- ]\\d{4})\\b",mode:"full",floorOnly:{reason:"The floor accepts the entirely bare 10-digit form because the weighted mod-11 gates it. A rego rule cannot run mod-11, and a bare \\d{10} in a rule is also every North American phone number, so the rule requires at least one printed separator in the 3-3-4 grouping.",examples:["9434765919"]},templateOnly:{reason:"A rego rule cannot run the weighted mod-11, so the rule masks EVERY printed 3-3-4 digit grouping \u2014 every North American phone number included \u2014 not just the ~1 in 10 that are NHS numbers.",examples:["943 476 5910","123 456 7890"],measuredOverMaskRate:.899}},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}|\\d{3}[- ]\\d{2,3})\\b",mode:"full",floorOnly:{reason:"The floor accepts the entirely bare 8-9 digit form because the weighted mod-11 gates it. A rego rule cannot run mod-11, and a bare \\d{8,9} in a rule collides with essentially every identifier of that length, so the rule requires at least one printed separator. BOTH lengths are in the gap: a TFN may be 8 digits (`12345679`) or 9 (`123456782`), and the 8-digit branch went undeclared while the parity sweep derived its population from the 9-digit example alone.",examples:["12345679","123456782"]},templateOnly:{reason:"A rego rule cannot run the weighted mod-11, so the rule masks EVERY printed 3-3-2/3-3-3 digit grouping \u2014 including the ~9 in 10 that are not TFNs.",examples:["123 456 783","123 456 78"],measuredOverMaskRate:.912}},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:A.date_of_birth,mode:"full"},defaultEnabled:!1},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept). Collision rate: MEASURED 100% of well-formed addresses \u2014 that is BY DESIGN, not a defect: an email address is structurally unambiguous, so matching every one is correct rather than over-matching.",category:"pii",example:"alice@acme.com",template:{pattern:A.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:A.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:A.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:A.mac_address,mode:"full"},defaultEnabled:!1}},re=Object.freeze(Object.fromEntries(De.map(e=>{let t=ei[e];return[e,{...t,template:{...t.template,pattern:jr(Ne(t.template.pattern))}}]})));var Xs=new Set(De.filter(e=>!re[e].defaultEnabled));function ti(e,t){let n=new Set;for(let r of De)(re[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function te(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=Fe(t),a=e;for(let{name:o,re:s}of Ft){let l=o;n.has(l)||(a=a.replace(s,c=>(r?.(l),i(c))))}for(let{name:o,re:s,normalize:l,validate:c}of jt)n.has(o)||(a=pi(a,s,l,c,t,o,r));return a}function Fe(e){return typeof e=="function"?e:()=>e}var bt=e=>"\0".repeat(e.length);function ni(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=$e(e);if(i.length===0)return te(e,t,n,r);let a=new Set,o=p=>{a.add(p)},s=te(e,bt,n,o),l=!0,c=new Array(e.length).fill(!1);for(let p=0;p<e.length;p++)c[p]=s[p]==="\0"&&e[p]!=="\0";for(let p of i){let m=te(p.text,bt,n,o);for(let h=0;h<p.text.length;h++)if(!(m[h]!=="\0"||p.text[h]==="\0"))for(let _=p.offsets[h];_<p.offsets[h+1];_++)c[_]||(c[_]=!0,l=!1)}if(l)return te(e,t,n,r);for(let p of a)r?.(p);let d="",u=0;for(;u<e.length;){if(!c[u]){d+=e[u],u++;continue}let p=u;for(;u<e.length&&c[u];)u++;d+=Fe(t)(e.slice(p,u))}return d}function q(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var vt=new Map;function ri(e){let t=vt.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),vt.set(e.source,t)),t}var ii=4096,ai=64,wt=null;function oi(e){return wt!==null?wt:ii+e.length*ai}var Bt=!1,C={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},Ut={spanBudget:0,depthCap:0};function si(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:oi(e),exhausted:!1}}function qt(e,t,n,r,i,a,o){C.spanCalls++;let s=t*o.stride+n.length,l=Bt?void 0:o.chosen.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,null;o.budget--,C.spanMisses++;let c=li(e,t,n,r,i,a,o);return o.chosen.set(s,c),c}function li(e,t,n,r,i,a,o){let s=ri(r),l=[];for(let d=n.length-1;d>=1;d--)if(q(n[d])){let u=n.slice(0,d);s.test(u)&&l.push(u)}let c=q(e[t+n.length])?[n,...l]:[...l,n];for(let d of c)if(a(i(d),d)&&!di(e,t,d,r,i,a,o))return d;return null}var At=new Map;function ci(e){let t=At.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),At.set(e.source,t)),t}function di(e,t,n,r,i,a,o){C.cutCalls++;let s=t*o.stride+n.length,l=Bt?void 0:o.cuts.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,!0;o.budget--,C.cutMisses++;let c=ui(e,t,n,r,i,a,o);return o.cuts.set(s,c),c}function ui(e,t,n,r,i,a,o){let s=t+n.length,l=ci(r);for(let c=1;c<n.length;c++){if(q(n[c])||!q(n[c-1]))continue;let d=t+c;l.lastIndex=d;let u=l.exec(e);if(u===null||u[0].length===0)continue;let p=qt(e,d,u[0],r,i,a,o);if(p!==null&&d+p.length>s&&q(e[d+p.length]))return!0}return!1}function pi(e,t,n,r,i,a,o){let s=Fe(i);t.lastIndex=0;let l="",c=0,d=si(e),u=C.spanMisses+C.cutMisses,p;for(;(p=t.exec(e))!==null;){let m=p[0],h=p.index;if(m.length===0){t.lastIndex=h+1;continue}let _;try{_=qt(e,h,m,t,n,r,d)}catch(y){if(y instanceof RangeError&&/call stack/i.test(y.message))d.exhausted=!0,_=null;else throw y}if(d.exhausted)return C.budgetExhausted++,Ut.spanBudget++,kt(u),l+e.slice(c,h)+s(e.slice(h));if(_!==null)o?.(a),l+=e.slice(c,h)+s(_),c=h+_.length,t.lastIndex=c;else{let y=m.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=y===-1?h+m.length:h+1+y+1}if(t.lastIndex>e.length)break}return kt(u),l+e.slice(c)}function kt(e){let t=C.spanMisses+C.cutMisses-e;t>C.maxMissesInAPass&&(C.maxMissesInAPass=t)}function je(e,t=Pt,n,r){return mi(e,t,ti(n,r))}var fi=256;function mi(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=(s,l)=>{if(l>fi)return Ut.depthCap++,t;if(typeof s=="string")return ni(s,t,n,a);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!i)return s;let c=String(s);return c.length>=13&&c.length<=19&&Te(c)?(r.add("pan"),t):s}if(Array.isArray(s))return s.map(c=>o(c,l+1));if(s!==null&&typeof s=="object"){let c=s,d={};for(let u of Object.keys(c))d[u]=o(c[u],l+1);return d}return s};return{value:o(e,0),detectors:[...r].sort()}}function zt(e,t=Pt){return je(e,t).value}function gi(e){let{value:t,detectors:n}=je(e),r=n.some(i=>re[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function ie(e,t){let{blocked:n,redacted:r,detectors:i}=gi(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 Be(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var hi=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function Ue(e){return hi.has(Be(e))}var _i=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Vt=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"}),yi=new RegExp(`[${Object.keys(Vt).join("")}]`,"gu"),bi=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),Gt="\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",vi=Object.freeze(Object.fromEntries([...Gt].map((e,t)=>[e,String.fromCharCode(97+t)]))),wi=new RegExp(`[${Gt}\u2800]`,"g"),Kt=/[⠀-⣿]/;function Ai(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 ki(e){return e.replace(_i,"")}function Wt(e){return e.replace(yi,t=>Vt[t]??t)}function Ii(e){return e.replace(/[4@31!05$79(8]/g,t=>bi[t]??t)}function Si(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 Ei(e){return Kt.test(e)?e.replace(wi,t=>t==="\u2800"?" ":vi[t]??t):e}function It(e){let t;try{t=Ai(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=ki(t),t=Wt(t),t}var Ci=/^[A-Za-z0-9+/]{16,}={0,2}$/,Ni=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,St=/[A-Za-z0-9+/]{20,}={0,2}/g;function xe(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 Qt(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 Ti(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(Ni.test(t))for(let r of Ti(t))n.push({decoded:r,textiness:xe(r)});if(Ci.test(t)&&t.length%4===0)for(let r of Qt(t))n.push({decoded:r,textiness:xe(r)});return n}function Ct(e,t){let n=[],r;for(St.lastIndex=0;(r=St.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of Qt(i))n.push({decoded:a,textiness:xe(a)})}return n}var xi=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function Yt(e,t=xi){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,u=0,p=[{s:e,depth:0}];for(;p.length>0;){if(d>=i){c=!0;break}let m=p.pop();if(m===void 0)break;let{s:h,depth:_}=m;if(h.length>r){c=!0;continue}d++,_>u&&(u=_);let y=It(h);s(y);let I=Ii(y);if(I!==y&&s(I),s(Si(y)),Kt.test(h)&&s(Ei(y)),_>=n){let k=It(h);(Et(k).length>0||Ct(k,a).length>0)&&(c=!0);continue}let v=[...Et(y),...Ct(y,a)];for(let k of v){if(l=!0,k.decoded.length>r){c=!0;continue}k.textiness>=.85&&k.decoded!==y?p.push({s:k.decoded,depth:_+1}):s(k.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:d,maxDepthSeen:u}}var Zt=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],Ri=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),Oi=8,Mi=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 $i(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||Mi.has(i)&&Nt(t[r-1])&&Nt(t[r+1])&&(n++,n>=Oi))return!0}return!1}var Pi=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function Li(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(Pi.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Di=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Fi(e){for(let t of Di)if(e>=t.lo&&e<=t.hi)return t.name;return null}function ji(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=Fi(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:Wt(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var Tt=Object.freeze({signals:[],contributes:!1});function Bi(e){if(typeof e!="string"||e.length===0)return{...Tt,signals:[]};let t=new Set;try{$i(e)&&t.add("hidden_text_carrier"),Li(e)&&t.add("injected_turn_boundary"),ji(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{...Tt,signals:[]}}return{signals:[...Zt.filter(n=>t.has(n))],contributes:Ri.some(n=>t.has(n))}}var ae=[{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 xt(e){return typeof e!="string"||e.length===0?[]:ae.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function Ui(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(xt(e)),{views:n}=Yt(e);for(let r of n)for(let i of xt(r))t.add(i);return ae.filter(r=>t.has(r.name)).map(r=>r.name)}function qi(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of Ui(a))t.add(s);let o=Bi(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:ae.filter(a=>t.has(a.name)).map(a=>a.name),structural:Zt.filter(a=>n.has(a))}}function zi(e){return qi(e).matched}var el=ae.map(e=>e.name);var Vi=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Gi="i:injection";function Jt(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=je(e.content);for(let a of i){let o=re[a]?.category;o&&t.add(`c:${o}`)}zi(e.content)&&t.add(Gi)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Vi.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var Ce="(?: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))",tl=[{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${Ce}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${Ce}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${Ce}\\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}],Rt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Ki=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${Rt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${Rt}|programming|training))`,Wi="(?:(?: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)",Hi="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",nl=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${Wi}${Ki}\\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+(?:${Hi}\\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 Qi="[SYSTEM-PROMPT-REDACTED]";function Re(e){return e.toLowerCase().replace(/\s+/g," ").trim().split(" ").filter(t=>t.length>0)}function Yi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xt(e,t){if(typeof e!="string"||typeof t!="string"||e.length===0||t.length===0)return[];let n=Re(e),r=Re(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 Zi(e,t){if(typeof e!="string"||e.length===0)return e;let n=e,r=Math.max(1,Re(e).length);for(let i=0;i<r;i++){let a=Xt(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(Yi).join("\\s+"),c;try{c=new RegExp(l,"gi")}catch{continue}n=n.replace(c,Qi)}}return n}function Oe(e,t,n){if(e==null)return e;if(typeof e=="string"){for(let r of Xt(t,e))n.add(r);return Zi(e,t)}if(Array.isArray(e))return e.map(r=>Oe(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]=Oe(r[a],t,n);return i}return e}function Ji(e,t){if(typeof t!="string"||t.length===0)return{leaked:!1,matchedSpans:[],redacted:e};let n=new Set,r=Oe(e,t,n),i=[...n].sort();return{leaked:i.length>0,matchedSpans:i,redacted:r}}function en(e,t,n){let{leaked:r,redacted:i,matchedSpans:a}=Ji(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 rl=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var M=e=>`[^.!?;\\n]{0,${e}}?`,Xi=["\\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("|"),tn="(?: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)",il=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Xi})\\s${M(40)}\\b${tn}\\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${M(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${M(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${M(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${M(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${M(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")}]),al=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${M(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${M(30)}\\b${tn}\\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 U=e=>`[^.!?;\\n]{0,${e}}?`,ol=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${U(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${U(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${U(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${U(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${U(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 ea=["competitor_mention","disallowed_topic","off_brand_claim","restricted_advice"];var ta=[{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 na={competitor_mention:"redact",off_brand_claim:"redact",disallowed_topic:"escalate",restricted_advice:"escalate"};function ra(e){return e.length===0?null:e.some(t=>na[t]==="escalate")?"escalate":"redact"}var ia="[BRAND-TOPIC-REDACTED]";function Me(e,t){if(e==null)return e;if(typeof e=="string"){let n=e;for(let{id:r,re:i}of ta){i.lastIndex=0;let a=n.replace(i,()=>ia);a!==n&&(t.add(r),n=a)}return n}if(Array.isArray(e))return e.map(n=>Me(n,t));if(typeof e=="object"){let n=e,r=Object.create(Object.getPrototypeOf(n));for(let i of Object.keys(n))r[i]=Me(n[i],t);return r}return e}function aa(e){let t=new Set,n=Me(e,t);return{matched:ea.filter(r=>t.has(r)),redacted:n}}function oe(e,t){let{matched:n,redacted:r}=aa(e),i=ra(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 qe="[REDACTED]",F="\u2022",ne=e=>/[\p{L}\p{N}]/u.test(e);function nn(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:F,c=o+s>=a;return i.map((d,u)=>!c&&(u<o||u>=a-s)?d:ne(d)?l:d).join("")}function oa(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return nn(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:F;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(o=>ne(o)?a:o).join(""))+i}function sa(e,t,n){let r=n.length>0?n:F,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 u=d.index;u<d.index+d[0].length;u++)i[u]=!0}}catch{}let a=!1,o=!0;for(let c=0;c<e.length;c++)if(ne(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]||!ne(d)?l+=d:l+=r}return l}function rn(e,t){let n=t.mode??"full";return n==="partial"?nn(e,t.keepFirst??0,t.keepLast??0,t.maskChar??F):n==="email"?oa(e,t.maskChar??F):n==="custom"?sa(e,t.keepPattern,t.maskChar??F):t.replacement??qe}function la(e,t){return typeof e=="string"?rn(e,t):t.replacement??qe}function an(e){let t=[],n=e.replacement??qe;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:Ne(r),replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:Ne(i),replacer:a=>rn(a,r)})}return t}function on(e){try{return new RegExp(e,"g")}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`[visiq-redact] Invalid redaction pattern "${e}": ${n}`)}}function sn(e,t){if($e(e).length===0){let n=e;for(let{source:r,replacer:i}of t)n=n.replace(on(r),a=>i(a));return n}return ca(e,t)}function ca(e,t){let n=e;for(let{source:r,replacer:i}of t){let a=on(r),o=[...yt(a,n)];for(let d of $e(n))for(let u of yt(a,d.text))o.push(Mr(d,u));let s=$r(o);if(s.length===0)continue;let l="",c=0;for(let{start:d,end:u}of s)l+=n.slice(c,d)+i(n.slice(d,u)),c=u;n=l+n.slice(c)}return n}function se(e,t){return e==null?e:typeof e=="string"?da(e,t):typeof e=="object"?ua(e,t):e}function da(e,t){if(typeof e!="string")return e;let n=an(t);return n.length===0?e:sn(e,n)}function ua(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=an(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 u=i?n.get(d):void 0;if(u){c[d]=la(l[d],u);continue}c[d]=o(l[d])}return c}return typeof s=="string"&&a?sn(s,r):s};return o(e)}import{readFile as pa}from"node:fs/promises";import{homedir as Ve}from"node:os";import{join as Ge,isAbsolute as fa,resolve as ma}from"node:path";import{createInterface as ga}from"node:readline";import{parseArgs as ha}from"node:util";var _a="https://api.visiqlabs.com",ln="@visiq/openclaw-plugin",de="open";function Ke(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}var ya={enabled:!0,thresholds:{}},ue=[{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"}],ba=["sequence-anomaly",...ue.map(e=>e.cli)];function ce(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 We(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 va(...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 wa='[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 Aa(e){return e==="~"||e.startsWith("~/")?Ge(Ve(),e.slice(1).replace(/^\//,"")):e}async function cn(e){try{let t=fa(e)?e:ma(e),n=await pa(t,"utf-8");return JSON.parse(n)}catch{return null}}function le(e,...t){for(let n of t){let r=e[n];if(typeof r=="string")return r}}function ze(e){if(!e||typeof e!="object")return{};let t=e,n=le(t,"apiKey","api_key"),r=le(t,"agentId","agent_id"),i=le(t,"baseUrl","base_url"),a=Ke(le(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=ce(s);if(l!==void 0)o.sequenceAnomalyEnabled=l;else if(typeof s=="object"&&!Array.isArray(s)){let c=s,d=ce(c.enabled);d!==void 0&&(o.sequenceAnomalyEnabled=d);let u={};for(let p of ue){let m=We(c[p.key]??c[p.json]);m!==void 0&&(u[p.key]=m)}Object.keys(u).length>0&&(o.sequenceAnomalyThresholds=u)}}return o}async function ka(e){if(!e)return{};let t=Aa(e),n=await cn(t);if(!n||typeof n!="object")return{};let r=n,i=r.plugins?.entries,a=i&&typeof i=="object"?i[ln]:void 0;return a&&typeof a=="object"&&a.config?ze(a.config):ze(r)}async function dn(e){if(!e)return{};let t=await cn(e);if(!t||typeof t!="object")return{};let a=t.plugins?.entries?.[ln];return!a||typeof a!="object"?{}:ze(a.config)}function Ia(){return dn(Ge(Ve(),".openclaw","openclaw.json"))}function Sa(){let e=process.env.OPENCLAW_CONFIG_PATH;return!e||e===Ge(Ve(),".openclaw","openclaw.json")?Promise.resolve({}):dn(e)}async function Ea(e){if(!process.stdout.isTTY)return{};let t=ga({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 Ca(){try{let e={"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"},"fail-mode":{type:"string"}};for(let c of ba)e[c]={type:"string"};let{values:t}=ha({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=Ke(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=ce(t["sequence-anomaly"]);s!==void 0&&(n.sequenceAnomalyEnabled=s);let l={};for(let c of ue){let d=We(t[c.cli]);d!==void 0&&(l[c.key]=d)}return Object.keys(l).length>0&&(n.sequenceAnomalyThresholds=l),n}catch{return{}}}async function fl(){return(await He()).config}async function He(){let e=Ca(),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=Ke(process.env.VISIQ_FAIL_MODE);n&&(t.failMode=n);let r=ce(process.env.VISIQ_SEQUENCE_ANOMALY);r!==void 0&&(t.sequenceAnomalyEnabled=r);let i={};for(let u of ue){let p=We(process.env[u.env]);p!==void 0&&(i[u.key]=p)}Object.keys(i).length>0&&(t.sequenceAnomalyThresholds=i);let a=await ka(process.env.VISIQ_CONFIG_PATH),o=await Ia(),s=await Sa(),l={...o,...s,...a,...t,...e,sequenceAnomalyThresholds:va(o.sequenceAnomalyThresholds,s.sequenceAnomalyThresholds,a.sequenceAnomalyThresholds,t.sequenceAnomalyThresholds,e.sequenceAnomalyThresholds)};(!l.apiKey||!l.agentId)&&process.stdout.isTTY&&process.stdin.isTTY&&(l=await Ea(l));let c=l.failMode??de;if(!l.apiKey||!l.agentId)return process.stderr.write(`${wa}
4
+ `),{config:null,failMode:c};let d={apiKey:l.apiKey,agentId:l.agentId,failMode:c,sequenceAnomaly:{enabled:l.sequenceAnomalyEnabled??ya.enabled,thresholds:l.sequenceAnomalyThresholds??{}}};return d.baseUrl=l.baseUrl||_a,{config:d,failMode:c}}var Qe=null,un={ready:!1,config:null,failMode:de};function Ye(){return Qe||(Qe=He().catch(e=>(process.stderr.write(`[VisIQ] Config resolution failed (treating as unconfigured): ${e instanceof Error?e.message:String(e)}
5
+ `),{config:null,failMode:de})).then(e=>(un={ready:!0,config:e.config,failMode:e.failMode},e))),Qe}function pe(){return Ye().then(e=>e.config)}function fe(){return Ye()}function me(){return un}function hl(){Ye()}var yl="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.",pn="0.1.21";import{z as g}from"zod";import*as T from"node:os";import{randomUUID as V}from"node:crypto";var Ze=1,mn="X-VisIQ-SDK",gn="X-VisIQ-Dialect",hn="unknown";function Je(e,t=1){return{[mn]:e&&e.length>0?e:hn,[gn]:String(t)}}var _n="interceptor_source",Na=g.enum(["enforce","audit","off"]),Ta=g.enum(["closed","open"]),yn=g.enum(["enforce","monitor","off"]),xa=g.object({apiKey:g.string().min(1,"apiKey is required"),agentId:g.string().min(1,"agentId is required"),endpoint:g.string().url().optional(),mode:Na.optional(),timeoutMs:g.number().int().positive().optional(),hitlTimeoutMs:g.number().int().positive().optional(),failBehavior:Ta.optional()}),wl=g.object({agent_id:g.string().min(1),target_app:g.string().min(1),action:g.string().min(1),context:g.record(g.unknown()).optional(),session_id:g.string().min(1).max(255).optional(),action_schema_id:g.string().min(1).max(128).optional(),telemetry:g.record(g.unknown()).optional()}),Ra=g.object({field:g.string().optional(),pattern:g.string().optional(),replacement:g.string().optional(),mode:g.enum(["full","partial","email"]).optional(),keepFirst:g.number().optional(),keepLast:g.number().optional(),maskChar:g.string().optional()}),Oa=g.object({decision_id:g.string().min(1),decision:g.enum(["permit","deny","approval_required","mask"]),reason:g.string().optional(),rule_code:g.string().nullable().optional(),enforced:g.boolean().optional(),agent_mode:yn.optional(),arg_redaction_rules:g.array(Ra).optional(),plane:g.string().nullable().optional(),operation:g.string().nullable().optional(),is_retrieval:g.boolean().optional(),metadata:g.record(g.unknown()).optional()}),Ma=g.object({field:g.string().min(1),operator:g.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:g.union([g.string(),g.number(),g.array(g.string())])}),$a=g.object({id:g.string().min(1),rule_code:g.string().default(""),name:g.string().min(1),description:g.string().nullable().default(null),effect:g.enum(["allow","deny","hitl","mask"]),resource_type:g.string().min(1),rego_source:g.string().default(""),target_app:g.string().nullable().default(null),action_pattern:g.string().nullable().default(null),conditions:g.array(Ma).default([]),priority:g.number().int().default(0)}),Pa=g.object({version:g.string().min(1),agent_mode:yn.optional(),rules:g.array($a),no_coverage:g.object({no_coverage_defaults:g.record(g.string()),autopilot_enabled:g.boolean(),enduser_hitl_enabled:g.boolean(),hitl_timeout_seconds:g.number()}).optional()}),La=2e3,Da=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function Fa(e){let t=e.rules.filter(n=>Da(n.rego_source)).map(n=>n.id);return t.length>0&&console.warn(`[VISIQ] ${t.length} bundle rule(s) carry an EMPTY rego body and will be evaluated as an UNCONDITIONAL PERMIT credited to their own rule id: ${t.join(", ")}. If any of these is meant to deny, it is not denying. Fix the rule body at the control plane; the SDK cannot tell an intentional stub from a dropped column.`),t}var Xe=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return Je(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 Oa.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(),o=Pa.parse(a);return Fa(o),o}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 reportSkillInventory(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/skills`;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,skills:e})});n.ok||console.warn(`[ALLOW] Skill-inventory report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Skill-inventory 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 ja(La)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function ja(e){return new Promise(t=>setTimeout(t,e))}function _e(){let e={};try{let t=`${T.platform()} ${T.release()}`.trim();t&&(e.os=t)}catch{}try{let t=T.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=T.userInfo();t&&(e.username=t)}catch{}try{let t=Ba();t&&(e.ip=t)}catch{}return e}function Ba(){let e=T.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 Ua(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function ge(e,...t){for(let n of t){let r=Ua(e[n]);if(r)return r}}function he(e){if(ge(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(ge(e,"user_id","userId"))return"user";if(ge(e,"agent_id","agentId"))return"agent";if(ge(e,"org_id","orgId","namespace"))return"org"}var qa=[{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=he(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=he(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=he(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=he(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function z(e,t){if(!e)return null;let n=t??{};for(let r of qa)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function et(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 fn=new Map;function G(e){let t=(fn.get(e)??0)+1;return fn.set(e,t),t}function bn(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 tt(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=bn(n.usage);e.emitCognition({clientEventId:V(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:G(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 nt(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:V(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:G(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 K(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?et(n.memory):void 0;e.emitCognition({clientEventId:V(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:G(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 rt(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=et(n.memory,{itemCount:o,bytes:a})),e.emitCognition({clientEventId:V(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:G(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 it(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:V(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:G(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 ye(e){try{let t=JSON.stringify(e);return typeof t=="string"?t.length:void 0}catch{return}}function be(e){try{return Array.isArray(e)?e.length:void 0}catch{return}}import{z as f}from"zod";import{createHash as za}from"crypto";import{createHash as Lo}from"crypto";var vn=new Map;function wn(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function ot(e){let t=za("sha256").update(e).digest("hex"),n=vn.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
8
+ `).map(l=>Va(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 p=c[1],m=c[2].trim();r.set(p,H(m)),o++;continue}let d=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(d){let p=d[1],m=d[2].trim(),h=d[3].trim(),_=[];if(h&&h!=="}"){let I=h.endsWith("}")?h.slice(0,-1).trim():h;I&&_.push(I),h.endsWith("}")||(o++,o=ve(a,o,_))}else h==="}"||(o++,o=ve(a,o,_));let y=An(_);i.push({variable:p,value:H(m),conditions:y,rawConditions:wn(_)}),o++;continue}let u=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(u){let p=u[1],m=u[2].trim(),h=[];if(m&&m!=="}"){let y=m.endsWith("}")?m.slice(0,-1).trim():m;y&&h.push(y),m.endsWith("}")||(o++,o=ve(a,o,h))}else m==="}"||(o++,o=ve(a,o,h));let _=An(h);i.push({variable:p,value:"true",conditions:_,rawConditions:wn(h)}),o++;continue}o++}let s={defaults:r,rules:i};return vn.set(t,s),s}function Va(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 ve(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 H(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ga(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function An(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=Xa(i);a&&t.push(a)}}return t}var st=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,Ka=new RegExp(`^(${st.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),Wa=new RegExp(`^(${st.source})\\s*==\\s*((?:input|data)\\S*)$`),Ae=/(?:input|data)(?:\.[A-Za-z0-9_]+|\["[^"]+"\]|\['[^']+'\])+/,Ha=new RegExp(`^(${Ae.source})\\s*(==|!=)\\s*(${Ae.source})$`),Qa=new RegExp(`^(${Ae.source})\\s+in\\s+(${Ae.source})$`),Ya=/^([^\s=!]+)\s*==\s*(.+)$/,Za=/^([^\s=!]+)\s*!=\s*(.+)$/,El=new RegExp(`^(?:${st.source})$`);var Ja=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function Xa(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:Q,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(Ja);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:Ga(s[1])};let l=n.match(Qa);if(l)return{type:"field_in_set",negated:t,field:l[1].trim(),rightField:l[2].trim()};let c=n.match(Ha);if(c)return{type:"field_equality",negated:c[2]==="!="?!t:t,field:c[1].trim(),rightField:c[3].trim()};let d=n.match(Ka);if(d)return{type:"array_includes",negated:t,field:d[2].trim(),value:Tn(d[1])};let u=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(u){let I=io(u[2]);if(I!==null)return{type:"in_set",negated:t,field:u[1].trim(),values:I}}let p=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(p)return{type:"comparison",negated:t,field:p[1].trim(),operator:p[2],value:parseFloat(p[3])};let m=n.match(Wa);if(m)return{type:"equality",negated:t,field:m[2].trim(),value:H(m[1].trim())};let h=n.match(Ya);if(h)return{type:"equality",negated:t,field:h[1].trim(),value:H(h[2].trim())};let _=n.match(Za);if(_)return{type:"inequality",negated:t,field:_[1].trim(),value:H(_[2].trim())};let y=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return y?{type:"truthy",negated:t,field:y[1].trim()}:{type:"truthy",negated:!1,field:Q,value:e.trim()}}var Q="__unrecognized_condition_forces_deny__";var eo=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Nn(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==Q&&eo.test(r.field)&&t.push(r.field);return t}var to=["input.normalized.","input.normalized["];function no(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions)for(let i of ro(r))typeof i!="string"||i===Q||to.some(a=>i.startsWith(a))&&t.add(i);return[...t].sort()}var kn=/\binput\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/g;function ro(e){let{field:t,rightField:n}=e;if(t!==Q){let i=typeof t=="string"?[t]:[];return typeof n=="string"&&n.length>0&&i.push(n),i}let r=typeof e.value=="string"?e.value:"";return kn.lastIndex=0,[...r.matchAll(kn)].map(i=>i[0])}function Tn(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 io(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(Tn(s))}return o}var xn=["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"],ao=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],oo=["production","staging","development","test"],so=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function lo(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 In={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 co(e){let t=lo(e);return t===null?"other":In[t]??In[t.replace(/_/g,"")]??"other"}function Rn(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=co(t.targetApp)),n.context=r}return n}var Sn=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],uo=["read","write","delete","share","export","decide","execute"],En=["none","low","medium","high","critical"],po=["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"],fo={action_class:xn,operation:uo,"context/app_category":ao,"context/environment":oo,"context/actor_function":so,"read/classification":po,"read/data_categories":Sn,"read/data_sensitivity":En,"write/data_categories":Sn,"write/data_sensitivity":En};function On(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(fo)){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 Cn=64,mo=64,Y={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}};function Se(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:$n()}}var go=new Set(["deny","approval_required","escalate"]);function $(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>Cn?r.slice(0,Cn):r}function ke(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function W(e){return typeof e=="string"&&e.length>0?e:null}function Mn(e,t){let n=ke(t.data_categories),r=W(t.classification),i=ke(t.taint),a=W(t.action_class),o=a&&xn.includes(a)?a:null,s=W(t.target_app),l=W(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<mo)c[o]=1;else{let d=Object.keys(c).sort(),u=d[d.length-1];u!==void 0&&o<u&&(delete c[u],c[o]=1)}return{retrieved_data_categories:$(e.retrieved_data_categories,n),retrieved_classifications:$(e.retrieved_classifications,r?[r]:[]),taint:$(e.taint,i),action_classes:$(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&go.has(l)?1:0),event_count:e.event_count+1,target_apps:$(e.target_apps,s?[s]:[]),identity:ho(e.identity,t)}}function ho(e,t){let n=e??$n(),r=ke(t.attested_subjects),i=$(n.attested_subjects,r),a=W(t.subject_id);return{attested_subjects:i,claimed_subjects:$(n.claimed_subjects,ke(t.claimed_subjects)),acted_subjects:$(n.acted_subjects,a?[a]:[])}}function $n(){return{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}}var _o=["tier1","tier2","tier3"];function Pn(e){return typeof e=="string"&&_o.includes(e)}var yo=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],bo=["internal","customer_facing","experimental","third_party"],Ln=[...yo,...bo];function vo(e){return typeof e=="string"&&Ln.includes(e)}function Dn(e){let t=new Set;for(let n of e)vo(n)&&t.add(n);return Ln.filter(n=>t.has(n))}var wo={trust_tier:null,categories:[],business_functions:[],business_function:null,blast_radius_tier:null};function Fn(e,t,n){if(t.length>0&&n.add(t),!(e===null||typeof e!="object"||Array.isArray(e)))for(let[r,i]of Object.entries(e))Fn(i,t.length>0?`${t}.${r}`:r,n)}function jn(e){let t=new Set;return Fn(e,"",t),t}var Cl=jn(Se()),Nl=jn(wo),Ao=["action_counts"];for(let e of Ao){let t=Se()[e];if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`closed-input-paths: session.${e} is no longer a dynamic map \u2014 remove it from DYNAMIC_SESSION_MAPS or the carve-out admits every spelling under it.`)}var Tl=new RegExp("^\\p{White_Space}*$","u");var Bn={minEvents:12,minClasses:3,concentrationSigma:2,dominanceRatio:4,dominanceShare:.5,frictionRatio:.75,minFrictionEvents:6};function ko(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 at(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 we(e){return Number.isFinite(e)?Math.round(e*1e3)/1e3:0}var Io=.5;function So(e){let t=e.length;if(t===0)return 0;let n=[...e].sort((s,l)=>s-l),r=at(n),i=n[t-1],a=n.map(s=>Math.abs(s-r)).sort((s,l)=>s-l),o=at(a);return o>0?.6745*(i-r)/o:i===r?0:.6745*(i-r)/Io}function lt(e,t){let n={...Bn,...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=ko(r),l={};for(let E of Object.keys(r).sort()){let L=Math.max(0,r[E]??0);L>0&&(l[E]=L)}let c=Object.values(l),d=c.reduce((E,L)=>E+L,0),u=[...c].sort((E,L)=>E-L),p=at(u),m=So(c),h=p>0?s.count/p:0,_=d>0?s.count/d:0,y=i>0?(a+o)/i:0,I={action_class:null,repeats:s.count,event_count:i,denied_count:a,inhibited_count:o,class_count:c.length,class_counts:l,concentration_score:we(m),dominance_ratio:we(h),dominance_share:we(_),friction_score:we(y),signals:[]};if(i<n.minEvents)return{verdict:"allow",signals:[],evidence:I};let v=[],k=null;return c.length>=n.minClasses&&m>=n.concentrationSigma&&h>=n.dominanceRatio&&_>=n.dominanceShare&&(v.push("concentration"),k=s.label),y>=n.frictionRatio&&a+o>=n.minFrictionEvents&&v.push("friction"),v.length===0?{verdict:"allow",signals:[],evidence:I}:{verdict:t.failMode==="closed"?"deny":"hold",signals:[...v],evidence:{...I,action_class:k,signals:[...v]}}}var Un="generic",qn=[{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:Un,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."}],Eo=qn.map(e=>e.id),xl=new Map(qn.map(e=>[e.id,e])),Rl=new Set(Eo);function zn(e){return Array.isArray(e)&&e.length>0?[...e]:[Un]}var Co=/^[a-z][a-z0-9_]*$/;function Vn(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Co.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var No=["narrow","moderate","broad","unbounded","unknown"];function Gn(e){return typeof e=="string"&&No.includes(e)}function To(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(" ").filter(t=>t.length>0)}function xo(e){let t=2166136261,n=16777619;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,16777619)>>>0,n=Math.imul(n^(i<<1|1),2246822507)>>>0}return[t>>>0,n>>>0]}function Ro(e,t=5){if(e.length===0)return[];if(e.length<t)return[e.join(" ")];let n=new Set;for(let r=0;r+t<=e.length;r++)n.add(e.slice(r,r+t).join(" "));return[...n]}function Kn(e){let t=Ro(To(e)),n=new Int32Array(64);for(let i of t){let[a,o]=xo(i);for(let s=0;s<32;s++)n[s]+=o>>>s&1?1:-1,n[s+32]+=a>>>s&1?1:-1}let r="";for(let i=1;i>=0;i--){let a=0;for(let o=31;o>=0;o--)a=(a<<1|(n[i*32+o]>0?1:0))>>>0;r+=a.toString(16).padStart(8,"0")}return r}function Oo(e){let t=e-(e>>>1&1431655765);return t=(t&858993459)+(t>>>2&858993459),t=t+(t>>>4)&252645135,Math.imul(t,16843009)>>>24&255}function Mo(e,t){if(typeof e!="string"||typeof t!="string"||e.length!==16||t.length!==16)return 64;let n=0;for(let r=0;r<16;r+=8){let i=parseInt(e.slice(r,r+8),16),a=parseInt(t.slice(r,r+8),16);if(!Number.isFinite(i)||!Number.isFinite(a))return 64;n+=Oo((i^a)>>>0)}return n}var $o=["proposed","approved","revoked"];function Po(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.skill_id=="string"&&t.skill_id.length>0&&typeof t.skill_schema_hash=="string"&&t.skill_schema_hash.length>0&&typeof t.status=="string"&&$o.includes(t.status)}function Wn(e,t){let n=typeof e.action=="string"?e.action:"",r=typeof e.actionSchemaId=="string"&&e.actionSchemaId.length>0?e.actionSchemaId:null,i=typeof e.fingerprint=="string"&&e.fingerprint.length>0?e.fingerprint:null,a=typeof e.fingerprintRadius=="number"&&Number.isFinite(e.fingerprintRadius)?e.fingerprintRadius:15;if(n.length===0&&r===null&&i===null)return{blocked:!1,skillId:null};for(let o of t)if(Po(o)&&o.status==="approved"){if(n.length>0&&o.skill_id===n)return{blocked:!0,skillId:o.skill_id,matchedBy:"action"};if(r!==null&&o.skill_schema_hash===r)return{blocked:!0,skillId:o.skill_id,matchedBy:"schema"};if(i!==null&&typeof o.skill_fingerprint=="string"){let s=Mo(i,o.skill_fingerprint);if(s<=a&&s<64)return{blocked:!0,skillId:o.skill_id,matchedBy:"fingerprint",fingerprintDistance:s}}}return{blocked:!1,skillId:null}}function Hn(e){return e==="open"||e==="closed"?e:null}var Do=["tool_name","function","name","action"];function Ie(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)Ie(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)Ie(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Fo(e){let t=[];return Ie(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function jo(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function Bo(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function Uo(e,t={}){if(t.discriminatorField===null)return null;let n=[];Ie(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??Do;for(let i of r){let a=null;for(let[o,s]of n){if(jo(o)!==i)continue;let l=Bo(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function Qn(e,t={}){let n=Lo("sha256").update(Fo(e).join(",")).digest("hex").slice(0,16),r=Uo(e,t);return r!==null?`${n}:${r}`:n}var qo=["action","retrieval","delegation"];function zo(e){return typeof e=="string"&&qo.includes(e)}var Vo=new Set(["rules"]);function Yn(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Vo.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(zo):[];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}}function Zn(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=ot(r)}catch{continue}let a=no(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()}}import{z as Ee}from"zod";import{createHash as js}from"node:crypto";var Jn=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Go(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:Jn(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:Jn(t.spawn.prompt)}),t}function Ko(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 Wo=1440*60*1e3,Ho="VISIQ_BUNDLE_GRACE_TTL_MS",Qo="VISIQ_BUNDLE_CACHE_DISABLED",Yo="VISIQ_CACHE_DIR",Zo=Ee.object({graceTtlMs:Ee.number().int().nonnegative().optional(),disabled:Ee.boolean().optional(),cacheDir:Ee.string().min(1).optional()}).strict();function Jo(e){return e==null?{}:Zo.parse(e)}function Xo(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Ho];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Wo}function es(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Qo]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var Xn;function ts(){if(Xn!==void 0)return Xn;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function ns(e){return JSON.stringify(dt(e))}function dt(e){if(Array.isArray(e))return e.map(dt);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=dt(t[r]);return n}return e}function rs(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function is(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 sr(){if(!ts())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 lr(e,t){return e.createHash("sha256").update(ns(t)).digest("hex")}function as(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Yo]?.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 os(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function cr(e,t,n){return e.path.join(as(e,n),"bundles",`${os(e,t)}.json`)}async function ss(e,t,n,r={}){let i=await sr();if(i)try{let a=cr(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:lr(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 ls(e,t={}){let n=await sr();if(!n)return null;try{let r=await n.fs.readFile(cr(n,e,t),"utf-8"),i=is(JSON.parse(r));return!i||lr(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var Z;async function cs(){if(Z!==void 0)return Z;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;Z=typeof t=="function"?t:null}catch{Z=null}return Z}function ds(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=ot(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of Nn(a))t.push(`${o}: ${s}`)}return t}function us(e){return Zn(e)}function ps(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var fs=5e3,ms=600*1e3,gs=1e4,hs=25,er=1e3,_s=5e3,ys=100,tr=2e3,bs=10,vs=512,ws=1800*1e3,As=.7,ks="monitor",Is="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",nr="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.",Ss="open";function rr(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Es(e,t){return Jt({content:e,resourceMetadata:t})}var Cs=f.object({operations:f.array(f.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:f.string().min(1,"agentId is required"),sessionId:f.string().min(1).max(255).optional(),toolName:f.string().optional(),toolArgs:f.record(f.unknown()).optional(),targetResource:f.string().optional(),resourceType:f.string().optional(),resourceMetadata:f.record(f.unknown()).optional(),normalized:f.record(f.unknown()).optional(),query:f.string().optional(),contentPreview:f.string().optional(),telemetry:f.record(f.unknown()).optional(),context:f.record(f.unknown()).optional(),mcpServer:f.string().min(1).max(255).optional(),identity:f.object({attested:f.array(f.string().min(1).max(255)).max(32).optional(),claimed:f.array(f.string().min(1).max(255)).max(32).optional(),subjectId:f.string().min(1).max(255).optional()}).optional()}),Ns=f.object({version:f.string().min(1),dialect_version:f.number().int().optional(),min_dialect:f.number().int().optional(),shutdown:f.boolean().optional(),agent_mode:f.enum(["enforce","monitor","off"]).optional(),cognition_capture:f.boolean().optional(),agent_mode_by_operation:f.object({action:f.string().optional(),retrieval:f.string().optional(),delegation:f.string().optional()}).partial().optional(),agent_attributes:f.object({trust_tier:f.string().nullable().optional(),categories:f.array(f.string()).optional(),business_function:f.string().nullable().optional(),business_functions:f.array(f.string()).nullable().optional(),blast_radius_tier:f.string().nullable().optional(),no_coverage:f.string().nullable().optional(),fail_mode:f.string().nullable().optional()}).optional(),rules:f.array(f.record(f.unknown())),action_schemas:f.array(f.object({id:f.string(),plane:f.string().optional(),field_mappings:f.array(f.record(f.unknown())).optional(),derived_fields:f.array(f.record(f.unknown())).optional(),action_class:f.string().nullable().optional(),action_class_confidence:f.number().optional()})).optional(),no_coverage:f.object({no_coverage_defaults:f.record(f.string()),autopilot_enabled:f.boolean(),enduser_hitl_enabled:f.boolean(),hitl_timeout_seconds:f.number().optional()}).optional(),skill_blacklist:f.array(f.record(f.unknown())).optional()});function Ts(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=zn(Vn(n));return{trust_tier:Pn(t)?t:null,categories:Dn(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&Gn(e.blast_radius_tier)?e.blast_radius_tier:null}}function xs(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 Rs(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var ut=new Set,ir=!1;async function ar(e){let t=[];for(let n of ut){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 Os(){if(!ir&&!(typeof process>"u"||typeof process.once!="function")){ir=!0,process.once("beforeExit",()=>{ar(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await ar(!0)}finally{process.kill(process.pid,e)}})()})}}var dr=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];skillBlacklist=[];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=ks;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=rr(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Ss;governedFailMode=null;telemetryBuffer=[];droppedTelemetry=0;inFlightTelemetry=new Set;telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastSkillInventorySig=null;skillInventoryPromise=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 u=Jo(s);if(this.bundleCacheDisabled=es(u.disabled),this.bundleGraceTtlMs=Xo(u.graceTtlMs),this.bundleCacheDirOverride=u.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:d,apiKey:l}:null,l&&c){let p={apiKey:l,agentId:d,endpoint:c,mode:"enforce",timeoutMs:Ko(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new Xe(p,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},fs),ct(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},gs),ct(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},_s),ct(this.cognitionTimer),ut.add(this),Os()}else this.client=null}async evaluate(e){let t=Cs.parse(e),n=Date.now();if(this.operatorShutdown){let m=this.denyAll(t,Is);return this.applyAgentMode(m,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,nr,n);let m=this.denyAll(t,nr);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)}if(this.modeFor("action")!=="off"){let m=this.matchSkillQuarantine(t);if(m){let h=this.denyAll(t,m);return this.applyAgentMode(h,this.modeFor("action"),t,n)}}let r=this.readSession(t.sessionId),i=await cs();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")?Rn(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 u=[...new Set(t.operations.flatMap(m=>this.normalizedRefs[m]??[]))].sort();u.length>0&&ps(t.normalized)&&(d.normalizedColdStart=u,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${u.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: ${u.slice(0,5).join("; ")}${u.length>5?`; +${u.length-5} more`:""}`)));let p=On(t.normalized);return p.length>0&&(d.normalizedDrift=p,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${p.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: ${p.slice(0,5).join("; ")}${p.length>5?`; +${p.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}matchSkillQuarantine(e){if(this.skillBlacklist.length===0)return null;let t=e.context?.skill;if(!t||t.activated!==!0)return null;let n=typeof t.name=="string"?t.name:"",r=typeof t.fingerprint=="string"?t.fingerprint:null;if(n.length===0&&r===null)return null;let i=Wn({action:n,fingerprint:r},this.skillBlacklist);return i.blocked?i.matchedBy==="fingerprint"?"skill quarantined for the agent \u2014 its content signature matches a blacklisted skill (a renamed or edited re-skin); blocked ([D-27])":"skill quarantined for the agent \u2014 it is on the approved blacklist; blocked ([D-27])":null}readSession(e){if(!e)return Y;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>ws?(this.sessions.delete(e),Y):t.state:Y}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>=As)return a}foldSubjectId(e){let t=e.identity?.subjectId;if(typeof t=="string"&&t.length>0)return t;let n=e.normalized?.write;if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let r=n.subject_id;if(typeof r=="string"&&r.length>0)return r}}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=Mn(r===Y?Se():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?Es(e.contentPreview,i):void 0,action_class:o?this.foldActionClass(e):void 0,target_app:o?e.targetResource??e.toolName:void 0,attested_subjects:e.identity?.attested,claimed_subjects:e.identity?.claimed,subject_id:o?this.foldSubjectId(e):void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>vs){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=Ns.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=ds(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=>Yn(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?Ts(t.agent_attributes):null,this.agentNoCoverage=Hn(t.agent_attributes?.no_coverage),this.governedFailMode=rr(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=xs(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=us(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",...Je(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>=ms&&(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 ls(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(rs(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 ss(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({..._e(),...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))}reportSkillInventory(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,h:n.content_hash})).sort((n,r)=>n.n===r.n?n.h.localeCompare(r.h):n.n.localeCompare(r.n)));t!==this.lastSkillInventorySig&&(this.lastSkillInventorySig=t,this.skillInventoryPromise=this.client.reportSkillInventory(e).catch(()=>{}))}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({..._e(),...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=Qn(n),i={...n};return e.toolArgs&&(i.tool_args=zt(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?Rs(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?{[_n]: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,bs)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=hs&&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),{client:t}=this,n=(async()=>{try{await t.sendTelemetry(e)}catch(r){this.droppedTelemetry+=e.length,console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",r)}})();this.inFlightTelemetry.add(n);try{await n}finally{this.inFlightTelemetry.delete(n)}}async drainInFlightTelemetry(){for(let e=0;e<8&&this.inFlightTelemetry.size>0;e+=1)await Promise.allSettled([...this.inFlightTelemetry])}droppedTelemetryCount(){return this.droppedTelemetry}enforceTelemetryCap(){let e=this.telemetryBuffer.length-er;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${er})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Go(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=ys&&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-tr;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${tr})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}if(this.skillInventoryPromise)try{await this.skillInventoryPromise}catch{}await this.flushTelemetry(),await this.drainInFlightTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),ut.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 ct(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function J(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function ur(e,t){if(e!=="sessions_spawn")return null;let n=J(t.agentId);return n?{childAgentId:n,childName:J(t.taskName)??J(t.label)??n,kind:"subagent",task:J(t.task),model:J(t.model),source:"structural"}:null}function pr(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 Ms={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"},$s=new Set(["workspace_deactivate_skill"]),Ps=new Set(["read","read_file","readfile","view","cat"]);function Ls(e){return $s.has((e??"").trim())}function Ds(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function fr(e){if(typeof e!="string"||e.length===0)return[];let t=[],n=new Set,r=/<skill\s+name="([^"]+)"\s+location="([^"]*)"\s*>/gi,i;for(;(i=r.exec(e))!==null;){let a=(i[1]??"").trim(),o=(i[2]??"").trim();if(!a)continue;let s=`${a}
9
+ ${o}`;n.has(s)||(n.add(s),t.push({name:a,location:o}))}return t}function or(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function Fs(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=Ms[n];if(i){let a=or(r,["name","skill_name","identifier","skill","path"]);return a?{skill:a,via:n,framework:i}:null}if(Ps.has(n.toLowerCase())){let a=or(r,["path","file_path","filePath","target","file"]),o=a?Ds(a):null;return o?{skill:o,via:n,framework:"unknown"}:null}return null}function mr(e,t){let{activation:n,attributedSkill:r}=e;if(r)return{skill:{name:r,activated:!!n,...n?{via:n.via,framework:n.framework}:{},...t?{fingerprint:t}:{}}}}var gr=class{#e=null;activate(e){return this.#e=e,e}deactivate(e){(!e||this.#e?.skill===e)&&(this.#e=null)}current(){return this.#e}observe(e,t){let n=Fs(e,t);if(n)return this.activate(n),{activation:n,attributedSkill:n.skill};if(Ls(e)){let r=this.#e?.skill??null,i=t&&typeof t.name=="string"?t.name:void 0;return this.deactivate(i),{activation:null,attributedSkill:r}}return{activation:null,attributedSkill:this.#e?.skill??null}}},Bs=/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,Us=/^([A-Za-z0-9_.-]+):[ \t]*(.*)$/;function qs(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1):t}function zs(e,t){let n=t.startsWith("|");return(n?e.join(`
10
+ `):e.join(" ")).replace(/[ \t]+/g,n?"$&":" ").trim()}function Vs(e){let t=Bs.exec(e);if(!t)return{attrs:{},body:e};let[,n]=t,r=e.slice(t[0].length),i={},a=(n??"").split(/\r?\n/);for(let o=0;o<a.length;o+=1){let s=a[o]??"";if(!s.trim()||s.trimStart().startsWith("#")||/^[ \t]/.test(s))continue;let l=Us.exec(s);if(!l)continue;let c=l[1],d=(l[2]??"").trim();if(/^[|>][+-]?\d*$/.test(d)){let u=[],p=o+1;for(;p<a.length;p+=1){let m=a[p]??"";if(m.trim()&&!/^[ \t]/.test(m))break;u.push(m.trim())}o=p-1,i[c]=zs(u,d);continue}d&&(i[c]=qs(d))}return{attrs:i,body:r}}function Gs(e){return js("sha256").update(e,"utf8").digest("hex")}function hr(e,t,n){let{attrs:r,body:i}=Vs(e),{description:a}=r;return{name:r.name?.trim()||n,path:t,...a?{description:a}:{},contentHash:Gs(i),fingerprint:Kn(i)}}var Ul=512*1024;var P=null;function N(e){let t=`${e.apiKey}::${e.agentId}::${e.baseUrl??""}`;if(P&&P.key===t)return P.runtimes;let n=new dr(e.apiKey,e.baseUrl,e.agentId,"cli_harness",void 0,pn,Ze);return n.setFailMode(e.failMode),n.registerHostEnvironment(),P={key:t,runtimes:{unified:n}},P.runtimes}async function Ql(){if(P)try{await P.runtimes.unified.flush()}catch{}}async function Yl(e){try{let t=await pe();if(!t)return;let{unified:n}=N(t);await n.awaitBundleReady(e)}catch{}}function _r(){return P?.runtimes.unified.getAgentMode()}function S(e){try{process.stderr.write(`[VisIQ] FAIL-OPEN (${e.stage}): ${e.detail} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.
11
+ `)}catch{}if(e.config)try{N(e.config).unified.reportFailOpen(`${e.stage}: ${e.detail}`,{...e.toolName?{toolName:e.toolName}:{},...e.sessionId?{sessionId:e.sessionId}:{}})}catch{}}function X(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.
12
+ `)}catch{}}function O(e,t){return e?.sessionKey??t?.sessionKey??t?.sessionId??"default"}var pt=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}},ft=new Map;function j(e){let t=ft.get(e);return t||(t=new pt,ft.set(e,t)),t}function yr(e){ft.delete(e)}var br=new Set(["web_search","x_search","web_fetch","tool_search","tool_describe","get_account","get_transactions","get_devices","check_watchlist","search_knowledge"]);function vr(e){return br.has(Be(e))}function nc(){return br}var Ks=512*1024;async function wr(e){try{let t=e??{},n=["path","file_path","filePath","target","file"].map(s=>t[s]).find(s=>typeof s=="string"&&s.trim().length>0)?.trim();if(!n||!/SKILL\.md$/i.test(n))return;let{readFile:r,stat:i}=await import("node:fs/promises"),a=await i(n);if(!a.isFile()||a.size>Ks)return;let o=await r(n,"utf8");return hr(o,n,n).fingerprint}catch{return}}var ee=new Map,Ws=2e3;function Hs(e){let t=ee.get(e);if(!t){if(ee.size>=Ws){let{value:n}=ee.keys().next();n!==void 0&&ee.delete(n)}t=new gr,ee.set(e,t)}return t}var mt="@visiq/openclaw-plugin";function Ar(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 wc(e,t){let{config:n,failMode:r}=await fe();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."};S({stage:"unconfigured",detail:"no VisIQ credentials resolved (need VISIQ_API_KEY + VISIQ_AGENT_ID)",toolName:e.toolName,sessionId:O(e,t)});return}let i=N(n),a=n.agentId??t.agentId,o=O(e,t),s=t.toolCallId??e.toolCallId,c=vr(e.toolName)?["retrieval","action"]:["action"],d=Qs(e.params),u=ur(e.toolName,e.params??{}),p;u&&a&&(nt(i.unified,{agentId:a,sessionId:o,framework:"openclaw"},u),c.push("delegation"),p=pr(u,a));let m;try{let b=Hs(o).observe(e.toolName,e.params??{}),w=b.activation?await wr(e.params):void 0;m=mr(b,w)}catch{m=void 0}let h=p||m?{...p??{},...m??{}}:void 0,_=a?{agentId:a,sessionId:o,framework:"openclaw"}:null,y=z(e.toolName,e.params??{});if(_)try{K(i.unified,_,{toolName:e.toolName,...y?{memory:y}:{}})}catch(b){X("step-beat",e.toolName,b)}let I=(b,w,D,x)=>{if(_)try{it(i.unified,_,{toolName:e.toolName,decision:b,...w?{ruleCode:w}:{},...D?{ruleLabel:D}:{},enforced:!0,...x?{harnessMessage:x}:{}})}catch(R){X("intervention-beat",e.toolName,R)}},v;try{if(await i.unified.awaitBundleReady(),!i.unified.isBundleLoaded()&&n.failMode!=="closed"){S({stage:"no-bundle",detail:"no rule bundle available after warm-up",toolName:e.toolName,sessionId:o,config:n});return}v=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}:{},...h?{context:h}:{}})}catch(b){let w=b instanceof Error?b.message:String(b);if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ] Evaluation error \u2014 blocked (VISIQ_FAIL_MODE=closed): ${w}`};S({stage:"eval-error",detail:w,toolName:e.toolName,sessionId:o,config:n});return}if(!v.enforced)return;let{action:k}=v;if(k.decision==="approval_required")return I("approval_required",v.ruleCode??void 0,v.reason),{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:v.reason,severity:"critical",allowedDecisions:["allow-once","allow-always","deny"],pluginId:mt}};if(!k.allowed){let w=`[VisIQ ${v.ruleCode??"DENY"}] ${v.reason}`;return I("deny",v.ruleCode??void 0,v.reason,w),{block:!0,blockReason:w}}let E;if(k.decision==="mask"&&k.argRedactionRules&&k.argRedactionRules.length>0)try{E=se(e.params??{},Ar(k.argRedactionRules)),I("mask",v.ruleCode??void 0,v.reason)}catch(b){let w=b instanceof Error?b.message:String(b);if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ] Argument masking failed \u2014 blocked (VISIQ_FAIL_MODE=closed): ${w}`};S({stage:"mask-error",detail:`argument masking failed \u2014 running with UNMASKED params: ${w}`,toolName:e.toolName,sessionId:o,config:n}),E=void 0}if(c.includes("retrieval"))switch(v.retrieval.action){case"allow":case null:break;case"deny":{let b=`[VisIQ retrieval governance] ${v.reason}`;return I("deny",v.ruleCode??void 0,v.reason,b),{block:!0,blockReason:b}}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)"};S({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 b=v.retrieval.redactionRules??[];b.length>0&&j(o).set(s,Ar(b));break}case"escalate":return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:v.reason,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:mt}};default:{let b=v.retrieval.action;if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ retrieval governance] Unknown action "${String(b)}" \u2014 blocked (VISIQ_FAIL_MODE=closed)`};S({stage:"unknown-retrieval-verb",detail:`unknown retrieval action "${String(b)}" (harness/backend version skew)`,toolName:e.toolName,sessionId:o,config:n});break}}if(Ue(e.toolName)){let b=n.failMode==="closed"?"closed":"open",w=E??e.params??{},D=!1,x=ie(w,{failMode:b});if(x.verdict==="block")return{block:!0,blockReason:`[VisIQ OUTPUT-BLOCK] outbound content carried a live secret (${x.detectors.join(",")}) \u2014 blocked (VISIQ_FAIL_MODE=closed)`};x.verdict==="redact"&&(w=x.redacted,D=!0,S({stage:"outbound-secret-redacted",detail:`outbound secret screen redacted ${x.detectors.length} detector(s): ${x.detectors.join(",")}`,toolName:e.toolName,sessionId:o,config:n}));let R=oe(w,{failMode:b});if(R.verdict==="block")return{block:!0,blockReason:`[VisIQ OUTPUT-BLOCK] outbound content matched a brand/topic rule (${R.matched.join(",")}) \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(R.verdict==="redact"&&(w=R.redacted,D=!0,S({stage:"outbound-brand-topic-redacted",detail:`outbound brand/topic screen redacted ${R.matched.length} rule(s): ${R.matched.join(",")} (recommended: ${R.recommendedOutcome??"none"})`,toolName:e.toolName,sessionId:o,config:n})),D)return{params:w}}if((n.sequenceAnomaly?.enabled??!0)&&typeof i.unified.getSessionState=="function"&&o){let b=i.unified.getSessionState(o),w=lt(b,{failMode:n.failMode==="closed"?"closed":"open",config:n.sequenceAnomaly?.thresholds});if(w.verdict==="deny")return{block:!0,blockReason:`[VisIQ ANOMALY] session-sequence anomaly (${w.signals.join(",")}) over ${w.evidence.event_count} events \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(w.verdict==="hold")return S({stage:"sequence-anomaly-hold",detail:`session-sequence anomaly held for approval (${w.signals.join(",")}) over ${w.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 (${w.signals.join(",")}). Approve to proceed, or deny to stop the run.`,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:mt}}}if(E)return{params:E}}function Qs(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 Tc(e,t){let{ready:n,config:r}=me();if(!n||!r)return;let i=O(e,t),a=e.toolName??t.toolName,o=r.agentId??t.agentId;if(a&&o)try{let u=e.message?.content,p=z(a);rt(N(r).unified,{agentId:o,sessionId:i,framework:"openclaw"},{toolName:a,ok:!0,...ye(u)!==void 0?{bytes:ye(u)}:{},...be(u)!==void 0?{itemCount:be(u)}:{},...p?{memory:p}:{}})}catch(u){X("observation-beat",a,u)}let s=e.toolCallId??t.toolCallId;if(!s)return;let l=j(i),c=l.get(s);if(!c)return;let d={...e.message};return d.content!==void 0&&(d.content=se(d.content,c)),l.delete(s),{message:d}}function B(e,t){return e?.sessionKey||e?.sessionId||t?.sessionKey||t?.sessionId||void 0}var gt=new Map;function kr(e,t){e&&gt.set(e,t)}function Ir(e){return e?gt.get(e):void 0}function Sr(e){e&&gt.delete(e)}function Fc(e,t){let{ready:n,config:r,failMode:i}=me();if(n&&!r)return;let a=O(e,t),o=j(a);if(o.size()>0){if(o.clear(),i==="closed")return{block:!0};S({stage:"unconsumed-redaction",detail:"queued redaction was never applied to a tool result before message write",sessionId:a,config:r})}if(r&&_r()==="enforce"){let s=i==="closed"?"closed":"open",l=ie(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 u=!1,p=Ir(B(e,t));if(p){let _=en(c,p,{failMode:s});if(_.verdict==="block")return{block:!0};_.verdict==="redact"&&(c=_.redacted,u=!0,S({stage:"final-message-prompt-leak-redacted",detail:`final assistant message leaked the system prompt \u2014 masked ${_.matchedSpans.length} verbatim span(s)`,sessionId:a,config:r}))}let m=!1,h=oe(c,{failMode:s});if(h.verdict==="block")return{block:!0};if(h.verdict==="redact"&&(c=h.redacted,m=!0,S({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&&S({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||u||m)return{message:c}}}async function Gc(e,t){try{let{config:n}=await fe();if(!n)return;typeof e.systemPrompt=="string"&&e.systemPrompt.trim().length>0&&kr(B(e,t),e.systemPrompt);let{unified:r}=N(n);if(t.agentId)try{for(let i of fr(e.prompt))K(r,{agentId:t.agentId,sessionId:t.sessionKey??t.sessionId,framework:"openclaw"},{toolName:"skill:invoke",verb:"activate",argSummary:`${i.name} @ ${i.location}`})}catch{}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 Yc(e,t){try{let n=await pe();if(!n)return;let r=n.agentId??t.agentId;if(!r)return;let i=e.sessionId??t.sessionId??t.sessionKey,{unified:a}=N(n);await a.awaitBundleReady(),tt(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 ed(e,t){yr(O(e,t)),Sr(B(e,t))}export{Be as a,de as b,Ke as c,fl as d,He as e,hl as f,yl as g,pn as h,Ql as i,Yl as j,S as k,pt as l,j as m,yr as n,vr as o,nc as p,wc as q,Tc as r,Fc as s,Gc as t,Yc as u,ed as v};
package/dist/index.js CHANGED
@@ -1 +1 @@
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-IUJACBHD.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};
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-5VRHQXXS.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};
@@ -1,4 +1,4 @@
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-IUJACBHD.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(`
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-5VRHQXXS.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
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
3
  ${r.content}`).join(`
4
4
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "@visiq/openclaw-plugin",
3
3
  "name": "VisIQ OpenClaw Plugin",
4
- "version": "0.1.19",
4
+ "version": "0.1.21",
5
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": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visiq/openclaw-plugin",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
4
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",
@@ -65,7 +65,7 @@
65
65
  "homepage": "https://docs.visiqlabs.com",
66
66
  "repository": {
67
67
  "type": "git",
68
- "url": "https://github.com/VISIQ-LABS/xy.git",
68
+ "url": "https://github.com/VISIQ-LABS/visiq-platform.git",
69
69
  "directory": "packages/visiq-openclaw-plugin"
70
70
  },
71
71
  "keywords": [
@@ -1,12 +0,0 @@
1
- var wr=/[^\u0000-\u007F]/,xt=new RegExp("^\\p{Nd}$","u"),Ar=new RegExp("^\\p{Pd}$","u"),kr=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,Ir=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,Sr=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),Rt="<invisible>",ft=new Map;function Er(e){let t=String.fromCodePoint(e).normalize("NFKC");if(t.length===1&&t>="0"&&t<="9")return t;let n=e;for(let i=0;i<256&&n>0&&xt.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function Cr(e){if(e<128)return null;let t=ft.get(e);if(t!==void 0)return t;let n=(()=>{if(e>=65281&&e<=65374)return String.fromCharCode(e-65248);let r=String.fromCodePoint(e);return xt.test(r)?Er(e):Ar.test(r)||Sr.has(e)?"-":kr.test(r)?" ":Ir.test(r)?Rt:null})();return ft.set(e,n),n}function Re(e){if(typeof e!="string"||e.length===0||!wr.test(e))return[];let t=mt(e,"as-separator");if(t===null)return[];let n=mt(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function mt(e,t){let n=[],r=[],i=!1;for(let a=0;a<e.length;){let o=e.codePointAt(a),s=o>65535?2:1,l=Cr(o);if(l===null){for(let c=0;c<s;c++)n.push(e[a+c]),r.push(a+c);a+=s;continue}if(i=!0,l===Rt){t==="as-separator"&&(n.push(" "),r.push(a)),a+=s;continue}n.push(l),r.push(a),a+=s}return i?(r.push(e.length),{label:t,text:n.join(""),offsets:Int32Array.from(r)}):null}function Nr(e,t){return{start:e.offsets[t.start],end:e.offsets[t.end]}}function Tr(e){if(e.length<=1)return[...e];let t=[...e].sort((i,a)=>i.start-a.start||i.end-a.end),n=[],r={start:t[0].start,end:t[0].end};for(let i=1;i<t.length;i++){let a=t[i];a.start<=r.end?a.end>r.end&&(r={start:r.start,end:a.end}):(n.push(r),r={start:a.start,end:a.end})}return n.push(r),n}function gt(e,t){let n=[];e.lastIndex=0;let r;for(;(r=e.exec(t))!==null;){if(r[0].length===0){e.lastIndex++;continue}n.push({start:r.index,end:r.index+r[0].length})}return n}var Ot="[REDACTED]",Oe=[{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:/(?<![A-Za-z0-9._%+-])[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}],js=Oe.map(({name:e,re:t})=>({name:e,source:t.source})),xr="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function Rr(e){return Mt(e,xr)}function Mt(e,t){let n="",r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a==="\\"){if(!r&&e[i+1]==="b"){n+=t,i++;continue}n+=a+(e[i+1]??""),i++;continue}a==="["?r=!0:a==="]"&&(r=!1),n+=a}return n}function $t(e){return new RegExp(Rr(e.source),e.flags)}var Or="(?:\\b|_)";function Se(e){return Mt(e,Or)}var Mr=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function $r(e){let t=Mr.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function Ee(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 Pr(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 Lr(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 Dr=[[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]],Fr=[[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 jr(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=Dr[t][Fr[r%8][n[r].charCodeAt(0)-48]];return t===0}function Br(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 Ur(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 qr=[1,4,3,7,5,8,6,9,10];function zr(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)*qr[n];return t%11===0}var Vr="TRWAGMYFPDXBNJZSQVHLCKE";function Gr(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 Vr[Number(o)%23]===a}var Kr=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Wr(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Kr.has(t.slice(0,2)):!1}var Me=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&Ee(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:Pr},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Lr},{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:Wr(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&&jr(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:Br},{name:"es_dni_nie",re:/\b(?:[XYZxyz]-?)?(?:\d{7,8}|\d{1,2}[. ]\d{3}[. ]\d{3})[ -]?[A-Za-z]\b/g,normalize:e=>e.replace(/[\s.-]/g,"").toUpperCase(),validate:Gr},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&Ee(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Ur},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:zr}],Hr=Object.fromEntries([...Oe,...Me].map(e=>[e.name,e.re.source])),A=Hr,Bs=Me.map(e=>e.name),Pt=Oe.map(({name:e,re:t})=>({name:e,re:$t(t)})),Lt=Me.map(e=>({...e,re:$t(e.re)})),Us=[...Pt,...Lt].map(({name:e,re:t})=>({name:String(e),source:t.source})),$e=["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"],Qr={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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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:A.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). Collision rate: MEASURED 9.8% of benign 16-digit runs \u2014 Luhn leaves ~1 in 10. Default-ON because PCI-DSS makes masking mandatory; note in_aadhaar sits at the same rate and is often proposed for removal on that basis.",category:"financial",example:"4242 4242 4242 4242",template:{pattern:A.pan,mode:"partial",keepLast:4,templateOnly:{reason:"A rego rule cannot run Luhn, so the rule masks EVERY 13-19 digit run (grouped or not) \u2014 the floor's regex without the checksum that makes it precise. ~9 in 10 of those are not card numbers.",examples:["4242 4242 4242 4243","4242424242424241"],measuredOverMaskRate:.531}},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible. Collision rate: MEASURED 1.0% \u2014 mod-97 leaves ~1 in 97, the most precise detector on this floor alongside br_cpf.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:A.iban,mode:"partial",keepLast:4,templateOnly:{reason:"A rego rule cannot run mod-97, so the rule masks EVERY IBAN-SHAPED token (2 letters, 2 digits, 10-30 alphanumerics) \u2014 and mod-97 is what makes this the most precise detector on the floor, so almost all of those are not IBANs.",examples:["DE89 3704 0044 0532 0130 01","GB00 NWBK 6016 1331 9268 19"],measuredOverMaskRate:.934}},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:A.aba_routing,mode:"full",templateOnly:{reason:"A rego rule cannot run the weighted 3-7-1 mod-10, so the rule masks EVERY bare 9-digit run \u2014 which is why this detector is default-OFF on the floor and why its rule form is broader still.",examples:["021000022","123456789"],measuredOverMaskRate:.899}},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX). Collision rate: MEASURED 100% \u2014 no checksum, so every 2-then-7 dashed digit run matches. Same trade as ssn: the punctuated shape is rare in benign traffic, not precise.",category:"financial",example:"12-3456789",template:{pattern:A.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:A.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789). Collision rate: MEASURED 100% \u2014 there is NO checksum, so every dashed 3-2-4 digit run matches. Default-ON regardless, because that punctuated shape is essentially absent from benign agent traffic; if your traffic carries 3-2-4 dashed reference codes, opt out.",category:"pii",example:"123-45-6789",template:{pattern:A.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-Za-ceghj-npr-tw-z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-Da-d]|[A-CEGHJ-PR-TW-Za-ceghj-pr-tw-z][A-CEGHJ-NPR-TW-Z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-Da-d]|[A-CEGHJ-PR-TW-Za-ceghj-pr-tw-z][A-CEGHJ-NPR-TW-Za-ceghj-npr-tw-z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-D])\\b",mode:"full",templateOnly:{reason:"uk_nino has no checksum, but the floor still rejects the seven NEVER-ISSUED administrative prefixes (BG GB NK KN TN NT ZZ). A rego rule cannot express that exclusion without enumerating hundreds of letter pairs (RE2 has no lookahead), so the rule masks those too.",examples:["NK 12 34 56 A","ZZ 12 34 56 C"],measuredOverMaskRate:.019}},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. Collision rate: MEASURED 10.0% of benign 12-digit ids starting 2-9 (order/transaction numbers) \u2014 Verhoeff leaves ~1 in 10. Comparable to the long-shipped pan (10.0%) and well behind iban (1.0%); it stays default-ON because the two US identifiers this floor has always shipped, ssn and us_ein, collide at 100%.",category:"pii",example:"2345 6789 0124",template:{pattern:"\\b[2-9]\\d{3}(?:[ -]\\d{4}[ -]?\\d{4}|\\d{4}[ -]\\d{4})\\b",mode:"partial",keepLast:4,floorOnly:{reason:"The floor accepts the entirely UNPUNCTUATED 12-digit form because Verhoeff gates it (~1 in 10 survive). A rego rule cannot run Verhoeff, so a bare \\d{12} in a rule would mask every 12-digit order id and E.164 Indian mobile number in the tenant. The rule requires at least one printed separator \u2014 every half-punctuated form is covered; only the bare digit run stays floor-only.",examples:["234567890124","id=234567890124"]},templateOnly:{reason:"A rego rule cannot run the Verhoeff checksum, so the rule masks EVERY 4-4-4 grouping that starts 2-9 \u2014 including the ~9 in 10 that are not Aadhaar numbers at all.",examples:["2345 6789 0125","2345-6789-0123"],measuredOverMaskRate:.903}},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:A.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. Collision rate: MEASURED 1.0% of benign 11-digit runs (~1-in-100) \u2014 the most precise detector on this floor, alongside iban. 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}|\\d{3}(?:\\.\\d{3}-?\\d{2}|\\d{3}-\\d{2}))\\b",mode:"partial",keepLast:2,floorOnly:{reason:"The floor accepts the entirely bare 11-digit form because TWO mod-11 check digits gate it (~1 in 100 survive). A rego rule cannot run mod-11, so a bare \\d{11} in a rule would mask every 11-digit identifier in the tenant. The rule requires at least one printed separator; the bare form stays floor-only.",examples:["11144477735","ref 11144477735","12345678909"]},templateOnly:{reason:"A rego rule cannot run the two mod-11 check digits, so the rule masks EVERY punctuated 3-3-3-2 digit grouping \u2014 including the ~99 in 100 that are not CPFs.",examples:["123.456.789-10","111.444.777-34"],measuredOverMaskRate:.995}},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. Collision rate: MEASURED 4.0% of benign 8-digit-plus-letter tokens (invoice/order numbers with a suffix letter) \u2014 mod-23 leaves ~1 in 23. More precise than in_aadhaar (10.0%) and pan (10.0%); behind br_cpf (1.0%) and iban (1.0%).",category:"pii",example:"12345678Z",template:{pattern:A.es_dni_nie,mode:"full",templateOnly:{reason:"A rego rule cannot run the mod-23 check letter, so the rule masks EVERY 7-8 digit run followed by a letter \u2014 invoice and order numbers with a suffix letter included. mod-23 admits ~1 in 23; the rule admits all of them. Re-measured 0.973 \u2192 0.981 when the floor learned the printed forms (dotted DNI, hyphenated NIE): the rule now also matches those written forms, and ~22 in 23 of them are not DNI/NIEs. The FLOOR's own rate is unchanged \u2014 mod-23, not punctuation, gates it.",examples:["12345678A","X1234567H"],measuredOverMaskRate:.976}},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}|\\d{3}[- ]\\d{3})\\b",mode:"partial",keepLast:3,floorOnly:{reason:"The floor accepts the entirely bare 9-digit form because Luhn gates it. A rego rule cannot run Luhn, and a bare \\d{9} in a rule is also every ABA routing number and every 9-digit identifier, so the rule requires at least one printed separator in the 3-3-3 grouping.",examples:["046454286"]},templateOnly:{reason:"A rego rule cannot run Luhn, so the rule masks EVERY printed 3-3-3 digit grouping \u2014 including the ~9 in 10 that are not SINs.",examples:["046 454 287","123 456 789"],measuredOverMaskRate:.914}},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}|\\d{3}[- ]\\d{4})\\b",mode:"full",floorOnly:{reason:"The floor accepts the entirely bare 10-digit form because the weighted mod-11 gates it. A rego rule cannot run mod-11, and a bare \\d{10} in a rule is also every North American phone number, so the rule requires at least one printed separator in the 3-3-4 grouping.",examples:["9434765919"]},templateOnly:{reason:"A rego rule cannot run the weighted mod-11, so the rule masks EVERY printed 3-3-4 digit grouping \u2014 every North American phone number included \u2014 not just the ~1 in 10 that are NHS numbers.",examples:["943 476 5910","123 456 7890"],measuredOverMaskRate:.899}},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}|\\d{3}[- ]\\d{2,3})\\b",mode:"full",floorOnly:{reason:"The floor accepts the entirely bare 8-9 digit form because the weighted mod-11 gates it. A rego rule cannot run mod-11, and a bare \\d{8,9} in a rule collides with essentially every identifier of that length, so the rule requires at least one printed separator. BOTH lengths are in the gap: a TFN may be 8 digits (`12345679`) or 9 (`123456782`), and the 8-digit branch went undeclared while the parity sweep derived its population from the 9-digit example alone.",examples:["12345679","123456782"]},templateOnly:{reason:"A rego rule cannot run the weighted mod-11, so the rule masks EVERY printed 3-3-2/3-3-3 digit grouping \u2014 including the ~9 in 10 that are not TFNs.",examples:["123 456 783","123 456 78"],measuredOverMaskRate:.912}},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:A.date_of_birth,mode:"full"},defaultEnabled:!1},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept). Collision rate: MEASURED 100% of well-formed addresses \u2014 that is BY DESIGN, not a defect: an email address is structurally unambiguous, so matching every one is correct rather than over-matching.",category:"pii",example:"alice@acme.com",template:{pattern:A.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:A.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:A.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:A.mac_address,mode:"full"},defaultEnabled:!1}},te=Object.freeze(Object.fromEntries($e.map(e=>{let t=Qr[e];return[e,{...t,template:{...t.template,pattern:$r(Se(t.template.pattern))}}]})));var qs=new Set($e.filter(e=>!te[e].defaultEnabled));function Yr(e,t){let n=new Set;for(let r of $e)(te[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function X(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=Pe(t),a=e;for(let{name:o,re:s}of Pt){let l=o;n.has(l)||(a=a.replace(s,c=>(r?.(l),i(c))))}for(let{name:o,re:s,normalize:l,validate:c}of Lt)n.has(o)||(a=si(a,s,l,c,t,o,r));return a}function Pe(e){return typeof e=="function"?e:()=>e}var ht=e=>"\0".repeat(e.length);function Zr(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=Re(e);if(i.length===0)return X(e,t,n,r);let a=new Set,o=p=>{a.add(p)},s=X(e,ht,n,o),l=!0,c=new Array(e.length).fill(!1);for(let p=0;p<e.length;p++)c[p]=s[p]==="\0"&&e[p]!=="\0";for(let p of i){let f=X(p.text,ht,n,o);for(let h=0;h<p.text.length;h++)if(!(f[h]!=="\0"||p.text[h]==="\0"))for(let _=p.offsets[h];_<p.offsets[h+1];_++)c[_]||(c[_]=!0,l=!1)}if(l)return X(e,t,n,r);for(let p of a)r?.(p);let d="",u=0;for(;u<e.length;){if(!c[u]){d+=e[u],u++;continue}let p=u;for(;u<e.length&&c[u];)u++;d+=Pe(t)(e.slice(p,u))}return d}function U(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var _t=new Map;function Jr(e){let t=_t.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),_t.set(e.source,t)),t}var Xr=4096,ei=64,yt=null;function ti(e){return yt!==null?yt:Xr+e.length*ei}var Dt=!1,C={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},Ft={spanBudget:0,depthCap:0};function ni(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:ti(e),exhausted:!1}}function jt(e,t,n,r,i,a,o){C.spanCalls++;let s=t*o.stride+n.length,l=Dt?void 0:o.chosen.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,null;o.budget--,C.spanMisses++;let c=ri(e,t,n,r,i,a,o);return o.chosen.set(s,c),c}function ri(e,t,n,r,i,a,o){let s=Jr(r),l=[];for(let d=n.length-1;d>=1;d--)if(U(n[d])){let u=n.slice(0,d);s.test(u)&&l.push(u)}let c=U(e[t+n.length])?[n,...l]:[...l,n];for(let d of c)if(a(i(d),d)&&!ai(e,t,d,r,i,a,o))return d;return null}var bt=new Map;function ii(e){let t=bt.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),bt.set(e.source,t)),t}function ai(e,t,n,r,i,a,o){C.cutCalls++;let s=t*o.stride+n.length,l=Dt?void 0:o.cuts.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,!0;o.budget--,C.cutMisses++;let c=oi(e,t,n,r,i,a,o);return o.cuts.set(s,c),c}function oi(e,t,n,r,i,a,o){let s=t+n.length,l=ii(r);for(let c=1;c<n.length;c++){if(U(n[c])||!U(n[c-1]))continue;let d=t+c;l.lastIndex=d;let u=l.exec(e);if(u===null||u[0].length===0)continue;let p=jt(e,d,u[0],r,i,a,o);if(p!==null&&d+p.length>s&&U(e[d+p.length]))return!0}return!1}function si(e,t,n,r,i,a,o){let s=Pe(i);t.lastIndex=0;let l="",c=0,d=ni(e),u=C.spanMisses+C.cutMisses,p;for(;(p=t.exec(e))!==null;){let f=p[0],h=p.index;if(f.length===0){t.lastIndex=h+1;continue}let _;try{_=jt(e,h,f,t,n,r,d)}catch(w){if(w instanceof RangeError&&/call stack/i.test(w.message))d.exhausted=!0,_=null;else throw w}if(d.exhausted)return C.budgetExhausted++,Ft.spanBudget++,vt(u),l+e.slice(c,h)+s(e.slice(h));if(_!==null)o?.(a),l+=e.slice(c,h)+s(_),c=h+_.length,t.lastIndex=c;else{let w=f.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=w===-1?h+f.length:h+1+w+1}if(t.lastIndex>e.length)break}return vt(u),l+e.slice(c)}function vt(e){let t=C.spanMisses+C.cutMisses-e;t>C.maxMissesInAPass&&(C.maxMissesInAPass=t)}function Le(e,t=Ot,n,r){return ci(e,t,Yr(n,r))}var li=256;function ci(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=(s,l)=>{if(l>li)return Ft.depthCap++,t;if(typeof s=="string")return Zr(s,t,n,a);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!i)return s;let c=String(s);return c.length>=13&&c.length<=19&&Ee(c)?(r.add("pan"),t):s}if(Array.isArray(s))return s.map(c=>o(c,l+1));if(s!==null&&typeof s=="object"){let c=s,d={};for(let u of Object.keys(c))d[u]=o(c[u],l+1);return d}return s};return{value:o(e,0),detectors:[...r].sort()}}function Bt(e,t=Ot){return Le(e,t).value}function di(e){let{value:t,detectors:n}=Le(e),r=n.some(i=>te[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function ne(e,t){let{blocked:n,redacted:r,detectors:i}=di(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 De(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var ui=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function Fe(e){return ui.has(De(e))}var pi=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Ut=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"}),fi=new RegExp(`[${Object.keys(Ut).join("")}]`,"gu"),mi=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),qt="\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",gi=Object.freeze(Object.fromEntries([...qt].map((e,t)=>[e,String.fromCharCode(97+t)]))),hi=new RegExp(`[${qt}\u2800]`,"g"),zt=/[⠀-⣿]/;function _i(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 yi(e){return e.replace(pi,"")}function Vt(e){return e.replace(fi,t=>Ut[t]??t)}function bi(e){return e.replace(/[4@31!05$79(8]/g,t=>mi[t]??t)}function vi(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 wi(e){return zt.test(e)?e.replace(hi,t=>t==="\u2800"?" ":gi[t]??t):e}function wt(e){let t;try{t=_i(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=yi(t),t=Vt(t),t}var Ai=/^[A-Za-z0-9+/]{16,}={0,2}$/,ki=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,At=/[A-Za-z0-9+/]{20,}={0,2}/g;function Ce(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 Gt=new TextDecoder("utf-8",{fatal:!1});function Kt(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=Gt.decode(n);return t===r?[t]:[r,t]}function Ii(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=Gt.decode(n);return r===i?[r]:[i,r]}function kt(e){let t=e.trim(),n=[];if(ki.test(t))for(let r of Ii(t))n.push({decoded:r,textiness:Ce(r)});if(Ai.test(t)&&t.length%4===0)for(let r of Kt(t))n.push({decoded:r,textiness:Ce(r)});return n}function It(e,t){let n=[],r;for(At.lastIndex=0;(r=At.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of Kt(i))n.push({decoded:a,textiness:Ce(a)})}return n}var Si=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function Wt(e,t=Si){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=f=>{f.length>0&&f.length<=r&&o.add(f)},l=!1,c=!1,d=0,u=0,p=[{s:e,depth:0}];for(;p.length>0;){if(d>=i){c=!0;break}let f=p.pop();if(f===void 0)break;let{s:h,depth:_}=f;if(h.length>r){c=!0;continue}d++,_>u&&(u=_);let w=wt(h);s(w);let S=bi(w);if(S!==w&&s(S),s(vi(w)),zt.test(h)&&s(wi(w)),_>=n){let k=wt(h);(kt(k).length>0||It(k,a).length>0)&&(c=!0);continue}let b=[...kt(w),...It(w,a)];for(let k of b){if(l=!0,k.decoded.length>r){c=!0;continue}k.textiness>=.85&&k.decoded!==w?p.push({s:k.decoded,depth:_+1}):s(k.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:d,maxDepthSeen:u}}var Ht=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],Ei=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),Ci=8,Ni=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),St=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function Ti(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||Ni.has(i)&&St(t[r-1])&&St(t[r+1])&&(n++,n>=Ci))return!0}return!1}var xi=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function Ri(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(xi.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Oi=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Mi(e){for(let t of Oi)if(e>=t.lo&&e<=t.hi)return t.name;return null}function $i(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=Mi(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:Vt(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var Et=Object.freeze({signals:[],contributes:!1});function Pi(e){if(typeof e!="string"||e.length===0)return{...Et,signals:[]};let t=new Set;try{Ti(e)&&t.add("hidden_text_carrier"),Ri(e)&&t.add("injected_turn_boundary"),$i(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=Wt(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Et,signals:[]}}return{signals:[...Ht.filter(n=>t.has(n))],contributes:Ei.some(n=>t.has(n))}}var re=[{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 Ct(e){return typeof e!="string"||e.length===0?[]:re.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function Li(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(Ct(e)),{views:n}=Wt(e);for(let r of n)for(let i of Ct(r))t.add(i);return re.filter(r=>t.has(r.name)).map(r=>r.name)}function Di(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of Li(a))t.add(s);let o=Pi(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:re.filter(a=>t.has(a.name)).map(a=>a.name),structural:Ht.filter(a=>n.has(a))}}function Fi(e){return Di(e).matched}var zs=re.map(e=>e.name);var ji=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Bi="i:injection";function Qt(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=Le(e.content);for(let a of i){let o=te[a]?.category;o&&t.add(`c:${o}`)}Fi(e.content)&&t.add(Bi)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&ji.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var Ie="(?: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))",Vs=[{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${Ie}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${Ie}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${Ie}\\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}],Nt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Ui=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${Nt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${Nt}|programming|training))`,qi="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Tt="(?:\\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)",zi="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Gs=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${qi}${Ui}\\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}?${Tt}`,"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+(?:${zi}\\b|[\\s\\S]{0,40}?${Tt})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Vi="[SYSTEM-PROMPT-REDACTED]";function Ne(e){return e.toLowerCase().replace(/\s+/g," ").trim().split(" ").filter(t=>t.length>0)}function Gi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yt(e,t){if(typeof e!="string"||typeof t!="string"||e.length===0||t.length===0)return[];let n=Ne(e),r=Ne(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 Ki(e,t){if(typeof e!="string"||e.length===0)return e;let n=e,r=Math.max(1,Ne(e).length);for(let i=0;i<r;i++){let a=Yt(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(Gi).join("\\s+"),c;try{c=new RegExp(l,"gi")}catch{continue}n=n.replace(c,Vi)}}return n}function Te(e,t,n){if(e==null)return e;if(typeof e=="string"){for(let r of Yt(t,e))n.add(r);return Ki(e,t)}if(Array.isArray(e))return e.map(r=>Te(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]=Te(r[a],t,n);return i}return e}function Wi(e,t){if(typeof t!="string"||t.length===0)return{leaked:!1,matchedSpans:[],redacted:e};let n=new Set,r=Te(e,t,n),i=[...n].sort();return{leaked:i.length>0,matchedSpans:i,redacted:r}}function Zt(e,t,n){let{leaked:r,redacted:i,matchedSpans:a}=Wi(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 Ks=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var M=e=>`[^.!?;\\n]{0,${e}}?`,Hi=["\\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("|"),Jt="(?: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)",Ws=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Hi})\\s${M(40)}\\b${Jt}\\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${M(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${M(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${M(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${M(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${M(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")}]),Hs=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${M(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${M(30)}\\b${Jt}\\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 B=e=>`[^.!?;\\n]{0,${e}}?`,Qs=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${B(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${B(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${B(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${B(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${B(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 Qi=["competitor_mention","disallowed_topic","off_brand_claim","restricted_advice"];var Yi=[{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 Zi={competitor_mention:"redact",off_brand_claim:"redact",disallowed_topic:"escalate",restricted_advice:"escalate"};function Ji(e){return e.length===0?null:e.some(t=>Zi[t]==="escalate")?"escalate":"redact"}var Xi="[BRAND-TOPIC-REDACTED]";function xe(e,t){if(e==null)return e;if(typeof e=="string"){let n=e;for(let{id:r,re:i}of Yi){i.lastIndex=0;let a=n.replace(i,()=>Xi);a!==n&&(t.add(r),n=a)}return n}if(Array.isArray(e))return e.map(n=>xe(n,t));if(typeof e=="object"){let n=e,r=Object.create(Object.getPrototypeOf(n));for(let i of Object.keys(n))r[i]=xe(n[i],t);return r}return e}function ea(e){let t=new Set,n=xe(e,t);return{matched:Qi.filter(r=>t.has(r)),redacted:n}}function ie(e,t){let{matched:n,redacted:r}=ea(e),i=Ji(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 je="[REDACTED]",D="\u2022",ee=e=>/[\p{L}\p{N}]/u.test(e);function Xt(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:D,c=o+s>=a;return i.map((d,u)=>!c&&(u<o||u>=a-s)?d:ee(d)?l:d).join("")}function ta(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Xt(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:D;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(o=>ee(o)?a:o).join(""))+i}function na(e,t,n){let r=n.length>0?n:D,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 u=d.index;u<d.index+d[0].length;u++)i[u]=!0}}catch{}let a=!1,o=!0;for(let c=0;c<e.length;c++)if(ee(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]||!ee(d)?l+=d:l+=r}return l}function en(e,t){let n=t.mode??"full";return n==="partial"?Xt(e,t.keepFirst??0,t.keepLast??0,t.maskChar??D):n==="email"?ta(e,t.maskChar??D):n==="custom"?na(e,t.keepPattern,t.maskChar??D):t.replacement??je}function ra(e,t){return typeof e=="string"?en(e,t):t.replacement??je}function tn(e){let t=[],n=e.replacement??je;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:Se(r),replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:Se(i),replacer:a=>en(a,r)})}return t}function nn(e){try{return new RegExp(e,"g")}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`[visiq-redact] Invalid redaction pattern "${e}": ${n}`)}}function rn(e,t){if(Re(e).length===0){let n=e;for(let{source:r,replacer:i}of t)n=n.replace(nn(r),a=>i(a));return n}return ia(e,t)}function ia(e,t){let n=e;for(let{source:r,replacer:i}of t){let a=nn(r),o=[...gt(a,n)];for(let d of Re(n))for(let u of gt(a,d.text))o.push(Nr(d,u));let s=Tr(o);if(s.length===0)continue;let l="",c=0;for(let{start:d,end:u}of s)l+=n.slice(c,d)+i(n.slice(d,u)),c=u;n=l+n.slice(c)}return n}function ae(e,t){return e==null?e:typeof e=="string"?aa(e,t):typeof e=="object"?oa(e,t):e}function aa(e,t){if(typeof e!="string")return e;let n=tn(t);return n.length===0?e:rn(e,n)}function oa(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=tn(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 u=i?n.get(d):void 0;if(u){c[d]=ra(l[d],u);continue}c[d]=o(l[d])}return c}return typeof s=="string"&&a?rn(s,r):s};return o(e)}import{readFile as sa}from"node:fs/promises";import{homedir as Ue}from"node:os";import{join as qe,isAbsolute as la,resolve as ca}from"node:path";import{createInterface as da}from"node:readline";import{parseArgs as ua}from"node:util";var pa="https://api.visiqlabs.com",an="@visiq/openclaw-plugin",le="open";function ze(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}var fa={enabled:!0,thresholds:{}},ce=[{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"}],ma=["sequence-anomaly",...ce.map(e=>e.cli)];function se(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 Ve(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 ga(...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 ha='[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 _a(e){return e==="~"||e.startsWith("~/")?qe(Ue(),e.slice(1).replace(/^\//,"")):e}async function on(e){try{let t=la(e)?e:ca(e),n=await sa(t,"utf-8");return JSON.parse(n)}catch{return null}}function oe(e,...t){for(let n of t){let r=e[n];if(typeof r=="string")return r}}function Be(e){if(!e||typeof e!="object")return{};let t=e,n=oe(t,"apiKey","api_key"),r=oe(t,"agentId","agent_id"),i=oe(t,"baseUrl","base_url"),a=ze(oe(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=se(s);if(l!==void 0)o.sequenceAnomalyEnabled=l;else if(typeof s=="object"&&!Array.isArray(s)){let c=s,d=se(c.enabled);d!==void 0&&(o.sequenceAnomalyEnabled=d);let u={};for(let p of ce){let f=Ve(c[p.key]??c[p.json]);f!==void 0&&(u[p.key]=f)}Object.keys(u).length>0&&(o.sequenceAnomalyThresholds=u)}}return o}async function ya(e){if(!e)return{};let t=_a(e),n=await on(t);if(!n||typeof n!="object")return{};let r=n,i=r.plugins?.entries,a=i&&typeof i=="object"?i[an]:void 0;return a&&typeof a=="object"&&a.config?Be(a.config):Be(r)}async function sn(e){if(!e)return{};let t=await on(e);if(!t||typeof t!="object")return{};let a=t.plugins?.entries?.[an];return!a||typeof a!="object"?{}:Be(a.config)}function ba(){return sn(qe(Ue(),".openclaw","openclaw.json"))}function va(){let e=process.env.OPENCLAW_CONFIG_PATH;return!e||e===qe(Ue(),".openclaw","openclaw.json")?Promise.resolve({}):sn(e)}async function wa(e){if(!process.stdout.isTTY)return{};let t=da({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 Aa(){try{let e={"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"},"fail-mode":{type:"string"}};for(let c of ma)e[c]={type:"string"};let{values:t}=ua({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=ze(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=se(t["sequence-anomaly"]);s!==void 0&&(n.sequenceAnomalyEnabled=s);let l={};for(let c of ce){let d=Ve(t[c.cli]);d!==void 0&&(l[c.key]=d)}return Object.keys(l).length>0&&(n.sequenceAnomalyThresholds=l),n}catch{return{}}}async function nl(){return(await Ge()).config}async function Ge(){let e=Aa(),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=ze(process.env.VISIQ_FAIL_MODE);n&&(t.failMode=n);let r=se(process.env.VISIQ_SEQUENCE_ANOMALY);r!==void 0&&(t.sequenceAnomalyEnabled=r);let i={};for(let u of ce){let p=Ve(process.env[u.env]);p!==void 0&&(i[u.key]=p)}Object.keys(i).length>0&&(t.sequenceAnomalyThresholds=i);let a=await ya(process.env.VISIQ_CONFIG_PATH),o=await ba(),s=await va(),l={...o,...s,...a,...t,...e,sequenceAnomalyThresholds:ga(o.sequenceAnomalyThresholds,s.sequenceAnomalyThresholds,a.sequenceAnomalyThresholds,t.sequenceAnomalyThresholds,e.sequenceAnomalyThresholds)};(!l.apiKey||!l.agentId)&&process.stdout.isTTY&&process.stdin.isTTY&&(l=await wa(l));let c=l.failMode??le;if(!l.apiKey||!l.agentId)return process.stderr.write(`${ha}
4
- `),{config:null,failMode:c};let d={apiKey:l.apiKey,agentId:l.agentId,failMode:c,sequenceAnomaly:{enabled:l.sequenceAnomalyEnabled??fa.enabled,thresholds:l.sequenceAnomalyThresholds??{}}};return d.baseUrl=l.baseUrl||pa,{config:d,failMode:c}}var Ke=null,ln={ready:!1,config:null,failMode:le};function We(){return Ke||(Ke=Ge().catch(e=>(process.stderr.write(`[VisIQ] Config resolution failed (treating as unconfigured): ${e instanceof Error?e.message:String(e)}
5
- `),{config:null,failMode:le})).then(e=>(ln={ready:!0,config:e.config,failMode:e.failMode},e))),Ke}function de(){return We().then(e=>e.config)}function ue(){return We()}function pe(){return ln}function al(){We()}var sl="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.",cn="0.1.19";import{z as m}from"zod";import*as T from"node:os";import{randomUUID as z}from"node:crypto";var He=1,un="X-VisIQ-SDK",pn="X-VisIQ-Dialect",fn="unknown";function Qe(e,t=1){return{[un]:e&&e.length>0?e:fn,[pn]:String(t)}}var mn="interceptor_source",ka=m.enum(["enforce","audit","off"]),Ia=m.enum(["closed","open"]),gn=m.enum(["enforce","monitor","off"]),Sa=m.object({apiKey:m.string().min(1,"apiKey is required"),agentId:m.string().min(1,"agentId is required"),endpoint:m.string().url().optional(),mode:ka.optional(),timeoutMs:m.number().int().positive().optional(),hitlTimeoutMs:m.number().int().positive().optional(),failBehavior:Ia.optional()}),dl=m.object({agent_id:m.string().min(1),target_app:m.string().min(1),action:m.string().min(1),context:m.record(m.unknown()).optional(),session_id:m.string().min(1).max(255).optional(),action_schema_id:m.string().min(1).max(128).optional(),telemetry:m.record(m.unknown()).optional()}),Ea=m.object({field:m.string().optional(),pattern:m.string().optional(),replacement:m.string().optional(),mode:m.enum(["full","partial","email"]).optional(),keepFirst:m.number().optional(),keepLast:m.number().optional(),maskChar:m.string().optional()}),Ca=m.object({decision_id:m.string().min(1),decision:m.enum(["permit","deny","approval_required","mask"]),reason:m.string().optional(),rule_code:m.string().nullable().optional(),enforced:m.boolean().optional(),agent_mode:gn.optional(),arg_redaction_rules:m.array(Ea).optional(),plane:m.string().nullable().optional(),operation:m.string().nullable().optional(),is_retrieval:m.boolean().optional(),metadata:m.record(m.unknown()).optional()}),Na=m.object({field:m.string().min(1),operator:m.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:m.union([m.string(),m.number(),m.array(m.string())])}),Ta=m.object({id:m.string().min(1),rule_code:m.string().default(""),name:m.string().min(1),description:m.string().nullable().default(null),effect:m.enum(["allow","deny","hitl","mask"]),resource_type:m.string().min(1),rego_source:m.string().default(""),target_app:m.string().nullable().default(null),action_pattern:m.string().nullable().default(null),conditions:m.array(Na).default([]),priority:m.number().int().default(0)}),xa=m.object({version:m.string().min(1),agent_mode:gn.optional(),rules:m.array(Ta),no_coverage:m.object({no_coverage_defaults:m.record(m.string()),autopilot_enabled:m.boolean(),enduser_hitl_enabled:m.boolean(),hitl_timeout_seconds:m.number()}).optional()}),Ra=2e3,Oa=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function Ma(e){let t=e.rules.filter(n=>Oa(n.rego_source)).map(n=>n.id);return t.length>0&&console.warn(`[VISIQ] ${t.length} bundle rule(s) carry an EMPTY rego body and will be evaluated as an UNCONDITIONAL PERMIT credited to their own rule id: ${t.join(", ")}. If any of these is meant to deny, it is not denying. Fix the rule body at the control plane; the SDK cannot tell an intentional stub from a dropped column.`),t}var Ye=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return Qe(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 Ca.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(),o=xa.parse(a);return Ma(o),o}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 reportSkillInventory(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/skills`;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,skills:e})});n.ok||console.warn(`[ALLOW] Skill-inventory report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Skill-inventory 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 $a(Ra)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function $a(e){return new Promise(t=>setTimeout(t,e))}function ge(){let e={};try{let t=`${T.platform()} ${T.release()}`.trim();t&&(e.os=t)}catch{}try{let t=T.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=T.userInfo();t&&(e.username=t)}catch{}try{let t=Pa();t&&(e.ip=t)}catch{}return e}function Pa(){let e=T.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 La(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function fe(e,...t){for(let n of t){let r=La(e[n]);if(r)return r}}function me(e){if(fe(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(fe(e,"user_id","userId"))return"user";if(fe(e,"agent_id","agentId"))return"agent";if(fe(e,"org_id","orgId","namespace"))return"org"}var Da=[{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=me(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=me(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=me(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=me(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function q(e,t){if(!e)return null;let n=t??{};for(let r of Da)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function Ze(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 dn=new Map;function V(e){let t=(dn.get(e)??0)+1;return dn.set(e,t),t}function hn(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=hn(n.usage);e.emitCognition({clientEventId:z(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:V(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 Xe(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:z(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:V(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 G(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?Ze(n.memory):void 0;e.emitCognition({clientEventId:z(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:V(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 et(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=Ze(n.memory,{itemCount:o,bytes:a})),e.emitCognition({clientEventId:z(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:V(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 tt(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:z(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:V(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 he(e){try{let t=JSON.stringify(e);return typeof t=="string"?t.length:void 0}catch{return}}function _e(e){try{return Array.isArray(e)?e.length:void 0}catch{return}}import{z as g}from"zod";import{createHash as Fa}from"crypto";import{createHash as So}from"crypto";var _n=new Map;function yn(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function rt(e){let t=Fa("sha256").update(e).digest("hex"),n=_n.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
8
- `).map(l=>ja(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 p=c[1],f=c[2].trim();r.set(p,W(f)),o++;continue}let d=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(d){let p=d[1],f=d[2].trim(),h=d[3].trim(),_=[];if(h&&h!=="}"){let S=h.endsWith("}")?h.slice(0,-1).trim():h;S&&_.push(S),h.endsWith("}")||(o++,o=ye(a,o,_))}else h==="}"||(o++,o=ye(a,o,_));let w=bn(_);i.push({variable:p,value:W(f),conditions:w,rawConditions:yn(_)}),o++;continue}let u=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(u){let p=u[1],f=u[2].trim(),h=[];if(f&&f!=="}"){let w=f.endsWith("}")?f.slice(0,-1).trim():f;w&&h.push(w),f.endsWith("}")||(o++,o=ye(a,o,h))}else f==="}"||(o++,o=ye(a,o,h));let _=bn(h);i.push({variable:p,value:"true",conditions:_,rawConditions:yn(h)}),o++;continue}o++}let s={defaults:r,rules:i};return _n.set(t,s),s}function ja(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 ye(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 W(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ba(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function bn(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=Ka(i);a&&t.push(a)}}return t}var it=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,Ua=new RegExp(`^(${it.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),qa=new RegExp(`^(${it.source})\\s*==\\s*((?:input|data)\\S*)$`),za=/^([^\s=!]+)\s*==\s*(.+)$/,Va=/^([^\s=!]+)\s*!=\s*(.+)$/,gl=new RegExp(`^(?:${it.source})$`);var Ga=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function Ka(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:we,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(Ga);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:Ba(s[1])};let l=n.match(Ua);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:En(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let _=Ya(c[2]);if(_!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:_}}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 u=n.match(qa);if(u)return{type:"equality",negated:t,field:u[2].trim(),value:W(u[1].trim())};let p=n.match(za);if(p)return{type:"equality",negated:t,field:p[1].trim(),value:W(p[2].trim())};let f=n.match(Va);if(f)return{type:"inequality",negated:t,field:f[1].trim(),value:W(f[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:we,value:e.trim()}}var we="__unrecognized_condition_forces_deny__";var Wa=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Sn(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==we&&Wa.test(r.field)&&t.push(r.field);return t}var Ha=["input.normalized.","input.normalized["];function Qa(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===we||Ha.some(a=>i.startsWith(a))&&t.add(i)}return[...t].sort()}function En(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 Ya(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(En(s))}return o}var hl=new RegExp("^\\p{White_Space}*$","u");var Za=["tier1","tier2","tier3"];function Cn(e){return typeof e=="string"&&Za.includes(e)}var Ja=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Xa=["internal","customer_facing","experimental","third_party"],Nn=[...Ja,...Xa];function eo(e){return typeof e=="string"&&Nn.includes(e)}function Tn(e){let t=new Set;for(let n of e)eo(n)&&t.add(n);return Nn.filter(n=>t.has(n))}var xn=["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"],to=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],no=["production","staging","development","test"],ro=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function io(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 vn={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 ao(e){let t=io(e);return t===null?"other":vn[t]??vn[t.replace(/_/g,"")]??"other"}function Rn(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=ao(t.targetApp)),n.context=r}return n}var wn=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],oo=["read","write","delete","share","export","decide","execute"],An=["none","low","medium","high","critical"],so=["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"],lo={action_class:xn,operation:oo,"context/app_category":to,"context/environment":no,"context/actor_function":ro,"read/classification":so,"read/data_categories":wn,"read/data_sensitivity":An,"write/data_categories":wn,"write/data_sensitivity":An};function On(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(lo)){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 kn=64,co=64,H={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function Mn(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var uo=new Set(["deny","approval_required","escalate"]);function K(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>kn?r.slice(0,kn):r}function In(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function be(e){return typeof e=="string"&&e.length>0?e:null}function $n(e,t){let n=In(t.data_categories),r=be(t.classification),i=In(t.taint),a=be(t.action_class),o=a&&xn.includes(a)?a:null,s=be(t.target_app),l=be(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<co)c[o]=1;else{let d=Object.keys(c).sort(),u=d[d.length-1];u!==void 0&&o<u&&(delete c[u],c[o]=1)}return{retrieved_data_categories:K(e.retrieved_data_categories,n),retrieved_classifications:K(e.retrieved_classifications,r?[r]:[]),taint:K(e.taint,i),action_classes:K(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&uo.has(l)?1:0),event_count:e.event_count+1,target_apps:K(e.target_apps,s?[s]:[])}}var Pn={minEvents:12,minClasses:3,concentrationSigma:2,dominanceRatio:4,dominanceShare:.5,frictionRatio:.75,minFrictionEvents:6};function po(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 nt(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 ve(e){return Number.isFinite(e)?Math.round(e*1e3)/1e3:0}var fo=.5;function mo(e){let t=e.length;if(t===0)return 0;let n=[...e].sort((s,l)=>s-l),r=nt(n),i=n[t-1],a=n.map(s=>Math.abs(s-r)).sort((s,l)=>s-l),o=nt(a);return o>0?.6745*(i-r)/o:i===r?0:.6745*(i-r)/fo}function at(e,t){let n={...Pn,...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=po(r),l={};for(let E of Object.keys(r).sort()){let P=Math.max(0,r[E]??0);P>0&&(l[E]=P)}let c=Object.values(l),d=c.reduce((E,P)=>E+P,0),u=[...c].sort((E,P)=>E-P),p=nt(u),f=mo(c),h=p>0?s.count/p:0,_=d>0?s.count/d:0,w=i>0?(a+o)/i:0,S={action_class:null,repeats:s.count,event_count:i,denied_count:a,inhibited_count:o,class_count:c.length,class_counts:l,concentration_score:ve(f),dominance_ratio:ve(h),dominance_share:ve(_),friction_score:ve(w),signals:[]};if(i<n.minEvents)return{verdict:"allow",signals:[],evidence:S};let b=[],k=null;return c.length>=n.minClasses&&f>=n.concentrationSigma&&h>=n.dominanceRatio&&_>=n.dominanceShare&&(b.push("concentration"),k=s.label),w>=n.frictionRatio&&a+o>=n.minFrictionEvents&&b.push("friction"),b.length===0?{verdict:"allow",signals:[],evidence:S}:{verdict:t.failMode==="closed"?"deny":"hold",signals:[...b],evidence:{...S,action_class:k,signals:[...b]}}}var Ln="generic",Dn=[{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."}],go=Dn.map(e=>e.id),_l=new Map(Dn.map(e=>[e.id,e])),yl=new Set(go);function Fn(e){return Array.isArray(e)&&e.length>0?[...e]:[Ln]}var ho=/^[a-z][a-z0-9_]*$/;function jn(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&ho.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var _o=["narrow","moderate","broad","unbounded","unknown"];function Bn(e){return typeof e=="string"&&_o.includes(e)}function yo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(" ").filter(t=>t.length>0)}function bo(e){let t=2166136261,n=16777619;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,16777619)>>>0,n=Math.imul(n^(i<<1|1),2246822507)>>>0}return[t>>>0,n>>>0]}function vo(e,t=5){if(e.length===0)return[];if(e.length<t)return[e.join(" ")];let n=new Set;for(let r=0;r+t<=e.length;r++)n.add(e.slice(r,r+t).join(" "));return[...n]}function Un(e){let t=vo(yo(e)),n=new Int32Array(64);for(let i of t){let[a,o]=bo(i);for(let s=0;s<32;s++)n[s]+=o>>>s&1?1:-1,n[s+32]+=a>>>s&1?1:-1}let r="";for(let i=1;i>=0;i--){let a=0;for(let o=31;o>=0;o--)a=(a<<1|(n[i*32+o]>0?1:0))>>>0;r+=a.toString(16).padStart(8,"0")}return r}function wo(e){let t=e-(e>>>1&1431655765);return t=(t&858993459)+(t>>>2&858993459),t=t+(t>>>4)&252645135,Math.imul(t,16843009)>>>24&255}function Ao(e,t){if(typeof e!="string"||typeof t!="string"||e.length!==16||t.length!==16)return 64;let n=0;for(let r=0;r<16;r+=8){let i=parseInt(e.slice(r,r+8),16),a=parseInt(t.slice(r,r+8),16);if(!Number.isFinite(i)||!Number.isFinite(a))return 64;n+=wo((i^a)>>>0)}return n}var ko=["proposed","approved","revoked"];function Io(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.skill_id=="string"&&t.skill_id.length>0&&typeof t.skill_schema_hash=="string"&&t.skill_schema_hash.length>0&&typeof t.status=="string"&&ko.includes(t.status)}function qn(e,t){let n=typeof e.action=="string"?e.action:"",r=typeof e.actionSchemaId=="string"&&e.actionSchemaId.length>0?e.actionSchemaId:null,i=typeof e.fingerprint=="string"&&e.fingerprint.length>0?e.fingerprint:null,a=typeof e.fingerprintRadius=="number"&&Number.isFinite(e.fingerprintRadius)?e.fingerprintRadius:15;if(n.length===0&&r===null&&i===null)return{blocked:!1,skillId:null};for(let o of t)if(Io(o)&&o.status==="approved"){if(n.length>0&&o.skill_id===n)return{blocked:!0,skillId:o.skill_id,matchedBy:"action"};if(r!==null&&o.skill_schema_hash===r)return{blocked:!0,skillId:o.skill_id,matchedBy:"schema"};if(i!==null&&typeof o.skill_fingerprint=="string"){let s=Ao(i,o.skill_fingerprint);if(s<=a&&s<64)return{blocked:!0,skillId:o.skill_id,matchedBy:"fingerprint",fingerprintDistance:s}}}return{blocked:!1,skillId:null}}function zn(e){return e==="open"||e==="closed"?e:null}var Eo=["tool_name","function","name","action"];function Ae(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)Ae(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)Ae(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Co(e){let t=[];return Ae(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function No(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function To(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function xo(e,t={}){if(t.discriminatorField===null)return null;let n=[];Ae(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??Eo;for(let i of r){let a=null;for(let[o,s]of n){if(No(o)!==i)continue;let l=To(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function Vn(e,t={}){let n=So("sha256").update(Co(e).join(",")).digest("hex").slice(0,16),r=xo(e,t);return r!==null?`${n}:${r}`:n}var Ro=["action","retrieval","delegation"];function Oo(e){return typeof e=="string"&&Ro.includes(e)}var Mo=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(!Mo.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Oo):[];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}}function Kn(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=rt(r)}catch{continue}let a=Qa(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()}}import{z as ke}from"zod";import{createHash as Ns}from"node:crypto";var Wn=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function $o(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:Wn(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:Wn(t.spawn.prompt)}),t}function Po(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 Lo=1440*60*1e3,Do="VISIQ_BUNDLE_GRACE_TTL_MS",Fo="VISIQ_BUNDLE_CACHE_DISABLED",jo="VISIQ_CACHE_DIR",Bo=ke.object({graceTtlMs:ke.number().int().nonnegative().optional(),disabled:ke.boolean().optional(),cacheDir:ke.string().min(1).optional()}).strict();function Uo(e){return e==null?{}:Bo.parse(e)}function qo(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Do];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Lo}function zo(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Fo]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var Hn;function Vo(){if(Hn!==void 0)return Hn;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Go(e){return JSON.stringify(st(e))}function st(e){if(Array.isArray(e))return e.map(st);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=st(t[r]);return n}return e}function Ko(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Wo(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 nr(){if(!Vo())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 rr(e,t){return e.createHash("sha256").update(Go(t)).digest("hex")}function Ho(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[jo]?.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 Qo(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function ir(e,t,n){return e.path.join(Ho(e,n),"bundles",`${Qo(e,t)}.json`)}async function Yo(e,t,n,r={}){let i=await nr();if(i)try{let a=ir(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:rr(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 Zo(e,t={}){let n=await nr();if(!n)return null;try{let r=await n.fs.readFile(ir(n,e,t),"utf-8"),i=Wo(JSON.parse(r));return!i||rr(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var Q;async function Jo(){if(Q!==void 0)return Q;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;Q=typeof t=="function"?t:null}catch{Q=null}return Q}function Xo(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=rt(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of Sn(a))t.push(`${o}: ${s}`)}return t}function es(e){return Kn(e)}function ts(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var ns=5e3,rs=600*1e3,is=1e4,as=25,Qn=1e3,os=5e3,ss=100,Yn=2e3,ls=10,cs=512,ds=1800*1e3,us=.7,ps="monitor",fs="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",Zn="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.",ms="open";function Jn(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function gs(e,t){return Qt({content:e,resourceMetadata:t})}var hs=g.object({operations:g.array(g.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:g.string().min(1,"agentId is required"),sessionId:g.string().min(1).max(255).optional(),toolName:g.string().optional(),toolArgs:g.record(g.unknown()).optional(),targetResource:g.string().optional(),resourceType:g.string().optional(),resourceMetadata:g.record(g.unknown()).optional(),normalized:g.record(g.unknown()).optional(),query:g.string().optional(),contentPreview:g.string().optional(),telemetry:g.record(g.unknown()).optional(),context:g.record(g.unknown()).optional(),mcpServer:g.string().min(1).max(255).optional()}),_s=g.object({version:g.string().min(1),dialect_version:g.number().int().optional(),min_dialect:g.number().int().optional(),shutdown:g.boolean().optional(),agent_mode:g.enum(["enforce","monitor","off"]).optional(),cognition_capture:g.boolean().optional(),agent_mode_by_operation:g.object({action:g.string().optional(),retrieval:g.string().optional(),delegation:g.string().optional()}).partial().optional(),agent_attributes:g.object({trust_tier:g.string().nullable().optional(),categories:g.array(g.string()).optional(),business_function:g.string().nullable().optional(),business_functions:g.array(g.string()).nullable().optional(),blast_radius_tier:g.string().nullable().optional(),no_coverage:g.string().nullable().optional(),fail_mode:g.string().nullable().optional()}).optional(),rules:g.array(g.record(g.unknown())),action_schemas:g.array(g.object({id:g.string(),plane:g.string().optional(),field_mappings:g.array(g.record(g.unknown())).optional(),derived_fields:g.array(g.record(g.unknown())).optional(),action_class:g.string().nullable().optional(),action_class_confidence:g.number().optional()})).optional(),no_coverage:g.object({no_coverage_defaults:g.record(g.string()),autopilot_enabled:g.boolean(),enduser_hitl_enabled:g.boolean(),hitl_timeout_seconds:g.number().optional()}).optional(),skill_blacklist:g.array(g.record(g.unknown())).optional()});function ys(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=Fn(jn(n));return{trust_tier:Cn(t)?t:null,categories:Tn(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&Bn(e.blast_radius_tier)?e.blast_radius_tier:null}}function bs(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 vs(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var lt=new Set,Xn=!1;async function er(e){let t=[];for(let n of lt){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 ws(){if(!Xn&&!(typeof process>"u"||typeof process.once!="function")){Xn=!0,process.once("beforeExit",()=>{er(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await er(!0)}finally{process.kill(process.pid,e)}})()})}}var ar=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];skillBlacklist=[];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=ps;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=Jn(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??ms;governedFailMode=null;telemetryBuffer=[];droppedTelemetry=0;inFlightTelemetry=new Set;telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastSkillInventorySig=null;skillInventoryPromise=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 u=Uo(s);if(this.bundleCacheDisabled=zo(u.disabled),this.bundleGraceTtlMs=qo(u.graceTtlMs),this.bundleCacheDirOverride=u.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:d,apiKey:l}:null,l&&c){let p={apiKey:l,agentId:d,endpoint:c,mode:"enforce",timeoutMs:Po(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new Ye(p,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},ns),ot(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},is),ot(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},os),ot(this.cognitionTimer),lt.add(this),ws()}else this.client=null}async evaluate(e){let t=hs.parse(e),n=Date.now();if(this.operatorShutdown){let f=this.denyAll(t,fs);return this.applyAgentMode(f,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,Zn,n);let f=this.denyAll(t,Zn);return this.applyAgentMode(f,"enforce",t,n)}if(t.operations.every(f=>this.modeFor(f)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let f;if(this.agentModeConfirmed?f=this.agentMode:this.bundleApplyFailed?f="enforce":f="monitor",f==="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,f,t,n)}if(this.modeFor("action")!=="off"){let f=this.matchSkillQuarantine(t);if(f){let h=this.denyAll(t,f);return this.applyAgentMode(h,this.modeFor("action"),t,n)}}let r=this.readSession(t.sessionId),i=await Jo();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")?Rn(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(f){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${f instanceof Error?f.message:String(f)}`,n);throw f}let u=[...new Set(t.operations.flatMap(f=>this.normalizedRefs[f]??[]))].sort();u.length>0&&ts(t.normalized)&&(d.normalizedColdStart=u,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${u.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: ${u.slice(0,5).join("; ")}${u.length>5?`; +${u.length-5} more`:""}`)));let p=On(t.normalized);return p.length>0&&(d.normalizedDrift=p,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${p.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: ${p.slice(0,5).join("; ")}${p.length>5?`; +${p.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}matchSkillQuarantine(e){if(this.skillBlacklist.length===0)return null;let t=e.context?.skill;if(!t||t.activated!==!0)return null;let n=typeof t.name=="string"?t.name:"",r=typeof t.fingerprint=="string"?t.fingerprint:null;if(n.length===0&&r===null)return null;let i=qn({action:n,fingerprint:r},this.skillBlacklist);return i.blocked?i.matchedBy==="fingerprint"?"skill quarantined for the agent \u2014 its content signature matches a blacklisted skill (a renamed or edited re-skin); blocked ([D-27])":"skill quarantined for the agent \u2014 it is on the approved blacklist; blocked ([D-27])":null}readSession(e){if(!e)return H;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>ds?(this.sessions.delete(e),H):t.state:H}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>=us)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=$n(r===H?Mn():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?gs(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>cs){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=_s.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=Xo(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.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?ys(t.agent_attributes):null,this.agentNoCoverage=zn(t.agent_attributes?.no_coverage),this.governedFailMode=Jn(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=bs(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=es(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",...Qe(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>=rs&&(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 Zo(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Ko(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 Yo(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({...ge(),...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))}reportSkillInventory(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,h:n.content_hash})).sort((n,r)=>n.n===r.n?n.h.localeCompare(r.h):n.n.localeCompare(r.n)));t!==this.lastSkillInventorySig&&(this.lastSkillInventorySig=t,this.skillInventoryPromise=this.client.reportSkillInventory(e).catch(()=>{}))}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({...ge(),...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=Vn(n),i={...n};return e.toolArgs&&(i.tool_args=Bt(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?vs(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?{[mn]: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,ls)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=as&&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),{client:t}=this,n=(async()=>{try{await t.sendTelemetry(e)}catch(r){this.droppedTelemetry+=e.length,console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",r)}})();this.inFlightTelemetry.add(n);try{await n}finally{this.inFlightTelemetry.delete(n)}}async drainInFlightTelemetry(){for(let e=0;e<8&&this.inFlightTelemetry.size>0;e+=1)await Promise.allSettled([...this.inFlightTelemetry])}droppedTelemetryCount(){return this.droppedTelemetry}enforceTelemetryCap(){let e=this.telemetryBuffer.length-Qn;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Qn})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push($o(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=ss&&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-Yn;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Yn})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}if(this.skillInventoryPromise)try{await this.skillInventoryPromise}catch{}await this.flushTelemetry(),await this.drainInFlightTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),lt.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 ot(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function Y(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function or(e,t){if(e!=="sessions_spawn")return null;let n=Y(t.agentId);return n?{childAgentId:n,childName:Y(t.taskName)??Y(t.label)??n,kind:"subagent",task:Y(t.task),model:Y(t.model),source:"structural"}:null}function sr(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 As={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"},ks=new Set(["workspace_deactivate_skill"]),Is=new Set(["read","read_file","readfile","view","cat"]);function Ss(e){return ks.has((e??"").trim())}function Es(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function lr(e){if(typeof e!="string"||e.length===0)return[];let t=[],n=new Set,r=/<skill\s+name="([^"]+)"\s+location="([^"]*)"\s*>/gi,i;for(;(i=r.exec(e))!==null;){let a=(i[1]??"").trim(),o=(i[2]??"").trim();if(!a)continue;let s=`${a}
9
- ${o}`;n.has(s)||(n.add(s),t.push({name:a,location:o}))}return t}function tr(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function Cs(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=As[n];if(i){let a=tr(r,["name","skill_name","identifier","skill","path"]);return a?{skill:a,via:n,framework:i}:null}if(Is.has(n.toLowerCase())){let a=tr(r,["path","file_path","filePath","target","file"]),o=a?Es(a):null;return o?{skill:o,via:n,framework:"unknown"}:null}return null}function cr(e,t){let{activation:n,attributedSkill:r}=e;if(r)return{skill:{name:r,activated:!!n,...n?{via:n.via,framework:n.framework}:{},...t?{fingerprint:t}:{}}}}var dr=class{#e=null;activate(e){return this.#e=e,e}deactivate(e){(!e||this.#e?.skill===e)&&(this.#e=null)}current(){return this.#e}observe(e,t){let n=Cs(e,t);if(n)return this.activate(n),{activation:n,attributedSkill:n.skill};if(Ss(e)){let r=this.#e?.skill??null,i=t&&typeof t.name=="string"?t.name:void 0;return this.deactivate(i),{activation:null,attributedSkill:r}}return{activation:null,attributedSkill:this.#e?.skill??null}}},Ts=/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,xs=/^([A-Za-z0-9_.-]+):[ \t]*(.*)$/;function Rs(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1):t}function Os(e,t){let n=t.startsWith("|");return(n?e.join(`
10
- `):e.join(" ")).replace(/[ \t]+/g,n?"$&":" ").trim()}function Ms(e){let t=Ts.exec(e);if(!t)return{attrs:{},body:e};let[,n]=t,r=e.slice(t[0].length),i={},a=(n??"").split(/\r?\n/);for(let o=0;o<a.length;o+=1){let s=a[o]??"";if(!s.trim()||s.trimStart().startsWith("#")||/^[ \t]/.test(s))continue;let l=xs.exec(s);if(!l)continue;let c=l[1],d=(l[2]??"").trim();if(/^[|>][+-]?\d*$/.test(d)){let u=[],p=o+1;for(;p<a.length;p+=1){let f=a[p]??"";if(f.trim()&&!/^[ \t]/.test(f))break;u.push(f.trim())}o=p-1,i[c]=Os(u,d);continue}d&&(i[c]=Rs(d))}return{attrs:i,body:r}}function $s(e){return Ns("sha256").update(e,"utf8").digest("hex")}function ur(e,t,n){let{attrs:r,body:i}=Ms(e),{description:a}=r;return{name:r.name?.trim()||n,path:t,...a?{description:a}:{},contentHash:$s(i),fingerprint:Un(i)}}var Nl=512*1024;var $=null;function N(e){let t=`${e.apiKey}::${e.agentId}::${e.baseUrl??""}`;if($&&$.key===t)return $.runtimes;let n=new ar(e.apiKey,e.baseUrl,e.agentId,"cli_harness",void 0,cn,He);return n.setFailMode(e.failMode),n.registerHostEnvironment(),$={key:t,runtimes:{unified:n}},$.runtimes}async function Ll(){if($)try{await $.runtimes.unified.flush()}catch{}}async function Dl(e){try{let t=await de();if(!t)return;let{unified:n}=N(t);await n.awaitBundleReady(e)}catch{}}function pr(){return $?.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.
11
- `)}catch{}if(e.config)try{N(e.config).unified.reportFailOpen(`${e.stage}: ${e.detail}`,{...e.toolName?{toolName:e.toolName}:{},...e.sessionId?{sessionId:e.sessionId}:{}})}catch{}}function Z(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.
12
- `)}catch{}}function O(e,t){return e?.sessionKey??t?.sessionKey??t?.sessionId??"default"}var ct=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}},dt=new Map;function F(e){let t=dt.get(e);return t||(t=new ct,dt.set(e,t)),t}function fr(e){dt.delete(e)}var mr=new Set(["web_search","x_search","web_fetch","tool_search","tool_describe","get_account","get_transactions","get_devices","check_watchlist","search_knowledge"]);function gr(e){return mr.has(De(e))}function zl(){return mr}var Ps=512*1024;async function hr(e){try{let t=e??{},n=["path","file_path","filePath","target","file"].map(s=>t[s]).find(s=>typeof s=="string"&&s.trim().length>0)?.trim();if(!n||!/SKILL\.md$/i.test(n))return;let{readFile:r,stat:i}=await import("node:fs/promises"),a=await i(n);if(!a.isFile()||a.size>Ps)return;let o=await r(n,"utf8");return ur(o,n,n).fingerprint}catch{return}}var J=new Map,Ls=2e3;function Ds(e){let t=J.get(e);if(!t){if(J.size>=Ls){let{value:n}=J.keys().next();n!==void 0&&J.delete(n)}t=new dr,J.set(e,t)}return t}var ut="@visiq/openclaw-plugin";function _r(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 lc(e,t){let{config:n,failMode:r}=await ue();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=N(n),a=n.agentId??t.agentId,o=O(e,t),s=t.toolCallId??e.toolCallId,c=gr(e.toolName)?["retrieval","action"]:["action"],d=Fs(e.params),u=or(e.toolName,e.params??{}),p;u&&a&&(Xe(i.unified,{agentId:a,sessionId:o,framework:"openclaw"},u),c.push("delegation"),p=sr(u,a));let f;try{let y=Ds(o).observe(e.toolName,e.params??{}),v=y.activation?await hr(e.params):void 0;f=cr(y,v)}catch{f=void 0}let h=p||f?{...p??{},...f??{}}:void 0,_=a?{agentId:a,sessionId:o,framework:"openclaw"}:null,w=q(e.toolName,e.params??{});if(_)try{G(i.unified,_,{toolName:e.toolName,...w?{memory:w}:{}})}catch(y){Z("step-beat",e.toolName,y)}let S=(y,v,L,x)=>{if(_)try{tt(i.unified,_,{toolName:e.toolName,decision:y,...v?{ruleCode:v}:{},...L?{ruleLabel:L}:{},enforced:!0,...x?{harnessMessage:x}:{}})}catch(R){Z("intervention-beat",e.toolName,R)}},b;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}b=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}:{},...h?{context:h}:{}})}catch(y){let v=y instanceof Error?y.message:String(y);if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ] Evaluation error \u2014 blocked (VISIQ_FAIL_MODE=closed): ${v}`};I({stage:"eval-error",detail:v,toolName:e.toolName,sessionId:o,config:n});return}if(!b.enforced)return;let{action:k}=b;if(k.decision==="approval_required")return S("approval_required",b.ruleCode??void 0,b.reason),{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:b.reason,severity:"critical",allowedDecisions:["allow-once","allow-always","deny"],pluginId:ut}};if(!k.allowed){let v=`[VisIQ ${b.ruleCode??"DENY"}] ${b.reason}`;return S("deny",b.ruleCode??void 0,b.reason,v),{block:!0,blockReason:v}}let E;if(k.decision==="mask"&&k.argRedactionRules&&k.argRedactionRules.length>0)try{E=ae(e.params??{},_r(k.argRedactionRules)),S("mask",b.ruleCode??void 0,b.reason)}catch(y){let v=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): ${v}`};I({stage:"mask-error",detail:`argument masking failed \u2014 running with UNMASKED params: ${v}`,toolName:e.toolName,sessionId:o,config:n}),E=void 0}if(c.includes("retrieval"))switch(b.retrieval.action){case"allow":case null:break;case"deny":{let y=`[VisIQ retrieval governance] ${b.reason}`;return S("deny",b.ruleCode??void 0,b.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=b.retrieval.redactionRules??[];y.length>0&&F(o).set(s,_r(y));break}case"escalate":return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:b.reason,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:ut}};default:{let y=b.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(Fe(e.toolName)){let y=n.failMode==="closed"?"closed":"open",v=E??e.params??{},L=!1,x=ne(v,{failMode:y});if(x.verdict==="block")return{block:!0,blockReason:`[VisIQ OUTPUT-BLOCK] outbound content carried a live secret (${x.detectors.join(",")}) \u2014 blocked (VISIQ_FAIL_MODE=closed)`};x.verdict==="redact"&&(v=x.redacted,L=!0,I({stage:"outbound-secret-redacted",detail:`outbound secret screen redacted ${x.detectors.length} detector(s): ${x.detectors.join(",")}`,toolName:e.toolName,sessionId:o,config:n}));let R=ie(v,{failMode:y});if(R.verdict==="block")return{block:!0,blockReason:`[VisIQ OUTPUT-BLOCK] outbound content matched a brand/topic rule (${R.matched.join(",")}) \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(R.verdict==="redact"&&(v=R.redacted,L=!0,I({stage:"outbound-brand-topic-redacted",detail:`outbound brand/topic screen redacted ${R.matched.length} rule(s): ${R.matched.join(",")} (recommended: ${R.recommendedOutcome??"none"})`,toolName:e.toolName,sessionId:o,config:n})),L)return{params:v}}if((n.sequenceAnomaly?.enabled??!0)&&typeof i.unified.getSessionState=="function"&&o){let y=i.unified.getSessionState(o),v=at(y,{failMode:n.failMode==="closed"?"closed":"open",config:n.sequenceAnomaly?.thresholds});if(v.verdict==="deny")return{block:!0,blockReason:`[VisIQ ANOMALY] session-sequence anomaly (${v.signals.join(",")}) over ${v.evidence.event_count} events \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(v.verdict==="hold")return I({stage:"sequence-anomaly-hold",detail:`session-sequence anomaly held for approval (${v.signals.join(",")}) over ${v.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 (${v.signals.join(",")}). Approve to proceed, or deny to stop the run.`,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:ut}}}if(E)return{params:E}}function Fs(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 hc(e,t){let{ready:n,config:r}=pe();if(!n||!r)return;let i=O(e,t),a=e.toolName??t.toolName,o=r.agentId??t.agentId;if(a&&o)try{let u=e.message?.content,p=q(a);et(N(r).unified,{agentId:o,sessionId:i,framework:"openclaw"},{toolName:a,ok:!0,...he(u)!==void 0?{bytes:he(u)}:{},..._e(u)!==void 0?{itemCount:_e(u)}:{},...p?{memory:p}:{}})}catch(u){Z("observation-beat",a,u)}let s=e.toolCallId??t.toolCallId;if(!s)return;let l=F(i),c=l.get(s);if(!c)return;let d={...e.message};return d.content!==void 0&&(d.content=ae(d.content,c)),l.delete(s),{message:d}}function j(e,t){return e?.sessionKey||e?.sessionId||t?.sessionKey||t?.sessionId||void 0}var pt=new Map;function yr(e,t){e&&pt.set(e,t)}function br(e){return e?pt.get(e):void 0}function vr(e){e&&pt.delete(e)}function Sc(e,t){let{ready:n,config:r,failMode:i}=pe();if(n&&!r)return;let a=O(e,t),o=F(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&&pr()==="enforce"){let s=i==="closed"?"closed":"open",l=ne(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 u=!1,p=br(j(e,t));if(p){let _=Zt(c,p,{failMode:s});if(_.verdict==="block")return{block:!0};_.verdict==="redact"&&(c=_.redacted,u=!0,I({stage:"final-message-prompt-leak-redacted",detail:`final assistant message leaked the system prompt \u2014 masked ${_.matchedSpans.length} verbatim span(s)`,sessionId:a,config:r}))}let f=!1,h=ie(c,{failMode:s});if(h.verdict==="block")return{block:!0};if(h.verdict==="redact"&&(c=h.redacted,f=!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||u||f)return{message:c}}}async function Oc(e,t){try{let{config:n}=await ue();if(!n)return;typeof e.systemPrompt=="string"&&e.systemPrompt.trim().length>0&&yr(j(e,t),e.systemPrompt);let{unified:r}=N(n);if(t.agentId)try{for(let i of lr(e.prompt))G(r,{agentId:t.agentId,sessionId:t.sessionKey??t.sessionId,framework:"openclaw"},{toolName:"skill:invoke",verb:"activate",argSummary:`${i.name} @ ${i.location}`})}catch{}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 Dc(e,t){try{let n=await de();if(!n)return;let r=n.agentId??t.agentId;if(!r)return;let i=e.sessionId??t.sessionId??t.sessionKey,{unified:a}=N(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 Uc(e,t){fr(O(e,t)),vr(j(e,t))}export{De as a,le as b,ze as c,nl as d,Ge as e,al as f,sl as g,cn as h,Ll as i,Dl as j,I as k,ct as l,F as m,fr as n,gr as o,zl as p,lc as q,hc as r,Sc as s,Oc as t,Dc as u,Uc as v};