@visiq/claude-cowork-harness 0.1.7 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/chunk-4XVXECFH.js +10 -0
- package/dist/cli/main.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3OLBRX7B.js +0 -6
package/README.md
CHANGED
|
@@ -119,7 +119,7 @@ visiq-claude-cowork status
|
|
|
119
119
|
```
|
|
120
120
|
|
|
121
121
|
```
|
|
122
|
-
[VisIQ] Claude Cowork harness 0.1.
|
|
122
|
+
[VisIQ] Claude Cowork harness 0.1.10 — status
|
|
123
123
|
this process: unknown (cannot enforce)
|
|
124
124
|
credentials: resolved
|
|
125
125
|
agent id: agent_01HQ7ZK3M4N5P6R7S8T9V0W1X2
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
var Xn="CLAUDE_CONFIG_DIR";function Le(e){let t=e?.[Xn];if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}var Ks=["claude_code_cli","cowork_desktop","cowork_vm","unknown"],er="CLAUDE_CODE_HOST_PLATFORM",tr=[/[/\\]claude[^/\\]*[/\\]claude-code[/\\]/i,/[/\\]claude\.app[/\\]/i],nr=/^\/sessions\/[^/]+\/mnt\/\.claude(\/|$)/;function rr(e){if(e.configDir&&nr.test(e.configDir))return!0;let t=e.env?.[er];return typeof t=="string"&&t.length>0}function ir(e){return(e.processPaths??[]).some(t=>tr.some(n=>n.test(t)))}function ar(e){return(e.processPaths??[]).some(t=>/(^|[/\\])claude(\.exe)?$/.test(t))}function Ys(e){return rr(e)?"cowork_vm":ir(e)?"cowork_desktop":ar(e)?"claude_code_cli":"unknown"}function Zs(e){return e==="claude_code_cli"||e==="cowork_desktop"}function Js(e){return e==="cowork_desktop"||e==="cowork_vm"}function or(e){throw new Error(`unhandled ClaudeSurface: ${JSON.stringify(e)} \u2014 add a branch to every consumer`)}function Qs(e){switch(e){case"claude_code_cli":return"Claude Code CLI";case"cowork_desktop":return"Claude Cowork (host-local)";case"cowork_vm":return"Claude Cowork (VM sandbox)";case"unknown":return"unknown";default:return or(e)}}function Xs(e=process,t=[]){let n=[...t];e.argv?.[1]&&n.push(e.argv[1]),e.execPath&&n.push(e.execPath);let r=e.env??{},i=Le(r);return{processPaths:n,env:r,platform:e.platform,...i===void 0?{}:{configDir:i}}}var je="local-agent-mode-sessions",tl="claude-code-sessions";function sr(e){let{homeDir:t,platform:n,env:r={}}=e;if(n==="darwin")return`${t}/Library/Application Support/Claude`;if(n==="win32"){let a=r.APPDATA;return a?`${a}\\Claude`:`${t}\\AppData\\Roaming\\Claude`}let i=r.XDG_CONFIG_HOME;return i?`${i}/Claude`:`${t}/.config/Claude`}function lr(e,t,...n){let r=e==="win32"?"\\":"/";return[t,...n].join(r)}function nl(e){return lr(e.platform,sr(e),je)}function Be(e){let t=e.split(/[/\\]+/).filter(o=>o.length>0),n=t.lastIndexOf(je);if(n===-1||t.length<n+4)return null;let[r,i,a]=t.slice(n+1,n+4);return cr(a)?{accountId:r,orgId:i,sessionKey:a}:null}function cr(e){return/^local_[0-9a-fA-F-]{8,}$/.test(e)}function ur(e){return/^audit\d*\.jsonl$/.test(e)}function dr(e){let t=/^audit(\d*)\.jsonl$/.exec(e);return t?t[1]?Number.parseInt(t[1],10):0:null}function Ue(e){return e.filter(ur).map(t=>({name:t,idx:dr(t)??0})).sort((t,n)=>n.idx-t.idx).map(t=>t.name)}var ze="permission_request",pr="permission_response",fr="<unattributed>",il=8388608;function Ge(e){let t=[],n=0,r=0,i=e.lastIndexOf(`
|
|
2
|
+
`),a,o;i===-1?(a="",o=e):(a=e.slice(0,i),o=e.slice(i+1)),Buffer.byteLength(o,"utf8")>8388608&&(o="",r+=1);for(let s of a.split(`
|
|
3
|
+
`)){let c=s.trim();if(c.length!==0)try{t.push(JSON.parse(c))}catch{n+=1}}return{records:t,remainder:o,skipped:n,truncatedLines:r}}function w(e){return typeof e=="string"&&e.length>0?e:void 0}function se(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function mr(e){let t=se(e);if(!t)return[];let n=w(t.type),r=w(t.session_id)??"",i=w(t.uuid)??"",a=w(t._audit_timestamp);if(n==="result")return[{kind:"session_result",uuid:i,sessionId:r,timestamp:a}];if(n==="system"){let f=w(t.subtype);if(f!==ze&&f!==pr)return[];let p=w(t.tool_name),d=p??fr,g=p===void 0?{unattributed:!0}:{};return f===ze?[{kind:"permission_request",uuid:i,sessionId:r,toolName:d,toolInput:t.tool_input,timestamp:a,...g}]:[{kind:"permission_decision",uuid:i,sessionId:r,toolName:d,granted:typeof t.granted=="boolean"?t.granted:void 0,decision:w(t.decision),timestamp:a,...g}]}if(n!=="assistant"&&n!=="user")return[];let o=se(t.message),s=o?.content;if(!Array.isArray(s))return[];let c=w(o?.model),l=w(t.parent_tool_use_id),u=[];for(let f of s){let p=se(f);if(!p)continue;let d=w(p.type);if(n==="assistant"&&d==="tool_use"){let g=w(p.name),_=w(p.id);if(!g||!_)continue;u.push({kind:"tool_call",uuid:i,sessionId:r,toolUseId:_,toolName:g,toolInput:p.input,model:c,parentToolUseId:l,timestamp:a})}else if(n==="user"&&d==="tool_result"){let g=w(p.tool_use_id);if(!g)continue;u.push({kind:"tool_result",uuid:i,sessionId:r,toolUseId:g,isError:p.is_error===!0,timestamp:a})}}return u}function Ve(e){return e.flatMap(t=>mr(t))}function hr(e){return e===!0?"granted":e===!1?"refused":"unconfirmed"}function gr(e){let t=new Map;for(let n of e)n.kind==="permission_decision"&&n.uuid.length>0&&t.set(n.uuid,n.granted);return t}function He(e){let t=gr(e),n=[],r=new Map;for(let i of e){if(i.kind==="tool_call"){n.push({event:i,bound:!1});continue}if(!(i.kind!=="permission_request"||i.uuid.length===0))for(let a=0;a<n.length;a+=1){let o=n[a];if(!(!o||o.bound||!yr(i,o.event))){o.bound=!0,r.set(x(o.event),hr(t.get(i.uuid)));break}}}return r}function x(e){switch(e.kind){case"session_result":return`result:${e.sessionId}:${e.uuid}`;case"permission_request":case"permission_decision":{if(e.uuid.length>0)return`${e.kind}:${e.sessionId}:${e.uuid}`;let t=e.kind==="permission_decision"?`${String(e.granted)}:${e.decision??""}`:le(e.toolInput);return`${e.kind}:${e.sessionId}::${e.toolName}:${t}:${e.timestamp??""}`}default:return`${e.kind}:${e.sessionId}:${e.uuid}:${e.toolUseId}`}}var _r=["\0undefined","\0unserializable"];function qe(e){return!_r.includes(e)}function le(e){try{return JSON.stringify(e)??"\0undefined"}catch{return"\0unserializable"}}function yr(e,t){if(e.unattributed)return!1;let n=le(e.toolInput),r=le(t.toolInput);return!qe(n)||!qe(r)?!1:e.sessionId===t.sessionId&&e.toolName===t.toolName&&n===r}var We=5e3;function H(){return{cursors:{},seen:[]}}function Ke(e,t,n,r){let i=e.cursors[t];if(!i)return{offset:0,remainder:"",restarted:!1};let a=r!==void 0&&i.identity!==void 0&&i.identity!==r;return n<i.offset||a?{offset:0,remainder:"",restarted:!0}:{offset:i.offset,remainder:i.remainder,restarted:!1}}function Ye(e,t,n){let r=Ge(n.carriedRemainder+n.chunk),i=Ve(r.records),a=new Set(e.seen),o=[],s=0;for(let p of i){let d=x(p);if(a.has(d)){s+=1;continue}a.add(d),o.push(p)}let c=[...e.seen,...o.map(x)],l=e.cursors[t]?.identity,u=n.identity??l;return{state:{cursors:{...e.cursors,[t]:{offset:n.startOffset+n.bytesRead,remainder:r.remainder,...u===void 0?{}:{identity:u}}},seen:Ze(c)},events:o,duplicates:s,skipped:r.skipped,truncatedLines:r.truncatedLines}}function Ze(e){return e.length<=We?[...e]:e.slice(e.length-We)}function Je(e){if(!e||typeof e!="object"||Array.isArray(e))return H();let t=e,n={},r=t.cursors;if(r&&typeof r=="object"&&!Array.isArray(r))for(let[a,o]of Object.entries(r)){if(!o||typeof o!="object")continue;let s=o,c=typeof s.offset=="number"&&s.offset>=0?s.offset:0,l=typeof s.remainder=="string"?s.remainder:"",u=typeof s.identity=="string"?s.identity:void 0;n[a]={offset:c,remainder:l,...u?{identity:u}:{}}}let i=Array.isArray(t.seen)?t.seen.filter(a=>typeof a=="string"):[];return{cursors:n,seen:Ze(i)}}var Qe="visiq-claude-code-hook";var Xe="WebFetch|WebSearch|Read|Grep|Glob|LSP|NotebookRead|ListMcpResourcesTool|ReadMcpResourceTool|mcp__.*",br=[{event:"SessionStart",matcher:""},{event:"PreToolUse",matcher:"*"},{event:"PostToolUse",matcher:Xe}];function W(e,t){return!!e.hooks?.some(n=>typeof n.command=="string"&&(n.command.includes("visiq-claude-code")||t!==void 0&&n.command===t))}function vr(e,t){return{matcher:e,hooks:[{type:"command",command:t,timeout:30}]}}function wr(e,t=Qe){let n={...e},r={...n.hooks??{}};for(let{event:i,matcher:a}of br){let o=(Array.isArray(r[i])?r[i]:[]).filter(s=>!W(s,t));r[i]=[...o,vr(a,t)]}return n.hooks=r,n}function kr(e,t){let n={...e};if(!n.hooks)return n;let r={};for(let[i,a]of Object.entries(n.hooks)){let o=(Array.isArray(a)?a:[]).filter(s=>!W(s,t));o.length>0&&(r[i]=o)}return n.hooks=r,n}function Ar(e){let{hooks:t}=e;return t?Object.values(t).some(n=>(Array.isArray(n)?n:[]).some(r=>W(r))):!1}import{readFile as ms}from"node:fs/promises";import{homedir as jn}from"node:os";import{join as Ce,isAbsolute as hs,resolve as gs}from"node:path";import{mkdir as ks,readFile as As,writeFile as Is,stat as dc}from"node:fs/promises";import{createHash as Ss}from"node:crypto";import{join as qn}from"node:path";import{z as h}from"zod";import*as A from"node:os";import{randomUUID as pl}from"node:crypto";var N=1,et="X-VisIQ-SDK",tt="X-VisIQ-Dialect",nt="unknown";function O(e,t=1){return{[et]:e&&e.length>0?e:nt,[tt]:String(t)}}var rt="interceptor_source",Ir=h.enum(["enforce","audit","off"]),Sr=h.enum(["closed","open"]),it=h.enum(["enforce","monitor","off"]),Er=h.object({apiKey:h.string().min(1,"apiKey is required"),agentId:h.string().min(1,"agentId is required"),endpoint:h.string().url().optional(),mode:Ir.optional(),timeoutMs:h.number().int().positive().optional(),hitlTimeoutMs:h.number().int().positive().optional(),failBehavior:Sr.optional()}),ul=h.object({agent_id:h.string().min(1),target_app:h.string().min(1),action:h.string().min(1),context:h.record(h.unknown()).optional(),session_id:h.string().min(1).max(255).optional(),action_schema_id:h.string().min(1).max(128).optional(),telemetry:h.record(h.unknown()).optional()}),Cr=h.object({field:h.string().optional(),pattern:h.string().optional(),replacement:h.string().optional(),mode:h.enum(["full","partial","email"]).optional(),keepFirst:h.number().optional(),keepLast:h.number().optional(),maskChar:h.string().optional()}),Tr=h.object({decision_id:h.string().min(1),decision:h.enum(["permit","deny","approval_required","mask"]),reason:h.string().optional(),rule_code:h.string().nullable().optional(),enforced:h.boolean().optional(),agent_mode:it.optional(),arg_redaction_rules:h.array(Cr).optional(),plane:h.string().nullable().optional(),operation:h.string().nullable().optional(),is_retrieval:h.boolean().optional(),metadata:h.record(h.unknown()).optional()}),xr=h.object({field:h.string().min(1),operator:h.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:h.union([h.string(),h.number(),h.array(h.string())])}),Nr=h.object({id:h.string().min(1),rule_code:h.string().default(""),name:h.string().min(1),description:h.string().nullable().default(null),effect:h.enum(["allow","deny","hitl","mask"]),resource_type:h.string().min(1),rego_source:h.string().default(""),target_app:h.string().nullable().default(null),action_pattern:h.string().nullable().default(null),conditions:h.array(xr).default([]),priority:h.number().int().default(0)}),Or=h.object({version:h.string().min(1),agent_mode:it.optional(),rules:h.array(Nr),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()}),Rr=2e3,$r=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function Dr(e){let t=e.rules.filter(n=>$r(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 at=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return O(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 Tr.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=Or.parse(a);return Dr(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 Pr(Rr)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Pr(e){return new Promise(t=>setTimeout(t,e))}function ce(){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=Fr();t&&(e.ip=t)}catch{}return e}function Fr(){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}import{z as m}from"zod";import{createHash as Mr}from"crypto";import{createHash as Mi}from"crypto";var ot=new Map;function st(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function pe(e){let t=Mr("sha256").update(e).digest("hex"),n=ot.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
|
|
4
|
+
`).map(c=>Lr(c)).filter(c=>c.trim().length>0),o=0;for(;o<a.length;){let c=a[o].trim();if(c.startsWith("package ")||c.startsWith("import ")){o++;continue}let l=c.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(l){let p=l[1],d=l[2].trim();r.set(p,D(d)),o++;continue}let u=c.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let p=u[1],d=u[2].trim(),g=u[3].trim(),_=[];if(g&&g!=="}"){let v=g.endsWith("}")?g.slice(0,-1).trim():g;v&&_.push(v),g.endsWith("}")||(o++,o=K(a,o,_))}else g==="}"||(o++,o=K(a,o,_));let y=lt(_);i.push({variable:p,value:D(d),conditions:y,rawConditions:st(_)}),o++;continue}let f=c.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(f){let p=f[1],d=f[2].trim(),g=[];if(d&&d!=="}"){let y=d.endsWith("}")?d.slice(0,-1).trim():d;y&&g.push(y),d.endsWith("}")||(o++,o=K(a,o,g))}else d==="}"||(o++,o=K(a,o,g));let _=lt(g);i.push({variable:p,value:"true",conditions:_,rawConditions:st(g)}),o++;continue}o++}let s={defaults:r,rules:i};return ot.set(t,s),s}function Lr(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 K(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 D(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function jr(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function lt(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=Wr(i);a&&t.push(a)}}return t}var fe=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,Br=new RegExp(`^(${fe.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),Ur=new RegExp(`^(${fe.source})\\s*==\\s*((?:input|data)\\S*)$`),Y=/(?:input|data)(?:\.[A-Za-z0-9_]+|\["[^"]+"\]|\['[^']+'\])+/,zr=new RegExp(`^(${Y.source})\\s*(==|!=)\\s*(${Y.source})$`),qr=new RegExp(`^(${Y.source})\\s+in\\s+(${Y.source})$`),Gr=/^([^\s=!]+)\s*==\s*(.+)$/,Vr=/^([^\s=!]+)\s*!=\s*(.+)$/,gl=new RegExp(`^(?:${fe.source})$`);var Hr=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function Wr(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:P,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:jr(s[1])};let c=n.match(qr);if(c)return{type:"field_in_set",negated:t,field:c[1].trim(),rightField:c[2].trim()};let l=n.match(zr);if(l)return{type:"field_equality",negated:l[2]==="!="?!t:t,field:l[1].trim(),rightField:l[3].trim()};let u=n.match(Br);if(u)return{type:"array_includes",negated:t,field:u[2].trim(),value:ht(u[1])};let f=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(f){let v=Qr(f[2]);if(v!==null)return{type:"in_set",negated:t,field:f[1].trim(),values:v}}let p=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(p)return{type:"comparison",negated:t,field:p[1].trim(),operator:p[2],value:parseFloat(p[3])};let d=n.match(Ur);if(d)return{type:"equality",negated:t,field:d[2].trim(),value:D(d[1].trim())};let g=n.match(Gr);if(g)return{type:"equality",negated:t,field:g[1].trim(),value:D(g[2].trim())};let _=n.match(Vr);if(_)return{type:"inequality",negated:t,field:_[1].trim(),value:D(_[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:P,value:e.trim()}}var P="__unrecognized_condition_forces_deny__";var Kr=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function mt(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==P&&Kr.test(r.field)&&t.push(r.field);return t}var Yr=["input.normalized.","input.normalized["];function Zr(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions)for(let i of Jr(r))typeof i!="string"||i===P||Yr.some(a=>i.startsWith(a))&&t.add(i);return[...t].sort()}var ct=/\binput\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/g;function Jr(e){let{field:t,rightField:n}=e;if(t!==P){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 ct.lastIndex=0,[...r.matchAll(ct)].map(i=>i[0])}function ht(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 Qr(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 c=t[s];i?(r+=c,c===a&&t[s-1]!=="\\"&&(i=!1)):c==='"'||c==="'"?(r+=c,i=!0,a=c):c===","?(n.push(r.trim()),r=""):r+=c}if(i)return null;r.trim().length>0&&n.push(r.trim());let o=[];for(let s of n){let c=s.startsWith('"')&&s.endsWith('"')&&s.length>=2||s.startsWith("'")&&s.endsWith("'")&&s.length>=2,l=/^-?\d+(?:\.\d+)?$/.test(s);if(!c&&!l&&!(s==="true"||s==="false"))return null;o.push(ht(s))}return o}var Xr=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 _l=new Map(Xr.map(e=>[e.seedId,e]));var gt=["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"],ei=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],ti=["production","staging","development","test"],ni=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function ri(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return t.length>0?t:null}var ut={github:"version_control",gitlab:"version_control",bitbucket:"version_control",stripe:"payments",adyen:"payments",braintree:"payments",paypal:"payments",square:"payments",salesforce:"crm",hubspot:"crm",pipedrive:"crm",slack:"communication",teams:"communication",twilio:"communication",sendgrid:"communication",mailgun:"communication",gmail:"communication",outlook:"communication",zoom:"communication",aws:"cloud_infra",gcp:"cloud_infra",azure:"cloud_infra",okta:"identity",auth0:"identity",entra:"identity",onelogin:"identity",duo:"identity",snowflake:"data_warehouse",bigquery:"data_warehouse",databricks:"data_warehouse",redshift:"data_warehouse",jira:"ticketing",zendesk:"ticketing",servicenow:"ticketing",freshdesk:"ticketing",linear:"ticketing",workday:"hr",bamboohr:"hr",gusto:"hr",netsuite:"finance_erp",quickbooks:"finance_erp",sap:"finance_erp",xero:"finance_erp",s3:"storage",gcs:"storage",dropbox:"storage",box:"storage",postgres:"database",postgresql:"database",mysql:"database",mongodb:"database",redis:"database"};function ii(e){let t=ri(e);return t===null?"other":ut[t]??ut[t.replace(/_/g,"")]??"other"}function _t(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=ii(t.targetApp)),n.context=r}return n}var F=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],ai=["read","write","delete","share","export","decide","execute"],dt=["none","low","medium","high","critical"],ue=["public","internal","confidential","restricted"],oi=[...ue,"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"],si={action_class:gt,operation:ai,"context/app_category":ei,"context/environment":ti,"context/actor_function":ni,"read/classification":oi,"read/data_categories":F,"read/data_sensitivity":dt,"read/sensitivity":ue,"write/data_categories":F,"write/data_sensitivity":dt,"write/sensitivity":ue};function yt(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 c of s)typeof c!="string"||c.length===0||o.includes(c)||n.add(`${i}=${c}`)};for(let[i,a]of Object.entries(si)){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 c=i.slice(o+1),l=s;Object.prototype.hasOwnProperty.call(l,c)&&r(i,l[c],a)}}return[...n].sort()}var Q=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"]}]),li=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"}),yl=new Map(Q.map(e=>[e.slug,e])),bl=new Map(Q.flatMap(e=>e.detectors.map(t=>[t,e]))),ci=Q.flatMap(e=>e.detectors);function M(e){for(let t of hi(e))if(F.includes(t))return t;return null}function ui(){let e={};for(let t of ci){let n=M(t);n!==null&&(e[t]=n)}return e}function di(){let e={secret:new Set,financial:new Set,pii:new Set,identifier:new Set};for(let[n,r]of Object.entries(li)){let i=M(n);i!==null&&e[r].add(i)}let t=n=>F.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 pi=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"],R=["sensitive_organizational"],fi=["sensitive_personal","sensitive_organizational"],me=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:fi},{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:R},{slug:"secrets",label:"Secrets",description:"Live keys and tokens: anyone holding one can act as the system it unlocks.",topics:R},{slug:"credentials",label:"Credentials",description:"Anything that grants access, and talk about it: keys, tokens, passwords, security incidents.",topics:R},{slug:"mnpi",label:"MNPI",description:"Material non-public information, including pay and compensation.",topics:R},{slug:"legal",label:"Legal / Privileged",description:"Attorney-client communications and material under legal hold.",topics:R}]),mi=Object.freeze(me.map(e=>e.slug)),vl=Object.freeze(Object.fromEntries(mi.map(e=>[e,Object.freeze({field:"data_categories",tokens:Object.freeze([e])})])));var wl=Object.freeze({mnpi:["mnpi","material_nonpublic","pre_release_earnings"],legal:["attorney_client","legal_hold","privileged"]}),I=["secrets","credentials"],de=Object.freeze({private_key:I,aws_access_key:I,github_token:I,slack_token:I,stripe_secret:I,google_api_key:I,llm_api_key:I,connection_string:I,jwt:I,bearer_token:I,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"]}),kl=Object.freeze({phone:"us_phone",card:"pan"}),Al=new Map(me.map(e=>[e.slug,e]));function hi(e){return Object.prototype.hasOwnProperty.call(de,e)?de[e]??[]:[]}var Il=Object.freeze(Object.fromEntries(Q.flatMap(e=>e.detectors.flatMap(t=>{let n=M(t);return n!==null&&n!==e.generic?[[t,n]]:[]})))),Sl=Object.freeze(Object.fromEntries(["phi","compensation","legal_privileged","credentials","security_incident","person_name"].map(e=>[e,M(e)])));var bt=["compensation","credentials","legal_privileged","phi","security_incident"];var gi=new Set(bt),_i=Object.freeze(Object.keys(de).filter(e=>!gi.has(e))),yi=Object.freeze([...new Set([...F,...me.map(e=>e.slug)])]),bi=Object.freeze(pi.map(e=>e.slug)),El=Object.freeze({data_categories:yi,detectors:_i,topics:bt,data_topics:bi}),pt="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",Cl=new RegExp(`^(?=.{1,253}$)${pt}(?:\\.${pt})+$`,"i");var vi='"secret" in input.categories',Tl=`
|
|
5
|
+
decision = "deny" if {
|
|
6
|
+
${vi}
|
|
7
|
+
}
|
|
8
|
+
`;var ft=64,wi=64,L={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 X(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:wt()}}var ki=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>ft?r.slice(0,ft):r}function Z(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function $(e){return typeof e=="string"&&e.length>0?e:null}function vt(e,t){let n=Z(t.data_categories),r=$(t.classification),i=Z(t.taint),a=$(t.action_class),o=a&>.includes(a)?a:null,s=$(t.target_app),c=$(t.decision),l={...e.action_counts};if(o)if(o in l)l[o]=(l[o]??0)+1;else if(Object.keys(l).length<wi)l[o]=1;else{let u=Object.keys(l).sort(),f=u[u.length-1];f!==void 0&&o<f&&(delete l[f],l[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:l,denied_count:e.denied_count+(c==="deny"?1:0),inhibited_count:e.inhibited_count+(c&&ki.has(c)?1:0),event_count:e.event_count+1,target_apps:C(e.target_apps,s?[s]:[]),identity:Ai(e.identity,t)}}function Ai(e,t){let n=e??wt(),r=Z(t.attested_subjects),i=C(n.attested_subjects,r),a=$(t.subject_id);return{attested_subjects:i,claimed_subjects:C(n.claimed_subjects,Z(t.claimed_subjects)),acted_subjects:C(n.acted_subjects,a?[a]:[])}}function wt(){return{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}}var Ii=["tier1","tier2","tier3"];function kt(e){return typeof e=="string"&&Ii.includes(e)}var Si=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Ei=["internal","customer_facing","experimental","third_party"],At=[...Si,...Ei];function Ci(e){return typeof e=="string"&&At.includes(e)}function It(e){let t=new Set;for(let n of e)Ci(n)&&t.add(n);return At.filter(n=>t.has(n))}var Ti={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 Et(e){let t=new Set;return St(e,"",t),t}var xl=Et(X()),Nl=Et(Ti),xi=["action_counts"];for(let e of xi){let t=X()[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 Ol=new RegExp("^\\p{White_Space}*$","u");var Ct="generic",Tt=[{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."}],Ni=Tt.map(e=>e.id),Rl=new Map(Tt.map(e=>[e.id,e])),$l=new Set(Ni);function xt(e){return Array.isArray(e)&&e.length>0?[...e]:[Ct]}var Oi=/^[a-z][a-z0-9_]*$/;function Nt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Oi.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Ri=["narrow","moderate","broad","unbounded","unknown"];function Ot(e){return typeof e=="string"&&Ri.includes(e)}function $i(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 Di(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+=$i((i^a)>>>0)}return n}var Pi=["proposed","approved","revoked"];function Fi(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"&&Pi.includes(t.status)}function Rt(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(Fi(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=Di(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 $t(e){return e==="open"||e==="closed"?e:null}var Li=["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 ji=["tool_name","function","name","action"];function J(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)J(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)J(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Bi(e){let t=[];return J(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function Ui(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function zi(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function qi(e,t={}){if(t.discriminatorField===null)return null;let n=[];J(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??ji;for(let i of r){let a=null;for(let[o,s]of n){if(Ui(o)!==i)continue;let c=zi(s);c!==null&&(a===null||o<a.path)&&(a={path:o,value:c})}if(a)return a.value}return null}function Dt(e,t={}){let n=Mi("sha256").update(Bi(e).join(",")).digest("hex").slice(0,16),r=qi(e,t);return r!==null?`${n}:${r}`:n}var Gi={phone:"us_phone",card:"pan"},Vi=(()=>{let e=ui(),t={};for(let n of Li){let r=Gi[n]??n,i=e[r]??M(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)})(),Pl=di();function Pt(e){return Vi[e]}var Hi=["action","retrieval","delegation"];function Wi(e){return typeof e=="string"&&Hi.includes(e)}var Ki=new Set(["rules"]);function Ft(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Ki.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Wi):[];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 Mt(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=pe(r)}catch{continue}let a=Zr(i);if(a.length!==0)for(let o of n.appliesTo){let s=t[o];if(s)for(let c of a)s.add(`${n.id}: ${c}`)}}return{retrieval:[...t.retrieval].sort(),action:[...t.action].sort(),delegation:[...t.delegation].sort()}}import{z as ne}from"zod";var Yi=/[^\u0000-\u007F]/,Xt=new RegExp("^\\p{Nd}$","u"),Zi=new RegExp("^\\p{Pd}$","u"),Ji=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,Qi=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,Xi=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),en="<invisible>",Lt=new Map;function ea(e){let t=String.fromCodePoint(e).normalize("NFKC");if(t.length===1&&t>="0"&&t<="9")return t;let n=e;for(let i=0;i<256&&n>0&&Xt.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function ta(e){if(e<128)return null;let t=Lt.get(e);if(t!==void 0)return t;let n=(()=>{if(e>=65281&&e<=65374)return String.fromCharCode(e-65248);let r=String.fromCodePoint(e);return Xt.test(r)?ea(e):Zi.test(r)||Xi.has(e)?"-":Ji.test(r)?" ":Qi.test(r)?en:null})();return Lt.set(e,n),n}function na(e){if(typeof e!="string"||e.length===0||!Yi.test(e))return[];let t=jt(e,"as-separator");if(t===null)return[];let n=jt(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function jt(e,t){let n=[],r=[],i=!1;for(let a=0;a<e.length;){let o=e.codePointAt(a),s=o>65535?2:1,c=ta(o);if(c===null){for(let l=0;l<s;l++)n.push(e[a+l]),r.push(a+l);a+=s;continue}if(i=!0,c===en){t==="as-separator"&&(n.push(" "),r.push(a)),a+=s;continue}n.push(c),r.push(a),a+=s}return i?(r.push(e.length),{label:t,text:n.join(""),offsets:Int32Array.from(r)}):null}var ee="[REDACTED]",ye=[{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}],Ml=ye.map(({name:e,re:t})=>({name:e,source:t.source})),ra="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function ia(e){return tn(e,ra)}function tn(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 nn(e){return new RegExp(ia(e.source),e.flags)}var aa="(?:\\b|_)";function oa(e){return tn(e,aa)}var sa=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function la(e){let t=sa.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function be(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 ca=[{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 ua(e){if(!/^\d+$/.test(e))return null;for(let t of ca)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 da(e){return e.length>=13&&e.length<=19&&ua(e)!==null&&be(e)}function pa(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 fa(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 ma=[[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]],ha=[[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 ga(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=ma[t][ha[r%8][n[r].charCodeAt(0)-48]];return t===0}function _a(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 ya(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 ba=[1,4,3,7,5,8,6,9,10];function va(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)*ba[n];return t%11===0}var wa="TRWAGMYFPDXBNJZSQVHLCKE";function ka(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 wa[Number(o)%23]===a}var Aa=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Ia(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Aa.has(t.slice(0,2)):!1}var ve=[{name:"pan",re:/\b\d(?:[ -]?\d){12,18}\b/g,normalize:e=>e.replace(/[ -]/g,""),validate:da},{name:"iban",re:/\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]){10,30}\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:pa},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:fa},{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:Ia(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&&ga(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:_a},{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:ka},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&be(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:ya},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:va}],rn=[{name:"person_name",detect:(e,t)=>t.person_name?.(e)??[]}],Sa="[^\\s\\S]",Ea=rn.map(e=>e.name),Ll=new Set(Ea),Ca=Object.fromEntries([...ye,...ve].map(e=>[e.name,e.re.source])),b=Ca,jl=ve.map(e=>e.name),an=ye.map(({name:e,re:t})=>({name:e,re:nn(t)})),on=ve.map(e=>({...e,re:nn(e.re)})),Bl=[...an,...on].map(({name:e,re:t})=>({name:String(e),source:t.source})),we=["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"],Ta={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
9
|
+
MIIEv\u2026
|
|
10
|
+
-----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:Sa,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}},ke=Object.freeze(Object.fromEntries(we.map(e=>{let t=Ta[e];return[e,{...t,template:{...t.template,pattern:la(oa(t.template.pattern))}}]})));var Ul=new Set(we.filter(e=>!ke[e].defaultEnabled));function xa(e,t){let n=new Set;for(let r of we)(ke[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function Na(e,t,n,r,i){let a=rn.filter(p=>!n.has(p.name));if(a.length===0)return e;let o=B(e,ge,n),s=(p,d)=>{for(let g=p;g<d;g++)if(o[g]==="\0"&&e[g]!=="\0")return!0;return!1},c=[];for(let p of a){let d=p.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?.(p.name);for(let g of d)c.push({start:g.start,end:g.end,value:g.value,id:p.name})}}if(c.length===0)return e;c.sort((p,d)=>p.start-d.start||p.end-d.end);let l=z(t),u="",f=0;for(let p of c)p.start<f||(u+=e.slice(f,p.start),u+=l(e.slice(p.start,p.end),p.id),f=p.end);return u+e.slice(f)}function B(e,t,n,r,i){if(typeof e!="string"||e.length===0)return e;let a=z(t),o=i===void 0?e:Na(e,t,n,r,i);for(let{name:s,re:c}of an){let l=s;n.has(l)||(o=o.replace(c,u=>(r?.(l),a(u,l))))}for(let{name:s,re:c,normalize:l,validate:u}of on)n.has(s)||(o=Ua(o,c,l,u,t,s,r));return o}function z(e){return typeof e=="function"?e:()=>e}var ge=e=>"\0".repeat(e.length);function Oa(e,t,n,r,i){if(typeof e!="string"||e.length===0)return e;let a=na(e);if(a.length===0)return B(e,t,n,r,i);let o=new Set,s=d=>{o.add(d)},c=B(e,ge,n,s,i),l=!0,u=new Array(e.length).fill(!1);for(let d=0;d<e.length;d++)u[d]=c[d]==="\0"&&e[d]!=="\0";for(let d of a){let g=B(d.text,ge,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,l=!1)}if(l)return B(e,t,n,r,i);for(let d of o)r?.(d);let f="",p=0;for(;p<e.length;){if(!u[p]){f+=e[p],p++;continue}let d=p;for(;p<e.length&&u[p];)p++;f+=z(t)(e.slice(d,p))}return f}function U(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var Bt=new Map;function Ra(e){let t=Bt.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),Bt.set(e.source,t)),t}var $a=4096,Da=64,Ut=null;function Pa(e){return Ut!==null?Ut:$a+e.length*Da}var sn=!1,k={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},ln={spanBudget:0,depthCap:0};function Fa(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:Pa(e),exhausted:!1}}function cn(e,t,n,r,i,a,o){k.spanCalls++;let s=t*o.stride+n.length,c=sn?void 0:o.chosen.get(s);if(c!==void 0)return c;if(o.budget<=0)return o.exhausted=!0,null;o.budget--,k.spanMisses++;let l=Ma(e,t,n,r,i,a,o);return o.chosen.set(s,l),l}function Ma(e,t,n,r,i,a,o){let s=Ra(r),c=[];for(let u=n.length-1;u>=1;u--)if(U(n[u])){let f=n.slice(0,u);s.test(f)&&c.push(f)}let l=U(e[t+n.length])?[n,...c]:[...c,n];for(let u of l)if(a(i(u),u)&&!ja(e,t,u,r,i,a,o))return u;return null}var zt=new Map;function La(e){let t=zt.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),zt.set(e.source,t)),t}function ja(e,t,n,r,i,a,o){k.cutCalls++;let s=t*o.stride+n.length,c=sn?void 0:o.cuts.get(s);if(c!==void 0)return c;if(o.budget<=0)return o.exhausted=!0,!0;o.budget--,k.cutMisses++;let l=Ba(e,t,n,r,i,a,o);return o.cuts.set(s,l),l}function Ba(e,t,n,r,i,a,o){let s=t+n.length,c=La(r);for(let l=1;l<n.length;l++){if(U(n[l])||!U(n[l-1]))continue;let u=t+l;c.lastIndex=u;let f=c.exec(e);if(f===null||f[0].length===0)continue;let p=cn(e,u,f[0],r,i,a,o);if(p!==null&&u+p.length>s&&U(e[u+p.length]))return!0}return!1}function Ua(e,t,n,r,i,a,o){let s=z(i);t.lastIndex=0;let c="",l=0,u=Fa(e),f=k.spanMisses+k.cutMisses,p;for(;(p=t.exec(e))!==null;){let d=p[0],g=p.index;if(d.length===0){t.lastIndex=g+1;continue}let _;try{_=cn(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 k.budgetExhausted++,ln.spanBudget++,qt(f),c+e.slice(l,g)+s(e.slice(g),a);if(_!==null)o?.(a),c+=e.slice(l,g)+s(_,a),l=g+_.length,t.lastIndex=l;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 qt(f),c+e.slice(l)}function qt(e){let t=k.spanMisses+k.cutMisses-e;t>k.maxMissesInAPass&&(k.maxMissesInAPass=t)}function un(e,t=ee,n,r){return qa(e,t,xa(n,r))}var za=256;function qa(e,t,n,r){let i=z(t),a=new Set,o=!n.has("pan"),s=l=>{a.add(l)},c=(l,u)=>{if(u>za)return ln.depthCap++,typeof t=="string"?t:ee;if(typeof l=="string")return Oa(l,t,n,s,r);if(typeof l=="number"&&Number.isInteger(l)&&l>0){if(!o)return l;let f=String(l);if(f.length>=13&&f.length<=19&&be(f)){a.add("pan");let p=i(f,"pan");return p===f?ee:p}return l}if(Array.isArray(l))return l.map(f=>c(f,u+1));if(l!==null&&typeof l=="object"){let f=l,p={};for(let d of Object.keys(f))p[d]=c(f[d],u+1);return p}return l};return{value:c(e,0),detectors:[...a].sort()}}function dn(e,t=ee){return un(e,t).value}var Ga=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,pn=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"}),Va=new RegExp(`[${Object.keys(pn).join("")}]`,"gu"),Ha=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),fn="\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",Wa=Object.freeze(Object.fromEntries([...fn].map((e,t)=>[e,String.fromCharCode(97+t)]))),Ka=new RegExp(`[${fn}\u2800]`,"g"),mn=/[⠀-⣿]/;function Ya(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 Za(e){return e.replace(Ga,"")}function hn(e){return e.replace(Va,t=>pn[t]??t)}function Ja(e){return e.replace(/[4@31!05$79(8]/g,t=>Ha[t]??t)}function Qa(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 Xa(e){return mn.test(e)?e.replace(Ka,t=>t==="\u2800"?" ":Wa[t]??t):e}function Gt(e){let t;try{t=Ya(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=Za(t),t=hn(t),t}var eo=/^[A-Za-z0-9+/]{16,}={0,2}$/,to=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,Vt=/[A-Za-z0-9+/]{20,}={0,2}/g;function _e(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 gn=new TextDecoder("utf-8",{fatal:!1});function _n(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=gn.decode(n);return t===r?[t]:[r,t]}function no(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=gn.decode(n);return r===i?[r]:[i,r]}function Ht(e){let t=e.trim(),n=[];if(to.test(t))for(let r of no(t))n.push({decoded:r,textiness:_e(r)});if(eo.test(t)&&t.length%4===0)for(let r of _n(t))n.push({decoded:r,textiness:_e(r)});return n}function Wt(e,t){let n=[],r;for(Vt.lastIndex=0;(r=Vt.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of _n(i))n.push({decoded:a,textiness:_e(a)})}return n}var ro=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function yn(e,t=ro){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)},c=!1,l=!1,u=0,f=0,p=[{s:e,depth:0}];for(;p.length>0;){if(u>=i){l=!0;break}let d=p.pop();if(d===void 0)break;let{s:g,depth:_}=d;if(g.length>r){l=!0;continue}u++,_>f&&(f=_);let y=Gt(g);s(y);let v=Ja(y);if(v!==y&&s(v),s(Qa(y)),mn.test(g)&&s(Xa(y)),_>=n){let S=Gt(g);(Ht(S).length>0||Wt(S,a).length>0)&&(l=!0);continue}let V=[...Ht(y),...Wt(y,a)];for(let S of V){if(c=!0,S.decoded.length>r){l=!0;continue}S.textiness>=.85&&S.decoded!==y?p.push({s:S.decoded,depth:_+1}):s(S.decoded)}}return{views:[...o],anyDecoded:c,truncated:l,nodes:u,maxDepthSeen:f}}var bn=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],io=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),ao=8,oo=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Kt=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function so(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||oo.has(i)&&Kt(t[r-1])&&Kt(t[r+1])&&(n++,n>=ao))return!0}return!1}var lo=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function co(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(lo.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var uo=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function po(e){for(let t of uo)if(e>=t.lo&&e<=t.hi)return t.name;return null}function fo(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=po(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:hn(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var Yt=Object.freeze({signals:[],contributes:!1});function mo(e){if(typeof e!="string"||e.length===0)return{...Yt,signals:[]};let t=new Set;try{so(e)&&t.add("hidden_text_carrier"),co(e)&&t.add("injected_turn_boundary"),fo(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=yn(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Yt,signals:[]}}return{signals:[...bn.filter(n=>t.has(n))],contributes:io.some(n=>t.has(n))}}var te=[{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 Zt(e){return typeof e!="string"||e.length===0?[]:te.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function ho(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(Zt(e)),{views:n}=yn(e);for(let r of n)for(let i of Zt(r))t.add(i);return te.filter(r=>t.has(r.name)).map(r=>r.name)}function go(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of ho(a))t.add(s);let o=mo(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:te.filter(a=>t.has(a.name)).map(a=>a.name),structural:bn.filter(a=>n.has(a))}}function _o(e){return go(e).matched}var zl=te.map(e=>e.name);var yo=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var bo="i:injection";function vn(e){let t=new Set,n=[];if(e.content!==void 0&&e.content!==null){let{detectors:a}=un(e.content);for(let o of a){n.push(o);let s=ke[o]?.category;s&&t.add(`c:${s}`)}_o(e.content)&&t.add(bo)}let r=e.resourceMetadata??{},i=r.source_trust;return(r.untrusted_source===!0||typeof i=="string"&&yo.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))",ql=[{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}],Jt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",vo=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${Jt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${Jt}|programming|training))`,wo="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Qt="(?:\\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)",ko="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Gl=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${wo}${vo}\\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}?${Qt}`,"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+(?:${ko}\\b|[\\s\\S]{0,40}?${Qt})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Vl=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var T=e=>`[^.!?;\\n]{0,${e}}?`,Ao=["\\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("|"),wn="(?: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)",Hl=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Ao})\\s${T(40)}\\b${wn}\\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")}]),Wl=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${wn}\\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 j=e=>`[^.!?;\\n]{0,${e}}?`,Kl=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${j(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${j(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${j(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${j(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${j(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]}]);import{createHash as rc}from"node:crypto";var kn=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function So(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:kn(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:kn(t.spawn.prompt)}),t}function Eo(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 Co=1440*60*1e3,To="VISIQ_BUNDLE_GRACE_TTL_MS",xo="VISIQ_BUNDLE_CACHE_DISABLED",No="VISIQ_CACHE_DIR",Oo=ne.object({graceTtlMs:ne.number().int().nonnegative().optional(),disabled:ne.boolean().optional(),cacheDir:ne.string().min(1).optional()}).strict();function Ro(e){return e==null?{}:Oo.parse(e)}function $o(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[To];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Co}function Do(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[xo]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var An;function Po(){if(An!==void 0)return An;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Fo(e){return JSON.stringify(Ie(e))}function Ie(e){if(Array.isArray(e))return e.map(Ie);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Ie(t[r]);return n}return e}function Mo(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Lo(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(!Po())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 Rn(e,t){return e.createHash("sha256").update(Fo(t)).digest("hex")}function jo(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[No]?.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 $n(e,t,n){return e.path.join(jo(e,n),"bundles",`${Bo(e,t)}.json`)}async function Uo(e,t,n,r={}){let i=await On();if(i)try{let a=$n(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:Rn(i.crypto,t),body:t},c=`${a}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(c,JSON.stringify(s),{mode:384});try{await i.fs.rename(c,a)}catch(l){throw await i.fs.rm(c,{force:!0}).catch(()=>{}),l}}catch{}}async function zo(e,t={}){let n=await On();if(!n)return null;try{let r=await n.fs.readFile($n(n,e,t),"utf-8"),i=Lo(JSON.parse(r));return!i||Rn(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var q;async function qo(){if(q!==void 0)return q;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;q=typeof t=="function"?t:null}catch{q=null}return q}function Go(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=pe(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of mt(a))t.push(`${o}: ${s}`)}return t}function Vo(e){return Mt(e)}function Ho(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var Wo=5e3,Ko=600*1e3,Yo=1e4,Zo=25,In=1e3,Jo=5e3,Qo=100,Sn=2e3,Xo=10,es=512,ts=1800*1e3,ns=.7,rs="monitor",is="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.",as="open";function Cn(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}var os=m.object({operations:m.array(m.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:m.string().min(1,"agentId is required"),sessionId:m.string().min(1).max(255).optional(),toolName:m.string().optional(),toolArgs:m.record(m.unknown()).optional(),targetResource:m.string().optional(),resourceType:m.string().optional(),resourceMetadata:m.record(m.unknown()).optional(),normalized:m.record(m.unknown()).optional(),query:m.string().optional(),contentPreview:m.string().optional(),telemetry:m.record(m.unknown()).optional(),context:m.record(m.unknown()).optional(),mcpServer:m.string().min(1).max(255).optional(),identity:m.object({attested:m.array(m.string().min(1).max(255)).max(32).optional(),claimed:m.array(m.string().min(1).max(255)).max(32).optional(),subjectId:m.string().min(1).max(255).optional()}).optional()}),ss=m.object({version:m.string().min(1),dialect_version:m.number().int().optional(),min_dialect:m.number().int().optional(),shutdown:m.boolean().optional(),agent_mode:m.enum(["enforce","monitor","off"]).optional(),cognition_capture:m.boolean().optional(),agent_mode_by_operation:m.object({action:m.string().optional(),retrieval:m.string().optional(),delegation:m.string().optional()}).partial().optional(),agent_attributes:m.object({trust_tier:m.string().nullable().optional(),categories:m.array(m.string()).optional(),business_function:m.string().nullable().optional(),business_functions:m.array(m.string()).nullable().optional(),blast_radius_tier:m.string().nullable().optional(),no_coverage:m.string().nullable().optional(),fail_mode:m.string().nullable().optional()}).optional(),rules:m.array(m.record(m.unknown())),action_schemas:m.array(m.object({id:m.string(),plane:m.string().optional(),field_mappings:m.array(m.record(m.unknown())).optional(),derived_fields:m.array(m.record(m.unknown())).optional(),action_class:m.string().nullable().optional(),action_class_confidence:m.number().optional()})).optional(),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()}).optional(),skill_blacklist:m.array(m.record(m.unknown())).optional()});function ls(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=xt(Nt(n));return{trust_tier:kt(t)?t:null,categories:It(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&Ot(e.blast_radius_tier)?e.blast_radius_tier:null}}function cs(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 us(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Se=new Set,Tn=!1;async function xn(e){let t=[];for(let n of Se){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 ds(){if(!Tn&&!(typeof process>"u"||typeof process.once!="function")){Tn=!0,process.once("beforeExit",()=>{xn(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await xn(!0)}finally{process.kill(process.pid,e)}})()})}}var Dn=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=rs;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=Cn(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??as;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 c=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,l=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,u=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=c,this.resolvedEndpoint=l,this.resolvedAgentId=u,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=o,this.originalFetch=globalThis.fetch.bind(globalThis);let f=Ro(s);if(this.bundleCacheDisabled=Do(f.disabled),this.bundleGraceTtlMs=$o(f.graceTtlMs),this.bundleCacheDirOverride=f.cacheDir,this.cacheIdentity=c&&l&&!this.bundleCacheDisabled?{endpoint:l,agentId:u,apiKey:c}:null,c&&l){let p={apiKey:c,agentId:u,endpoint:l,mode:"enforce",timeoutMs:Eo(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new at(p,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Wo),Ae(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Yo),Ae(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Jo),Ae(this.cognitionTimer),Se.add(this),ds()}else this.client=null}async evaluate(e){let t=os.parse(e),n=Date.now();if(this.operatorShutdown){let d=this.denyAll(t,is);return this.applyAgentMode(d,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,En,n);let d=this.denyAll(t,En);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 qo();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")?_t(t.normalized??{},{targetApp:t.targetResource??t.toolName??""}):t.normalized,o=this.buildActionSchemaEvent(t),s=t.mcpServer?{...a??{},mcp_server:t.mcpServer}:a,c={...t,normalized:s,session:r,at:Date.now(),action_schema_id:o.id,action_schema_raw:o.canonical},l={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},u;try{u=i(c,l)}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 f=[...new Set(t.operations.flatMap(d=>this.normalizedRefs[d]??[]))].sort();f.length>0&&Ho(t.normalized)&&(u.normalizedColdStart=f,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${f.length} loaded rule condition(s) on this event's operation(s) read input.normalized.* \u2014 those conditions resolve to undefined here, so a deny carrying one does not fire. (Builtin-derived paths such as context/app_category ARE still populated in-core, so this is a dependency report, not a proof that every listed condition was the decider.) Cold start / no action-schema mapping yet. Affected: ${f.slice(0,5).join("; ")}${f.length>5?`; +${f.length-5} more`:""}`)));let p=yt(t.normalized);return p.length>0&&(u.normalizedDrift=p,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${p.length} value(s) outside the canonical vocabulary \u2014 a builder-authored rule can only select in-vocab values, so these cannot match one, so a rule keyed on the canonical value does not fire here. Check the harness classifier's casing/spelling. Affected: ${p.slice(0,5).join("; ")}${p.length>5?`; +${p.length-5} more`:""}`))),this.foldSession(t,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=Rt({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 L;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>ts?(this.sessions.delete(e),L):t.state:L}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>=ns)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?vn({content:e.contentPreview,resourceMetadata:i}):void 0,c=s?.labels,l=Array.isArray(i.data_categories)?i.data_categories:[],u=(s?.detectors??[]).map(d=>Pt(d)).filter(d=>d!==void 0),f=a?[...new Set([...l,...u])]:void 0,p=vt(r===L?X():r,{data_categories:f,classification:a?i.classification:void 0,taint:c,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:p,touchedAt:Date.now()}),this.sessions.size>es){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=ss.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=Go(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=>Ft(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?ls(t.agent_attributes):null,this.agentNoCoverage=$t(t.agent_attributes?.no_coverage),this.governedFailMode=Cn(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=cs(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=Vo(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",...O(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>=Ko&&(this.lastNormalizedWarnRearmMs=o,this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1);return}if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let a=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&a?this.bundleEtag=r:a||(this.bundleEtag=null),a&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await zo(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Mo(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 Uo(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({...ce(),...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({...ce(),...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=Dt(n),i={...n};return e.toolArgs&&(i.tool_args=dn(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?us(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?{[rt]: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,Xo)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Zo&&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-In;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${In})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(So(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Qo&&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-Sn;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Sn})`))}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(),Se.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 Ae(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}var ps={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"};var fs=new Set(["read","read_file","readfile","view","cat"]);function Pn(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function Nn(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function Ee(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=ps[n];if(i){let a=Nn(r,["name","skill_name","identifier","skill","path"]);return a?{skill:a,via:n,framework:i}:null}if(fs.has(n.toLowerCase())){let a=Nn(r,["path","file_path","filePath","target","file"]),o=a?Pn(a):null;return o?{skill:o,via:n,framework:"unknown"}:null}return null}function Fn(e,t){let{activation:n,attributedSkill:r}=e;if(r)return{skill:{name:r,activated:!!n,...n?{via:n.via,framework:n.framework}:{},...t?{fingerprint:t}:{}}}}var ic=512*1024;var _s="https://api.visiqlabs.com",ys="@visiq/claude-code-harness",Te="open";function xe(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function G(){let e=process.env.VISIQ_HOME;return e&&e.trim().length>0?e:Ce(jn(),".visiq","claude-code")}function Bn(){return Ce(G(),"config.json")}function bs(e){return e==="~"||e.startsWith("~/")?Ce(jn(),e.slice(1).replace(/^\//,"")):e}async function vs(e){try{let t=hs(e)?e:gs(e),n=await ms(t,"utf-8");return JSON.parse(n)}catch{return null}}function re(e,...t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function Mn(e){if(!e||typeof e!="object")return{};let t=e,n={},r=re(t,"apiKey","api_key"),i=re(t,"agentId","agent_id"),a=re(t,"baseUrl","base_url"),o=xe(re(t,"failMode","fail_mode"));return r&&(n.apiKey=r),i&&(n.agentId=i),a&&(n.baseUrl=a),o&&(n.failMode=o),n}async function Ln(e){if(!e)return{};let t=await vs(bs(e));if(!t||typeof t!="object")return{};let n=t,r=n.plugins?.entries,i=r&&typeof r=="object"?r[ys]:void 0;return i&&typeof i=="object"&&i.config?Mn(i.config):Mn(n)}function Un(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=xe(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??Te};return i.baseUrl=r.baseUrl||_s,i}async function ws(){let e=Un(),t=await Ln(process.env.VISIQ_CONFIG_PATH),n=await Ln(Bn()),r={...n,...t,...e};return{config:zn(n,t,e),failMode:r.failMode??Te}}var Ne="0.1.19",Oe=3e4,Es=4e3;function Gn(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,200)||"default"}function Cs(e){let t=Ss("sha1").update(e).digest("hex").slice(0,10);return`${Gn(e)}-${t}`}function Re(e,t,n){return n-e.fetchedAt<t}function Vn(e){return qn(G(),"bundles",`${Cs(e)}.json`)}async function $e(e){try{let t=await As(Vn(e),"utf-8"),n=JSON.parse(t);return n&&typeof n.fetchedAt=="number"&&"body"in n?n:null}catch{return null}}async function De(e,t,n){try{let r=Vn(e);await ks(qn(G(),"bundles"),{recursive:!0});let i={fetchedAt:Date.now(),version:n,body:t};await Is(r,JSON.stringify(i),{mode:384})}catch{}}async function Pe(e,t,n){try{let r=`${e.replace(/\/+$/,"")}/rules/bundle?agent_id=${encodeURIComponent(n)}`,i=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...O(Ne,N)},signal:AbortSignal.timeout(Es)});if(!i.ok)return null;let a=i.headers.get("etag");return{body:await i.json(),version:a}}catch{return null}}import{appendFile as Cc,mkdir as Tc}from"node:fs/promises";import{join as Nc}from"node:path";var Ns=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),Os=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function Hn(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 Wn(e){return typeof e!="string"?!1:Ns.has(e)?!0:e.startsWith("mcp__")?Os.test(Hn(e)):!1}function ie(e){return Wn(e)?["retrieval","action"]:["action"]}var Rs=["query","q","url","prompt","pattern","file_path","path"];function Me(e){if(!e||typeof e!="object")return;let t=e,n=[];for(let r of Rs){let i=t[r];typeof i=="string"&&i.length>0&&n.push(i)}return n.length>0?n.join(" "):void 0}var Kn="cli_harness";function $s(e){let t=new Dn(e.apiKey,e.baseUrl,e.agentId,Kn,void 0,Ne,N);return t.setFailMode(e.failMode),t}function ae(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 Ds(e,t,n=Oe){let{agentId:r}=t,i=await $e(r);if(i&&Re(i,n,Date.now())&&Fe(e,i.body))return!0;let a=e.getEndpoint();if(a){let o=await Pe(a,t.apiKey,r);if(o&&Fe(e,o.body))return await De(r,o.body,o.version),!0}if(i&&Fe(e,i.body))return!0;try{await e.awaitBundleReady(2500)}catch{}return e.isBundleLoaded()}function Fe(e,t){try{return e.applyBundle(t),!0}catch{return!1}}async function Ps(e){try{await e.flush()}catch{}let t=typeof e.droppedTelemetryCount=="function"?e.droppedTelemetryCount():0;try{e.dispose()}catch{}return t}var Yn="visiq_surface";function Fs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:e===void 0?{}:{value:e}}function Zn(e){let{call:t,agentId:n,surface:r,session:i}=e,a=e.execution??"unconfirmed",o=ie(t.toolName),s=Fs(t.toolInput),c=Me(t.toolInput),l={[Yn]:r,cowork:{mode:"monitor",record:"tool_call",execution:a,sessionKey:i?.sessionKey,accountId:i?.accountId,orgId:i?.orgId,model:t.model,parentToolUseId:t.parentToolUseId,observedAt:t.timestamp}},u=Ee(t.toolName,s),f=Fn({activation:u,attributedSkill:u?.skill??null});return f&&(l.skill=f.skill),{event:ae({operations:o,agentId:n,toolName:t.toolName,toolInput:s,sessionId:t.sessionId,toolUseId:t.toolUseId,...c?{query:c}:{},context:l}),operations:o,enforceable:!1}}function Jn(e){let{decision:t,agentId:n,surface:r,session:i}=e,a=ie(t.toolName),o="unconfirmed";return t.granted===!1?o="refused":t.granted===!0&&(o="granted"),{event:ae({operations:a,agentId:n,toolName:t.toolName,toolInput:{},sessionId:t.sessionId,toolUseId:t.uuid,context:{[Yn]:r,cowork:{mode:"monitor",record:"permission_decision",execution:o,toolAttributed:t.unattributed!==!0,standing:t.decision==="always",decision:t.decision,sessionKey:i?.sessionKey,accountId:i?.accountId,orgId:i?.orgId,observedAt:t.timestamp}}}),operations:a,enforceable:!1}}import{open as Ms,readdir as Ls,readFile as js,stat as Qn,writeFile as Bs,mkdir as Us}from"node:fs/promises";import{dirname as zs}from"node:path";var qs=4*1024*1024;function oe(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return`${e}${e.endsWith(n)?"":n}${t}`}async function Gs(e,t){let n=[];for(let r of await e.readdir(t)){let i=oe(t,r);for(let a of await e.readdir(i)){let o=oe(i,a);for(let s of await e.readdir(o)){let c=oe(o,s),l=Be(c);if(l)for(let u of Ue(await e.readdir(c)))n.push({path:oe(c,u),session:l})}}}return n}async function pu(e){let t=e.surface??"cowork_vm",{state:n}=e,r=new Set,i=[],a=[],o=[],s={logsScanned:0,eventsSeen:0,duplicates:0,corruptLines:0,restarts:0,truncatedLines:0,permissionRequests:0,permissionDecisions:0,permissionsRefused:0,callsRefused:0};for(let l of await Gs(e.fs,e.root)){r.add(l.path);let u=await e.fs.size(l.path);if(u===null)continue;s.logsScanned+=1;let f=await e.fs.identity?.(l.path),p=Ke(n,l.path,u,f);if(p.restarted&&(s.restarts+=1),u<=p.offset){let v=f??n.cursors[l.path]?.identity;n={...n,cursors:{...n.cursors,[l.path]:{offset:p.offset,remainder:p.remainder,...v===void 0?{}:{identity:v}}}};continue}let{text:d,bytes:g}=await e.fs.read(l.path,p.offset,Math.min(u-p.offset,e.maxReadBytes??qs));if(g<=0)continue;let _=Ye(n,l.path,{startOffset:p.offset,bytesRead:g,carriedRemainder:p.remainder,chunk:d,identity:f});({state:n}=_),s.duplicates+=_.duplicates,s.corruptLines+=_.skipped,s.truncatedLines+=_.truncatedLines;let y=He(_.events);for(let v of _.events){if(s.eventsSeen+=1,v.kind==="permission_request"){s.permissionRequests+=1;continue}if(v.kind==="permission_decision"){s.permissionDecisions+=1,v.granted===!1&&(s.permissionsRefused+=1),a.push(v),o.push(Jn({decision:v,agentId:e.agentId,surface:t,session:l.session}));continue}if(v.kind!=="tool_call")continue;let V=y.get(x(v))??"unconfirmed";V==="refused"&&(s.callsRefused+=1),i.push(Zn({call:v,agentId:e.agentId,surface:t,session:l.session,execution:V}))}}let c={};for(let l of r){let u=n.cursors[l];u&&(c[l]=u)}return n={...n,cursors:c},{state:n,observations:i,permissions:a,permissionObservations:o,stats:s}}function fu(e){let t=e.permissions.filter(o=>o.granted===!1),n=e.permissions.filter(o=>o.decision==="always"&&o.granted===!0).length,r=e.permissions.filter(o=>o.granted===void 0).length,i=e.permissions.filter(o=>o.unattributed===!0).length,a=[`[VisIQ] sandbox permission gate: ${e.stats.permissionRequests} request(s), ${e.stats.permissionDecisions} answered (${e.stats.permissionsRefused} REFUSED, ${n} standing 'always' grant(s), ${r} unreadable, ${i} unattributed)`];if(t.length>0){let o=new Map;for(let c of t){let l=c.sessionId.length>0?c.sessionId:"unknown session",u=o.get(l)??new Map;u.set(c.toolName,(u.get(c.toolName)??0)+1),o.set(l,u)}let s=[...o].map(([c,l])=>`session ${c}: ${[...l].map(([u,f])=>`${u} \xD7${f}`).join(", ")}`).join("; ");a.push(`[VisIQ] REFUSED by the sandbox's own gate, so these calls did NOT run: ${s} \u2014 ${e.stats.callsRefused} bound to a tool call in this pass`)}return a}async function mu(e,t){let n=await e.readFile(t);if(n===null)return H();try{return Je(JSON.parse(n))}catch{return H()}}async function hu(e,t,n){try{return await e.writeFile(t,JSON.stringify(n)),null}catch(r){return r instanceof Error?r.message:String(r)}}function gu(e){return e.kind!=="delivered"}function Vs(e){let t=e.lastIndexOf(10);return t===-1?e.length:t+1}function _u(){return{async readdir(e){try{return await Ls(e)}catch{return[]}},async size(e){try{let t=await Qn(e);return t.isFile()?t.size:null}catch{return null}},async identity(e){try{let t=await Qn(e);return`${t.dev}:${t.ino}`}catch{return}},async read(e,t,n){if(n<=0)return{text:"",bytes:0};let r;try{r=await Ms(e,"r");let i=Buffer.alloc(n),{bytesRead:a}=await r.read(i,0,n,t),o=Vs(i.subarray(0,a));return{text:i.subarray(0,o).toString("utf8"),bytes:o}}catch{return{text:"",bytes:0}}finally{await r?.close().catch(()=>{})}},async readFile(e){try{return await js(e,"utf8")}catch{return null}},async writeFile(e,t){await Us(zs(e),{recursive:!0}),await Bs(e,t,"utf8")}}}var bu="0.1.10";export{Le as a,Ks as b,er as c,Ys as d,Zs as e,Js as f,or as g,Qs as h,Xs as i,je as j,tl as k,sr as l,nl as m,Be as n,cr as o,ur as p,dr as q,Ue as r,ze as s,pr as t,fr as u,il as v,Ge as w,mr as x,Ve as y,gr as z,He as A,x as B,_r as C,qe as D,le as E,yr as F,We as G,H,Ke as I,Ye as J,Ze as K,Je as L,Qe as M,W as N,wr as O,kr as P,Ar as Q,Dn as R,ws as S,$e as T,$s as U,Ds as V,Ps as W,Yn as X,Fs as Y,Zn as Z,qs as _,Gs as $,pu as aa,fu as ba,mu as ca,hu as da,gu as ea,Vs as fa,_u as ga,bu as ha};
|
package/dist/cli/main.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{$ as X,M as _,N as U,O as j,P as H,Q as G,R as Q,S as w,T as B,U as q,V as J,W,a as F,aa as K,ba as Y,ca as R,d as V,da as z,e as S,ea as Z,ga as T,h as O,ha as ee,i as D,m as x}from"../chunk-
|
|
2
|
+
import{$ as X,M as _,N as U,O as j,P as H,Q as G,R as Q,S as w,T as B,U as q,V as J,W,a as F,aa as K,ba as Y,ca as R,d as V,da as z,e as S,ea as Z,ga as T,h as O,ha as ee,i as D,m as x}from"../chunk-4XVXECFH.js";import{homedir as b,platform as Ne}from"node:os";import{basename as We,dirname as Xe,join as I}from"node:path";import{readFile as Ke,writeFile as Ye,mkdir as ze,rename as Ze,unlink as en}from"node:fs/promises";import{existsSync as Ee}from"node:fs";import{parseArgs as nn}from"node:util";import{accessSync as Ce,constants as Ie,statSync as Pe}from"node:fs";var $="PreToolUse";function Me(e){return e.type===void 0||e.type==="command"}function Ae(e,n){return e.includes("visiq-claude-code")||n!==void 0&&e===n}function Le(e){if(e==null)return!0;if(typeof e!="string")return!1;let n=e.trim();return n===""||n==="*"||n===".*"||n==="^.*$"}function ne(e,n){let t=[],o=e.hooks?.[$];for(let s of Array.isArray(o)?o:[]){if(!U(s,n))continue;let l=(s.hooks??[]).find(i=>Me(i)&&typeof i.command=="string"&&i.command.trim().length>0&&Ae(i.command,n));if(!l)continue;let{matcher:r}=s,c=typeof r=="string"?r.trim():JSON.stringify(r);t.push({command:l.command,scopedTo:Le(r)?null:c})}return t}function te(e,n){if(e.length===0)return null;let t=new Map,o=i=>(t.has(i)||t.set(i,n(i)),t.get(i)??null),s=e.map(i=>({group:i,path:o(i.command)})).filter(i=>i.path!==null),a=[...new Set(e.filter(i=>o(i.command)===null).map(i=>i.command))],l=s.find(i=>i.group.scopedTo===null),r=l??s[0];if(r===void 0)return{kind:"unresolvable",command:e[0]?.command??""};let c=[...new Set(s.map(i=>i.group.scopedTo).filter(i=>i!==null))];return{kind:"resolved",command:r.group.command,resolvedPath:r.path,scopedTo:l?null:c.join("|"),unresolved:a}}function Fe(e){let n=e.trim();if(n.length===0)return null;let t=/^(?:"([^"]+)"|'([^']+)')/.exec(n);if(t)return t[1]??t[2]??null;let o=n.split(/\s+/)[0];return o&&o.length>0?o:null}function Ve(e,n,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${n}`:`${e}${t}${n}`}function oe(e,n){let t=Fe(e);if(t===null)return null;let o=n.platform==="win32",s=o?(n.env?.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(r=>r.length>0):[],a=r=>[r,...s.map(c=>`${r}${c}`)];if(t.includes("/")||t.includes("\\"))return a(t).find(r=>n.isExecutable(r))??null;let l=o?"\\":"/";for(let r of(n.env?.PATH??"").split(o?";":":")){if(r.length===0)continue;let c=a(Ve(r,t,l)).find(i=>n.isExecutable(i));if(c)return c}return null}function se(){return{env:process.env,platform:process.platform,isExecutable(e){try{return Ce(e,Ie.X_OK),Pe(e).isFile()}catch{return!1}}}}function k(e){throw new Error(`unhandled HostLocalEnforcement state: ${JSON.stringify(e)} \u2014 add a branch to every consumer`)}function re(e){switch(e.state){case"enforced":return!0;case"dispatcher-unresolvable":return!1;case"no-pre-tool-use-hook":return!1;case"unconfigured":return!1;case"scoped":return!1;case"settings-unreadable":return!1;case"no-rule-bundle":return!1;case"agent-mode":return!1;default:return k(e)}}function ie(e,n={resolved:!0,failMode:"open"},t={state:"enforcing",version:null},o){if(o!==void 0)return{state:"settings-unreadable",reason:o};if(e===null)return{state:"no-pre-tool-use-hook"};if(e.kind==="unresolvable")return{state:"dispatcher-unresolvable",command:e.command};let{command:s,resolvedPath:a,scopedTo:l,unresolved:r}=e;return n.resolved?t.state==="no-bundle"?{state:"no-rule-bundle",command:s,resolvedPath:a,reason:t.reason,failMode:n.failMode}:t.state==="observing"?{state:"agent-mode",command:s,resolvedPath:a,mode:t.mode}:l!==null?{state:"scoped",command:s,resolvedPath:a,scopedTo:l,unresolved:r}:{state:"enforced",command:s,resolvedPath:a}:{state:"unconfigured",command:s,resolvedPath:a,failMode:n.failMode,scopedTo:l}}function ae(e){if(e===null)return{state:"no-bundle",reason:"absent"};let n=new Q;try{if(n.applyBundle(e.body),!n.isBundleLoaded())return{state:"no-bundle",reason:"unusable"};let t=n.getAgentMode();return t==="enforce"?{state:"enforcing",version:e.version}:{state:"observing",mode:t,version:e.version}}catch{return{state:"no-bundle",reason:"unusable"}}finally{n.dispose()}}var h=["install","uninstall","status","monitor"];var ce=e=>{let n=e.trim();if(!/^\d+$/.test(n))return`needs a whole number of milliseconds (got \`${e}\`)`;let t=Number(n);return t<1e3?`needs at least 1000 ms (got \`${e}\`)`:t>2147483647?`needs at most 2147483647 ms (got \`${e}\`) \u2014 setTimeout clamps a larger delay and fires immediately, so the monitor would spin`:null},le=e=>{let n=e.trim();return n.length===0?"needs a non-empty value":/^-/.test(n)?`looks like a flag, not a value (got \`${e}\`) \u2014 a flag whose argument is missing silently consumes the NEXT one`:null};var u={settings:{type:"string",identifiesTarget:!0,value:le,metavar:"<path>",commands:["install","uninstall","status"]},command:{type:"string",identifiesTarget:!0,value:le,metavar:"<cmd>",commands:["install","uninstall","status"]},once:{type:"boolean",identifiesTarget:!1,commands:["monitor"]},interval:{type:"string",identifiesTarget:!1,value:ce,metavar:"<ms>",commands:["monitor"]}};function ue(e){return Object.entries(u).filter(([,n])=>n.commands.includes(e)).map(([n])=>n)}var me=Object.fromEntries(Object.entries(u).map(([e,n])=>[e,{type:n.type}]));function ge(e){return Object.keys(e).filter(n=>!Object.hasOwn(u,n))}function fe(e,n){if(!h.includes(e))return[];let t=[];for(let o of Object.keys(n)){let s=Object.hasOwn(u,o)?u[o]:void 0;s===void 0||s.commands.includes(e)||t.push(`--${o} is not a \`${e}\` flag (it belongs to: ${s.commands.join(", ")}) \u2014 it would have been ignored`)}return t}function pe(e){let n=[];for(let[t,o]of Object.entries(e)){let s=Object.hasOwn(u,t)?u[t]:void 0;if(s===void 0||o===void 0)continue;if(s.type==="boolean"){typeof o!="boolean"&&n.push(`--${t} takes no value (got \`${String(o)}\`) \u2014 write \`--${t}\``);continue}if(typeof o!="string"||o.length===0){n.push(`--${t} needs a non-empty value`);continue}let a=s.value(o);a!==null&&n.push(`--${t} ${a}`)}return n}function he(e){return e===void 0?de(String(15e3)," \u2014 that is the built-in default, not something you typed"):de(typeof e=="string"?e:null,"")}function de(e,n){let t=e===null?"needs a string value":ce(e);if(t!==null)throw new Error(`--interval ${t}${n}`);return Number(e.trim())}import{join as ye}from"node:path";var De=".claude",_e="settings.json";function Ue(e){return F(e.env)??ye(e.homeDir,De)}function N(e){let{explicit:n}=e;return typeof n=="string"&&n.length>0?n:ye(Ue(e),_e)}var C="visiq-claude-cowork",je={install:"wire the hooks \u2014 host-local enforcement",uninstall:"remove them, leaving your own hooks alone",status:"what is installed, detected, and actually covered",monitor:"tail the sandbox audit stream (monitor-only)"};function He(e){let n=Object.hasOwn(u,e)?u[e]:void 0;if(n===void 0)throw new Error(`unknown flag: --${e}`);return n.type==="boolean"?`--${e}`:`--${e} ${n.metavar}`}function Ge(e){let n=ue(e).map(t=>`[${He(t)}]`);return[e,...n].join(" ")}function Qe(){return`<${h.join("|")}>`}function be(){let e=h.map(o=>({signature:Ge(o),summary:je[o]})),n=Math.max(...e.map(o=>o.signature.length)),t=e.map(o=>` ${o.signature.padEnd(n)} ${o.summary}`).join(`
|
|
3
3
|
`);return`Usage: ${C} ${Qe()} [flags]
|
|
4
4
|
|
|
5
5
|
${t}
|
package/dist/index.d.ts
CHANGED
|
@@ -1047,6 +1047,6 @@ export declare function nodeFs(): MonitorFs;
|
|
|
1047
1047
|
* (package-relative on purpose: a bare `__tests__/…` path reads as a monorepo leak to
|
|
1048
1048
|
* the publish-bundle validator, because this JSDoc ships inside the published .d.ts).
|
|
1049
1049
|
*/
|
|
1050
|
-
export declare const HARNESS_VERSION = "0.1.
|
|
1050
|
+
export declare const HARNESS_VERSION = "0.1.10";
|
|
1051
1051
|
|
|
1052
1052
|
export {};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as X,A as I,B as v,C as k,D as L,E as M,F as P,G as D,H as w,I as x,J as U,K as F,L as g,X as B,Y as K,Z as Y,_ as b,aa as h,b as e,ba as j,c as o,ca as q,d as t,da as z,e as r,ea as H,f as s,fa as V,g as n,ga as G,h as S,ha as Q,i as a,j as i,k as E,l as p,m as u,n as c,o as R,p as l,q as d,r as _,s as y,t as C,u as N,v as A,w as T,x as m,y as f,z as O}from"./chunk-
|
|
1
|
+
import{$ as X,A as I,B as v,C as k,D as L,E as M,F as P,G as D,H as w,I as x,J as U,K as F,L as g,X as B,Y as K,Z as Y,_ as b,aa as h,b as e,ba as j,c as o,ca as q,d as t,da as z,e as r,ea as H,f as s,fa as V,g as n,ga as G,h as S,ha as Q,i as a,j as i,k as E,l as p,m as u,n as c,o as R,p as l,q as d,r as _,s as y,t as C,u as N,v as A,w as T,x as m,y as f,z as O}from"./chunk-4XVXECFH.js";export{e as CLAUDE_SURFACES,i as COWORK_SESSIONS_DIRNAME,E as DESKTOP_SESSIONS_DIRNAME,Q as HARNESS_VERSION,o as HOST_PLATFORM_ENV,k as INPUT_SIGNATURE_SENTINELS,A as MAX_BUFFERED_LINE_BYTES,b as MAX_READ_BYTES,D as MAX_SEEN_KEYS,y as PERMISSION_REQUEST_SUBTYPE,C as PERMISSION_RESPONSE_SUBTYPE,B as SURFACE_CONTEXT_KEY,N as UNATTRIBUTED_TOOL_NAME,U as advance,V as alignToRecordBoundary,n as assertNeverSurface,v as auditEventKey,d as auditLogIndex,Y as buildCoworkObservation,t as classifySurface,p as claudeSupportDir,u as coworkSessionsRoot,X as discoverAuditLogs,w as emptyState,l as isAuditLogName,s as isCoworkSurface,L as isRepresentedInput,R as isSessionKey,q as loadState,H as monitorPassLost,G as nodeFs,m as normalizeAuditRecord,f as normalizeAuditRecords,_ as orderAuditLogs,T as parseNdjsonChunk,c as parseSessionDir,g as parseState,O as permissionDecisionIndex,j as permissionReportLines,P as permissionRequestMatchesCall,x as planRead,F as pruneSeen,I as resolveCallExecution,z as saveState,h as scanOnce,a as surfaceFactsFromProcess,S as surfaceLabel,r as surfaceSupportsEnforcement,K as toolArgsOf,M as toolInputSignature};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@visiq/claude-cowork-harness",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.10",
|
|
4
4
|
"description": "VisIQ agent-governance harness for Claude Cowork (the Claude desktop agent) — pre-execution enforcement on host-local sessions via Claude Code hooks, plus audit-stream monitoring for VM-sandboxed sessions the hooks cannot reach.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
package/dist/chunk-3OLBRX7B.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
var Un="CLAUDE_CONFIG_DIR";function Ce(e){let t=e?.[Un];if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}var ms=["claude_code_cli","cowork_desktop","cowork_vm","unknown"],zn="CLAUDE_CODE_HOST_PLATFORM",qn=[/[/\\]claude[^/\\]*[/\\]claude-code[/\\]/i,/[/\\]claude\.app[/\\]/i],Gn=/^\/sessions\/[^/]+\/mnt\/\.claude(\/|$)/;function Vn(e){if(e.configDir&&Gn.test(e.configDir))return!0;let t=e.env?.[zn];return typeof t=="string"&&t.length>0}function Hn(e){return(e.processPaths??[]).some(t=>qn.some(n=>n.test(t)))}function Wn(e){return(e.processPaths??[]).some(t=>/(^|[/\\])claude(\.exe)?$/.test(t))}function hs(e){return Vn(e)?"cowork_vm":Hn(e)?"cowork_desktop":Wn(e)?"claude_code_cli":"unknown"}function gs(e){return e==="claude_code_cli"||e==="cowork_desktop"}function _s(e){return e==="cowork_desktop"||e==="cowork_vm"}function Kn(e){throw new Error(`unhandled ClaudeSurface: ${JSON.stringify(e)} \u2014 add a branch to every consumer`)}function ys(e){switch(e){case"claude_code_cli":return"Claude Code CLI";case"cowork_desktop":return"Claude Cowork (host-local)";case"cowork_vm":return"Claude Cowork (VM sandbox)";case"unknown":return"unknown";default:return Kn(e)}}function bs(e=process,t=[]){let n=[...t];e.argv?.[1]&&n.push(e.argv[1]),e.execPath&&n.push(e.execPath);let r=e.env??{},i=Ce(r);return{processPaths:n,env:r,platform:e.platform,...i===void 0?{}:{configDir:i}}}var xe="local-agent-mode-sessions",ws="claude-code-sessions";function Yn(e){let{homeDir:t,platform:n,env:r={}}=e;if(n==="darwin")return`${t}/Library/Application Support/Claude`;if(n==="win32"){let a=r.APPDATA;return a?`${a}\\Claude`:`${t}\\AppData\\Roaming\\Claude`}let i=r.XDG_CONFIG_HOME;return i?`${i}/Claude`:`${t}/.config/Claude`}function Zn(e,t,...n){let r=e==="win32"?"\\":"/";return[t,...n].join(r)}function ks(e){return Zn(e.platform,Yn(e),xe)}function Ne(e){let t=e.split(/[/\\]+/).filter(o=>o.length>0),n=t.lastIndexOf(xe);if(n===-1||t.length<n+4)return null;let[r,i,a]=t.slice(n+1,n+4);return Jn(a)?{accountId:r,orgId:i,sessionKey:a}:null}function Jn(e){return/^local_[0-9a-fA-F-]{8,}$/.test(e)}function Qn(e){return/^audit\d*\.jsonl$/.test(e)}function Xn(e){let t=/^audit(\d*)\.jsonl$/.exec(e);return t?t[1]?Number.parseInt(t[1],10):0:null}function Te(e){return e.filter(Qn).map(t=>({name:t,idx:Xn(t)??0})).sort((t,n)=>n.idx-t.idx).map(t=>t.name)}var Oe="permission_request",er="permission_response",tr="<unattributed>",Ss=8388608;function $e(e){let t=[],n=0,r=0,i=e.lastIndexOf(`
|
|
2
|
-
`),a,o;i===-1?(a="",o=e):(a=e.slice(0,i),o=e.slice(i+1)),Buffer.byteLength(o,"utf8")>8388608&&(o="",r+=1);for(let s of a.split(`
|
|
3
|
-
`)){let l=s.trim();if(l.length!==0)try{t.push(JSON.parse(l))}catch{n+=1}}return{records:t,remainder:o,skipped:n,truncatedLines:r}}function w(e){return typeof e=="string"&&e.length>0?e:void 0}function X(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function nr(e){let t=X(e);if(!t)return[];let n=w(t.type),r=w(t.session_id)??"",i=w(t.uuid)??"",a=w(t._audit_timestamp);if(n==="result")return[{kind:"session_result",uuid:i,sessionId:r,timestamp:a}];if(n==="system"){let m=w(t.subtype);if(m!==Oe&&m!==er)return[];let d=w(t.tool_name),h=d??tr,g=d===void 0?{unattributed:!0}:{};return m===Oe?[{kind:"permission_request",uuid:i,sessionId:r,toolName:h,toolInput:t.tool_input,timestamp:a,...g}]:[{kind:"permission_decision",uuid:i,sessionId:r,toolName:h,granted:typeof t.granted=="boolean"?t.granted:void 0,decision:w(t.decision),timestamp:a,...g}]}if(n!=="assistant"&&n!=="user")return[];let o=X(t.message),s=o?.content;if(!Array.isArray(s))return[];let l=w(o?.model),c=w(t.parent_tool_use_id),u=[];for(let m of s){let d=X(m);if(!d)continue;let h=w(d.type);if(n==="assistant"&&h==="tool_use"){let g=w(d.name),_=w(d.id);if(!g||!_)continue;u.push({kind:"tool_call",uuid:i,sessionId:r,toolUseId:_,toolName:g,toolInput:d.input,model:l,parentToolUseId:c,timestamp:a})}else if(n==="user"&&h==="tool_result"){let g=w(d.tool_use_id);if(!g)continue;u.push({kind:"tool_result",uuid:i,sessionId:r,toolUseId:g,isError:d.is_error===!0,timestamp:a})}}return u}function De(e){return e.flatMap(t=>nr(t))}function rr(e){return e===!0?"granted":e===!1?"refused":"unconfirmed"}function ir(e){let t=new Map;for(let n of e)n.kind==="permission_decision"&&n.uuid.length>0&&t.set(n.uuid,n.granted);return t}function Me(e){let t=ir(e),n=[],r=new Map;for(let i of e){if(i.kind==="tool_call"){n.push({event:i,bound:!1});continue}if(!(i.kind!=="permission_request"||i.uuid.length===0))for(let a=0;a<n.length;a+=1){let o=n[a];if(!(!o||o.bound||!or(i,o.event))){o.bound=!0,r.set(C(o.event),rr(t.get(i.uuid)));break}}}return r}function C(e){switch(e.kind){case"session_result":return`result:${e.sessionId}:${e.uuid}`;case"permission_request":case"permission_decision":{if(e.uuid.length>0)return`${e.kind}:${e.sessionId}:${e.uuid}`;let t=e.kind==="permission_decision"?`${String(e.granted)}:${e.decision??""}`:ee(e.toolInput);return`${e.kind}:${e.sessionId}::${e.toolName}:${t}:${e.timestamp??""}`}default:return`${e.kind}:${e.sessionId}:${e.uuid}:${e.toolUseId}`}}var ar=["\0undefined","\0unserializable"];function Re(e){return!ar.includes(e)}function ee(e){try{return JSON.stringify(e)??"\0undefined"}catch{return"\0unserializable"}}function or(e,t){if(e.unattributed)return!1;let n=ee(e.toolInput),r=ee(t.toolInput);return!Re(n)||!Re(r)?!1:e.sessionId===t.sessionId&&e.toolName===t.toolName&&n===r}var Pe=5e3;function j(){return{cursors:{},seen:[]}}function Le(e,t,n,r){let i=e.cursors[t];if(!i)return{offset:0,remainder:"",restarted:!1};let a=r!==void 0&&i.identity!==void 0&&i.identity!==r;return n<i.offset||a?{offset:0,remainder:"",restarted:!0}:{offset:i.offset,remainder:i.remainder,restarted:!1}}function Fe(e,t,n){let r=$e(n.carriedRemainder+n.chunk),i=De(r.records),a=new Set(e.seen),o=[],s=0;for(let d of i){let h=C(d);if(a.has(h)){s+=1;continue}a.add(h),o.push(d)}let l=[...e.seen,...o.map(C)],c=e.cursors[t]?.identity,u=n.identity??c;return{state:{cursors:{...e.cursors,[t]:{offset:n.startOffset+n.bytesRead,remainder:r.remainder,...u===void 0?{}:{identity:u}}},seen:je(l)},events:o,duplicates:s,skipped:r.skipped,truncatedLines:r.truncatedLines}}function je(e){return e.length<=Pe?[...e]:e.slice(e.length-Pe)}function Be(e){if(!e||typeof e!="object"||Array.isArray(e))return j();let t=e,n={},r=t.cursors;if(r&&typeof r=="object"&&!Array.isArray(r))for(let[a,o]of Object.entries(r)){if(!o||typeof o!="object")continue;let s=o,l=typeof s.offset=="number"&&s.offset>=0?s.offset:0,c=typeof s.remainder=="string"?s.remainder:"",u=typeof s.identity=="string"?s.identity:void 0;n[a]={offset:l,remainder:c,...u?{identity:u}:{}}}let i=Array.isArray(t.seen)?t.seen.filter(a=>typeof a=="string"):[];return{cursors:n,seen:je(i)}}var Ue="visiq-claude-code-hook";var ze="WebFetch|WebSearch|Read|Grep|Glob|LSP|NotebookRead|ListMcpResourcesTool|ReadMcpResourceTool|mcp__.*",sr=[{event:"SessionStart",matcher:""},{event:"PreToolUse",matcher:"*"},{event:"PostToolUse",matcher:ze}];function B(e,t){return!!e.hooks?.some(n=>typeof n.command=="string"&&(n.command.includes("visiq-claude-code")||t!==void 0&&n.command===t))}function lr(e,t){return{matcher:e,hooks:[{type:"command",command:t,timeout:30}]}}function cr(e,t=Ue){let n={...e},r={...n.hooks??{}};for(let{event:i,matcher:a}of sr){let o=(Array.isArray(r[i])?r[i]:[]).filter(s=>!B(s,t));r[i]=[...o,lr(a,t)]}return n.hooks=r,n}function ur(e,t){let n={...e};if(!n.hooks)return n;let r={};for(let[i,a]of Object.entries(n.hooks)){let o=(Array.isArray(a)?a:[]).filter(s=>!B(s,t));o.length>0&&(r[i]=o)}return n.hooks=r,n}function dr(e){let{hooks:t}=e;return t?Object.values(t).some(n=>(Array.isArray(n)?n:[]).some(r=>B(r))):!1}import{readFile as Do}from"node:fs/promises";import{homedir as Cn}from"node:os";import{join as ge,isAbsolute as Mo,resolve as Po}from"node:path";import{mkdir as zo,readFile as qo,writeFile as Go,stat as gl}from"node:fs/promises";import{createHash as Vo}from"node:crypto";import{join as On}from"node:path";import{z as f}from"zod";import*as A from"node:os";import{randomUUID as Rs}from"node:crypto";var x=1,qe="X-VisIQ-SDK",Ge="X-VisIQ-Dialect",Ve="unknown";function N(e,t=1){return{[qe]:e&&e.length>0?e:Ve,[Ge]:String(t)}}var He="interceptor_source",pr=f.enum(["enforce","audit","off"]),fr=f.enum(["closed","open"]),We=f.enum(["enforce","monitor","off"]),mr=f.object({apiKey:f.string().min(1,"apiKey is required"),agentId:f.string().min(1,"agentId is required"),endpoint:f.string().url().optional(),mode:pr.optional(),timeoutMs:f.number().int().positive().optional(),hitlTimeoutMs:f.number().int().positive().optional(),failBehavior:fr.optional()}),Ts=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()}),hr=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()}),gr=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:We.optional(),arg_redaction_rules:f.array(hr).optional(),plane:f.string().nullable().optional(),operation:f.string().nullable().optional(),is_retrieval:f.boolean().optional(),metadata:f.record(f.unknown()).optional()}),_r=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())])}),yr=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(_r).default([]),priority:f.number().int().default(0)}),br=f.object({version:f.string().min(1),agent_mode:We.optional(),rules:f.array(yr),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()}),vr=2e3,wr=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function kr(e){let t=e.rules.filter(n=>wr(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 Ke=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return N(this.config.sdkVersion,this.config.sdkDialect)}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return gr.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=br.parse(a);return kr(o),o}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async reportSkillInventory(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/skills`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,skills:e})});n.ok||console.warn(`[ALLOW] Skill-inventory report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Skill-inventory report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let o=a,s=o.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof o.reason=="string"?o.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await Ar(vr)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Ar(e){return new Promise(t=>setTimeout(t,e))}function te(){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=Sr();t&&(e.ip=t)}catch{}return e}function Sr(){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}import{z as p}from"zod";import{createHash as Ir}from"crypto";import{createHash as di}from"crypto";var Ye=new Map;function Ze(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function ne(e){let t=Ir("sha256").update(e).digest("hex"),n=Ye.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
|
|
4
|
-
`).map(l=>Er(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 d=c[1],h=c[2].trim();r.set(d,O(h)),o++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let d=u[1],h=u[2].trim(),g=u[3].trim(),_=[];if(g&&g!=="}"){let v=g.endsWith("}")?g.slice(0,-1).trim():g;v&&_.push(v),g.endsWith("}")||(o++,o=U(a,o,_))}else g==="}"||(o++,o=U(a,o,_));let y=Je(_);i.push({variable:d,value:O(h),conditions:y,rawConditions:Ze(_)}),o++;continue}let m=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(m){let d=m[1],h=m[2].trim(),g=[];if(h&&h!=="}"){let y=h.endsWith("}")?h.slice(0,-1).trim():h;y&&g.push(y),h.endsWith("}")||(o++,o=U(a,o,g))}else h==="}"||(o++,o=U(a,o,g));let _=Je(g);i.push({variable:d,value:"true",conditions:_,rawConditions:Ze(g)}),o++;continue}o++}let s={defaults:r,rules:i};return Ye.set(t,s),s}function Er(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 U(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 Cr(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Je(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 re=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,xr=new RegExp(`^(${re.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),Nr=new RegExp(`^(${re.source})\\s*==\\s*((?:input|data)\\S*)$`),z=/(?:input|data)(?:\.[A-Za-z0-9_]+|\["[^"]+"\]|\['[^']+'\])+/,Tr=new RegExp(`^(${z.source})\\s*(==|!=)\\s*(${z.source})$`),Or=new RegExp(`^(${z.source})\\s+in\\s+(${z.source})$`),Rr=/^([^\s=!]+)\s*==\s*(.+)$/,$r=/^([^\s=!]+)\s*!=\s*(.+)$/,Ps=new RegExp(`^(?:${re.source})$`);var Dr=/^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: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(Dr);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:Cr(s[1])};let l=n.match(Or);if(l)return{type:"field_in_set",negated:t,field:l[1].trim(),rightField:l[2].trim()};let c=n.match(Tr);if(c)return{type:"field_equality",negated:c[2]==="!="?!t:t,field:c[1].trim(),rightField:c[3].trim()};let u=n.match(xr);if(u)return{type:"array_includes",negated:t,field:u[2].trim(),value:it(u[1])};let m=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(m){let v=Br(m[2]);if(v!==null)return{type:"in_set",negated:t,field:m[1].trim(),values:v}}let d=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(d)return{type:"comparison",negated:t,field:d[1].trim(),operator:d[2],value:parseFloat(d[3])};let h=n.match(Nr);if(h)return{type:"equality",negated:t,field:h[2].trim(),value:O(h[1].trim())};let g=n.match(Rr);if(g)return{type:"equality",negated:t,field:g[1].trim(),value:O(g[2].trim())};let _=n.match($r);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 Pr=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function rt(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==R&&Pr.test(r.field)&&t.push(r.field);return t}var Lr=["input.normalized.","input.normalized["];function Fr(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions)for(let i of jr(r))typeof i!="string"||i===R||Lr.some(a=>i.startsWith(a))&&t.add(i);return[...t].sort()}var Qe=/\binput\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/g;function jr(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 Qe.lastIndex=0,[...r.matchAll(Qe)].map(i=>i[0])}function it(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 Br(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(it(s))}return o}var at=["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"],Ur=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],zr=["production","staging","development","test"],qr=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function Gr(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 Xe={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 Vr(e){let t=Gr(e);return t===null?"other":Xe[t]??Xe[t.replace(/_/g,"")]??"other"}function ot(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=Vr(t.targetApp)),n.context=r}return n}var et=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],Hr=["read","write","delete","share","export","decide","execute"],tt=["none","low","medium","high","critical"],Wr=["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"],Kr={action_class:at,operation:Hr,"context/app_category":Ur,"context/environment":zr,"context/actor_function":qr,"read/classification":Wr,"read/data_categories":et,"read/data_sensitivity":tt,"write/data_categories":et,"write/data_sensitivity":tt};function st(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(Kr)){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 nt=64,Yr=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 V(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:ct()}}var Zr=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>nt?r.slice(0,nt):r}function q(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function T(e){return typeof e=="string"&&e.length>0?e:null}function lt(e,t){let n=q(t.data_categories),r=T(t.classification),i=q(t.taint),a=T(t.action_class),o=a&&at.includes(a)?a:null,s=T(t.target_app),l=T(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<Yr)c[o]=1;else{let u=Object.keys(c).sort(),m=u[u.length-1];m!==void 0&&o<m&&(delete c[m],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&&Zr.has(l)?1:0),event_count:e.event_count+1,target_apps:I(e.target_apps,s?[s]:[]),identity:Jr(e.identity,t)}}function Jr(e,t){let n=e??ct(),r=q(t.attested_subjects),i=I(n.attested_subjects,r),a=T(t.subject_id);return{attested_subjects:i,claimed_subjects:I(n.claimed_subjects,q(t.claimed_subjects)),acted_subjects:I(n.acted_subjects,a?[a]:[])}}function ct(){return{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}}var Qr=["tier1","tier2","tier3"];function ut(e){return typeof e=="string"&&Qr.includes(e)}var Xr=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],ei=["internal","customer_facing","experimental","third_party"],dt=[...Xr,...ei];function ti(e){return typeof e=="string"&&dt.includes(e)}function pt(e){let t=new Set;for(let n of e)ti(n)&&t.add(n);return dt.filter(n=>t.has(n))}var ni={trust_tier:null,categories:[],business_functions:[],business_function:null,blast_radius_tier:null};function ft(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))ft(i,t.length>0?`${t}.${r}`:r,n)}function mt(e){let t=new Set;return ft(e,"",t),t}var Ls=mt(V()),Fs=mt(ni),ri=["action_counts"];for(let e of ri){let t=V()[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 js=new RegExp("^\\p{White_Space}*$","u");var ht="generic",gt=[{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:ht,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."}],ii=gt.map(e=>e.id),Bs=new Map(gt.map(e=>[e.id,e])),Us=new Set(ii);function _t(e){return Array.isArray(e)&&e.length>0?[...e]:[ht]}var ai=/^[a-z][a-z0-9_]*$/;function yt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&ai.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var oi=["narrow","moderate","broad","unbounded","unknown"];function bt(e){return typeof e=="string"&&oi.includes(e)}function si(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 li(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+=si((i^a)>>>0)}return n}var ci=["proposed","approved","revoked"];function ui(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"&&ci.includes(t.status)}function vt(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(ui(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=li(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 wt(e){return e==="open"||e==="closed"?e:null}var pi=["tool_name","function","name","action"];function G(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)G(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)G(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function fi(e){let t=[];return G(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function mi(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function hi(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function gi(e,t={}){if(t.discriminatorField===null)return null;let n=[];G(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??pi;for(let i of r){let a=null;for(let[o,s]of n){if(mi(o)!==i)continue;let l=hi(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function kt(e,t={}){let n=di("sha256").update(fi(e).join(",")).digest("hex").slice(0,16),r=gi(e,t);return r!==null?`${n}:${r}`:n}var _i=["action","retrieval","delegation"];function yi(e){return typeof e=="string"&&_i.includes(e)}var bi=new Set(["rules"]);function At(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 St(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=ne(r)}catch{continue}let a=Fr(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 K}from"zod";var vi=/[^\u0000-\u007F]/,Ut=new RegExp("^\\p{Nd}$","u"),wi=new RegExp("^\\p{Pd}$","u"),ki=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,Ai=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,Si=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),zt="<invisible>",It=new Map;function Ii(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 Ei(e){if(e<128)return null;let t=It.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)?Ii(e):wi.test(r)||Si.has(e)?"-":ki.test(r)?" ":Ai.test(r)?zt:null})();return It.set(e,n),n}function Ci(e){if(typeof e!="string"||e.length===0||!vi.test(e))return[];let t=Et(e,"as-separator");if(t===null)return[];let n=Et(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function Et(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=Ei(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===zt){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}var qt="[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}],Gs=se.map(({name:e,re:t})=>({name:e,source:t.source})),xi="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function Ni(e){return Gt(e,xi)}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(Ni(e.source),e.flags)}var Ti="(?:\\b|_)";function Oi(e){return Gt(e,Ti)}var Ri=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function $i(e){let t=Ri.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function ae(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 Di(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 Mi(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 Pi=[[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]],Li=[[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 Fi(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=Pi[t][Li[r%8][n[r].charCodeAt(0)-48]];return t===0}function ji(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 Bi(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 Ui=[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)*Ui[n];return t%11===0}var qi="TRWAGMYFPDXBNJZSQVHLCKE";function Gi(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 qi[Number(o)%23]===a}var Vi=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Hi(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Vi.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&&ae(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:Di},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Mi},{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:Hi(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&&Fi(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:ji},{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:Gi},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&ae(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Bi},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:zi}],Wi=Object.fromEntries([...se,...le].map(e=>[e.name,e.re.source])),b=Wi,Vs=le.map(e=>e.name),Ht=se.map(({name:e,re:t})=>({name:e,re:Vt(t)})),Wt=le.map(e=>({...e,re:Vt(e.re)})),Hs=[...Ht,...Wt].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"],Ki={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
5
|
-
MIIEv\u2026
|
|
6
|
-
-----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=Ki[e];return[e,{...t,template:{...t.template,pattern:$i(Oi(t.template.pattern))}}]})));var Ws=new Set(ce.filter(e=>!ue[e].defaultEnabled));function Yi(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 H(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 Ht){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 Wt)n.has(o)||(a=oa(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 Zi(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=Ci(e);if(i.length===0)return H(e,t,n,r);let a=new Set,o=d=>{a.add(d)},s=H(e,Ct,n,o),l=!0,c=new Array(e.length).fill(!1);for(let d=0;d<e.length;d++)c[d]=s[d]==="\0"&&e[d]!=="\0";for(let d of i){let h=H(d.text,Ct,n,o);for(let g=0;g<d.text.length;g++)if(!(h[g]!=="\0"||d.text[g]==="\0"))for(let _=d.offsets[g];_<d.offsets[g+1];_++)c[_]||(c[_]=!0,l=!1)}if(l)return H(e,t,n,r);for(let d of a)r?.(d);let u="",m=0;for(;m<e.length;){if(!c[m]){u+=e[m],m++;continue}let d=m;for(;m<e.length&&c[m];)m++;u+=de(t)(e.slice(d,m))}return u}function M(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var xt=new Map;function Ji(e){let t=xt.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),xt.set(e.source,t)),t}var Qi=4096,Xi=64,Nt=null;function ea(e){return Nt!==null?Nt:Qi+e.length*Xi}var Kt=!1,k={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},Yt={spanBudget:0,depthCap:0};function ta(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:ea(e),exhausted:!1}}function Zt(e,t,n,r,i,a,o){k.spanCalls++;let s=t*o.stride+n.length,l=Kt?void 0:o.chosen.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,null;o.budget--,k.spanMisses++;let c=na(e,t,n,r,i,a,o);return o.chosen.set(s,c),c}function na(e,t,n,r,i,a,o){let s=Ji(r),l=[];for(let u=n.length-1;u>=1;u--)if(M(n[u])){let m=n.slice(0,u);s.test(m)&&l.push(m)}let c=M(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(a(i(u),u)&&!ia(e,t,u,r,i,a,o))return u;return null}var Tt=new Map;function ra(e){let t=Tt.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),Tt.set(e.source,t)),t}function ia(e,t,n,r,i,a,o){k.cutCalls++;let s=t*o.stride+n.length,l=Kt?void 0:o.cuts.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,!0;o.budget--,k.cutMisses++;let c=aa(e,t,n,r,i,a,o);return o.cuts.set(s,c),c}function aa(e,t,n,r,i,a,o){let s=t+n.length,l=ra(r);for(let c=1;c<n.length;c++){if(M(n[c])||!M(n[c-1]))continue;let u=t+c;l.lastIndex=u;let m=l.exec(e);if(m===null||m[0].length===0)continue;let d=Zt(e,u,m[0],r,i,a,o);if(d!==null&&u+d.length>s&&M(e[u+d.length]))return!0}return!1}function oa(e,t,n,r,i,a,o){let s=de(i);t.lastIndex=0;let l="",c=0,u=ta(e),m=k.spanMisses+k.cutMisses,d;for(;(d=t.exec(e))!==null;){let h=d[0],g=d.index;if(h.length===0){t.lastIndex=g+1;continue}let _;try{_=Zt(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 k.budgetExhausted++,Yt.spanBudget++,Ot(m),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 Ot(m),l+e.slice(c)}function Ot(e){let t=k.spanMisses+k.cutMisses-e;t>k.maxMissesInAPass&&(k.maxMissesInAPass=t)}function Jt(e,t=qt,n,r){return la(e,t,Yi(n,r))}var sa=256;function la(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=(s,l)=>{if(l>sa)return Yt.depthCap++,t;if(typeof s=="string")return Zi(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&&ae(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 m of Object.keys(c))u[m]=o(c[m],l+1);return u}return s};return{value:o(e,0),detectors:[...r].sort()}}function Qt(e,t=qt){return Jt(e,t).value}var ca=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Xt=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"}),ua=new RegExp(`[${Object.keys(Xt).join("")}]`,"gu"),da=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),en="\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",pa=Object.freeze(Object.fromEntries([...en].map((e,t)=>[e,String.fromCharCode(97+t)]))),fa=new RegExp(`[${en}\u2800]`,"g"),tn=/[⠀-⣿]/;function ma(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 ha(e){return e.replace(ca,"")}function nn(e){return e.replace(ua,t=>Xt[t]??t)}function ga(e){return e.replace(/[4@31!05$79(8]/g,t=>da[t]??t)}function _a(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 ya(e){return tn.test(e)?e.replace(fa,t=>t==="\u2800"?" ":pa[t]??t):e}function Rt(e){let t;try{t=ma(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=ha(t),t=nn(t),t}var ba=/^[A-Za-z0-9+/]{16,}={0,2}$/,va=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,$t=/[A-Za-z0-9+/]{20,}={0,2}/g;function oe(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 rn=new TextDecoder("utf-8",{fatal:!1});function an(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=rn.decode(n);return t===r?[t]:[r,t]}function wa(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=rn.decode(n);return r===i?[r]:[i,r]}function Dt(e){let t=e.trim(),n=[];if(va.test(t))for(let r of wa(t))n.push({decoded:r,textiness:oe(r)});if(ba.test(t)&&t.length%4===0)for(let r of an(t))n.push({decoded:r,textiness:oe(r)});return n}function Mt(e,t){let n=[],r;for($t.lastIndex=0;(r=$t.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of an(i))n.push({decoded:a,textiness:oe(a)})}return n}var ka=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function on(e,t=ka){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,m=0,d=[{s:e,depth:0}];for(;d.length>0;){if(u>=i){c=!0;break}let h=d.pop();if(h===void 0)break;let{s:g,depth:_}=h;if(g.length>r){c=!0;continue}u++,_>m&&(m=_);let y=Rt(g);s(y);let v=ga(y);if(v!==y&&s(v),s(_a(y)),tn.test(g)&&s(ya(y)),_>=n){let S=Rt(g);(Dt(S).length>0||Mt(S,a).length>0)&&(c=!0);continue}let F=[...Dt(y),...Mt(y,a)];for(let S of F){if(l=!0,S.decoded.length>r){c=!0;continue}S.textiness>=.85&&S.decoded!==y?d.push({s:S.decoded,depth:_+1}):s(S.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:m}}var sn=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],Aa=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),Sa=8,Ia=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Pt=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function Ea(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||Ia.has(i)&&Pt(t[r-1])&&Pt(t[r+1])&&(n++,n>=Sa))return!0}return!1}var Ca=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function xa(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(Ca.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Na=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Ta(e){for(let t of Na)if(e>=t.lo&&e<=t.hi)return t.name;return null}function Oa(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=Ta(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:nn(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var Lt=Object.freeze({signals:[],contributes:!1});function Ra(e){if(typeof e!="string"||e.length===0)return{...Lt,signals:[]};let t=new Set;try{Ea(e)&&t.add("hidden_text_carrier"),xa(e)&&t.add("injected_turn_boundary"),Oa(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=on(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Lt,signals:[]}}return{signals:[...sn.filter(n=>t.has(n))],contributes:Aa.some(n=>t.has(n))}}var W=[{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?[]:W.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function $a(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(Ft(e)),{views:n}=on(e);for(let r of n)for(let i of Ft(r))t.add(i);return W.filter(r=>t.has(r.name)).map(r=>r.name)}function Da(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of $a(a))t.add(s);let o=Ra(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:W.filter(a=>t.has(a.name)).map(a=>a.name),structural:sn.filter(a=>n.has(a))}}function Ma(e){return Da(e).matched}var Ks=W.map(e=>e.name);var Pa=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var La="i:injection";function ln(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=Jt(e.content);for(let a of i){let o=ue[a]?.category;o&&t.add(`c:${o}`)}Ma(e.content)&&t.add(La)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Pa.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var ie="(?:system\\s+prompt|initial\\s+(?:instructions|prompt)|system\\s+(?:instructions|message)|hidden\\s+(?:instructions|prompt)|your\\s+(?:system\\s+prompt|initial\\s+instructions|instructions|prompt)|the\\s+prompt\\s+(?:above|you\\s+were\\s+given))",Ys=[{name:"reveal_prompt",re:new RegExp(`\\b(?:reveal|show|print|repeat|output|echo|display|expose|dump|leak|reprint|divulge|disclose)\\b[\\s\\S]{0,40}?\\b${ie}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${ie}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${ie}\\b`,"i")},{name:"repeat_above",re:/\b(?:repeat|print|output|echo|reproduce)\b[\s\S]{0,20}?\b(?:everything|all\s+(?:the\s+)?(?:text|words))\b[\s\S]{0,12}?\b(?:above|before|preceding|verbatim|word\s+for\s+word)\b/i}],jt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Fa=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${jt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${jt}|programming|training))`,ja="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Bt="(?:\\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)",Ba="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Zs=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${ja}${Fa}\\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}?${Bt}`,"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+(?:${Ba}\\b|[\\s\\S]{0,40}?${Bt})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Js=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var E=e=>`[^.!?;\\n]{0,${e}}?`,Ua=["\\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("|"),cn="(?: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)",Qs=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Ua})\\s${E(40)}\\b${cn}\\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")}]),Xs=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${cn}\\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}}?`,el=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]}]);import{createHash as ll}from"node:crypto";var un=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function qa(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:un(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:un(t.spawn.prompt)}),t}function Ga(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 Va=1440*60*1e3,Ha="VISIQ_BUNDLE_GRACE_TTL_MS",Wa="VISIQ_BUNDLE_CACHE_DISABLED",Ka="VISIQ_CACHE_DIR",Ya=K.object({graceTtlMs:K.number().int().nonnegative().optional(),disabled:K.boolean().optional(),cacheDir:K.string().min(1).optional()}).strict();function Za(e){return e==null?{}:Ya.parse(e)}function Ja(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Ha];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Va}function Qa(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Wa]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var dn;function Xa(){if(dn!==void 0)return dn;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function eo(e){return JSON.stringify(fe(e))}function fe(e){if(Array.isArray(e))return e.map(fe);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=fe(t[r]);return n}return e}function to(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function no(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 bn(){if(!Xa())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 vn(e,t){return e.createHash("sha256").update(eo(t)).digest("hex")}function ro(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Ka]?.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 io(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function wn(e,t,n){return e.path.join(ro(e,n),"bundles",`${io(e,t)}.json`)}async function ao(e,t,n,r={}){let i=await bn();if(i)try{let a=wn(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:vn(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 oo(e,t={}){let n=await bn();if(!n)return null;try{let r=await n.fs.readFile(wn(n,e,t),"utf-8"),i=no(JSON.parse(r));return!i||vn(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var P;async function so(){if(P!==void 0)return P;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;P=typeof t=="function"?t:null}catch{P=null}return P}function lo(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=ne(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of rt(a))t.push(`${o}: ${s}`)}return t}function co(e){return St(e)}function uo(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var po=5e3,fo=600*1e3,mo=1e4,ho=25,pn=1e3,go=5e3,_o=100,fn=2e3,yo=10,bo=512,vo=1800*1e3,wo=.7,ko="monitor",Ao="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",mn="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.",So="open";function hn(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Io(e,t){return ln({content:e,resourceMetadata:t})}var Eo=p.object({operations:p.array(p.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:p.string().min(1,"agentId is required"),sessionId:p.string().min(1).max(255).optional(),toolName:p.string().optional(),toolArgs:p.record(p.unknown()).optional(),targetResource:p.string().optional(),resourceType:p.string().optional(),resourceMetadata:p.record(p.unknown()).optional(),normalized:p.record(p.unknown()).optional(),query:p.string().optional(),contentPreview:p.string().optional(),telemetry:p.record(p.unknown()).optional(),context:p.record(p.unknown()).optional(),mcpServer:p.string().min(1).max(255).optional(),identity:p.object({attested:p.array(p.string().min(1).max(255)).max(32).optional(),claimed:p.array(p.string().min(1).max(255)).max(32).optional(),subjectId:p.string().min(1).max(255).optional()}).optional()}),Co=p.object({version:p.string().min(1),dialect_version:p.number().int().optional(),min_dialect:p.number().int().optional(),shutdown:p.boolean().optional(),agent_mode:p.enum(["enforce","monitor","off"]).optional(),cognition_capture:p.boolean().optional(),agent_mode_by_operation:p.object({action:p.string().optional(),retrieval:p.string().optional(),delegation:p.string().optional()}).partial().optional(),agent_attributes:p.object({trust_tier:p.string().nullable().optional(),categories:p.array(p.string()).optional(),business_function:p.string().nullable().optional(),business_functions:p.array(p.string()).nullable().optional(),blast_radius_tier:p.string().nullable().optional(),no_coverage:p.string().nullable().optional(),fail_mode:p.string().nullable().optional()}).optional(),rules:p.array(p.record(p.unknown())),action_schemas:p.array(p.object({id:p.string(),plane:p.string().optional(),field_mappings:p.array(p.record(p.unknown())).optional(),derived_fields:p.array(p.record(p.unknown())).optional(),action_class:p.string().nullable().optional(),action_class_confidence:p.number().optional()})).optional(),no_coverage:p.object({no_coverage_defaults:p.record(p.string()),autopilot_enabled:p.boolean(),enduser_hitl_enabled:p.boolean(),hitl_timeout_seconds:p.number().optional()}).optional(),skill_blacklist:p.array(p.record(p.unknown())).optional()});function xo(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=_t(yt(n));return{trust_tier:ut(t)?t:null,categories:pt(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&bt(e.blast_radius_tier)?e.blast_radius_tier:null}}function No(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 To(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var me=new Set,gn=!1;async function _n(e){let t=[];for(let n of me){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 Oo(){if(!gn&&!(typeof process>"u"||typeof process.once!="function")){gn=!0,process.once("beforeExit",()=>{_n(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await _n(!0)}finally{process.kill(process.pid,e)}})()})}}var kn=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=ko;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=hn(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??So;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 m=Za(s);if(this.bundleCacheDisabled=Qa(m.disabled),this.bundleGraceTtlMs=Ja(m.graceTtlMs),this.bundleCacheDirOverride=m.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let d={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:Ga(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new Ke(d,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},po),pe(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},mo),pe(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},go),pe(this.cognitionTimer),me.add(this),Oo()}else this.client=null}async evaluate(e){let t=Eo.parse(e),n=Date.now();if(this.operatorShutdown){let h=this.denyAll(t,Ao);return this.applyAgentMode(h,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,mn,n);let h=this.denyAll(t,mn);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 so();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")?ot(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 m=[...new Set(t.operations.flatMap(h=>this.normalizedRefs[h]??[]))].sort();m.length>0&&uo(t.normalized)&&(u.normalizedColdStart=m,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${m.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: ${m.slice(0,5).join("; ")}${m.length>5?`; +${m.length-5} more`:""}`)));let d=st(t.normalized);return d.length>0&&(u.normalizedDrift=d,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${d.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: ${d.slice(0,5).join("; ")}${d.length>5?`; +${d.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=vt({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>vo?(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>=wo)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=lt(r===$?V():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?Io(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>bo){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=Co.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=lo(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=>At(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?xo(t.agent_attributes):null,this.agentNoCoverage=wt(t.agent_attributes?.no_coverage),this.governedFailMode=hn(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=No(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=co(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>=fo&&(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 oo(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(to(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 ao(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({...te(),...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({...te(),...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=kt(n),i={...n};return e.toolArgs&&(i.tool_args=Qt(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?To(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?{[He]: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,yo)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=ho&&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-pn;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${pn})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(qa(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=_o&&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-fn;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${fn})`))}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(),me.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 pe(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}var Ro={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"};var $o=new Set(["read","read_file","readfile","view","cat"]);function An(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function yn(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function he(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=Ro[n];if(i){let a=yn(r,["name","skill_name","identifier","skill","path"]);return a?{skill:a,via:n,framework:i}:null}if($o.has(n.toLowerCase())){let a=yn(r,["path","file_path","filePath","target","file"]),o=a?An(a):null;return o?{skill:o,via:n,framework:"unknown"}:null}return null}function Sn(e,t){let{activation:n,attributedSkill:r}=e;if(r)return{skill:{name:r,activated:!!n,...n?{via:n.via,framework:n.framework}:{},...t?{fingerprint:t}:{}}}}var cl=512*1024;var Lo="https://api.visiqlabs.com",Fo="@visiq/claude-code-harness",_e="open";function ye(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function L(){let e=process.env.VISIQ_HOME;return e&&e.trim().length>0?e:ge(Cn(),".visiq","claude-code")}function xn(){return ge(L(),"config.json")}function jo(e){return e==="~"||e.startsWith("~/")?ge(Cn(),e.slice(1).replace(/^\//,"")):e}async function Bo(e){try{let t=Mo(e)?e:Po(e),n=await Do(t,"utf-8");return JSON.parse(n)}catch{return null}}function Y(e,...t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function In(e){if(!e||typeof e!="object")return{};let t=e,n={},r=Y(t,"apiKey","api_key"),i=Y(t,"agentId","agent_id"),a=Y(t,"baseUrl","base_url"),o=ye(Y(t,"failMode","fail_mode"));return r&&(n.apiKey=r),i&&(n.agentId=i),a&&(n.baseUrl=a),o&&(n.failMode=o),n}async function En(e){if(!e)return{};let t=await Bo(jo(e));if(!t||typeof t!="object")return{};let n=t,r=n.plugins?.entries,i=r&&typeof r=="object"?r[Fo]:void 0;return i&&typeof i=="object"&&i.config?In(i.config):In(n)}function Nn(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=ye(e.VISIQ_FAIL_MODE);return n&&(t.failMode=n),t}function Tn(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||Lo,i}async function Uo(){let e=Nn(),t=await En(process.env.VISIQ_CONFIG_PATH),n=await En(xn()),r={...n,...t,...e};return{config:Tn(n,t,e),failMode:r.failMode??_e}}var be="0.1.16",ve=3e4,Ho=4e3;function Rn(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,200)||"default"}function Wo(e){let t=Vo("sha1").update(e).digest("hex").slice(0,10);return`${Rn(e)}-${t}`}function we(e,t,n){return n-e.fetchedAt<t}function $n(e){return On(L(),"bundles",`${Wo(e)}.json`)}async function ke(e){try{let t=await qo($n(e),"utf-8"),n=JSON.parse(t);return n&&typeof n.fetchedAt=="number"&&"body"in n?n:null}catch{return null}}async function Ae(e,t,n){try{let r=$n(e);await zo(On(L(),"bundles"),{recursive:!0});let i={fetchedAt:Date.now(),version:n,body:t};await Go(r,JSON.stringify(i),{mode:384})}catch{}}async function Se(e,t,n){try{let r=`${e.replace(/\/+$/,"")}/rules/bundle?agent_id=${encodeURIComponent(n)}`,i=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...N(be,x)},signal:AbortSignal.timeout(Ho)});if(!i.ok)return null;let a=i.headers.get("etag");return{body:await i.json(),version:a}}catch{return null}}import{appendFile as $l,mkdir as Dl}from"node:fs/promises";import{join as Pl}from"node:path";var Zo=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),Jo=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function Dn(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 Mn(e){return typeof e!="string"?!1:Zo.has(e)?!0:e.startsWith("mcp__")?Jo.test(Dn(e)):!1}function Z(e){return Mn(e)?["retrieval","action"]:["action"]}var Qo=["query","q","url","prompt","pattern","file_path","path"];function Ee(e){if(!e||typeof e!="object")return;let t=e,n=[];for(let r of Qo){let i=t[r];typeof i=="string"&&i.length>0&&n.push(i)}return n.length>0?n.join(" "):void 0}var Pn="cli_harness";function Xo(e){let t=new kn(e.apiKey,e.baseUrl,e.agentId,Pn,void 0,be,x);return t.setFailMode(e.failMode),t}function J(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 es(e,t,n=ve){let{agentId:r}=t,i=await ke(r);if(i&&we(i,n,Date.now())&&Ie(e,i.body))return!0;let a=e.getEndpoint();if(a){let o=await Se(a,t.apiKey,r);if(o&&Ie(e,o.body))return await Ae(r,o.body,o.version),!0}if(i&&Ie(e,i.body))return!0;try{await e.awaitBundleReady(2500)}catch{}return e.isBundleLoaded()}function Ie(e,t){try{return e.applyBundle(t),!0}catch{return!1}}async function ts(e){try{await e.flush()}catch{}let t=typeof e.droppedTelemetryCount=="function"?e.droppedTelemetryCount():0;try{e.dispose()}catch{}return t}var Ln="visiq_surface";function ns(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:e===void 0?{}:{value:e}}function Fn(e){let{call:t,agentId:n,surface:r,session:i}=e,a=e.execution??"unconfirmed",o=Z(t.toolName),s=ns(t.toolInput),l=Ee(t.toolInput),c={[Ln]:r,cowork:{mode:"monitor",record:"tool_call",execution:a,sessionKey:i?.sessionKey,accountId:i?.accountId,orgId:i?.orgId,model:t.model,parentToolUseId:t.parentToolUseId,observedAt:t.timestamp}},u=he(t.toolName,s),m=Sn({activation:u,attributedSkill:u?.skill??null});return m&&(c.skill=m.skill),{event:J({operations:o,agentId:n,toolName:t.toolName,toolInput:s,sessionId:t.sessionId,toolUseId:t.toolUseId,...l?{query:l}:{},context:c}),operations:o,enforceable:!1}}function jn(e){let{decision:t,agentId:n,surface:r,session:i}=e,a=Z(t.toolName),o="unconfirmed";return t.granted===!1?o="refused":t.granted===!0&&(o="granted"),{event:J({operations:a,agentId:n,toolName:t.toolName,toolInput:{},sessionId:t.sessionId,toolUseId:t.uuid,context:{[Ln]:r,cowork:{mode:"monitor",record:"permission_decision",execution:o,toolAttributed:t.unattributed!==!0,standing:t.decision==="always",decision:t.decision,sessionKey:i?.sessionKey,accountId:i?.accountId,orgId:i?.orgId,observedAt:t.timestamp}}}),operations:a,enforceable:!1}}import{open as rs,readdir as is,readFile as as,stat as Bn,writeFile as os,mkdir as ss}from"node:fs/promises";import{dirname as ls}from"node:path";var cs=4*1024*1024;function Q(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return`${e}${e.endsWith(n)?"":n}${t}`}async function us(e,t){let n=[];for(let r of await e.readdir(t)){let i=Q(t,r);for(let a of await e.readdir(i)){let o=Q(i,a);for(let s of await e.readdir(o)){let l=Q(o,s),c=Ne(l);if(c)for(let u of Te(await e.readdir(l)))n.push({path:Q(l,u),session:c})}}}return n}async function bc(e){let t=e.surface??"cowork_vm",{state:n}=e,r=new Set,i=[],a=[],o=[],s={logsScanned:0,eventsSeen:0,duplicates:0,corruptLines:0,restarts:0,truncatedLines:0,permissionRequests:0,permissionDecisions:0,permissionsRefused:0,callsRefused:0};for(let c of await us(e.fs,e.root)){r.add(c.path);let u=await e.fs.size(c.path);if(u===null)continue;s.logsScanned+=1;let m=await e.fs.identity?.(c.path),d=Le(n,c.path,u,m);if(d.restarted&&(s.restarts+=1),u<=d.offset){let v=m??n.cursors[c.path]?.identity;n={...n,cursors:{...n.cursors,[c.path]:{offset:d.offset,remainder:d.remainder,...v===void 0?{}:{identity:v}}}};continue}let{text:h,bytes:g}=await e.fs.read(c.path,d.offset,Math.min(u-d.offset,e.maxReadBytes??cs));if(g<=0)continue;let _=Fe(n,c.path,{startOffset:d.offset,bytesRead:g,carriedRemainder:d.remainder,chunk:h,identity:m});({state:n}=_),s.duplicates+=_.duplicates,s.corruptLines+=_.skipped,s.truncatedLines+=_.truncatedLines;let y=Me(_.events);for(let v of _.events){if(s.eventsSeen+=1,v.kind==="permission_request"){s.permissionRequests+=1;continue}if(v.kind==="permission_decision"){s.permissionDecisions+=1,v.granted===!1&&(s.permissionsRefused+=1),a.push(v),o.push(jn({decision:v,agentId:e.agentId,surface:t,session:c.session}));continue}if(v.kind!=="tool_call")continue;let F=y.get(C(v))??"unconfirmed";F==="refused"&&(s.callsRefused+=1),i.push(Fn({call:v,agentId:e.agentId,surface:t,session:c.session,execution:F}))}}let l={};for(let c of r){let u=n.cursors[c];u&&(l[c]=u)}return n={...n,cursors:l},{state:n,observations:i,permissions:a,permissionObservations:o,stats:s}}function vc(e){let t=e.permissions.filter(o=>o.granted===!1),n=e.permissions.filter(o=>o.decision==="always"&&o.granted===!0).length,r=e.permissions.filter(o=>o.granted===void 0).length,i=e.permissions.filter(o=>o.unattributed===!0).length,a=[`[VisIQ] sandbox permission gate: ${e.stats.permissionRequests} request(s), ${e.stats.permissionDecisions} answered (${e.stats.permissionsRefused} REFUSED, ${n} standing 'always' grant(s), ${r} unreadable, ${i} unattributed)`];if(t.length>0){let o=new Map;for(let l of t){let c=l.sessionId.length>0?l.sessionId:"unknown session",u=o.get(c)??new Map;u.set(l.toolName,(u.get(l.toolName)??0)+1),o.set(c,u)}let s=[...o].map(([l,c])=>`session ${l}: ${[...c].map(([u,m])=>`${u} \xD7${m}`).join(", ")}`).join("; ");a.push(`[VisIQ] REFUSED by the sandbox's own gate, so these calls did NOT run: ${s} \u2014 ${e.stats.callsRefused} bound to a tool call in this pass`)}return a}async function wc(e,t){let n=await e.readFile(t);if(n===null)return j();try{return Be(JSON.parse(n))}catch{return j()}}async function kc(e,t,n){try{return await e.writeFile(t,JSON.stringify(n)),null}catch(r){return r instanceof Error?r.message:String(r)}}function Ac(e){return e.kind!=="delivered"}function ds(e){let t=e.lastIndexOf(10);return t===-1?e.length:t+1}function Sc(){return{async readdir(e){try{return await is(e)}catch{return[]}},async size(e){try{let t=await Bn(e);return t.isFile()?t.size:null}catch{return null}},async identity(e){try{let t=await Bn(e);return`${t.dev}:${t.ino}`}catch{return}},async read(e,t,n){if(n<=0)return{text:"",bytes:0};let r;try{r=await rs(e,"r");let i=Buffer.alloc(n),{bytesRead:a}=await r.read(i,0,n,t),o=ds(i.subarray(0,a));return{text:i.subarray(0,o).toString("utf8"),bytes:o}}catch{return{text:"",bytes:0}}finally{await r?.close().catch(()=>{})}},async readFile(e){try{return await as(e,"utf8")}catch{return null}},async writeFile(e,t){await ss(ls(e),{recursive:!0}),await os(e,t,"utf8")}}}var Ec="0.1.7";export{Ce as a,ms as b,zn as c,hs as d,gs as e,_s as f,Kn as g,ys as h,bs as i,xe as j,ws as k,Yn as l,ks as m,Ne as n,Jn as o,Qn as p,Xn as q,Te as r,Oe as s,er as t,tr as u,Ss as v,$e as w,nr as x,De as y,ir as z,Me as A,C as B,ar as C,Re as D,ee as E,or as F,Pe as G,j as H,Le as I,Fe as J,je as K,Be as L,Ue as M,B as N,cr as O,ur as P,dr as Q,kn as R,Uo as S,ke as T,Xo as U,es as V,ts as W,Ln as X,ns as Y,Fn as Z,cs as _,us as $,bc as aa,vc as ba,wc as ca,kc as da,Ac as ea,ds as fa,Sc as ga,Ec as ha};
|