@visiq/claude-code-harness 0.1.17 → 0.1.19

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,9 @@
1
+ import{readFile as Rn}from"node:fs/promises";import{homedir as Re}from"node:os";import{join as oe,isAbsolute as $n,resolve as Pn}from"node:path";var Fn="https://api.visiqlabs.com",Dn="@visiq/claude-code-harness",$e="open";function Pe(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function A(){let e=process.env.VISIQ_HOME;return e&&e.trim().length>0?e:oe(Re(),".visiq","claude-code")}function Mn(){return oe(A(),"config.json")}function Ln(e){return e==="~"||e.startsWith("~/")?oe(Re(),e.slice(1).replace(/^\//,"")):e}async function jn(e){try{let t=$n(e)?e:Pn(e),n=await Rn(t,"utf-8");return JSON.parse(n)}catch{return null}}function V(e,...t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function xe(e){if(!e||typeof e!="object")return{};let t=e,n={},r=V(t,"apiKey","api_key"),i=V(t,"agentId","agent_id"),a=V(t,"baseUrl","base_url"),o=Pe(V(t,"failMode","fail_mode"));return r&&(n.apiKey=r),i&&(n.agentId=i),a&&(n.baseUrl=a),o&&(n.failMode=o),n}async function Oe(e){if(!e)return{};let t=await jn(Ln(e));if(!t||typeof t!="object")return{};let n=t,r=n.plugins?.entries,i=r&&typeof r=="object"?r[Dn]:void 0;return i&&typeof i=="object"&&i.config?xe(i.config):xe(n)}function Bn(e=process.env){let t={};e.VISIQ_API_KEY&&(t.apiKey=e.VISIQ_API_KEY),e.VISIQ_AGENT_ID&&(t.agentId=e.VISIQ_AGENT_ID),e.VISIQ_BASE_URL?t.baseUrl=e.VISIQ_BASE_URL:e.VISIQ_ENDPOINT&&(t.baseUrl=e.VISIQ_ENDPOINT);let n=Pe(e.VISIQ_FAIL_MODE);return n&&(t.failMode=n),t}function zn(e,t,n){let r={...e,...t,...n};if(!r.apiKey||!r.agentId)return null;let i={apiKey:r.apiKey,agentId:r.agentId,failMode:r.failMode??$e};return i.baseUrl=r.baseUrl||Fn,i}async function Un(){let e=Bn(),t=await Oe(process.env.VISIQ_CONFIG_PATH),n=await Oe(Mn()),r={...n,...t,...e};return{config:zn(n,t,e),failMode:r.failMode??$e}}async function fs(){return(await Un()).config}import{mkdir as re,readFile as Ne,writeFile as ie,stat as as}from"node:fs/promises";import{createHash as os}from"node:crypto";import{join as N}from"node:path";import{z as m}from"zod";import*as I from"node:os";import{randomUUID as nr}from"node:crypto";var se=1,De="X-VisIQ-SDK",Me="X-VisIQ-Dialect",Le="unknown";function R(e,t=1){return{[De]:e&&e.length>0?e:Le,[Me]:String(t)}}var je="interceptor_source",qn=m.enum(["enforce","audit","off"]),Gn=m.enum(["closed","open"]),Be=m.enum(["enforce","monitor","off"]),Vn=m.object({apiKey:m.string().min(1,"apiKey is required"),agentId:m.string().min(1,"agentId is required"),endpoint:m.string().url().optional(),mode:qn.optional(),timeoutMs:m.number().int().positive().optional(),hitlTimeoutMs:m.number().int().positive().optional(),failBehavior:Gn.optional()}),gs=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()}),Hn=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()}),Wn=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:Be.optional(),arg_redaction_rules:m.array(Hn).optional(),plane:m.string().nullable().optional(),operation:m.string().nullable().optional(),is_retrieval:m.boolean().optional(),metadata:m.record(m.unknown()).optional()}),Kn=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())])}),Yn=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(Kn).default([]),priority:m.number().int().default(0)}),Zn=m.object({version:m.string().min(1),agent_mode:Be.optional(),rules:m.array(Yn),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()}),Jn=2e3,Qn=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function Xn(e){let t=e.rules.filter(n=>Qn(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 ze=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return R(this.config.sdkVersion,this.config.sdkDialect)}async boundedFetch(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs);try{return await this.originalFetch(e,{...t,signal:n.signal})}finally{clearTimeout(r)}}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 Wn.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=Zn.parse(a);return Xn(o),o}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.boundedFetch(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.boundedFetch(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.boundedFetch(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.boundedFetch(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.boundedFetch(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.boundedFetch(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 er(Jn)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function er(e){return new Promise(t=>setTimeout(t,e))}function le(){let e={};try{let t=`${I.platform()} ${I.release()}`.trim();t&&(e.os=t)}catch{}try{let t=I.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=I.userInfo();t&&(e.username=t)}catch{}try{let t=tr();t&&(e.ip=t)}catch{}return e}function tr(){let e=I.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}var Fe=new Map;function rr(e){let t=(Fe.get(e)??0)+1;return Fe.set(e,t),t}function ir(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:nr(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:rr(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}:{}}})}import{z as h}from"zod";import{createHash as ar}from"crypto";import{createHash as li}from"crypto";var Ue=new Map;function qe(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function de(e){let t=ar("sha256").update(e).digest("hex"),n=Ue.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
2
+ `).map(l=>or(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 f=c[1],d=c[2].trim();r.set(f,F(d)),o++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let f=u[1],d=u[2].trim(),g=u[3].trim(),_=[];if(g&&g!=="}"){let k=g.endsWith("}")?g.slice(0,-1).trim():g;k&&_.push(k),g.endsWith("}")||(o++,o=H(a,o,_))}else g==="}"||(o++,o=H(a,o,_));let y=Ge(_);i.push({variable:f,value:F(d),conditions:y,rawConditions:qe(_)}),o++;continue}let p=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(p){let f=p[1],d=p[2].trim(),g=[];if(d&&d!=="}"){let y=d.endsWith("}")?d.slice(0,-1).trim():d;y&&g.push(y),d.endsWith("}")||(o++,o=H(a,o,g))}else d==="}"||(o++,o=H(a,o,g));let _=Ge(g);i.push({variable:f,value:"true",conditions:_,rawConditions:qe(g)}),o++;continue}o++}let s={defaults:r,rules:i};return Ue.set(t,s),s}function or(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 H(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 F(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function sr(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Ge(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=mr(i);a&&t.push(a)}}return t}var pe=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,lr=new RegExp(`^(${pe.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),cr=new RegExp(`^(${pe.source})\\s*==\\s*((?:input|data)\\S*)$`),W=/(?:input|data)(?:\.[A-Za-z0-9_]+|\["[^"]+"\]|\['[^']+'\])+/,ur=new RegExp(`^(${W.source})\\s*(==|!=)\\s*(${W.source})$`),dr=new RegExp(`^(${W.source})\\s+in\\s+(${W.source})$`),pr=/^([^\s=!]+)\s*==\s*(.+)$/,fr=/^([^\s=!]+)\s*!=\s*(.+)$/,ws=new RegExp(`^(?:${pe.source})$`);var hr=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function mr(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:D,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(hr);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:sr(s[1])};let l=n.match(dr);if(l)return{type:"field_in_set",negated:t,field:l[1].trim(),rightField:l[2].trim()};let c=n.match(ur);if(c)return{type:"field_equality",negated:c[2]==="!="?!t:t,field:c[1].trim(),rightField:c[3].trim()};let u=n.match(lr);if(u)return{type:"array_includes",negated:t,field:u[2].trim(),value:Je(u[1])};let p=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(p){let k=vr(p[2]);if(k!==null)return{type:"in_set",negated:t,field:p[1].trim(),values:k}}let f=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(f)return{type:"comparison",negated:t,field:f[1].trim(),operator:f[2],value:parseFloat(f[3])};let d=n.match(cr);if(d)return{type:"equality",negated:t,field:d[2].trim(),value:F(d[1].trim())};let g=n.match(pr);if(g)return{type:"equality",negated:t,field:g[1].trim(),value:F(g[2].trim())};let _=n.match(fr);if(_)return{type:"inequality",negated:t,field:_[1].trim(),value:F(_[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:D,value:e.trim()}}var D="__unrecognized_condition_forces_deny__";var gr=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Ze(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==D&&gr.test(r.field)&&t.push(r.field);return t}var _r=["input.normalized.","input.normalized["];function yr(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions)for(let i of br(r))typeof i!="string"||i===D||_r.some(a=>i.startsWith(a))&&t.add(i);return[...t].sort()}var Ve=/\binput\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/g;function br(e){let{field:t,rightField:n}=e;if(t!==D){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 Ve.lastIndex=0,[...r.matchAll(Ve)].map(i=>i[0])}function Je(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 vr(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(Je(s))}return o}var wr=Object.freeze([{seedId:"c91bd6e3-6530-438e-9a02-034faa7e89c6",legacyCode:"CF1",name:"Block secrets",formerNames:["Block credentials and secrets in outbound messages"]},{seedId:"cb2b2edc-8187-493e-8076-3d119f47ccc8",legacyCode:"CF3",name:"Mask PCI and financial data",formerNames:["Mask payment and bank identifiers","Mask financial data (PCI)"]},{seedId:"7039315d-fd88-4f23-83c2-7df68ad5899e",legacyCode:"CF4",name:"Mask PII",formerNames:["Mask government and national identifiers","Mask PII: government & national IDs","Mask PII identifiers"]},{seedId:"e670cefd-7b57-491b-9883-46010a9ac23c",legacyCode:"CF17",name:"Mask PII when PHI is present",formerNames:[]},{seedId:"7343eda7-99e1-419d-8f77-93f4a32b6bfe",legacyCode:"CF6",name:"Block sensitive subject matter",formerNames:["Ask before sending sensitive subject matter"]},{seedId:"15f1ad89-e27b-46b9-825c-0ca2417b4122",legacyCode:"CF7",name:"Block compensation data",formerNames:["Block pay and compensation data","Hold pay and compensation data","Block pay & compensation"]},{seedId:"2120140a-9720-4624-9b88-d43d62907d6b",legacyCode:"CF8",name:"Block legal and privileged material",formerNames:["Hold legal and privileged material","Block legal & privileged material"]},{seedId:"e1e19ea7-cbc9-4e4f-8931-0c02c88ef467",legacyCode:"CF9",name:"Block security incident details",formerNames:["Hold security-incident detail","Block security-incident detail"]},{seedId:"57d64032-c804-4566-811e-a013c5fd3496",legacyCode:"CF10",name:"Block PHI",formerNames:["Block health information","Hold health information","Block PHI (health information)"]},{seedId:"b5dd9f3a-3d4f-41c7-941f-6b0dacaafd2b",legacyCode:"CF11",name:"Block credential discussions",formerNames:["Block credential discussion without a secret","Hold credential discussion without a secret","Block credential discussion (no secret present)"]},{seedId:"8896cc10-2111-4001-b6a5-4d7187206182",legacyCode:"CF14",name:"Block PCI",formerNames:["Block payment cards outright"]},{seedId:"64b2ee93-31d6-404c-867f-cb5ef5e37785",legacyCode:"CF15",name:"Block PII",formerNames:["Block government identifiers outright","Block government IDs outright","Block PII identifiers outright"]},{seedId:"dbc59b09-7514-4667-a320-ba6ddab5a11c",legacyCode:"CF16",name:"Mask sensitive subject matter",formerNames:[],retired:!0},{seedId:"ca177a99-afda-43ca-a20f-e1c5a5339b2d",legacyCode:"CF18",name:"Mask PHI",formerNames:["Mask PHI (health identifiers)"]}]);var ks=new Map(wr.map(e=>[e.seedId,e]));var Qe=["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"],kr=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],Ar=["production","staging","development","test"],Ir=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function Sr(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 He={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 Er(e){let t=Sr(e);return t===null?"other":He[t]??He[t.replace(/_/g,"")]??"other"}function Xe(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=Er(t.targetApp)),n.context=r}return n}var M=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],Cr=["read","write","delete","share","export","decide","execute"],We=["none","low","medium","high","critical"],ce=["public","internal","confidential","restricted"],Tr=[...ce,"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"],Nr={action_class:Qe,operation:Cr,"context/app_category":kr,"context/environment":Ar,"context/actor_function":Ir,"read/classification":Tr,"read/data_categories":M,"read/data_sensitivity":We,"read/sensitivity":ce,"write/data_categories":M,"write/data_sensitivity":We,"write/sensitivity":ce};function et(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(Nr)){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 Z=Object.freeze([{slug:"secret",label:"Secrets and credentials",description:"API keys, tokens, private keys, connection strings.",icon:"KeyRound",generic:"credentials",cfFamily:!0,detectors:["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string"]},{slug:"financial",label:"Payment and banking",description:"Card numbers, IBANs, routing numbers, tax IDs.",icon:"Landmark",generic:"financial",cfFamily:!0,detectors:["pan","iban","aba_routing","us_ein","swift_bic","in_pan_tax","au_tfn"]},{slug:"national_id",label:"Government and national IDs",description:"SSN, National Insurance, Aadhaar, CPF, DNI/NIE, SIN, NHS, TFN.",icon:"Contact",generic:"pii",cfFamily:!0,detectors:["ssn","uk_nino","in_aadhaar","br_cpf","es_dni_nie","ca_sin","uk_nhs_number"]},{slug:"contact",label:"Contact details",description:"Email addresses, phone numbers, dates of birth.",icon:"Mail",generic:"pii",cfFamily:!0,detectors:["email","us_phone","date_of_birth"]},{slug:"network_identifier",label:"Network identifiers",description:"IP and MAC addresses - recognised by the catalog, governed by no firewall family.",icon:"Network",generic:"pii",cfFamily:!1,detectors:["ipv4","mac_address"]}]),xr=Object.freeze({private_key:"secret",jwt:"secret",aws_access_key:"secret",github_token:"secret",slack_token:"secret",stripe_secret:"secret",google_api_key:"secret",llm_api_key:"secret",bearer_token:"secret",connection_string:"secret",pan:"financial",iban:"financial",aba_routing:"financial",us_ein:"financial",swift_bic:"financial",in_pan_tax:"financial",au_tfn:"financial",ssn:"pii",uk_nino:"pii",in_aadhaar:"pii",br_cpf:"pii",es_dni_nie:"pii",ca_sin:"pii",uk_nhs_number:"pii",email:"pii",us_phone:"pii",date_of_birth:"pii",ipv4:"identifier",mac_address:"identifier"}),As=new Map(Z.map(e=>[e.slug,e])),Is=new Map(Z.flatMap(e=>e.detectors.map(t=>[t,e]))),Or=Z.flatMap(e=>e.detectors);function L(e){for(let t of Mr(e))if(M.includes(t))return t;return null}function Rr(){let e={};for(let t of Or){let n=L(t);n!==null&&(e[t]=n)}return e}function $r(){let e={secret:new Set,financial:new Set,pii:new Set,identifier:new Set};for(let[n,r]of Object.entries(xr)){let i=L(n);i!==null&&e[r].add(i)}let t=n=>M.filter(r=>n.has(r));return Object.freeze({secret:t(e.secret),financial:t(e.financial),pii:t(e.pii),identifier:t(e.identifier)})}var Pr=Object.freeze([{slug:"sensitive_personal",label:"Sensitive Personal",description:"Data about a person."},{slug:"sensitive_organizational",label:"Sensitive Organizational",description:"The organization's own secrets, finances and confidential matters."}]),E=["sensitive_personal"],$=["sensitive_organizational"],Fr=["sensitive_personal","sensitive_organizational"],fe=Object.freeze([{slug:"pii",label:"PII",description:"Anything that identifies a person: names, government IDs, contact details, personal tax numbers.",topics:E},{slug:"phi",label:"PHI",description:"Health information about a person, and the identifiers that tie it to them.",topics:E},{slug:"pci",label:"PCI",description:"Payment card data: card numbers and the details that travel with them.",topics:Fr},{slug:"special_category_gdpr",label:"GDPR Special Category",description:"Data GDPR protects most strictly: beliefs, ethnicity, union membership, sex life.",topics:E},{slug:"biometric",label:"Biometric",description:"Fingerprints, face and voice templates, and other body measurements used to identify someone.",topics:E},{slug:"genetic",label:"Genetic",description:"DNA and other inherited characteristics.",topics:E},{slug:"contact",label:"Contact",description:"How to reach a person: email addresses and phone numbers.",topics:E},{slug:"location",label:"Location",description:"Where a person is or has been.",topics:E},{slug:"children",label:"Children",description:"Data about people under the age of consent.",topics:E},{slug:"financial",label:"Financial",description:"The organization's banking and tax-entity identifiers: IBANs, routing numbers, EINs.",topics:$},{slug:"secrets",label:"Secrets",description:"Live keys and tokens: anyone holding one can act as the system it unlocks.",topics:$},{slug:"credentials",label:"Credentials",description:"Anything that grants access, and talk about it: keys, tokens, passwords, security incidents.",topics:$},{slug:"mnpi",label:"MNPI",description:"Material non-public information, including pay and compensation.",topics:$},{slug:"legal",label:"Legal / Privileged",description:"Attorney-client communications and material under legal hold.",topics:$}]),Dr=Object.freeze(fe.map(e=>e.slug)),Ss=Object.freeze(Object.fromEntries(Dr.map(e=>[e,Object.freeze({field:"data_categories",tokens:Object.freeze([e])})])));var Es=Object.freeze({mnpi:["mnpi","material_nonpublic","pre_release_earnings"],legal:["attorney_client","legal_hold","privileged"]}),S=["secrets","credentials"],ue=Object.freeze({private_key:S,aws_access_key:S,github_token:S,slack_token:S,stripe_secret:S,google_api_key:S,llm_api_key:S,connection_string:S,jwt:S,bearer_token:S,iban:["financial"],aba_routing:["financial"],us_ein:["financial"],swift_bic:["financial"],pan:["pci"],in_pan_tax:["pii"],au_tfn:["pii"],ssn:["pii"],uk_nino:["pii"],in_aadhaar:["pii"],br_cpf:["pii"],es_dni_nie:["pii"],ca_sin:["pii"],uk_nhs_number:["phi","pii"],email:["pii","contact"],us_phone:["pii","contact"],date_of_birth:["pii"],ipv4:["pii"],mac_address:["pii"],person_name:["pii"],phi:["phi"],compensation:["mnpi"],legal_privileged:["legal"],security_incident:["credentials"],credentials:["credentials"]}),Cs=Object.freeze({phone:"us_phone",card:"pan"}),Ts=new Map(fe.map(e=>[e.slug,e]));function Mr(e){return Object.prototype.hasOwnProperty.call(ue,e)?ue[e]??[]:[]}var Ns=Object.freeze(Object.fromEntries(Z.flatMap(e=>e.detectors.flatMap(t=>{let n=L(t);return n!==null&&n!==e.generic?[[t,n]]:[]})))),xs=Object.freeze(Object.fromEntries(["phi","compensation","legal_privileged","credentials","security_incident","person_name"].map(e=>[e,L(e)])));var tt=["compensation","credentials","legal_privileged","phi","security_incident"];var Lr=new Set(tt),jr=Object.freeze(Object.keys(ue).filter(e=>!Lr.has(e))),Br=Object.freeze([...new Set([...M,...fe.map(e=>e.slug)])]),zr=Object.freeze(Pr.map(e=>e.slug)),Os=Object.freeze({data_categories:Br,detectors:jr,topics:tt,data_topics:zr}),Ke="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",Rs=new RegExp(`^(?=.{1,253}$)${Ke}(?:\\.${Ke})+$`,"i");var Ur='"secret" in input.categories',$s=`
3
+ decision = "deny" if {
4
+ ${Ur}
5
+ }
6
+ `;var Ye=64,qr=64,j={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 J(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:rt()}}var Gr=new Set(["deny","approval_required","escalate"]);function C(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>Ye?r.slice(0,Ye):r}function K(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function P(e){return typeof e=="string"&&e.length>0?e:null}function nt(e,t){let n=K(t.data_categories),r=P(t.classification),i=K(t.taint),a=P(t.action_class),o=a&&Qe.includes(a)?a:null,s=P(t.target_app),l=P(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<qr)c[o]=1;else{let u=Object.keys(c).sort(),p=u[u.length-1];p!==void 0&&o<p&&(delete c[p],c[o]=1)}return{retrieved_data_categories:C(e.retrieved_data_categories,n),retrieved_classifications:C(e.retrieved_classifications,r?[r]:[]),taint:C(e.taint,i),action_classes:C(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&Gr.has(l)?1:0),event_count:e.event_count+1,target_apps:C(e.target_apps,s?[s]:[]),identity:Vr(e.identity,t)}}function Vr(e,t){let n=e??rt(),r=K(t.attested_subjects),i=C(n.attested_subjects,r),a=P(t.subject_id);return{attested_subjects:i,claimed_subjects:C(n.claimed_subjects,K(t.claimed_subjects)),acted_subjects:C(n.acted_subjects,a?[a]:[])}}function rt(){return{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}}var Hr=["tier1","tier2","tier3"];function it(e){return typeof e=="string"&&Hr.includes(e)}var Wr=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Kr=["internal","customer_facing","experimental","third_party"],at=[...Wr,...Kr];function Yr(e){return typeof e=="string"&&at.includes(e)}function ot(e){let t=new Set;for(let n of e)Yr(n)&&t.add(n);return at.filter(n=>t.has(n))}var Zr={trust_tier:null,categories:[],business_functions:[],business_function:null,blast_radius_tier:null};function st(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))st(i,t.length>0?`${t}.${r}`:r,n)}function lt(e){let t=new Set;return st(e,"",t),t}var Ps=lt(J()),Fs=lt(Zr),Jr=["action_counts"];for(let e of Jr){let t=J()[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 Ds=new RegExp("^\\p{White_Space}*$","u");var ct="generic",ut=[{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:ct,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."}],Qr=ut.map(e=>e.id),Ms=new Map(ut.map(e=>[e.id,e])),Ls=new Set(Qr);function dt(e){return Array.isArray(e)&&e.length>0?[...e]:[ct]}var Xr=/^[a-z][a-z0-9_]*$/;function pt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Xr.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var ei=["narrow","moderate","broad","unbounded","unknown"];function ft(e){return typeof e=="string"&&ei.includes(e)}function ti(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(" ").filter(t=>t.length>0)}function ni(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 ri(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 ht(e){let t=ri(ti(e)),n=new Int32Array(64);for(let i of t){let[a,o]=ni(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 ii(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 ai(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+=ii((i^a)>>>0)}return n}var oi=["proposed","approved","revoked"];function si(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"&&oi.includes(t.status)}function mt(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(si(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=ai(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 gt(e){return e==="open"||e==="closed"?e:null}var ci=["ssn","email","phone","card","iban","jwt","aws_access_key","pan","us_phone","private_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","us_ein","swift_bic","in_pan_tax","aba_routing","ca_sin","uk_nhs_number","au_tfn","in_aadhaar","br_cpf","uk_nino","es_dni_nie","ipv4","mac_address","date_of_birth"];var ui=["tool_name","function","name","action"];function Y(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)Y(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)Y(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function di(e){let t=[];return Y(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function pi(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function fi(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function hi(e,t={}){if(t.discriminatorField===null)return null;let n=[];Y(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??ui;for(let i of r){let a=null;for(let[o,s]of n){if(pi(o)!==i)continue;let l=fi(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function _t(e,t={}){let n=li("sha256").update(di(e).join(",")).digest("hex").slice(0,16),r=hi(e,t);return r!==null?`${n}:${r}`:n}var mi={phone:"us_phone",card:"pan"},gi=(()=>{let e=Rr(),t={};for(let n of ci){let r=mi[n]??n,i=e[r]??L(r);if(i===null)throw new Error(`DETECTOR_DATA_CATEGORY: no data-taxonomy generic for detector "${n}" (canonical "${r}") \u2014 add it to DATA_TAXONOMY.`);t[n]=i}return Object.freeze(t)})(),Bs=$r();function yt(e){return gi[e]}var _i=["action","retrieval","delegation"];function yi(e){return typeof e=="string"&&_i.includes(e)}var bi=new Set(["rules"]);function bt(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!bi.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(yi):[];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 vt(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=de(r)}catch{continue}let a=yr(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 te}from"zod";var be="[REDACTED]";function Q(e){return!/[\p{P}\p{Z}]/u.test(e)}function Lt(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:"\u2022",c=o+s>=a;return i.map((u,p)=>!c&&(p<o||p>=a-s)?u:Q(u)?l:u).join("")}function vi(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Lt(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:"\u2022",o=Array.from(r);return(o.length<=1?a:o[0]+o.slice(1).map(s=>Q(s)?a:s).join(""))+i}function jt(e){let t=[],n=0,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(o==="\\"){a++;continue}if(r){o==="]"&&(r=!1);continue}if(o==="["){r=!0;continue}if(o==="("){n++;continue}if(o===")"){n--;continue}o==="|"&&n===0&&(t.push(e.slice(i,a)),i=a+1)}return t.push(e.slice(i)),t}function wt(e,t){let n=e[t];if(n==="*")return{min:0,max:null,next:t+1};if(n==="+")return{min:1,max:null,next:t+1};if(n==="?")return{min:0,max:1,next:t+1};if(n==="{"){let r=e.indexOf("}",t);if(r===-1)return null;let i=e.slice(t+1,r),a=/^(\d+)(?:,(\d*))?$/.exec(i);if(!a)return null;let o=Number(a[1]),s=o;return a[2]!==void 0&&(s=a[2]===""?null:Number(a[2])),{min:o,max:s,next:r+1}}return null}function wi(e){let t;try{t=new RegExp(`^(?:${e})$`,"u")}catch{return null}let n=new Set;for(let r=0;r<128;r++){let i=String.fromCharCode(r);try{t.test(i)&&n.add(i)}catch{return null}}return n}function Bt(e){if(e.length===0)return null;let t=e[0];if(t==="\\")return e.length>1?e.slice(0,2):null;if(t==="["){let n=1;for(;n<e.length&&e[n]!=="]";)n+=e[n]==="\\"?2:1;return n<e.length?e.slice(0,n+1):null}if(t==="("){let n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a==="\\"){i++;continue}if(r){a==="]"&&(r=!1);continue}if(a==="["){r=!0;continue}if(a==="("){n++;continue}if(a===")"){if(n--,n===0){let o=e.slice(1,i),s=/^\?(?::|<[=!]|[=!])/.exec(o);return s&&(o=o.slice(s[0].length)),Bt(jt(o)[0]??"")}continue}}return null}return t==="^"||t==="$"?null:t}function ki(e){let t=e.map(n=>{let r=Bt(n);return r===null?null:wi(r)});for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let i=t[n],a=t[r];if(i===null||a===null)return!0;for(let o of i)if(a.has(o))return!0}return!1}function me(e,t,n=!1,r=!1){let i=jt(e);if(i.length>1){n&&r&&ki(i)&&(t.safe=!1);let c=i.map(u=>me(u,t,n,r));return c.some(u=>u===null)?null:c.every(u=>u===c[0])?c[0]:null}let a=0,o=0,s=0,l=0;for(;o<e.length;){let c=1,u=e[o];if(u==="\\")o+=2;else if(u==="["){let f=o+1;for(;f<e.length&&e[f]!=="]";)e[f]==="\\"&&f++,f++;o=f+1}else if(u==="("){let f=1,d=o+1,g=!1;for(;d<e.length&&f>0;){let O=e[d];if(O==="\\"){d+=2;continue}if(g){O==="]"&&(g=!1),d++;continue}if(O==="["){g=!0,d++;continue}O==="("?f++:O===")"&&f--,d++}let _=e.slice(o+1,d-1),y=/^\?(?::|<?[=!]|<[A-Za-z_$][\w$]*>)/.exec(_),k=/^\?(?:<?[=!])/.test(_);y&&(_=_.slice(y[0].length));let x=wt(e,d),v=x!==null&&(x.max===null||x.max>1);c=k?0:me(_,t,n||v,v),o=d}else(u==="^"||u==="$")&&(c=0),o++;let p=wt(e,o);p!==null&&(o=p.next,(e[o]==="?"||e[o]==="+")&&o++,p.max===null&&c===null&&(t.safe=!1),(p.max===null||p.max>1)&&(l+=1,c===null&&(s+=1,(n||s>1)&&(t.safe=!1)),n&&l>1&&(t.safe=!1)),c=p.min===p.max&&c!==null?c*p.min:null),c===null||a===null?a=null:a+=c}return a}function zt(e){let t={safe:!0};try{me(e,t)}catch{return!1}return t.safe}function Ai(e,t,n){let r=n.length>0?n:"\u2022",i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{if(!zt(t))throw new Error("keepPattern is not safe for a backtracking engine");let p=new RegExp(t,"g"),f;for(;(f=p.exec(e))!==null;){if(f[0].length===0){p.lastIndex++;continue}for(let d=f.index;d<f.index+f[0].length;d++)i[d]=!0}}catch{}let a=[],o=0;for(let p of e)a.push({ch:p,at:o}),o+=p.length;let s=!1,l=!0;for(let{ch:p,at:f}of a)if(Q(p)&&(s=!0,i[f]!==!0)){l=!1;break}let c=s&&l,u="";for(let{ch:p,at:f}of a)u+=!c&&i[f]===!0||!Q(p)?p:r;return u}function Ii(e,t){let n=t.maskChar??"\u2022";switch(t.mode){case"partial":return Lt(e,t.keepFirst??0,t.keepLast??0,n);case"email":return vi(e,n);case"custom":return Ai(e,t.keepPattern,n);default:return t.replacement??be}}var Si=/[^\u0000-\u007F]/,Ut=new RegExp("^\\p{Nd}$","u"),Ei=new RegExp("^\\p{Pd}$","u"),Ci=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,Ti=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,Ni=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),qt="<invisible>",kt=new Map;function xi(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&&Ut.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function Oi(e){if(e<128)return null;let t=kt.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 Ut.test(r)?xi(e):Ei.test(r)||Ni.has(e)?"-":Ci.test(r)?" ":Ti.test(r)?qt:null})();return kt.set(e,n),n}function ve(e){if(typeof e!="string"||e.length===0||!Si.test(e))return[];let t=At(e,"as-separator");if(t===null)return[];let n=At(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function At(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=Oi(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===qt){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 Ri(e,t){return{start:e.offsets[t.start],end:e.offsets[t.end]}}function $i(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 It(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 X="[REDACTED]",we=[{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:/(?:\(\d{3}\)|\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}],Us=we.map(({name:e,re:t})=>({name:e,source:t.source})),Pi="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function Fi(e){return Gt(e,Pi)}function Gt(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 Vt(e){return new RegExp(Fi(e.source),e.flags)}var Di="(?:\\b|_)";function ge(e){return Gt(e,Di)}var Mi=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function Li(e){let t=Mi.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function ke(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}var ji=[{network:"visa",ranges:[["4","4"]],lengths:[13,16,19]},{network:"mastercard",ranges:[["51","55"],["2221","2720"]],lengths:[16]},{network:"amex",ranges:[["34","34"],["37","37"]],lengths:[15]},{network:"discover",ranges:[["6011","6011"],["644","649"],["65","65"],["622126","622925"]],lengths:[16,17,18,19]},{network:"jcb",ranges:[["3528","3589"]],lengths:[16,17,18,19]},{network:"unionpay",ranges:[["62","62"],["81","81"]],lengths:[16,17,18,19]},{network:"china_t_union",ranges:[["31","31"]],lengths:[19]},{network:"diners",ranges:[["36","36"],["38","39"],["300","305"]],lengths:[14,15,16,17,18,19]},{network:"maestro",ranges:[["5018","5018"],["5020","5020"],["5038","5038"],["5893","5893"],["6304","6304"],["6759","6759"],["6761","6763"]],lengths:[13,14,15,16,17,18,19]},{network:"mir",ranges:[["2200","2204"]],lengths:[16,17,18,19]},{network:"borica",ranges:[["2205","2205"]],lengths:[16]},{network:"dankort",ranges:[["5019","5019"]],lengths:[16]},{network:"rupay",ranges:[["60","60"],["65","65"],["81","82"],["508","508"],["353","353"],["356","356"]],lengths:[16]},{network:"interpayment",ranges:[["636","636"]],lengths:[16,17,18,19]},{network:"instapayment",ranges:[["637","639"]],lengths:[16]},{network:"troy",ranges:[["9792","9792"]],lengths:[16]},{network:"verve",ranges:[["506099","506198"],["650002","650027"],["507865","507964"]],lengths:[16,18,19]},{network:"lankapay",ranges:[["357111","357111"]],lengths:[16]},{network:"uzcard",ranges:[["8600","8600"]],lengths:[16]},{network:"humo",ranges:[["9860","9860"]],lengths:[16]},{network:"napas",ranges:[["9704","9704"]],lengths:[16,19]}];function Bi(e){if(!/^\d+$/.test(e))return null;for(let t of ji)if(t.lengths.includes(e.length))for(let[n,r]of t.ranges){let i=e.slice(0,n.length);if(i.length===n.length&&i>=n&&i<=r)return t.network}return null}function zi(e){return e.length>=13&&e.length<=19&&Bi(e)!==null&&ke(e)}function Ui(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 qi(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 Gi=[[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]],Vi=[[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 Hi(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=Gi[t][Vi[r%8][n[r].charCodeAt(0)-48]];return t===0}function Wi(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 Ki(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 Yi=[1,4,3,7,5,8,6,9,10];function Zi(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)*Yi[n];return t%11===0}var Ji="TRWAGMYFPDXBNJZSQVHLCKE";function Qi(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 Ji[Number(o)%23]===a}var Xi=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function ea(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Xi.has(t.slice(0,2)):!1}var Ae=[{name:"pan",re:/\b\d(?:[ -]?\d){12,18}\b/g,normalize:e=>e.replace(/[ -]/g,""),validate:zi},{name:"iban",re:/\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]){10,30}\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:Ui},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:qi},{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:ea(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&&Hi(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:Wi},{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:Qi},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&ke(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Ki},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Zi}],Ht=[{name:"person_name",detect:(e,t)=>t.person_name?.(e)??[]}],ta="[^\\s\\S]",na=Ht.map(e=>e.name),qs=new Set(na),ra=Object.fromEntries([...we,...Ae].map(e=>[e.name,e.re.source])),b=ra,Gs=Ae.map(e=>e.name),Wt=we.map(({name:e,re:t})=>({name:e,re:Vt(t)})),Kt=Ae.map(e=>({...e,re:Vt(e.re)})),Vs=[...Wt,...Kt].map(({name:e,re:t})=>({name:String(e),source:t.source})),Ie=["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","person_name","ipv4","mac_address"],ia={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
7
+ MIIEv\u2026
8
+ -----END PRIVATE KEY-----`,template:{pattern:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"13\u201319 digit primary account numbers (PCI-DSS), token-fenced, issued by a card network at that length (Visa, Mastercard, Amex, Discover, JCB, UnionPay, Diners, Maestro and the regional networks), and Luhn-valid. Collision rate: MEASURED 3.0% of benign 16-digit runs: the network table admits ~30% of 16-digit prefixes and Luhn leaves ~1 in 10 of those. A 13-digit run is only ever a Visa card, so epoch-millisecond timestamps never match. Default-ON because PCI-DSS makes masking mandatory.",category:"financial",example:"4242 4242 4242 4242",template:{pattern:b.pan,mode:"partial",keepLast:4,templateOnly:{reason:"A rego rule cannot run Luhn or the card-network table, so the rule masks EVERY token-fenced 13-19 digit run (grouped or not): the floor's regex without the two validators that make it precise. More than 9 in 10 of those are not card numbers.",examples:["4242 4242 4242 4243","4242424242424241"],measuredOverMaskRate:.924}},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:b.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:b.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:b.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:b.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:b.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): Verhoeff leaves ~1 in 10. Looser than pan (3.0%, card-network table plus Luhn) 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:b.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): mod-23 leaves ~1 in 23. More precise than in_aadhaar (10.0%); behind pan (3.0%), br_cpf (1.0%) and iban (1.0%).",category:"pii",example:"12345678Z",template:{pattern:b.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:b.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:b.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:b.us_phone,mode:"partial",keepLast:4},defaultEnabled:!1},person_name:{id:"person_name",label:"Person names",description:"Personal names, located by an on-device n-gram model rather than a pattern - a name has no written shape to anchor on. MEASURED on the committed corpora (experiments/browser-context-firewall/eval): clinical chat partial precision/recall 0.817/0.817; ordinary prose 0.177/0.750, i.e. on general text most flagged spans are places, works and organisations rather than people. Runs only where a model is supplied.",category:"pii",example:"Jane Doe",template:{pattern:ta,mode:"full"},defaultEnabled:!0},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:b.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:b.mac_address,mode:"full"},defaultEnabled:!1}},Se=Object.freeze(Object.fromEntries(Ie.map(e=>{let t=ia[e];return[e,{...t,template:{...t.template,pattern:Li(ge(t.template.pattern))}}]})));var Hs=new Set(Ie.filter(e=>!Se[e].defaultEnabled));function aa(e,t){let n=new Set;for(let r of Ie)(Se[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function oa(e,t,n,r,i){let a=Ht.filter(f=>!n.has(f.name));if(a.length===0)return e;let o=z(e,_e,n),s=(f,d)=>{for(let g=f;g<d;g++)if(o[g]==="\0"&&e[g]!=="\0")return!0;return!1},l=[];for(let f of a){let d=f.detect(e,i).filter(g=>g.start>=0&&g.end<=e.length&&g.start<g.end&&!s(g.start,g.end));if(d.length!==0){r?.(f.name);for(let g of d)l.push({start:g.start,end:g.end,value:g.value,id:f.name})}}if(l.length===0)return e;l.sort((f,d)=>f.start-d.start||f.end-d.end);let c=q(t),u="",p=0;for(let f of l)f.start<p||(u+=e.slice(p,f.start),u+=c(e.slice(f.start,f.end),f.id),p=f.end);return u+e.slice(p)}function z(e,t,n,r,i){if(typeof e!="string"||e.length===0)return e;let a=q(t),o=i===void 0?e:oa(e,t,n,r,i);for(let{name:s,re:l}of Wt){let c=s;n.has(c)||(o=o.replace(l,u=>(r?.(c),a(u,c))))}for(let{name:s,re:l,normalize:c,validate:u}of Kt)n.has(s)||(o=_a(o,l,c,u,t,s,r));return o}function q(e){return typeof e=="function"?e:()=>e}var _e=e=>"\0".repeat(e.length);function sa(e,t,n,r,i){if(typeof e!="string"||e.length===0)return e;let a=ve(e);if(a.length===0)return z(e,t,n,r,i);let o=new Set,s=d=>{o.add(d)},l=z(e,_e,n,s,i),c=!0,u=new Array(e.length).fill(!1);for(let d=0;d<e.length;d++)u[d]=l[d]==="\0"&&e[d]!=="\0";for(let d of a){let g=z(d.text,_e,n,s);for(let _=0;_<d.text.length;_++)if(!(g[_]!=="\0"||d.text[_]==="\0"))for(let y=d.offsets[_];y<d.offsets[_+1];y++)u[y]||(u[y]=!0,c=!1)}if(c)return z(e,t,n,r,i);for(let d of o)r?.(d);let p="",f=0;for(;f<e.length;){if(!u[f]){p+=e[f],f++;continue}let d=f;for(;f<e.length&&u[f];)f++;p+=q(t)(e.slice(d,f))}return p}function U(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var St=new Map;function la(e){let t=St.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),St.set(e.source,t)),t}var ca=4096,ua=64,Et=null;function da(e){return Et!==null?Et:ca+e.length*ua}var Yt=!1,w={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},Zt={spanBudget:0,depthCap:0};function pa(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:da(e),exhausted:!1}}function Jt(e,t,n,r,i,a,o){w.spanCalls++;let s=t*o.stride+n.length,l=Yt?void 0:o.chosen.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,null;o.budget--,w.spanMisses++;let c=fa(e,t,n,r,i,a,o);return o.chosen.set(s,c),c}function fa(e,t,n,r,i,a,o){let s=la(r),l=[];for(let u=n.length-1;u>=1;u--)if(U(n[u])){let p=n.slice(0,u);s.test(p)&&l.push(p)}let c=U(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(a(i(u),u)&&!ma(e,t,u,r,i,a,o))return u;return null}var Ct=new Map;function ha(e){let t=Ct.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),Ct.set(e.source,t)),t}function ma(e,t,n,r,i,a,o){w.cutCalls++;let s=t*o.stride+n.length,l=Yt?void 0:o.cuts.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,!0;o.budget--,w.cutMisses++;let c=ga(e,t,n,r,i,a,o);return o.cuts.set(s,c),c}function ga(e,t,n,r,i,a,o){let s=t+n.length,l=ha(r);for(let c=1;c<n.length;c++){if(U(n[c])||!U(n[c-1]))continue;let u=t+c;l.lastIndex=u;let p=l.exec(e);if(p===null||p[0].length===0)continue;let f=Jt(e,u,p[0],r,i,a,o);if(f!==null&&u+f.length>s&&U(e[u+f.length]))return!0}return!1}function _a(e,t,n,r,i,a,o){let s=q(i);t.lastIndex=0;let l="",c=0,u=pa(e),p=w.spanMisses+w.cutMisses,f;for(;(f=t.exec(e))!==null;){let d=f[0],g=f.index;if(d.length===0){t.lastIndex=g+1;continue}let _;try{_=Jt(e,g,d,t,n,r,u)}catch(y){if(y instanceof RangeError&&/call stack/i.test(y.message))u.exhausted=!0,_=null;else throw y}if(u.exhausted)return w.budgetExhausted++,Zt.spanBudget++,Tt(p),l+e.slice(c,g)+s(e.slice(g),a);if(_!==null)o?.(a),l+=e.slice(c,g)+s(_,a),c=g+_.length,t.lastIndex=c;else{let y=d.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=y===-1?g+d.length:g+1+y+1}if(t.lastIndex>e.length)break}return Tt(p),l+e.slice(c)}function Tt(e){let t=w.spanMisses+w.cutMisses-e;t>w.maxMissesInAPass&&(w.maxMissesInAPass=t)}function Qt(e,t=X,n,r){return ba(e,t,aa(n,r))}var ya=256;function ba(e,t,n,r){let i=q(t),a=new Set,o=!n.has("pan"),s=c=>{a.add(c)},l=(c,u)=>{if(u>ya)return Zt.depthCap++,typeof t=="string"?t:X;if(typeof c=="string")return sa(c,t,n,s,r);if(typeof c=="number"&&Number.isInteger(c)&&c>0){if(!o)return c;let p=String(c);if(p.length>=13&&p.length<=19&&ke(p)){a.add("pan");let f=i(p,"pan");return f===p?X:f}return c}if(Array.isArray(c))return c.map(p=>l(p,u+1));if(c!==null&&typeof c=="object"){let p=c,f={};for(let d of Object.keys(p))f[d]=l(p[d],u+1);return f}return c};return{value:l(e,0),detectors:[...a].sort()}}function Xt(e,t=X){return Qt(e,t).value}var va=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,en=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"}),wa=new RegExp(`[${Object.keys(en).join("")}]`,"gu"),ka=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),tn="\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",Aa=Object.freeze(Object.fromEntries([...tn].map((e,t)=>[e,String.fromCharCode(97+t)]))),Ia=new RegExp(`[${tn}\u2800]`,"g"),nn=/[⠀-⣿]/;function Sa(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 Ea(e){return e.replace(va,"")}function rn(e){return e.replace(wa,t=>en[t]??t)}function Ca(e){return e.replace(/[4@31!05$79(8]/g,t=>ka[t]??t)}function Ta(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 Na(e){return nn.test(e)?e.replace(Ia,t=>t==="\u2800"?" ":Aa[t]??t):e}function Nt(e){let t;try{t=Sa(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=Ea(t),t=rn(t),t}var xa=/^[A-Za-z0-9+/]{16,}={0,2}$/,Oa=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,xt=/[A-Za-z0-9+/]{20,}={0,2}/g;function ye(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);(r===9||r===10||r===13||r>=32&&r<=126||r>=160&&r!==65533)&&t++}return t/e.length}var an=new TextDecoder("utf-8",{fatal:!1});function on(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=an.decode(n);return t===r?[t]:[r,t]}function Ra(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=an.decode(n);return r===i?[r]:[i,r]}function Ot(e){let t=e.trim(),n=[];if(Oa.test(t))for(let r of Ra(t))n.push({decoded:r,textiness:ye(r)});if(xa.test(t)&&t.length%4===0)for(let r of on(t))n.push({decoded:r,textiness:ye(r)});return n}function Rt(e,t){let n=[],r;for(xt.lastIndex=0;(r=xt.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of on(i))n.push({decoded:a,textiness:ye(a)})}return n}var $a=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function sn(e,t=$a){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=d=>{d.length>0&&d.length<=r&&o.add(d)},l=!1,c=!1,u=0,p=0,f=[{s:e,depth:0}];for(;f.length>0;){if(u>=i){c=!0;break}let d=f.pop();if(d===void 0)break;let{s:g,depth:_}=d;if(g.length>r){c=!0;continue}u++,_>p&&(p=_);let y=Nt(g);s(y);let k=Ca(y);if(k!==y&&s(k),s(Ta(y)),nn.test(g)&&s(Na(y)),_>=n){let v=Nt(g);(Ot(v).length>0||Rt(v,a).length>0)&&(c=!0);continue}let x=[...Ot(y),...Rt(y,a)];for(let v of x){if(l=!0,v.decoded.length>r){c=!0;continue}v.textiness>=.85&&v.decoded!==y?f.push({s:v.decoded,depth:_+1}):s(v.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:p}}var ln=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],Pa=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),Fa=8,Da=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),$t=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function Ma(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||Da.has(i)&&$t(t[r-1])&&$t(t[r+1])&&(n++,n>=Fa))return!0}return!1}var La=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function ja(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(La.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Ba=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function za(e){for(let t of Ba)if(e>=t.lo&&e<=t.hi)return t.name;return null}function Ua(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=za(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:rn(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var Pt=Object.freeze({signals:[],contributes:!1});function qa(e){if(typeof e!="string"||e.length===0)return{...Pt,signals:[]};let t=new Set;try{Ma(e)&&t.add("hidden_text_carrier"),ja(e)&&t.add("injected_turn_boundary"),Ua(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=sn(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Pt,signals:[]}}return{signals:[...ln.filter(n=>t.has(n))],contributes:Pa.some(n=>t.has(n))}}var ee=[{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 Ft(e){return typeof e!="string"||e.length===0?[]:ee.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function Ga(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(Ft(e)),{views:n}=sn(e);for(let r of n)for(let i of Ft(r))t.add(i);return ee.filter(r=>t.has(r.name)).map(r=>r.name)}function Va(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of Ga(a))t.add(s);let o=qa(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:ee.filter(a=>t.has(a.name)).map(a=>a.name),structural:ln.filter(a=>n.has(a))}}function Ha(e){return Va(e).matched}var Ws=ee.map(e=>e.name);var Wa=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Ka="i:injection";function cn(e){let t=new Set,n=[];if(e.content!==void 0&&e.content!==null){let{detectors:a}=Qt(e.content);for(let o of a){n.push(o);let s=Se[o]?.category;s&&t.add(`c:${s}`)}Ha(e.content)&&t.add(Ka)}let r=e.resourceMetadata??{},i=r.source_trust;return(r.untrusted_source===!0||typeof i=="string"&&Wa.has(i.toLowerCase()))&&t.add("i:untrusted"),{labels:[...t].sort(),detectors:n}}var he="(?: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))",Ks=[{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${he}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${he}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${he}\\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}],Dt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Ya=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${Dt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${Dt}|programming|training))`,Za="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Mt="(?:\\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)",Ja="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Ys=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${Za}${Ya}\\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}?${Mt}`,"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+(?:${Ja}\\b|[\\s\\S]{0,40}?${Mt})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Zs=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var T=e=>`[^.!?;\\n]{0,${e}}?`,Qa=["\\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("|"),un="(?: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)",Js=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Qa})\\s${T(40)}\\b${un}\\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${T(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${T(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${T(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${T(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${T(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")}]),Qs=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${T(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${T(30)}\\b${un}\\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}}?`,Xs=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]}]);function dn(e,t){return Ii(e,{mode:t.mode??"full",...t.keepFirst===void 0?{}:{keepFirst:t.keepFirst},...t.keepLast===void 0?{}:{keepLast:t.keepLast},...t.maskChar===void 0?{}:{maskChar:t.maskChar},...t.replacement===void 0?{}:{replacement:t.replacement},...t.keepPattern===void 0?{}:{keepPattern:t.keepPattern}})}function Xa(e,t){return typeof e=="string"?dn(e,t):t.replacement??be}function pn(e){let t=[],n=e.replacement??be;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:ge(r),replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:ge(i),replacer:a=>dn(a,r)})}return t}function fn(e){if(!zt(e))throw new Error(`[visiq-redact] Redaction pattern "${e}" can backtrack exponentially and was refused. A group repeated with * or + must have a fixed-length body: (\\d{4})+ is fine, (\\d+)+ is not.`);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 hn(e,t){if(ve(e).length===0){let n=e;for(let{source:r,replacer:i}of t)n=n.replace(fn(r),a=>i(a));return n}return eo(e,t)}function eo(e,t){let n=e;for(let{source:r,replacer:i}of t){let a=fn(r),o=[...It(a,n)];for(let u of ve(n))for(let p of It(a,u.text))o.push(Ri(u,p));let s=$i(o);if(s.length===0)continue;let l="",c=0;for(let{start:u,end:p}of s)l+=n.slice(c,u)+i(n.slice(u,p)),c=p;n=l+n.slice(c)}return n}function el(e,t){return e==null?e:typeof e=="string"?to(e,t):typeof e=="object"?no(e,t):e}function to(e,t){if(typeof e!="string")return e;let n=pn(t);return n.length===0?e:hn(e,n)}function no(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=pn(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 u of Object.keys(l)){let p=i?n.get(u):void 0;if(p){c[u]=Xa(l[u],p);continue}c[u]=o(l[u])}return c}return typeof s=="string"&&a?hn(s,r):s};return o(e)}import{createHash as Yo}from"node:crypto";var mn=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function ro(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:mn(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:mn(t.spawn.prompt)}),t}function io(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 ao=1440*60*1e3,oo="VISIQ_BUNDLE_GRACE_TTL_MS",so="VISIQ_BUNDLE_CACHE_DISABLED",lo="VISIQ_CACHE_DIR",co=te.object({graceTtlMs:te.number().int().nonnegative().optional(),disabled:te.boolean().optional(),cacheDir:te.string().min(1).optional()}).strict();function uo(e){return e==null?{}:co.parse(e)}function po(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[oo];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return ao}function fo(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[so]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var gn;function ho(){if(gn!==void 0)return gn;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function mo(e){return JSON.stringify(Ce(e))}function Ce(e){if(Array.isArray(e))return e.map(Ce);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Ce(t[r]);return n}return e}function go(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function _o(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 In(){if(!ho())return null;try{let[e,t,n,r]=await Promise.all([import("node:fs/promises"),import("node:path"),import("node:os"),import("node:crypto")]);return{fs:e,path:t,os:n,crypto:r}}catch{return null}}function Sn(e,t){return e.createHash("sha256").update(mo(t)).digest("hex")}function yo(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[lo]?.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 bo(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function En(e,t,n){return e.path.join(yo(e,n),"bundles",`${bo(e,t)}.json`)}async function vo(e,t,n,r={}){let i=await In();if(i)try{let a=En(i,e,r),o=i.path.dirname(a);await i.fs.mkdir(o,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:Sn(i.crypto,t),body:t},l=`${a}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(l,JSON.stringify(s),{mode:384});try{await i.fs.rename(l,a)}catch(c){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),c}}catch{}}async function wo(e,t={}){let n=await In();if(!n)return null;try{let r=await n.fs.readFile(En(n,e,t),"utf-8"),i=_o(JSON.parse(r));return!i||Sn(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var G;async function ko(){if(G!==void 0)return G;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;G=typeof t=="function"?t:null}catch{G=null}return G}function Ao(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=de(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of Ze(a))t.push(`${o}: ${s}`)}return t}function Io(e){return vt(e)}function So(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var Eo=5e3,Co=600*1e3,To=1e4,No=25,_n=1e3,xo=5e3,Oo=100,yn=2e3,Ro=10,$o=512,Po=1800*1e3,Fo=.7,Do="monitor",Mo="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",bn="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.",Lo="open";function vn(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}var jo=h.object({operations:h.array(h.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:h.string().min(1,"agentId is required"),sessionId:h.string().min(1).max(255).optional(),toolName:h.string().optional(),toolArgs:h.record(h.unknown()).optional(),targetResource:h.string().optional(),resourceType:h.string().optional(),resourceMetadata:h.record(h.unknown()).optional(),normalized:h.record(h.unknown()).optional(),query:h.string().optional(),contentPreview:h.string().optional(),telemetry:h.record(h.unknown()).optional(),context:h.record(h.unknown()).optional(),mcpServer:h.string().min(1).max(255).optional(),identity:h.object({attested:h.array(h.string().min(1).max(255)).max(32).optional(),claimed:h.array(h.string().min(1).max(255)).max(32).optional(),subjectId:h.string().min(1).max(255).optional()}).optional()}),Bo=h.object({version:h.string().min(1),dialect_version:h.number().int().optional(),min_dialect:h.number().int().optional(),shutdown:h.boolean().optional(),agent_mode:h.enum(["enforce","monitor","off"]).optional(),cognition_capture:h.boolean().optional(),agent_mode_by_operation:h.object({action:h.string().optional(),retrieval:h.string().optional(),delegation:h.string().optional()}).partial().optional(),agent_attributes:h.object({trust_tier:h.string().nullable().optional(),categories:h.array(h.string()).optional(),business_function:h.string().nullable().optional(),business_functions:h.array(h.string()).nullable().optional(),blast_radius_tier:h.string().nullable().optional(),no_coverage:h.string().nullable().optional(),fail_mode:h.string().nullable().optional()}).optional(),rules:h.array(h.record(h.unknown())),action_schemas:h.array(h.object({id:h.string(),plane:h.string().optional(),field_mappings:h.array(h.record(h.unknown())).optional(),derived_fields:h.array(h.record(h.unknown())).optional(),action_class:h.string().nullable().optional(),action_class_confidence:h.number().optional()})).optional(),no_coverage:h.object({no_coverage_defaults:h.record(h.string()),autopilot_enabled:h.boolean(),enduser_hitl_enabled:h.boolean(),hitl_timeout_seconds:h.number().optional()}).optional(),skill_blacklist:h.array(h.record(h.unknown())).optional()});function zo(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=dt(pt(n));return{trust_tier:it(t)?t:null,categories:ot(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&ft(e.blast_radius_tier)?e.blast_radius_tier:null}}function Uo(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 qo(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Te=new Set,wn=!1;async function kn(e){let t=[];for(let n of Te){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 Go(){if(!wn&&!(typeof process>"u"||typeof process.once!="function")){wn=!0,process.once("beforeExit",()=>{kn(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await kn(!0)}finally{process.kill(process.pid,e)}})()})}}var ll=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=Do;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=vn(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Lo;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,u=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=l,this.resolvedEndpoint=c,this.resolvedAgentId=u,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=o,this.originalFetch=globalThis.fetch.bind(globalThis);let p=uo(s);if(this.bundleCacheDisabled=fo(p.disabled),this.bundleGraceTtlMs=po(p.graceTtlMs),this.bundleCacheDirOverride=p.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let f={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:io(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new ze(f,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Eo),Ee(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},To),Ee(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},xo),Ee(this.cognitionTimer),Te.add(this),Go()}else this.client=null}async evaluate(e){let t=jo.parse(e),n=Date.now();if(this.operatorShutdown){let d=this.denyAll(t,Mo);return this.applyAgentMode(d,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,bn,n);let d=this.denyAll(t,bn);return this.applyAgentMode(d,"enforce",t,n)}if(t.operations.every(d=>this.modeFor(d)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let d;if(this.agentModeConfirmed?d=this.agentMode:this.bundleApplyFailed?d="enforce":d="monitor",d==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let g=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(g,d,t,n)}if(this.modeFor("action")!=="off"){let d=this.matchSkillQuarantine(t);if(d){let g=this.denyAll(t,d);return this.applyAgentMode(g,this.modeFor("action"),t,n)}}let r=this.readSession(t.sessionId),i=await ko();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")?Xe(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}:{}},u;try{u=i(l,c)}catch(d){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${d instanceof Error?d.message:String(d)}`,n);throw d}let p=[...new Set(t.operations.flatMap(d=>this.normalizedRefs[d]??[]))].sort();p.length>0&&So(t.normalized)&&(u.normalizedColdStart=p,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${p.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: ${p.slice(0,5).join("; ")}${p.length>5?`; +${p.length-5} more`:""}`)));let f=et(t.normalized);return f.length>0&&(u.normalizedDrift=f,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${f.length} value(s) outside the canonical vocabulary \u2014 a builder-authored rule can only select in-vocab values, so these cannot match one, so a rule keyed on the canonical value does not fire here. Check the harness classifier's casing/spelling. Affected: ${f.slice(0,5).join("; ")}${f.length>5?`; +${f.length-5} more`:""}`))),this.foldSession(t,u.enforced?u.decision:"permit"),u.enforced&&u.action.decision==="approval_required"&&await this.registerHitl(t,u),this.bufferTelemetry(t,u,Date.now()-n,u.enforced),u}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=mt({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 j;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Po?(this.sessions.delete(e),j):t.state:j}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>=Fo)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=a?cn({content:e.contentPreview,resourceMetadata:i}):void 0,l=s?.labels,c=Array.isArray(i.data_categories)?i.data_categories:[],u=(s?.detectors??[]).map(d=>yt(d)).filter(d=>d!==void 0),p=a?[...new Set([...c,...u])]:void 0,f=nt(r===j?J():r,{data_categories:p,classification:a?i.classification:void 0,taint:l,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:f,touchedAt:Date.now()}),this.sessions.size>$o){let d=this.sessions.keys().next().value;d!==void 0&&this.sessions.delete(d)}}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=Bo.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=Ao(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=>bt(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?zo(t.agent_attributes):null,this.agentNoCoverage=gt(t.agent_attributes?.no_coverage),this.governedFailMode=vn(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=Uo(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=Io(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",...R(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>=Co&&(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 wo(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(go(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 vo(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}isBundleLoaded(){return this.bundleLoaded}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e,t){this.registerEnvironment({...le(),...e?{agent_type:e}:{},...t?.model?{model:t.model}:{},...t?.systemPrompt?{systemPrompt:t.systemPrompt}:{},...t?.toolSchemas&&t.toolSchemas.length>0?{toolSchemas:t.toolSchemas}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));for(let n of e)n.description&&this.toolDescriptions.set(n.name,n.description);t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}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({...le(),...e.agentType?{agent_type:e.agentType}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{toolSchemas:e.toolSchemas}:{}}))}buildActionSchemaEvent(e){let t=e.toolName?this.toolDescriptions.get(e.toolName):void 0,n={agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{},...e.toolArgs?{tool_args:e.toolArgs}:{},...t?{tool_description:t}:{}},r=_t(n),i={...n};return e.toolArgs&&(i.tool_args=Xt(e.toolArgs)),{canonical:n,id:r,rawEventForWire:i}}bufferTelemetry(e,t,n,r,i=!1){let a=this.buildActionSchemaEvent(e),o=crypto.randomUUID();t.decisionId=o,this.telemetryBuffer.push({decision_id:o,agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:r?qo(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?{[je]: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,Ro)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=No&&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-_n;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${_n})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(ro(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Oo&&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(),Te.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 Ee(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function ne(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function cl(e,t){if(e!=="Task"&&e!=="Agent")return null;let n=ne(t.description),r=ne(t.subagent_type),i=ne(t.prompt),a=n??r??"sub-agent";return{childAgentId:a,childName:a,kind:"subagent",agentType:r,description:n,task:i,goal:i,model:ne(t.model),source:"structural"}}function ul(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 Vo={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"},Ho=new Set(["workspace_deactivate_skill"]),Wo=new Set(["read","read_file","readfile","view","cat"]);function dl(e){return Ho.has((e??"").trim())}function Ko(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function An(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function pl(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=Vo[n];if(i){let a=An(r,["name","skill_name","identifier","skill","path"]);return a?{skill:a,via:n,framework:i}:null}if(Wo.has(n.toLowerCase())){let a=An(r,["path","file_path","filePath","target","file"]),o=a?Ko(a):null;return o?{skill:o,via:n,framework:"unknown"}:null}return null}var Zo=/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,Jo=/^([A-Za-z0-9_.-]+):[ \t]*(.*)$/;function Qo(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1):t}function Xo(e,t){let n=t.startsWith("|");return(n?e.join(`
9
+ `):e.join(" ")).replace(/[ \t]+/g,n?"$&":" ").trim()}function es(e){let t=Zo.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=Jo.exec(s);if(!l)continue;let c=l[1],u=(l[2]??"").trim();if(/^[|>][+-]?\d*$/.test(u)){let p=[],f=o+1;for(;f<a.length;f+=1){let d=a[f]??"";if(d.trim()&&!/^[ \t]/.test(d))break;p.push(d.trim())}o=f-1,i[c]=Xo(p,u);continue}u&&(i[c]=Qo(u))}return{attrs:i,body:r}}function ts(e){return Yo("sha256").update(e,"utf8").digest("hex")}function ns(e,t,n){let{attrs:r,body:i}=es(e),{description:a}=r;return{name:r.name?.trim()||n,path:t,...a?{description:a}:{},contentHash:ts(i),fingerprint:ht(i)}}var rs=500,is=512*1024;async function ml(e){let[t,n]=await Promise.all([import("node:fs/promises"),import("node:path")]),r=[],i=new Set;for(let a of e){let o;try{o=await t.readdir(a,{withFileTypes:!0})}catch{continue}for(let s of o){if(r.length>=rs)return r;if(!s.isDirectory())continue;let l=n.join(a,s.name,"SKILL.md");try{let c=await t.stat(l);if(!c.isFile()||c.size>is)continue;let u=await t.readFile(l,"utf8"),p=ns(u,`${s.name}/SKILL.md`,s.name),f=`${p.name}@${p.contentHash}`;if(i.has(f))continue;i.add(f),r.push(p)}catch{continue}}}return r}function gl(e){let t=[],n=[],r,i=[];for(let o of e){if(o.mode==="partial"||o.mode==="email"||o.mode==="custom"){let l={mode:o.mode};o.field&&(l.field=o.field),o.pattern&&(l.pattern=o.pattern),typeof o.keepFirst=="number"&&(l.keepFirst=o.keepFirst),typeof o.keepLast=="number"&&(l.keepLast=o.keepLast),o.maskChar&&(l.maskChar=o.maskChar),o.keepPattern&&(l.keepPattern=o.keepPattern),o.replacement!==void 0&&(l.replacement=o.replacement),i.push(l);continue}o.field&&t.push(o.field),o.pattern&&n.push(o.pattern);let{replacement:s}=o;s&&r===void 0&&(r=s)}let a={};return t.length>0&&(a.fields=t),n.length>0&&(a.patterns=n),r!==void 0&&(a.replacement=r),i.length>0&&(a.directives=i),a}var Cn="0.1.19";var El=3e4,ss=4e3;function ls(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,200)||"default"}function ae(e){let t=os("sha1").update(e).digest("hex").slice(0,10);return`${ls(e)}-${t}`}function Cl(e,t,n){return n-e.fetchedAt<t}function Tn(e){return N(A(),"bundles",`${ae(e)}.json`)}function Nn(e){return N(A(),"sessions",`${ae(e)}.registered`)}function xn(e){return N(A(),"sessions",`${ae(e)}.skill`)}function On(e){return N(A(),"sessions",`${ae(e)}.skillfp.json`)}var cs=/^[0-9a-f]{16}$/;async function Tl(e,t){try{await re(N(A(),"sessions"),{recursive:!0}),await ie(On(e),JSON.stringify(t),{mode:384})}catch{}}async function Nl(e){try{let t=await Ne(On(e),"utf8"),n=JSON.parse(t);if(n===null||typeof n!="object")return{};let r={};for(let[i,a]of Object.entries(n))typeof a=="string"&&cs.test(a)&&(r[i]=a);return r}catch{return{}}}async function xl(e){try{let n=(await Ne(xn(e),"utf8")).trim();return n.length>0?n:null}catch{return null}}async function Ol(e,t){try{await re(N(A(),"sessions"),{recursive:!0}),await ie(xn(e),t??"",{mode:384})}catch{}}async function Rl(e){try{let t=await Ne(Tn(e),"utf-8"),n=JSON.parse(t);return n&&typeof n.fetchedAt=="number"&&"body"in n?n:null}catch{return null}}async function $l(e,t,n){try{let r=Tn(e);await re(N(A(),"bundles"),{recursive:!0});let i={fetchedAt:Date.now(),version:n,body:t};await ie(r,JSON.stringify(i),{mode:384})}catch{}}async function Pl(e,t,n){try{let i=`${e.replace(/\/+$/,"")}/rules/bundle?agent_id=${encodeURIComponent(n)}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...R(Cn,se)},signal:AbortSignal.timeout(ss)});if(!a.ok)return null;let o=a.headers.get("etag");return{body:await a.json(),version:o}}catch{return null}}async function Fl(e){try{return await as(Nn(e)),!0}catch{return!1}}async function Dl(e){try{await re(N(A(),"sessions"),{recursive:!0}),await ie(Nn(e),String(Date.now()),{mode:384})}catch{}}export{$e as a,Pe as b,A as c,Mn as d,Bn as e,zn as f,Un as g,fs as h,el as i,se as j,ir as k,ll as l,cl as m,ul as n,dl as o,Ko as p,pl as q,ml as r,gl as s,Cn as t,El as u,ls as v,Cl as w,Tl as x,Nl as y,xl as z,Ol as A,Rl as B,$l as C,Pl as D,Fl as E,Dl as F};
@@ -1,3 +1,3 @@
1
- import{A as g,B as z,C as G,D as Y,E as X,F as k,c as O,i as b,j as D,k as A,l as V,m as q,n as L,o as M,p as H,q as j,r as B,s as x,t as Q,u as W,w as $,x as h,y as J,z as K}from"./chunk-MQHAJCDD.js";import{appendFile as se,mkdir as ae}from"node:fs/promises";import{join as le}from"node:path";function ce(){return le(O(),"fail-open.log")}async function u(e,t=!0){let n=`[VisIQ] FAIL-OPEN (${e.stage}): ${e.detail} \u2014 tool call proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`;try{process.stderr.write(`${n}
1
+ import{A as g,B as z,C as G,D as Y,E as X,F as k,c as O,i as b,j as D,k as A,l as V,m as q,n as L,o as M,p as H,q as j,r as B,s as x,t as Q,u as W,w as $,x as h,y as J,z as K}from"./chunk-AUKV5XLW.js";import{appendFile as se,mkdir as ae}from"node:fs/promises";import{join as le}from"node:path";function ce(){return le(O(),"fail-open.log")}async function u(e,t=!0){let n=`[VisIQ] FAIL-OPEN (${e.stage}): ${e.detail} \u2014 tool call proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`;try{process.stderr.write(`${n}
2
2
  `)}catch{}if(t)try{await ae(O(),{recursive:!0}),await se(ce(),`${JSON.stringify({at:new Date().toISOString(),...e})}
3
3
  `,{mode:384})}catch{}}async function _(e,t={}){e.failOpen===!0&&await u({stage:"runtime-fail-open",detail:e.reason,...t.toolName?{toolName:t.toolName}:{},...t.sessionId?{sessionId:t.sessionId}:{}})}var ue=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),de=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function pe(e){if(typeof e!="string"||!e.startsWith("mcp__"))return typeof e=="string"?e:"";let t=e.lastIndexOf("__");return t>=0?e.slice(t+2):e}function U(e){return typeof e!="string"?!1:ue.has(e)?!0:e.startsWith("mcp__")?de.test(pe(e)):!1}function Z(e){return U(e)?["retrieval","action"]:["action"]}var fe=["query","q","url","prompt","pattern","file_path","path"];function I(e){if(!e||typeof e!="object")return;let t=e,n=[];for(let o of fe){let i=t[o];typeof i=="string"&&i.length>0&&n.push(i)}return n.length>0?n.join(" "):void 0}function l(e,t){let n=t?`VisIQ ${t}`:"VisIQ",o=e&&e.trim().length>0?e.trim():"blocked by policy";return`[${n}] ${o}`}function ee(e){let t={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};return e&&(t.hookSpecificOutput.updatedInput=e),t}function y(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}function te(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:e}}}function d(e,t){let n={hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}};return t&&(n.hookSpecificOutput.additionalContext=t),n}function Oe(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.hook_event_name=="string"?t:null}catch{return null}}var me="[VisIQ: retrieval withheld by policy]";function w(e){return T(e)}function T(e){if(e==null)return e;if(typeof e=="string")return e.length>0?me:e;if(typeof e=="number")return 0;if(typeof e=="boolean")return!1;if(Array.isArray(e))return e.map(T);if(typeof e=="object"){let t=Object.create(null);for(let n of Object.keys(e))t[n]=T(e[n]);return t}return e}function ne(e){return e.fields&&e.fields.length>0||e.patterns&&e.patterns.length>0?!0:!!e.directives?.some(t=>t.field&&t.field.length>0||t.pattern&&t.pattern.length>0)}function ge(e){return e.patterns&&e.patterns.length>0?!0:!!e.directives?.some(t=>t.pattern&&t.pattern.length>0)}function oe(e,t){if(!e.enforced)return null;let{action:n,retrieval:o}=e,i=l(e.reason,e.ruleCode);if(n.decision==="deny"||o.action==="deny")return y(i);if(n.decision==="approval_required"||o.action==="escalate")return te(i);if(n.decision==="mask"&&n.argRedactionRules&&n.argRedactionRules.length>0){let r=x(n.argRedactionRules);if(ne(r)){let s=b(t,r)??t;if(JSON.stringify(s)!==JSON.stringify(t))return ee(s)}return null}return null}function ie(e,t){if(!e.enforced)return null;let{retrieval:n}=e,o=l(e.reason,e.ruleCode);if(n.action==="redact"){let i=x(n.redactionRules??[]);if(!(typeof t=="string"?ge(i):ne(i)))return d(w(t),o);let s=b(t,i);return JSON.stringify(s)===JSON.stringify(t)?null:d(s,o)}return n.action==="deny"?d(w(t),o):null}var ye="cli_harness";function f(e){let t=new V(e.apiKey,e.baseUrl,e.agentId,ye,void 0,Q,D);return t.setFailMode(e.failMode),t}function S(e){let t={operations:e.operations,agentId:e.agentId,toolName:e.toolName,toolArgs:e.toolInput,resourceType:"tool_result",resourceMetadata:{toolName:e.toolName,...e.toolUseId?{toolCallId:e.toolUseId}:{},...e.sessionId?{sessionId:e.sessionId}:{},...e.cwd?{cwd:e.cwd}:{}}};return e.query&&(t.query=e.query),e.context&&(t.context=e.context),t}async function m(e,t,n=W){let{agentId:o}=t,i=await z(o);if(i&&$(i,n,Date.now())&&E(e,i.body))return!0;let r=e.getEndpoint();if(r){let s=await Y(r,t.apiKey,o);if(s&&E(e,s.body))return await G(o,s.body,s.version),!0}if(i&&E(e,i.body))return!0;try{await e.awaitBundleReady(2500)}catch{}return e.isBundleLoaded()}function E(e,t){try{return e.applyBundle(t),!0}catch{return!1}}async function c(e){try{await e.flush()}catch{}let t=typeof e.droppedTelemetryCount=="function"?e.droppedTelemetryCount():0;try{e.dispose()}catch{}return t}var we=500;async function De(e,t=we){if(e.length===0)return;let n=Promise.allSettled(e.map(o=>o()));await Promise.race([n,new Promise(o=>{setTimeout(o,t).unref?.()})])}async function he(e){let{homedir:t}=await import("node:os"),{join:n}=await import("node:path");return[...e?[n(e,".claude","skills")]:[],n(t(),".claude","skills")]}async function R(e){let t=await B(await he(e)),n={};for(let o of t){n[o.name]=o.fingerprint;let i=H(o.path);i&&(n[i]=o.fingerprint)}return{records:t,fingerprints:n}}async function Je(e,t,n){let o=f(t),i=e.tool_input??{};try{if(await X(e.session_id)||(o.registerHostEnvironment(),await k(e.session_id)),!await m(o,t))return t.failMode==="closed"?y(l("no rule bundle available (cache empty + fetch failed) \u2014 blocked (VISIQ_FAIL_MODE=closed)",null)):(await u({stage:"no-bundle",detail:"no rule bundle available (cache empty + fetch failed)",toolName:e.tool_name,sessionId:e.session_id}),null);let s=q(e.tool_name,i),p=Z(e.tool_name),P;s&&(A(o,{agentId:t.agentId,sessionId:e.session_id,framework:"claude-code"},s),p=Array.from(new Set([...p,"delegation"])),P=L(s,t.agentId));let a=j(e.tool_name,i),v=await K(e.session_id);a?(v=a.skill,await g(e.session_id,a.skill)):M(e.tool_name)&&await g(e.session_id,null);let F=a?await ke(e.session_id,e.cwd,a.skill):void 0,C=v?{skill:{name:v,activated:!!a,...a?{via:a.via,framework:a.framework}:{},...F?{fingerprint:F}:{}}}:void 0,re=S({operations:p,agentId:t.agentId,toolName:e.tool_name,toolInput:i,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:I(i),...P||C?{context:{...P??{},...C??{}}}:{}}),N=await o.evaluate(re);return await _(N,{toolName:e.tool_name,sessionId:e.session_id}),oe(N,i)}catch(r){return t.failMode==="closed"?y(l("evaluation error \u2014 blocked (VISIQ_FAIL_MODE=closed)",null)):(await u({stage:"pre-eval-error",detail:r instanceof Error?r.message:String(r),toolName:e.tool_name,sessionId:e.session_id}),null)}finally{n?n.push(()=>c(o)):await c(o)}}async function ke(e,t,n){try{let o=await J(e);if(o[n])return o[n];let{fingerprints:i}=await R(t);return i[n]?(await h(e,{...o,...i}),i[n]):void 0}catch{return}}async function et(e,t,n){if(!U(e.tool_name))return null;let o=f(t);try{if(!await m(o,t))return t.failMode==="closed"?d(w(e.tool_response),l("no rule bundle available (cache empty + fetch failed) \u2014 withheld (VISIQ_FAIL_MODE=closed)",null)):(await u({stage:"no-bundle",detail:"no rule bundle available (cache empty + fetch failed)",toolName:e.tool_name,sessionId:e.session_id}),null);let r=e.tool_input??{},s=S({operations:["retrieval"],agentId:t.agentId,toolName:e.tool_name,toolInput:r,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:I(r)}),p=await o.evaluate(s);return await _(p,{toolName:e.tool_name,sessionId:e.session_id}),ie(p,e.tool_response)}catch(i){return t.failMode==="closed"?d(w(e.tool_response),l("evaluation error \u2014 withheld (VISIQ_FAIL_MODE=closed)",null)):(await u({stage:"post-eval-error",detail:i instanceof Error?i.message:String(i),toolName:e.tool_name,sessionId:e.session_id}),null)}finally{n?n.push(()=>c(o)):await c(o)}}async function _e(e,t,n){try{let{records:o,fingerprints:i}=await R(n);if(o.length===0)return;e.reportSkillInventory(o.map(r=>({name:r.name,path:r.path,...r.description?{description:r.description}:{},content_hash:r.contentHash,fingerprint:r.fingerprint,framework:"claude-code"}))),await h(t,i)}catch{}}async function rt(e,t){let n=f(t);try{n.registerHostEnvironment(),await m(n,t,0),await k(e.session_id),await _e(n,e.session_id,e.cwd),await g(e.session_id,null)}finally{await c(n)}return null}export{ce as a,u as b,pe as c,U as d,Z as e,I as f,l as g,ee as h,y as i,te as j,d as k,Oe as l,me as m,w as n,oe as o,ie as p,ye as q,f as r,S as s,m as t,c as u,De as v,Je as w,et as x,rt as y};
package/dist/cli/hook.js CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import{b as l,i as a,l as f,v as m,w as I,x as h,y as w}from"../chunk-P74HY33U.js";import{a as c,b as u,g as p}from"../chunk-MQHAJCDD.js";var S=process.env.VISIQ_DEBUG==="1",k=S?(...e)=>{process.stderr.write(`${e.map(String).join(" ")}
2
+ import{b as l,i as a,l as f,v as m,w as I,x as h,y as w}from"../chunk-OPG46NW6.js";import{a as c,b as u,g as p}from"../chunk-AUKV5XLW.js";var S=process.env.VISIQ_DEBUG==="1",k=S?(...e)=>{process.stderr.write(`${e.map(String).join(" ")}
3
3
  `)}:()=>{},v=console;for(let e of["log","info","debug","warn","error"])v[e]=k;var F={handlePre:(e,o,n)=>I(e,o,n),handlePost:(e,o,n)=>h(e,o,n),handleSession:(e,o)=>w(e,o),write:e=>{process.stdout.write(e)},reportFailOpen:e=>l(e),drainFinalizers:e=>m(e)};async function P(e,o,n=F){let i=e.hook_event_name==="PreToolUse",r=s=>{i&&n.write(JSON.stringify(a(s)))},t=[];try{let s=null;switch(e.hook_event_name){case"PreToolUse":s=await n.handlePre(e,o,t);break;case"PostToolUse":s=await n.handlePost(e,o,t);break;case"SessionStart":s=await n.handleSession(e,o);break;default:s=null}s&&n.write(JSON.stringify(s))}catch(s){let d=s instanceof Error?s.message:String(s);o.failMode==="closed"?r(`[VisIQ] harness error \u2014 blocked (VISIQ_FAIL_MODE=closed): ${d}`):await n.reportFailOpen({stage:"handler-crash",detail:d,toolName:e.tool_name,sessionId:e.session_id})}finally{await n.drainFinalizers?.(t)}}function E(e,o=process.env){return u(o.VISIQ_FAIL_MODE)??e}function g(e,o,n){let i=e instanceof Error?e.message:String(e),r=E(o,n.env??process.env);try{r==="closed"?n.writeOut(JSON.stringify(a("[VisIQ] harness crashed before evaluating the call \u2014 blocked (VISIQ_FAIL_MODE=closed)."))):n.writeErr(`[VisIQ] FAIL-OPEN (dispatch-crash): ${i} \u2014 tool call proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.
4
4
  `)}catch{}return r}var _=c;function D(){return new Promise(e=>{if(process.stdin.isTTY){e("");return}let o=[],n=!1,i=()=>{n||(n=!0,e(Buffer.concat(o).toString("utf-8")))};setTimeout(i,15e3).unref?.(),process.stdin.on("data",t=>o.push(t)),process.stdin.on("end",i),process.stdin.on("error",i)})}async function O(){let e=f(await D());if(!e)return;let o=e.hook_event_name==="PreToolUse",n=t=>{o&&process.stdout.write(JSON.stringify(a(t)))},{config:i,failMode:r}=await p();if(_=r,!i){r==="closed"?n("[VisIQ] Claude Code harness is loaded but NOT configured \u2014 set VISIQ_API_KEY + VISIQ_AGENT_ID (and optionally VISIQ_ENDPOINT), or run `visiq-claude-code configure`. Blocked because VISIQ_FAIL_MODE=closed."):o&&await l({stage:"unconfigured",detail:"no VisIQ credentials resolved (need VISIQ_API_KEY + VISIQ_AGENT_ID)",toolName:e.tool_name,sessionId:e.session_id},!1);return}await P(e,i)}O().then(()=>process.exit(0)).catch(e=>{g(e,_,{writeOut:o=>process.stdout.write(o),writeErr:o=>process.stderr.write(o)}),process.exit(0)});
package/dist/cli/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as m,e as w,f as y,g as l}from"../chunk-6DMSMBWM.js";import{B as h,c as u,d as g,e as p,h as f}from"../chunk-MQHAJCDD.js";import{mkdir as I,readFile as j,writeFile as $}from"node:fs/promises";import{existsSync as C}from"node:fs";import{homedir as k}from"node:os";import{dirname as S,isAbsolute as N,join as c,resolve as A}from"node:path";import{parseArgs as O}from"node:util";function x(){let{positionals:e,values:n}=O({args:process.argv.slice(2),options:{user:{type:"boolean"},project:{type:"boolean"},settings:{type:"string"},command:{type:"string"},"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"}},strict:!1,allowPositionals:!0});return{positionals:e,values:n}}function v(e){let n=e.settings;return typeof n=="string"&&n.length>0?N(n)?n:A(n):e.project?c(process.cwd(),".claude","settings.json"):c(k(),".claude","settings.json")}var a=class extends Error{constructor(s,t){super(`[visiq] refusing to write ${s}: it exists but could not be read as JSON (${t}).
2
+ import{a as m,e as w,f as y,g as l}from"../chunk-6DMSMBWM.js";import{B as h,c as u,d as g,e as p,h as f}from"../chunk-AUKV5XLW.js";import{mkdir as I,readFile as j,writeFile as $}from"node:fs/promises";import{existsSync as C}from"node:fs";import{homedir as k}from"node:os";import{dirname as S,isAbsolute as N,join as c,resolve as A}from"node:path";import{parseArgs as O}from"node:util";function x(){let{positionals:e,values:n}=O({args:process.argv.slice(2),options:{user:{type:"boolean"},project:{type:"boolean"},settings:{type:"string"},command:{type:"string"},"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"}},strict:!1,allowPositionals:!0});return{positionals:e,values:n}}function v(e){let n=e.settings;return typeof n=="string"&&n.length>0?N(n)?n:A(n):e.project?c(process.cwd(),".claude","settings.json"):c(k(),".claude","settings.json")}var a=class extends Error{constructor(s,t){super(`[visiq] refusing to write ${s}: it exists but could not be read as JSON (${t}).
3
3
  Writing would REPLACE it, discarding whatever it holds \u2014 permissions, model, MCP servers.
4
4
  Fix the JSON (a trailing comma is the usual cause) and re-run, or pass --settings <path> to install somewhere else.`);this.path=s;this.reason=t;this.name="UnreadableSettingsError"}path;reason};async function d(e){if(!C(e))return{};let n;try{n=await j(e,"utf-8")}catch(t){throw new a(e,t instanceof Error?t.message:String(t))}if(n.trim().length===0)return{};let s;try{s=JSON.parse(n)}catch(t){throw new a(e,t instanceof Error?t.message:String(t))}if(!s||typeof s!="object"||Array.isArray(s))throw new a(e,`expected a JSON object, got ${Array.isArray(s)?"an array":typeof s}`);return s}async function P(e,n){await I(S(e),{recursive:!0}),await $(e,`${JSON.stringify(n,null,2)}
5
5
  `,"utf-8")}async function Q(e){let n=v(e),s=typeof e.command=="string"?e.command:m,t=await d(n);return await P(n,w(t,s)),process.stdout.write(`[VisIQ] Installed Claude Code governance hooks \u2192 ${n}
package/dist/index.d.ts CHANGED
@@ -653,6 +653,27 @@ export interface UnifiedDecision {
653
653
  enforced: boolean;
654
654
  /** The agent mode the decision was evaluated under. */
655
655
  agentMode: AgentMode;
656
+ /**
657
+ * The id of the audit row THIS evaluation produces — the join key between what
658
+ * the runtime just did and what the tenant can see.
659
+ *
660
+ * It is not a new identifier. `bufferTelemetry` has always minted this uuid,
661
+ * and telemetry ingest adopts it VERBATIM as `allow_audit_log.id`
662
+ * (allow-telemetry-service.ts: `id: d.decision_id`), which the record envelope
663
+ * then references as `decision_id`. The whole chain existed; the SDK simply
664
+ * never handed the value back, so a caller holding a permit/deny/mask had no
665
+ * way to name the tenant-side row it created and no correlation was possible
666
+ * from the runtime end. Stamped here for every verdict, not just HITL.
667
+ *
668
+ * DISTINCT from `action.decisionId`, which is the server-issued poll key for a
669
+ * registered approval_required (same namespace — both are audit-row ids — but
670
+ * that one is set by registerHitl from the /allow/evaluate response, and must
671
+ * not be overwritten).
672
+ *
673
+ * Absent only where no telemetry is buffered (agent_mode=off short-circuits
674
+ * before buffering).
675
+ */
676
+ decisionId?: string;
656
677
  action: UnifiedActionSubDecision;
657
678
  retrieval: UnifiedRetrievalSubDecision;
658
679
  /**
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as h,b as x,c as O,d as S,e as C,f as H,g as _}from"./chunk-6DMSMBWM.js";import{a as s,b as p,c as m,d,e as f,f as E,g as K,h as V,i as w,j as z,k as G,l as Q,m as R,n as u,o as T,p as c,q as N,r as A,s as P,t as U,u as k,w as B,x as q,y as b}from"./chunk-P74HY33U.js";import{B as y,C as L,D as v,E as I,F as M,a as e,b as o,c as t,d as r,e as i,f as a,g as n,h as l,u as g,v as D,w as F}from"./chunk-MQHAJCDD.js";export{g as DEFAULT_BUNDLE_TTL_MS,e as DEFAULT_FAIL_MODE,N as HARNESS_KIND,h as HOOK_COMMAND,x as HOOK_TIMEOUT_SECONDS,O as RETRIEVAL_MATCHER,R as WITHHELD_SENTINEL,m as bareToolName,u as blankContent,P as buildEvaluateEvent,G as buildPostRedact,V as buildPreAllow,z as buildPreAsk,w as buildPreDeny,r as configFilePath,A as createRuntime,i as envConfig,E as extractQuery,s as failOpenLogPath,v as fetchBundle,k as finishRuntime,K as formatReason,q as handlePostToolUse,B as handlePreToolUse,b as handleSessionStart,_ as hooksInstalled,C as installHooks,F as isFresh,d as isRetrievalTool,I as isSessionRegistered,S as isVisiqGroup,l as loadConfig,n as loadHarnessState,c as mapPostRedaction,T as mapPreDecision,M as markSessionRegistered,a as mergeConfig,o as normalizeFailMode,Q as parseHookInput,y as readBundleCache,p as reportFailOpen,D as sanitizeId,f as toolOperations,H as uninstallHooks,t as visiqHomeDir,U as warmFromCache,L as writeBundleCache};
1
+ import{a as h,b as x,c as O,d as S,e as C,f as H,g as _}from"./chunk-6DMSMBWM.js";import{a as s,b as p,c as m,d,e as f,f as E,g as K,h as V,i as w,j as z,k as G,l as Q,m as R,n as u,o as T,p as c,q as N,r as A,s as P,t as U,u as k,w as B,x as q,y as b}from"./chunk-OPG46NW6.js";import{B as y,C as L,D as v,E as I,F as M,a as e,b as o,c as t,d as r,e as i,f as a,g as n,h as l,u as g,v as D,w as F}from"./chunk-AUKV5XLW.js";export{g as DEFAULT_BUNDLE_TTL_MS,e as DEFAULT_FAIL_MODE,N as HARNESS_KIND,h as HOOK_COMMAND,x as HOOK_TIMEOUT_SECONDS,O as RETRIEVAL_MATCHER,R as WITHHELD_SENTINEL,m as bareToolName,u as blankContent,P as buildEvaluateEvent,G as buildPostRedact,V as buildPreAllow,z as buildPreAsk,w as buildPreDeny,r as configFilePath,A as createRuntime,i as envConfig,E as extractQuery,s as failOpenLogPath,v as fetchBundle,k as finishRuntime,K as formatReason,q as handlePostToolUse,B as handlePreToolUse,b as handleSessionStart,_ as hooksInstalled,C as installHooks,F as isFresh,d as isRetrievalTool,I as isSessionRegistered,S as isVisiqGroup,l as loadConfig,n as loadHarnessState,c as mapPostRedaction,T as mapPreDecision,M as markSessionRegistered,a as mergeConfig,o as normalizeFailMode,Q as parseHookInput,y as readBundleCache,p as reportFailOpen,D as sanitizeId,f as toolOperations,H as uninstallHooks,t as visiqHomeDir,U as warmFromCache,L as writeBundleCache};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visiq/claude-code-harness",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
4
4
  "description": "VisIQ agent-governance harness for the Claude Code CLI — action governance on every tool call, retrieval governance on its built-in read tools and read-shaped MCP tools, and audit-trail reporting, installed as Claude Code hooks.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,5 +0,0 @@
1
- import{readFile as hn}from"node:fs/promises";import{homedir as be}from"node:os";import{join as J,isAbsolute as gn,resolve as _n}from"node:path";var yn="https://api.visiqlabs.com",bn="@visiq/claude-code-harness",ve="open";function we(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function w(){let e=process.env.VISIQ_HOME;return e&&e.trim().length>0?e:J(be(),".visiq","claude-code")}function vn(){return J(w(),"config.json")}function wn(e){return e==="~"||e.startsWith("~/")?J(be(),e.slice(1).replace(/^\//,"")):e}async function An(e){try{let t=gn(e)?e:_n(e),n=await hn(t,"utf-8");return JSON.parse(n)}catch{return null}}function F(e,...t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function _e(e){if(!e||typeof e!="object")return{};let t=e,n={},r=F(t,"apiKey","api_key"),i=F(t,"agentId","agent_id"),a=F(t,"baseUrl","base_url"),o=we(F(t,"failMode","fail_mode"));return r&&(n.apiKey=r),i&&(n.agentId=i),a&&(n.baseUrl=a),o&&(n.failMode=o),n}async function ye(e){if(!e)return{};let t=await An(wn(e));if(!t||typeof t!="object")return{};let n=t,r=n.plugins?.entries,i=r&&typeof r=="object"?r[bn]:void 0;return i&&typeof i=="object"&&i.config?_e(i.config):_e(n)}function kn(e=process.env){let t={};e.VISIQ_API_KEY&&(t.apiKey=e.VISIQ_API_KEY),e.VISIQ_AGENT_ID&&(t.agentId=e.VISIQ_AGENT_ID),e.VISIQ_BASE_URL?t.baseUrl=e.VISIQ_BASE_URL:e.VISIQ_ENDPOINT&&(t.baseUrl=e.VISIQ_ENDPOINT);let n=we(e.VISIQ_FAIL_MODE);return n&&(t.failMode=n),t}function Sn(e,t,n){let r={...e,...t,...n};if(!r.apiKey||!r.agentId)return null;let i={apiKey:r.apiKey,agentId:r.agentId,failMode:r.failMode??ve};return i.baseUrl=r.baseUrl||yn,i}async function In(){let e=kn(),t=await ye(process.env.VISIQ_CONFIG_PATH),n=await ye(vn()),r={...n,...t,...e};return{config:Sn(n,t,e),failMode:r.failMode??ve}}async function Io(){return(await In()).config}import{mkdir as K,readFile as ge,writeFile as Z,stat as _o}from"node:fs/promises";import{createHash as yo}from"node:crypto";import{join as C}from"node:path";import{z as f}from"zod";import*as A from"node:os";import{randomUUID as jn}from"node:crypto";var Q=1,ke="X-VisIQ-SDK",Se="X-VisIQ-Dialect",Ie="unknown";function N(e,t=1){return{[ke]:e&&e.length>0?e:Ie,[Se]:String(t)}}var Ee="interceptor_source",En=f.enum(["enforce","audit","off"]),Cn=f.enum(["closed","open"]),Ce=f.enum(["enforce","monitor","off"]),Tn=f.object({apiKey:f.string().min(1,"apiKey is required"),agentId:f.string().min(1,"agentId is required"),endpoint:f.string().url().optional(),mode:En.optional(),timeoutMs:f.number().int().positive().optional(),hitlTimeoutMs:f.number().int().positive().optional(),failBehavior:Cn.optional()}),To=f.object({agent_id:f.string().min(1),target_app:f.string().min(1),action:f.string().min(1),context:f.record(f.unknown()).optional(),session_id:f.string().min(1).max(255).optional(),action_schema_id:f.string().min(1).max(128).optional(),telemetry:f.record(f.unknown()).optional()}),Nn=f.object({field:f.string().optional(),pattern:f.string().optional(),replacement:f.string().optional(),mode:f.enum(["full","partial","email"]).optional(),keepFirst:f.number().optional(),keepLast:f.number().optional(),maskChar:f.string().optional()}),xn=f.object({decision_id:f.string().min(1),decision:f.enum(["permit","deny","approval_required","mask"]),reason:f.string().optional(),rule_code:f.string().nullable().optional(),enforced:f.boolean().optional(),agent_mode:Ce.optional(),arg_redaction_rules:f.array(Nn).optional(),plane:f.string().nullable().optional(),operation:f.string().nullable().optional(),is_retrieval:f.boolean().optional(),metadata:f.record(f.unknown()).optional()}),On=f.object({field:f.string().min(1),operator:f.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:f.union([f.string(),f.number(),f.array(f.string())])}),Rn=f.object({id:f.string().min(1),rule_code:f.string().default(""),name:f.string().min(1),description:f.string().nullable().default(null),effect:f.enum(["allow","deny","hitl","mask"]),resource_type:f.string().min(1),rego_source:f.string().default(""),target_app:f.string().nullable().default(null),action_pattern:f.string().nullable().default(null),conditions:f.array(On).default([]),priority:f.number().int().default(0)}),$n=f.object({version:f.string().min(1),agent_mode:Ce.optional(),rules:f.array(Rn),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()}),Dn=2e3,Pn=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function Mn(e){let t=e.rules.filter(n=>Pn(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 Te=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return N(this.config.sdkVersion,this.config.sdkDialect)}async boundedFetch(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs);try{return await this.originalFetch(e,{...t,signal:n.signal})}finally{clearTimeout(r)}}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 xn.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=$n.parse(a);return Mn(o),o}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.boundedFetch(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.boundedFetch(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.boundedFetch(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.boundedFetch(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.boundedFetch(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.boundedFetch(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 Fn(Dn)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Fn(e){return new Promise(t=>setTimeout(t,e))}function X(){let e={};try{let t=`${A.platform()} ${A.release()}`.trim();t&&(e.os=t)}catch{}try{let t=A.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=A.userInfo();t&&(e.username=t)}catch{}try{let t=Ln();t&&(e.ip=t)}catch{}return e}function Ln(){let e=A.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}var Ae=new Map;function Bn(e){let t=(Ae.get(e)??0)+1;return Ae.set(e,t),t}function Un(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:jn(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:Bn(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}:{}}})}import{z as d}from"zod";import{createHash as zn}from"crypto";import{createHash as Or}from"crypto";var Ne=new Map;function xe(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function ee(e){let t=zn("sha256").update(e).digest("hex"),n=Ne.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
2
- `).map(l=>qn(l)).filter(l=>l.trim().length>0),o=0;for(;o<a.length;){let l=a[o].trim();if(l.startsWith("package ")||l.startsWith("import ")){o++;continue}let c=l.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(c){let m=c[1],h=c[2].trim();r.set(m,O(h)),o++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let m=u[1],h=u[2].trim(),g=u[3].trim(),_=[];if(g&&g!=="}"){let k=g.endsWith("}")?g.slice(0,-1).trim():g;k&&_.push(k),g.endsWith("}")||(o++,o=L(a,o,_))}else g==="}"||(o++,o=L(a,o,_));let y=Oe(_);i.push({variable:m,value:O(h),conditions:y,rawConditions:xe(_)}),o++;continue}let p=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(p){let m=p[1],h=p[2].trim(),g=[];if(h&&h!=="}"){let y=h.endsWith("}")?h.slice(0,-1).trim():h;y&&g.push(y),h.endsWith("}")||(o++,o=L(a,o,g))}else h==="}"||(o++,o=L(a,o,g));let _=Oe(g);i.push({variable:m,value:"true",conditions:_,rawConditions:xe(g)}),o++;continue}o++}let s={defaults:r,rules:i};return Ne.set(t,s),s}function qn(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 L(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 O(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Gn(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Oe(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=Qn(i);a&&t.push(a)}}return t}var te=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,Vn=new RegExp(`^(${te.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),Wn=new RegExp(`^(${te.source})\\s*==\\s*((?:input|data)\\S*)$`),j=/(?:input|data)(?:\.[A-Za-z0-9_]+|\["[^"]+"\]|\['[^']+'\])+/,Hn=new RegExp(`^(${j.source})\\s*(==|!=)\\s*(${j.source})$`),Kn=new RegExp(`^(${j.source})\\s+in\\s+(${j.source})$`),Zn=/^([^\s=!]+)\s*==\s*(.+)$/,Yn=/^([^\s=!]+)\s*!=\s*(.+)$/,$o=new RegExp(`^(?:${te.source})$`);var Jn=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function Qn(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:R,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(Jn);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:Gn(s[1])};let l=n.match(Kn);if(l)return{type:"field_in_set",negated:t,field:l[1].trim(),rightField:l[2].trim()};let c=n.match(Hn);if(c)return{type:"field_equality",negated:c[2]==="!="?!t:t,field:c[1].trim(),rightField:c[3].trim()};let u=n.match(Vn);if(u)return{type:"array_includes",negated:t,field:u[2].trim(),value:Le(u[1])};let p=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(p){let k=rr(p[2]);if(k!==null)return{type:"in_set",negated:t,field:p[1].trim(),values:k}}let m=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(m)return{type:"comparison",negated:t,field:m[1].trim(),operator:m[2],value:parseFloat(m[3])};let h=n.match(Wn);if(h)return{type:"equality",negated:t,field:h[2].trim(),value:O(h[1].trim())};let g=n.match(Zn);if(g)return{type:"equality",negated:t,field:g[1].trim(),value:O(g[2].trim())};let _=n.match(Yn);if(_)return{type:"inequality",negated:t,field:_[1].trim(),value:O(_[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:R,value:e.trim()}}var R="__unrecognized_condition_forces_deny__";var Xn=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Fe(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==R&&Xn.test(r.field)&&t.push(r.field);return t}var er=["input.normalized.","input.normalized["];function tr(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions)for(let i of nr(r))typeof i!="string"||i===R||er.some(a=>i.startsWith(a))&&t.add(i);return[...t].sort()}var Re=/\binput\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/g;function nr(e){let{field:t,rightField:n}=e;if(t!==R){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 Re.lastIndex=0,[...r.matchAll(Re)].map(i=>i[0])}function Le(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 rr(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(Le(s))}return o}var je=["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"],ir=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],ar=["production","staging","development","test"],or=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function sr(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 $e={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 lr(e){let t=sr(e);return t===null?"other":$e[t]??$e[t.replace(/_/g,"")]??"other"}function Be(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=lr(t.targetApp)),n.context=r}return n}var De=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],cr=["read","write","delete","share","export","decide","execute"],Pe=["none","low","medium","high","critical"],ur=["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"],dr={action_class:je,operation:cr,"context/app_category":ir,"context/environment":ar,"context/actor_function":or,"read/classification":ur,"read/data_categories":De,"read/data_sensitivity":Pe,"write/data_categories":De,"write/data_sensitivity":Pe};function Ue(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(dr)){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 Me=64,pr=64,$={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 z(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:qe()}}var fr=new Set(["deny","approval_required","escalate"]);function I(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>Me?r.slice(0,Me):r}function B(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function x(e){return typeof e=="string"&&e.length>0?e:null}function ze(e,t){let n=B(t.data_categories),r=x(t.classification),i=B(t.taint),a=x(t.action_class),o=a&&je.includes(a)?a:null,s=x(t.target_app),l=x(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<pr)c[o]=1;else{let u=Object.keys(c).sort(),p=u[u.length-1];p!==void 0&&o<p&&(delete c[p],c[o]=1)}return{retrieved_data_categories:I(e.retrieved_data_categories,n),retrieved_classifications:I(e.retrieved_classifications,r?[r]:[]),taint:I(e.taint,i),action_classes:I(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&fr.has(l)?1:0),event_count:e.event_count+1,target_apps:I(e.target_apps,s?[s]:[]),identity:mr(e.identity,t)}}function mr(e,t){let n=e??qe(),r=B(t.attested_subjects),i=I(n.attested_subjects,r),a=x(t.subject_id);return{attested_subjects:i,claimed_subjects:I(n.claimed_subjects,B(t.claimed_subjects)),acted_subjects:I(n.acted_subjects,a?[a]:[])}}function qe(){return{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}}var hr=["tier1","tier2","tier3"];function Ge(e){return typeof e=="string"&&hr.includes(e)}var gr=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],_r=["internal","customer_facing","experimental","third_party"],Ve=[...gr,..._r];function yr(e){return typeof e=="string"&&Ve.includes(e)}function We(e){let t=new Set;for(let n of e)yr(n)&&t.add(n);return Ve.filter(n=>t.has(n))}var br={trust_tier:null,categories:[],business_functions:[],business_function:null,blast_radius_tier:null};function He(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))He(i,t.length>0?`${t}.${r}`:r,n)}function Ke(e){let t=new Set;return He(e,"",t),t}var Do=Ke(z()),Po=Ke(br),vr=["action_counts"];for(let e of vr){let t=z()[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 Mo=new RegExp("^\\p{White_Space}*$","u");var Ze="generic",Ye=[{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:Ze,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."}],wr=Ye.map(e=>e.id),Fo=new Map(Ye.map(e=>[e.id,e])),Lo=new Set(wr);function Je(e){return Array.isArray(e)&&e.length>0?[...e]:[Ze]}var Ar=/^[a-z][a-z0-9_]*$/;function Qe(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Ar.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var kr=["narrow","moderate","broad","unbounded","unknown"];function Xe(e){return typeof e=="string"&&kr.includes(e)}function Sr(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(" ").filter(t=>t.length>0)}function Ir(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 Er(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 et(e){let t=Er(Sr(e)),n=new Int32Array(64);for(let i of t){let[a,o]=Ir(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 Cr(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 Tr(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+=Cr((i^a)>>>0)}return n}var Nr=["proposed","approved","revoked"];function xr(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"&&Nr.includes(t.status)}function tt(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(xr(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=Tr(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 nt(e){return e==="open"||e==="closed"?e:null}var Rr=["tool_name","function","name","action"];function U(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)U(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)U(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function $r(e){let t=[];return U(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function Dr(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function Pr(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function Mr(e,t={}){if(t.discriminatorField===null)return null;let n=[];U(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??Rr;for(let i of r){let a=null;for(let[o,s]of n){if(Dr(o)!==i)continue;let l=Pr(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function rt(e,t={}){let n=Or("sha256").update($r(e).join(",")).digest("hex").slice(0,16),r=Mr(e,t);return r!==null?`${n}:${r}`:n}var Fr=["action","retrieval","delegation"];function Lr(e){return typeof e=="string"&&Fr.includes(e)}var jr=new Set(["rules"]);function it(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!jr.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Lr):[];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 at(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=ee(r)}catch{continue}let a=tr(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 W}from"zod";var Br=/[^\u0000-\u007F]/,kt=new RegExp("^\\p{Nd}$","u"),Ur=new RegExp("^\\p{Pd}$","u"),zr=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,qr=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,Gr=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),St="<invisible>",ot=new Map;function Vr(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&&kt.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function Wr(e){if(e<128)return null;let t=ot.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 kt.test(r)?Vr(e):Ur.test(r)||Gr.has(e)?"-":zr.test(r)?" ":qr.test(r)?St:null})();return ot.set(e,n),n}function oe(e){if(typeof e!="string"||e.length===0||!Br.test(e))return[];let t=st(e,"as-separator");if(t===null)return[];let n=st(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function st(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=Wr(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===St){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 Hr(e,t){return{start:e.offsets[t.start],end:e.offsets[t.end]}}function Kr(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 lt(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 It="[REDACTED]",se=[{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}],Uo=se.map(({name:e,re:t})=>({name:e,source:t.source})),Zr="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function Yr(e){return Et(e,Zr)}function Et(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 Ct(e){return new RegExp(Yr(e.source),e.flags)}var Jr="(?:\\b|_)";function re(e){return Et(e,Jr)}var Qr=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function Xr(e){let t=Qr.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function ie(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 ei(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 ti(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 ni=[[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]],ri=[[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 ii(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=ni[t][ri[r%8][n[r].charCodeAt(0)-48]];return t===0}function ai(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 oi(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 si=[1,4,3,7,5,8,6,9,10];function li(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)*si[n];return t%11===0}var ci="TRWAGMYFPDXBNJZSQVHLCKE";function ui(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 ci[Number(o)%23]===a}var di=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function pi(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!di.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&&ie(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:ei},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:ti},{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:pi(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&&ii(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:ai},{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:ui},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&ie(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:oi},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:li}],fi=Object.fromEntries([...se,...le].map(e=>[e.name,e.re.source])),b=fi,zo=le.map(e=>e.name),Tt=se.map(({name:e,re:t})=>({name:e,re:Ct(t)})),Nt=le.map(e=>({...e,re:Ct(e.re)})),qo=[...Tt,...Nt].map(({name:e,re:t})=>({name:String(e),source:t.source})),ce=["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"],mi={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
3
- MIIEv\u2026
4
- -----END PRIVATE KEY-----`,template:{pattern:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.mac_address,mode:"full"},defaultEnabled:!1}},ue=Object.freeze(Object.fromEntries(ce.map(e=>{let t=mi[e];return[e,{...t,template:{...t.template,pattern:Xr(re(t.template.pattern))}}]})));var Go=new Set(ce.filter(e=>!ue[e].defaultEnabled));function hi(e,t){let n=new Set;for(let r of ce)(ue[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function q(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=de(t),a=e;for(let{name:o,re:s}of Tt){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 Nt)n.has(o)||(a=Ei(a,s,l,c,t,o,r));return a}function de(e){return typeof e=="function"?e:()=>e}var ct=e=>"\0".repeat(e.length);function gi(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=oe(e);if(i.length===0)return q(e,t,n,r);let a=new Set,o=m=>{a.add(m)},s=q(e,ct,n,o),l=!0,c=new Array(e.length).fill(!1);for(let m=0;m<e.length;m++)c[m]=s[m]==="\0"&&e[m]!=="\0";for(let m of i){let h=q(m.text,ct,n,o);for(let g=0;g<m.text.length;g++)if(!(h[g]!=="\0"||m.text[g]==="\0"))for(let _=m.offsets[g];_<m.offsets[g+1];_++)c[_]||(c[_]=!0,l=!1)}if(l)return q(e,t,n,r);for(let m of a)r?.(m);let u="",p=0;for(;p<e.length;){if(!c[p]){u+=e[p],p++;continue}let m=p;for(;p<e.length&&c[p];)p++;u+=de(t)(e.slice(m,p))}return u}function P(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var ut=new Map;function _i(e){let t=ut.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),ut.set(e.source,t)),t}var yi=4096,bi=64,dt=null;function vi(e){return dt!==null?dt:yi+e.length*bi}var xt=!1,v={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},Ot={spanBudget:0,depthCap:0};function wi(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:vi(e),exhausted:!1}}function Rt(e,t,n,r,i,a,o){v.spanCalls++;let s=t*o.stride+n.length,l=xt?void 0:o.chosen.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,null;o.budget--,v.spanMisses++;let c=Ai(e,t,n,r,i,a,o);return o.chosen.set(s,c),c}function Ai(e,t,n,r,i,a,o){let s=_i(r),l=[];for(let u=n.length-1;u>=1;u--)if(P(n[u])){let p=n.slice(0,u);s.test(p)&&l.push(p)}let c=P(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(a(i(u),u)&&!Si(e,t,u,r,i,a,o))return u;return null}var pt=new Map;function ki(e){let t=pt.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),pt.set(e.source,t)),t}function Si(e,t,n,r,i,a,o){v.cutCalls++;let s=t*o.stride+n.length,l=xt?void 0:o.cuts.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,!0;o.budget--,v.cutMisses++;let c=Ii(e,t,n,r,i,a,o);return o.cuts.set(s,c),c}function Ii(e,t,n,r,i,a,o){let s=t+n.length,l=ki(r);for(let c=1;c<n.length;c++){if(P(n[c])||!P(n[c-1]))continue;let u=t+c;l.lastIndex=u;let p=l.exec(e);if(p===null||p[0].length===0)continue;let m=Rt(e,u,p[0],r,i,a,o);if(m!==null&&u+m.length>s&&P(e[u+m.length]))return!0}return!1}function Ei(e,t,n,r,i,a,o){let s=de(i);t.lastIndex=0;let l="",c=0,u=wi(e),p=v.spanMisses+v.cutMisses,m;for(;(m=t.exec(e))!==null;){let h=m[0],g=m.index;if(h.length===0){t.lastIndex=g+1;continue}let _;try{_=Rt(e,g,h,t,n,r,u)}catch(y){if(y instanceof RangeError&&/call stack/i.test(y.message))u.exhausted=!0,_=null;else throw y}if(u.exhausted)return v.budgetExhausted++,Ot.spanBudget++,ft(p),l+e.slice(c,g)+s(e.slice(g));if(_!==null)o?.(a),l+=e.slice(c,g)+s(_),c=g+_.length,t.lastIndex=c;else{let y=h.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=y===-1?g+h.length:g+1+y+1}if(t.lastIndex>e.length)break}return ft(p),l+e.slice(c)}function ft(e){let t=v.spanMisses+v.cutMisses-e;t>v.maxMissesInAPass&&(v.maxMissesInAPass=t)}function $t(e,t=It,n,r){return Ti(e,t,hi(n,r))}var Ci=256;function Ti(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=(s,l)=>{if(l>Ci)return Ot.depthCap++,t;if(typeof s=="string")return gi(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&&ie(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,u={};for(let p of Object.keys(c))u[p]=o(c[p],l+1);return u}return s};return{value:o(e,0),detectors:[...r].sort()}}function Dt(e,t=It){return $t(e,t).value}var Ni=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Pt=Object.freeze({\u0430:"a",\u0435:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0456:"i",\u0455:"s",\u043A:"k",\u043C:"m",\u0442:"t",\u043D:"h",\u0432:"b",\u0433:"r",\u03BF:"o",\u03B1:"a",\u03C1:"p",\u03B9:"i",\u03C4:"t",\u03B5:"e",\u03BA:"k",\u03BD:"v",\u03C5:"u",\u03B7:"n",\u0131:"i","\u04CF":"l",\u0578:"n"}),xi=new RegExp(`[${Object.keys(Pt).join("")}]`,"gu"),Oi=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),Mt="\u2801\u2803\u2809\u2819\u2811\u280B\u281B\u2813\u280A\u281A\u2805\u2807\u280D\u281D\u2815\u280F\u281F\u2817\u280E\u281E\u2825\u2827\u283A\u282D\u283D\u2835",Ri=Object.freeze(Object.fromEntries([...Mt].map((e,t)=>[e,String.fromCharCode(97+t)]))),$i=new RegExp(`[${Mt}\u2800]`,"g"),Ft=/[⠀-⣿]/;function Di(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 Pi(e){return e.replace(Ni,"")}function Lt(e){return e.replace(xi,t=>Pt[t]??t)}function Mi(e){return e.replace(/[4@31!05$79(8]/g,t=>Oi[t]??t)}function Fi(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 Li(e){return Ft.test(e)?e.replace($i,t=>t==="\u2800"?" ":Ri[t]??t):e}function mt(e){let t;try{t=Di(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=Pi(t),t=Lt(t),t}var ji=/^[A-Za-z0-9+/]{16,}={0,2}$/,Bi=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,ht=/[A-Za-z0-9+/]{20,}={0,2}/g;function ae(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 jt=new TextDecoder("utf-8",{fatal:!1});function Bt(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=jt.decode(n);return t===r?[t]:[r,t]}function Ui(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=jt.decode(n);return r===i?[r]:[i,r]}function gt(e){let t=e.trim(),n=[];if(Bi.test(t))for(let r of Ui(t))n.push({decoded:r,textiness:ae(r)});if(ji.test(t)&&t.length%4===0)for(let r of Bt(t))n.push({decoded:r,textiness:ae(r)});return n}function _t(e,t){let n=[],r;for(ht.lastIndex=0;(r=ht.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of Bt(i))n.push({decoded:a,textiness:ae(a)})}return n}var zi=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function Ut(e,t=zi){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=h=>{h.length>0&&h.length<=r&&o.add(h)},l=!1,c=!1,u=0,p=0,m=[{s:e,depth:0}];for(;m.length>0;){if(u>=i){c=!0;break}let h=m.pop();if(h===void 0)break;let{s:g,depth:_}=h;if(g.length>r){c=!0;continue}u++,_>p&&(p=_);let y=mt(g);s(y);let k=Mi(y);if(k!==y&&s(k),s(Fi(y)),Ft.test(g)&&s(Li(y)),_>=n){let S=mt(g);(gt(S).length>0||_t(S,a).length>0)&&(c=!0);continue}let mn=[...gt(y),..._t(y,a)];for(let S of mn){if(l=!0,S.decoded.length>r){c=!0;continue}S.textiness>=.85&&S.decoded!==y?m.push({s:S.decoded,depth:_+1}):s(S.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:p}}var zt=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],qi=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),Gi=8,Vi=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),yt=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function Wi(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||Vi.has(i)&&yt(t[r-1])&&yt(t[r+1])&&(n++,n>=Gi))return!0}return!1}var Hi=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function Ki(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(Hi.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Zi=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Yi(e){for(let t of Zi)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=Yi(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:Lt(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var bt=Object.freeze({signals:[],contributes:!1});function Qi(e){if(typeof e!="string"||e.length===0)return{...bt,signals:[]};let t=new Set;try{Wi(e)&&t.add("hidden_text_carrier"),Ki(e)&&t.add("injected_turn_boundary"),Ji(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=Ut(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...bt,signals:[]}}return{signals:[...zt.filter(n=>t.has(n))],contributes:qi.some(n=>t.has(n))}}var V=[{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 vt(e){return typeof e!="string"||e.length===0?[]:V.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function Xi(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(vt(e)),{views:n}=Ut(e);for(let r of n)for(let i of vt(r))t.add(i);return V.filter(r=>t.has(r.name)).map(r=>r.name)}function ea(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of Xi(a))t.add(s);let o=Qi(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:V.filter(a=>t.has(a.name)).map(a=>a.name),structural:zt.filter(a=>n.has(a))}}function ta(e){return ea(e).matched}var Vo=V.map(e=>e.name);var na=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var ra="i:injection";function qt(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=$t(e.content);for(let a of i){let o=ue[a]?.category;o&&t.add(`c:${o}`)}ta(e.content)&&t.add(ra)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&na.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var ne="(?: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))",Wo=[{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${ne}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${ne}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${ne}\\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}],wt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",ia=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${wt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${wt}|programming|training))`,aa="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",At="(?:\\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)",oa="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Ho=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${aa}${ia}\\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}?${At}`,"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+(?:${oa}\\b|[\\s\\S]{0,40}?${At})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Ko=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var E=e=>`[^.!?;\\n]{0,${e}}?`,sa=["\\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("|"),Gt="(?: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)",Zo=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${sa})\\s${E(40)}\\b${Gt}\\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${E(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${E(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${E(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${E(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${E(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")}]),Yo=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${E(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${E(30)}\\b${Gt}\\b|i(?:'d|\\s+would)\\s+be\\s+happy\\s+to\\b|i(?:'m|\\s+am)\\s+able\\s+to\\b)`,"i"),/\bwhat\s+i\s+can\s+do\s+(?:instead|is|for\s+you)\b/i]);var D=e=>`[^.!?;\\n]{0,${e}}?`,Jo=Object.freeze([{id:"vulnerability_scanning",objectPatterns:[/\b(?:vulnerability|vuln|security)\s+(?:scan|scans|scanning|assessment|audit|test|testing)\b/i,/\bpen(?:etration)?[\s-]?test(?:ing)?\b/i,/\bport\s+scan(?:ning)?\b/i,/\b(?:exploit|nmap|metasploit|nessus|burp\s+suite)\b/i,/\bCVE-\d{4}-\d{4,7}\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|vulnerability|incident\s+respon\w{0,4}|threat|soc|red\s+team|phishing|malware)\b/i]},{id:"credential_access",objectPatterns:[/\b(?:credential|password|passphrase|api\s+key|access\s+key|secret|token|private\s+key|ssh\s+key)s?\b/i,/\b(?:vault|secrets?\s+manager|keychain|keystore)\b/i,/\bservice\s+account\s+key\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|identity|iam|credential|secrets?\s+manage\w{0,4}|vault|platform|devops)\b/i]},{id:"financial_transaction",objectPatterns:[/\b(?:wire\s+transfer|bank\s+transfer|payout|disbursement|chargeback)\b/i,new RegExp(`\\b(?:approve|issue|initiate|process|release)\\s${D(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${D(20)}\\b(?:funds|money)\\b`,"i")],purposeFunctions:["finance_accounting","procurement"],purposePatterns:[/\b(?:finance|financial|accounting|invoice|invoicing|payment|payments|billing|refund|refunds|treasury|procurement|spend|purchasing|fraud|kyc)\b/i]},{id:"personnel_data",objectPatterns:[/\b(?:employee|personnel|payroll|hr|staff)\s+(?:record|records|data|file|files|information|details)\b/i,/\b(?:salary|salaries|compensation|performance\s+review|termination\s+letter)s?\b/i,/\b(?:home\s+address|social\s+security\s+number|national\s+insurance\s+number)e?s?\b/i],purposeFunctions:["hr","privacy_compliance"],purposePatterns:[/\b(?:hr|human\s+resources|people\s+ops|payroll|benefits|recruit\w{0,4}|onboarding|privacy|dsar|consent)\b/i]},{id:"regulated_advice",objectPatterns:[/\b(?:legal|medical|tax|investment|financial)\s+advice\b/i,/\bpractis\w{0,3}\s+law\b/i,/\b(?:diagnose|diagnosis|prescribe|prescription)\b/i,/\b(?:binding|enforceable)\s+(?:opinion|interpretation)\b/i],purposeFunctions:["legal","privacy_compliance"],purposePatterns:[/\b(?:legal|compliance|counsel|contract|contracts|litigation|nda|privacy|regulator\w{0,2}|audit\w{0,3})\b/i]},{id:"data_export",objectPatterns:[new RegExp(`\\b(?:export|download|dump|extract|exfiltrat\\w{0,3}|bulk\\s+copy)\\b\\s${D(30)}\\b(?:data|database|dataset|records?|table|tables|customer\\s+list|contact\\s+list|report)\\b`,"i"),/\b(?:full|entire|whole)\s+(?:database|dataset|customer\s+table)\b/i],purposeFunctions:["operations","engineering","privacy_compliance"],purposePatterns:[/\b(?:data\s+(?:pipeline|engineering|platform)|etl|export|reporting|analytics|operations|document\s+extract\w{0,3}|forecast\w{0,3})\b/i]},{id:"code_execution",objectPatterns:[new RegExp(`\\b(?:run|execute|invoke)\\s${D(24)}\\b(?:script|scripts|command|commands|shell|code|binary|query|migration)\\b`,"i"),/\b(?:shell|root|sudo|admin)\s+(?:access|command|session)\b/i,/\bagainst\s+(?:the\s+)?production\s+(?:system|server|database|environment)s?\b/i],purposeFunctions:["engineering","it_security"],purposePatterns:[/\b(?:engineering|developer|devops|platform|release|deploy\w{0,4}|build|pipeline|sandbox|test\s+data|change\s+window)\b/i]},{id:"external_communication",objectPatterns:[new RegExp(`\\b(?:send|post|publish|email|tweet|message|broadcast)\\b\\s${D(30)}\\b(?:external|customer|customers|public|press|social\\s+media|third[\\s-]party|prospect|prospects)\\b`,"i"),/\b(?:cold\s+outreach|marketing\s+blast|phishing\s+email|press\s+release)\b/i],purposeFunctions:["marketing","sales","customer_support"],purposePatterns:[/\b(?:marketing|campaign|outreach|email\s+assistant|support|customer|sales|lead|leads|communication|communications)\b/i]}]);var pe="[REDACTED]",T="\u2022",G=e=>/[\p{L}\p{N}]/u.test(e);function Vt(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:T,c=o+s>=a;return i.map((u,p)=>!c&&(p<o||p>=a-s)?u:G(u)?l:u).join("")}function la(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Vt(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:T;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(o=>G(o)?a:o).join(""))+i}function ca(e,t,n){let r=n.length>0?n:T,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let c=new RegExp(t,"g"),u;for(;(u=c.exec(e))!==null;){if(u[0].length===0){c.lastIndex++;continue}for(let p=u.index;p<u.index+u[0].length;p++)i[p]=!0}}catch{}let a=!1,o=!0;for(let c=0;c<e.length;c++)if(G(e[c])&&(a=!0,!i[c])){o=!1;break}let s=a&&o,l="";for(let c=0;c<e.length;c++){let u=e[c];!s&&i[c]||!G(u)?l+=u:l+=r}return l}function Wt(e,t){let n=t.mode??"full";return n==="partial"?Vt(e,t.keepFirst??0,t.keepLast??0,t.maskChar??T):n==="email"?la(e,t.maskChar??T):n==="custom"?ca(e,t.keepPattern,t.maskChar??T):t.replacement??pe}function ua(e,t){return typeof e=="string"?Wt(e,t):t.replacement??pe}function Ht(e){let t=[],n=e.replacement??pe;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:re(r),replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:re(i),replacer:a=>Wt(a,r)})}return t}function Kt(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 Zt(e,t){if(oe(e).length===0){let n=e;for(let{source:r,replacer:i}of t)n=n.replace(Kt(r),a=>i(a));return n}return da(e,t)}function da(e,t){let n=e;for(let{source:r,replacer:i}of t){let a=Kt(r),o=[...lt(a,n)];for(let u of oe(n))for(let p of lt(a,u.text))o.push(Hr(u,p));let s=Kr(o);if(s.length===0)continue;let l="",c=0;for(let{start:u,end:p}of s)l+=n.slice(c,u)+i(n.slice(u,p)),c=p;n=l+n.slice(c)}return n}function Qo(e,t){return e==null?e:typeof e=="string"?pa(e,t):typeof e=="object"?fa(e,t):e}function pa(e,t){if(typeof e!="string")return e;let n=Ht(t);return n.length===0?e:Zt(e,n)}function fa(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=Ht(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 u of Object.keys(l)){let p=i?n.get(u):void 0;if(p){c[u]=ua(l[u],p);continue}c[u]=o(l[u])}return c}return typeof s=="string"&&a?Zt(s,r):s};return o(e)}import{createHash as oo}from"node:crypto";var Yt=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function ma(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:Yt(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:Yt(t.spawn.prompt)}),t}function ha(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 ga=1440*60*1e3,_a="VISIQ_BUNDLE_GRACE_TTL_MS",ya="VISIQ_BUNDLE_CACHE_DISABLED",ba="VISIQ_CACHE_DIR",va=W.object({graceTtlMs:W.number().int().nonnegative().optional(),disabled:W.boolean().optional(),cacheDir:W.string().min(1).optional()}).strict();function wa(e){return e==null?{}:va.parse(e)}function Aa(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[_a];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return ga}function ka(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[ya]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var Jt;function Sa(){if(Jt!==void 0)return Jt;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Ia(e){return JSON.stringify(me(e))}function me(e){if(Array.isArray(e))return e.map(me);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=me(t[r]);return n}return e}function Ea(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Ca(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 on(){if(!Sa())return null;try{let[e,t,n,r]=await Promise.all([import("node:fs/promises"),import("node:path"),import("node:os"),import("node:crypto")]);return{fs:e,path:t,os:n,crypto:r}}catch{return null}}function sn(e,t){return e.createHash("sha256").update(Ia(t)).digest("hex")}function Ta(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[ba]?.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 Na(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function ln(e,t,n){return e.path.join(Ta(e,n),"bundles",`${Na(e,t)}.json`)}async function xa(e,t,n,r={}){let i=await on();if(i)try{let a=ln(i,e,r),o=i.path.dirname(a);await i.fs.mkdir(o,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:sn(i.crypto,t),body:t},l=`${a}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(l,JSON.stringify(s),{mode:384});try{await i.fs.rename(l,a)}catch(c){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),c}}catch{}}async function Oa(e,t={}){let n=await on();if(!n)return null;try{let r=await n.fs.readFile(ln(n,e,t),"utf-8"),i=Ca(JSON.parse(r));return!i||sn(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var M;async function Ra(){if(M!==void 0)return M;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;M=typeof t=="function"?t:null}catch{M=null}return M}function $a(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=ee(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of Fe(a))t.push(`${o}: ${s}`)}return t}function Da(e){return at(e)}function Pa(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var Ma=5e3,Fa=600*1e3,La=1e4,ja=25,Qt=1e3,Ba=5e3,Ua=100,Xt=2e3,za=10,qa=512,Ga=1800*1e3,Va=.7,Wa="monitor",Ha="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",en="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.",Ka="open";function tn(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Za(e,t){return qt({content:e,resourceMetadata:t})}var Ya=d.object({operations:d.array(d.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:d.string().min(1,"agentId is required"),sessionId:d.string().min(1).max(255).optional(),toolName:d.string().optional(),toolArgs:d.record(d.unknown()).optional(),targetResource:d.string().optional(),resourceType:d.string().optional(),resourceMetadata:d.record(d.unknown()).optional(),normalized:d.record(d.unknown()).optional(),query:d.string().optional(),contentPreview:d.string().optional(),telemetry:d.record(d.unknown()).optional(),context:d.record(d.unknown()).optional(),mcpServer:d.string().min(1).max(255).optional(),identity:d.object({attested:d.array(d.string().min(1).max(255)).max(32).optional(),claimed:d.array(d.string().min(1).max(255)).max(32).optional(),subjectId:d.string().min(1).max(255).optional()}).optional()}),Ja=d.object({version:d.string().min(1),dialect_version:d.number().int().optional(),min_dialect:d.number().int().optional(),shutdown:d.boolean().optional(),agent_mode:d.enum(["enforce","monitor","off"]).optional(),cognition_capture:d.boolean().optional(),agent_mode_by_operation:d.object({action:d.string().optional(),retrieval:d.string().optional(),delegation:d.string().optional()}).partial().optional(),agent_attributes:d.object({trust_tier:d.string().nullable().optional(),categories:d.array(d.string()).optional(),business_function:d.string().nullable().optional(),business_functions:d.array(d.string()).nullable().optional(),blast_radius_tier:d.string().nullable().optional(),no_coverage:d.string().nullable().optional(),fail_mode:d.string().nullable().optional()}).optional(),rules:d.array(d.record(d.unknown())),action_schemas:d.array(d.object({id:d.string(),plane:d.string().optional(),field_mappings:d.array(d.record(d.unknown())).optional(),derived_fields:d.array(d.record(d.unknown())).optional(),action_class:d.string().nullable().optional(),action_class_confidence:d.number().optional()})).optional(),no_coverage:d.object({no_coverage_defaults:d.record(d.string()),autopilot_enabled:d.boolean(),enduser_hitl_enabled:d.boolean(),hitl_timeout_seconds:d.number().optional()}).optional(),skill_blacklist:d.array(d.record(d.unknown())).optional()});function Qa(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=Je(Qe(n));return{trust_tier:Ge(t)?t:null,categories:We(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&Xe(e.blast_radius_tier)?e.blast_radius_tier:null}}function Xa(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 eo(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var he=new Set,nn=!1;async function rn(e){let t=[];for(let n of he){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 to(){if(!nn&&!(typeof process>"u"||typeof process.once!="function")){nn=!0,process.once("beforeExit",()=>{rn(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await rn(!0)}finally{process.kill(process.pid,e)}})()})}}var as=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=Wa;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=tn(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Ka;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,u=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=l,this.resolvedEndpoint=c,this.resolvedAgentId=u,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=o,this.originalFetch=globalThis.fetch.bind(globalThis);let p=wa(s);if(this.bundleCacheDisabled=ka(p.disabled),this.bundleGraceTtlMs=Aa(p.graceTtlMs),this.bundleCacheDirOverride=p.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let m={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:ha(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new Te(m,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Ma),fe(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},La),fe(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Ba),fe(this.cognitionTimer),he.add(this),to()}else this.client=null}async evaluate(e){let t=Ya.parse(e),n=Date.now();if(this.operatorShutdown){let h=this.denyAll(t,Ha);return this.applyAgentMode(h,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,en,n);let h=this.denyAll(t,en);return this.applyAgentMode(h,"enforce",t,n)}if(t.operations.every(h=>this.modeFor(h)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let h;if(this.agentModeConfirmed?h=this.agentMode:this.bundleApplyFailed?h="enforce":h="monitor",h==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let g=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(g,h,t,n)}if(this.modeFor("action")!=="off"){let h=this.matchSkillQuarantine(t);if(h){let g=this.denyAll(t,h);return this.applyAgentMode(g,this.modeFor("action"),t,n)}}let r=this.readSession(t.sessionId),i=await Ra();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")?Be(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}:{}},u;try{u=i(l,c)}catch(h){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${h instanceof Error?h.message:String(h)}`,n);throw h}let p=[...new Set(t.operations.flatMap(h=>this.normalizedRefs[h]??[]))].sort();p.length>0&&Pa(t.normalized)&&(u.normalizedColdStart=p,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${p.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: ${p.slice(0,5).join("; ")}${p.length>5?`; +${p.length-5} more`:""}`)));let m=Ue(t.normalized);return m.length>0&&(u.normalizedDrift=m,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${m.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: ${m.slice(0,5).join("; ")}${m.length>5?`; +${m.length-5} more`:""}`))),this.foldSession(t,u.enforced?u.decision:"permit"),u.enforced&&u.action.decision==="approval_required"&&await this.registerHitl(t,u),this.bufferTelemetry(t,u,Date.now()-n,u.enforced),u}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=tt({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 $;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Ga?(this.sessions.delete(e),$):t.state:$}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>=Va)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=ze(r===$?z():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?Za(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>qa){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=Ja.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=$a(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=>it(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?Qa(t.agent_attributes):null,this.agentNoCoverage=nt(t.agent_attributes?.no_coverage),this.governedFailMode=tn(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=Xa(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=Da(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",...N(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>=Fa&&(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 Oa(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Ea(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 xa(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({...X(),...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({...X(),...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=rt(n),i={...n};return e.toolArgs&&(i.tool_args=Dt(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?eo(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?{[Ee]: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,za)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=ja&&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-Qt;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Qt})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(ma(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Ua&&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-Xt;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Xt})`))}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(),he.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 fe(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function H(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function os(e,t){if(e!=="Task"&&e!=="Agent")return null;let n=H(t.description),r=H(t.subagent_type),i=H(t.prompt),a=n??r??"sub-agent";return{childAgentId:a,childName:a,kind:"subagent",agentType:r,description:n,task:i,goal:i,model:H(t.model),source:"structural"}}function ss(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 no={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"},ro=new Set(["workspace_deactivate_skill"]),io=new Set(["read","read_file","readfile","view","cat"]);function ls(e){return ro.has((e??"").trim())}function ao(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function an(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=no[n];if(i){let a=an(r,["name","skill_name","identifier","skill","path"]);return a?{skill:a,via:n,framework:i}:null}if(io.has(n.toLowerCase())){let a=an(r,["path","file_path","filePath","target","file"]),o=a?ao(a):null;return o?{skill:o,via:n,framework:"unknown"}:null}return null}var so=/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,lo=/^([A-Za-z0-9_.-]+):[ \t]*(.*)$/;function co(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1):t}function uo(e,t){let n=t.startsWith("|");return(n?e.join(`
5
- `):e.join(" ")).replace(/[ \t]+/g,n?"$&":" ").trim()}function po(e){let t=so.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=lo.exec(s);if(!l)continue;let c=l[1],u=(l[2]??"").trim();if(/^[|>][+-]?\d*$/.test(u)){let p=[],m=o+1;for(;m<a.length;m+=1){let h=a[m]??"";if(h.trim()&&!/^[ \t]/.test(h))break;p.push(h.trim())}o=m-1,i[c]=uo(p,u);continue}u&&(i[c]=co(u))}return{attrs:i,body:r}}function fo(e){return oo("sha256").update(e,"utf8").digest("hex")}function mo(e,t,n){let{attrs:r,body:i}=po(e),{description:a}=r;return{name:r.name?.trim()||n,path:t,...a?{description:a}:{},contentHash:fo(i),fingerprint:et(i)}}var ho=500,go=512*1024;async function ps(e){let[t,n]=await Promise.all([import("node:fs/promises"),import("node:path")]),r=[],i=new Set;for(let a of e){let o;try{o=await t.readdir(a,{withFileTypes:!0})}catch{continue}for(let s of o){if(r.length>=ho)return r;if(!s.isDirectory())continue;let l=n.join(a,s.name,"SKILL.md");try{let c=await t.stat(l);if(!c.isFile()||c.size>go)continue;let u=await t.readFile(l,"utf8"),p=mo(u,`${s.name}/SKILL.md`,s.name),m=`${p.name}@${p.contentHash}`;if(i.has(m))continue;i.add(m),r.push(p)}catch{continue}}}return r}function fs(e){let t=[],n=[],r,i=[];for(let o of e){if(o.mode==="partial"||o.mode==="email"||o.mode==="custom"){let l={mode:o.mode};o.field&&(l.field=o.field),o.pattern&&(l.pattern=o.pattern),typeof o.keepFirst=="number"&&(l.keepFirst=o.keepFirst),typeof o.keepLast=="number"&&(l.keepLast=o.keepLast),o.maskChar&&(l.maskChar=o.maskChar),o.keepPattern&&(l.keepPattern=o.keepPattern),o.replacement!==void 0&&(l.replacement=o.replacement),i.push(l);continue}o.field&&t.push(o.field),o.pattern&&n.push(o.pattern);let{replacement:s}=o;s&&r===void 0&&(r=s)}let a={};return t.length>0&&(a.fields=t),n.length>0&&(a.patterns=n),r!==void 0&&(a.replacement=r),i.length>0&&(a.directives=i),a}var cn="0.1.17";var ks=3e4,bo=4e3;function vo(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,200)||"default"}function Y(e){let t=yo("sha1").update(e).digest("hex").slice(0,10);return`${vo(e)}-${t}`}function Ss(e,t,n){return n-e.fetchedAt<t}function un(e){return C(w(),"bundles",`${Y(e)}.json`)}function dn(e){return C(w(),"sessions",`${Y(e)}.registered`)}function pn(e){return C(w(),"sessions",`${Y(e)}.skill`)}function fn(e){return C(w(),"sessions",`${Y(e)}.skillfp.json`)}var wo=/^[0-9a-f]{16}$/;async function Is(e,t){try{await K(C(w(),"sessions"),{recursive:!0}),await Z(fn(e),JSON.stringify(t),{mode:384})}catch{}}async function Es(e){try{let t=await ge(fn(e),"utf8"),n=JSON.parse(t);if(n===null||typeof n!="object")return{};let r={};for(let[i,a]of Object.entries(n))typeof a=="string"&&wo.test(a)&&(r[i]=a);return r}catch{return{}}}async function Cs(e){try{let n=(await ge(pn(e),"utf8")).trim();return n.length>0?n:null}catch{return null}}async function Ts(e,t){try{await K(C(w(),"sessions"),{recursive:!0}),await Z(pn(e),t??"",{mode:384})}catch{}}async function Ns(e){try{let t=await ge(un(e),"utf-8"),n=JSON.parse(t);return n&&typeof n.fetchedAt=="number"&&"body"in n?n:null}catch{return null}}async function xs(e,t,n){try{let r=un(e);await K(C(w(),"bundles"),{recursive:!0});let i={fetchedAt:Date.now(),version:n,body:t};await Z(r,JSON.stringify(i),{mode:384})}catch{}}async function Os(e,t,n){try{let i=`${e.replace(/\/+$/,"")}/rules/bundle?agent_id=${encodeURIComponent(n)}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...N(cn,Q)},signal:AbortSignal.timeout(bo)});if(!a.ok)return null;let o=a.headers.get("etag");return{body:await a.json(),version:o}}catch{return null}}async function Rs(e){try{return await _o(dn(e)),!0}catch{return!1}}async function $s(e){try{await K(C(w(),"sessions"),{recursive:!0}),await Z(dn(e),String(Date.now()),{mode:384})}catch{}}export{ve as a,we as b,w as c,vn as d,kn as e,Sn as f,In as g,Io as h,Qo as i,Q as j,Un as k,as as l,os as m,ss as n,ls as o,ao as p,cs as q,ps as r,fs as s,cn as t,ks as u,vo as v,Ss as w,Is as x,Es as y,Cs as z,Ts as A,Ns as B,xs as C,Os as D,Rs as E,$s as F};