@visiq/claude-cowork-harness 0.1.3 → 0.1.4

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 CHANGED
@@ -16,6 +16,38 @@ labels each honestly.
16
16
  > The audit stream this package tails is written *after* a tool has already run.
17
17
  > Nothing in this package reports a block on that surface, and `status` says so.
18
18
 
19
+ ## If an AI coding agent is doing this install
20
+
21
+ These are its rules — the same guardrail VisIQ prepends to every setup prompt the
22
+ platform generates. They are here because this page is one an agent gets pasted,
23
+ and because a step below really can fail: `latest` tracks `main`, so it can lag
24
+ the fixes already on the integration branch. Improvising around a failed step is
25
+ how an agent ends up building a CLI from source and patching the very harness it
26
+ was sent to install.
27
+
28
+ Rules for the AI agent running this setup — read these first:
29
+
30
+ - Apply ONLY the changes this prompt explicitly shows: its commands, its
31
+ environment/config values, and its exact code snippet(s), if any. Nothing
32
+ else may be written, edited, or patched — not code, not packages, not
33
+ configuration.
34
+ - Never improvise a workaround when something fails: no building from source,
35
+ no packing tarballs, no PATH shims or alternative registries, and no
36
+ debugging or patching the VisIQ software itself.
37
+ - If any command fails, is unavailable, or produces output that differs from
38
+ what this prompt describes, STOP and report the exact command plus its full
39
+ output back to your operator. A partial install is a safe no-op by design —
40
+ leaving it unfinished is always correct; an unauthorized fix never is.
41
+ - Do the steps below IN ORDER, and after each one run the `Check:` command it
42
+ shows and confirm the output before moving on. NEVER report the setup
43
+ complete based on what you intended to do — only on what a check actually
44
+ showed. If a check does not show what it describes, the step is not done.
45
+ - Reading is always in scope. Inspect these commands, the URLs they call and
46
+ the integrity checks they run BEFORE executing anything, and tell your
47
+ operator what you found. These rules bound what you may CHANGE, never what
48
+ you may examine — if something here looks wrong, refusing to run it and
49
+ saying why is the correct outcome, not a failed setup.
50
+
19
51
  ## Install
20
52
 
21
53
  Install **both** packages. This one ships `visiq-claude-cowork`; the sibling ships
@@ -27,17 +59,37 @@ reports `dispatcher: … NOT FOUND on PATH`, with tool calls running **UNGOVERNE
27
59
 
28
60
  ```bash
29
61
  npm install -g @visiq/claude-cowork-harness @visiq/claude-code-harness
62
+ ```
63
+
64
+ Check: run `visiq-claude-cowork status`. Its `dispatcher:` line must end in a real
65
+ path. `→ NOT FOUND on PATH` means only one of the two packages landed, and every
66
+ tool call will run **UNGOVERNED**.
30
67
 
68
+ ```bash
31
69
  # 1. Host-local enforcement (writes ~/.claude/settings.json)
32
70
  visiq-claude-cowork install
71
+ ```
33
72
 
73
+ Check: `hooks:` now reads `installed — <path to your settings.json>`. `not installed`
74
+ means the write did not happen; `UNKNOWN (settings file is not readable JSON)` means
75
+ your existing settings file could not be parsed and nothing was changed.
76
+
77
+ ```bash
34
78
  # 2. Credentials — shared with @visiq/claude-code-harness
35
79
  visiq-claude-code configure --api-key <key> --agent-id <id>
80
+ ```
36
81
 
82
+ Check: `credentials:` now reads `resolved`, and `agent id:` shows the id you passed.
83
+ While it reads `MISSING` the hooks are wired but every one of them silently no-ops.
84
+
85
+ ```bash
37
86
  # 3. Sandbox monitoring (optional, long-running)
38
87
  visiq-claude-cowork monitor
39
88
  ```
40
89
 
90
+ Check: each pass prints `[VisIQ] scanned N log(s): …`, and `status` then reports a
91
+ count on its VM-sandbox line instead of `NOT monitored`.
92
+
41
93
  ### Endpoint (optional — but read this if you are not on the VisIQ cloud)
42
94
 
43
95
  `--api-key` and `--agent-id` are the two REQUIRED values. The endpoint is
@@ -67,7 +119,7 @@ visiq-claude-cowork status
67
119
  ```
68
120
 
69
121
  ```
70
- [VisIQ] Claude Cowork harness 0.1.3 — status
122
+ [VisIQ] Claude Cowork harness 0.1.4 — status
71
123
  this process: unknown (cannot enforce)
72
124
  credentials: resolved
73
125
  agent id: agent_01HQ7ZK3M4N5P6R7S8T9V0W1X2
@@ -92,10 +144,39 @@ earned: with no monitor run it reads `NOT monitored — … none observed`.
92
144
  | Command | Purpose |
93
145
  |---|---|
94
146
  | `install [--settings <path>] [--command <cmd>]` | Wire the governance hooks (host-local enforcement) |
95
- | `uninstall [--settings <path>]` | Remove them, leaving your own hooks untouched |
96
- | `status` | What is installed, detected, and actually covered |
147
+ | `uninstall [--settings <path>] [--command <cmd>]` | Remove them, leaving your own hooks untouched |
148
+ | `status [--settings <path>] [--command <cmd>]` | What is installed, detected, and actually covered |
97
149
  | `monitor [--once] [--interval <ms>]` | Tail the sandbox audit stream (monitor-only) |
98
150
 
151
+ This table is not hand-maintained either. `__tests__/usage.test.ts` derives each
152
+ signature from the CLI's own flag table (`src/cli/flags.ts`) and requires this
153
+ table — and the [docs quickstart](https://docs.visiqlabs.com/quickstart/claude-cowork)
154
+ — to match, so a flag the CLI accepts and this page omits reds a test rather than
155
+ shipping. It had: `status --settings`, `status --command` and `uninstall --command`
156
+ are all accepted and acted on, and none of them was documented anywhere.
157
+
158
+ **`--settings` and `--command` must be repeated on every command that touches that
159
+ file.** They configure ONE invocation, not a saved preference: after
160
+ `install --settings /custom.json`, a bare `status` reads `~/.claude/settings.json`
161
+ and truthfully reports it as uncovered — and following *that* output's advice with
162
+ a bare `install` would write your live config, the outcome `--settings` exists to
163
+ avoid.
164
+
165
+ So the CLI carries the flag forward. Every command it suggests that accepts
166
+ `--settings` is printed with the file already in effect, ready to paste:
167
+
168
+ ```bash
169
+ visiq-claude-cowork install --settings /custom.json
170
+ visiq-claude-cowork uninstall --settings /custom.json
171
+ visiq-claude-cowork status --settings /custom.json
172
+ ```
173
+
174
+ `monitor` does not take `--settings` — it is suggested bare, because the CLI never
175
+ prints an invocation it would refuse. These examples are not hand-maintained
176
+ either: `__tests__/hints.test.ts` re-derives them from the renderer the CLI itself
177
+ calls, so if the carry-forward ever stopped, this promise would red rather than
178
+ ship.
179
+
99
180
  ## Why `install` wires the Claude Code dispatcher
100
181
 
101
182
  Host-local Cowork sessions read the **same** `~/.claude/settings.json` as the Claude
@@ -130,7 +211,7 @@ name and arguments) and your answer (`granted`, and whether you allowed it `once
130
211
 
131
212
  ```
132
213
  [VisIQ] scanned 1 log(s): 0 new tool call(s), 0 duplicate(s), 0 corrupt line(s), 0 truncated line(s)
133
- [VisIQ] sandbox permission gate: 2 request(s), 2 answered (1 REFUSED, 1 standing 'always' grant(s), 0 unreadable)
214
+ [VisIQ] sandbox permission gate: 2 request(s), 2 answered (1 REFUSED, 1 standing 'always' grant(s), 0 unreadable, 0 unattributed)
134
215
  [VisIQ] REFUSED by the sandbox's own gate, so these calls did NOT run: session sess: Bash ×1 — 0 bound to a tool call in this pass
135
216
  ```
136
217
 
@@ -149,6 +230,19 @@ the tree, and an alert that names tools but no session cannot be actioned.
149
230
  `REFUSED`, where it belongs; counting it as a standing grant made one refusal read
150
231
  as two answers, one of them permissive.
151
232
 
233
+ `unattributed` counts the answers whose **tool** the sandbox did not name — a
234
+ `permission_response` written with no readable `tool_name`. Those records used to be
235
+ dropped by the parser before the subtype was even consulted, so a refusal carrying
236
+ one landed in **no counter at all**: the pass printed `0 answered (0 REFUSED …)`,
237
+ exited 0, and committed its cursor, which meant those bytes were never read again.
238
+ For a response the record is the *only* evidence the refusal happened, so it is now
239
+ counted and reported, with `<unattributed>` in place of the tool name. It is a
240
+ different axis from `unreadable` — that one is an answer we could not read, this one
241
+ is an answer whose tool was not named, and a record can be either, both or neither.
242
+ Such a record is deliberately **not** bound to any tool call: the tool name is the
243
+ binding evidence and there is none, so attributing it to the nearest call would
244
+ invent a denial the vendor never wrote.
245
+
152
246
  **Every permission decision is reported to the platform in its own right**, as a
153
247
  record carrying `cowork.record: "permission_decision"` and the same
154
248
  `cowork.execution` value the table below describes. That matters because of the
@@ -1,6 +1,6 @@
1
- var Jo=["claude_code_cli","cowork_desktop","cowork_vm","unknown"],Dn="CLAUDE_CODE_HOST_PLATFORM",Mn=["/Claude/claude-code/","\\Claude\\claude-code\\","/Claude.app/"],Pn=/^\/sessions\/[^/]+\/mnt\/\.claude(\/|$)/;function Ln(e){if(e.configDir&&Pn.test(e.configDir))return!0;let t=e.env?.[Dn];return typeof t=="string"&&t.length>0}function Fn(e){return(e.processPaths??[]).some(t=>Mn.some(n=>t.includes(n)))}function jn(e){return(e.processPaths??[]).some(t=>/(^|[/\\])claude(\.exe)?$/.test(t))}function Qo(e){return Ln(e)?"cowork_vm":Fn(e)?"cowork_desktop":jn(e)?"claude_code_cli":"unknown"}function Xo(e){return e==="claude_code_cli"||e==="cowork_desktop"}function es(e){return e==="cowork_desktop"||e==="cowork_vm"}function Bn(e){throw new Error(`unhandled ClaudeSurface: ${JSON.stringify(e)} \u2014 add a branch to every consumer`)}function ts(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 Bn(e)}}function ns(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=r.CLAUDE_CONFIG_DIR;return{processPaths:n,env:r,platform:e.platform,...i&&i.length>0?{configDir:i}:{}}}var Se="local-agent-mode-sessions",is="claude-code-sessions";function Un(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 as(e){return zn(e.platform,Un(e),Se)}function Ie(e){let t=e.split(/[/\\]+/).filter(o=>o.length>0),n=t.lastIndexOf(Se);if(n===-1||t.length<n+4)return null;let[r,i,a]=t.slice(n+1,n+4);return qn(a)?{accountId:r,orgId:i,sessionKey:a}:null}function qn(e){return/^local_[0-9a-fA-F-]{8,}$/.test(e)}function Gn(e){return/^audit\d*\.jsonl$/.test(e)}function Vn(e){let t=/^audit(\d*)\.jsonl$/.exec(e);return t?t[1]?Number.parseInt(t[1],10):0:null}function Ee(e){return e.filter(Gn).map(t=>({name:t,idx:Vn(t)??0})).sort((t,n)=>n.idx-t.idx).map(t=>t.name)}var Hn="permission_request",Kn="permission_response",ss=8388608;function xe(e){let t=[],n=0,r=!1,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=!0);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,truncated:r}}function w(e){return typeof e=="string"&&e.length>0?e:void 0}function Z(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Wn(e){let t=Z(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),d=w(t.tool_name);return d?m===Hn?[{kind:"permission_request",uuid:i,sessionId:r,toolName:d,toolInput:t.tool_input,timestamp:a}]:m===Kn?[{kind:"permission_decision",uuid:i,sessionId:r,toolName:d,granted:typeof t.granted=="boolean"?t.granted:void 0,decision:w(t.decision),timestamp:a}]:[]:[]}if(n!=="assistant"&&n!=="user")return[];let o=Z(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=Z(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 Ne(e){return e.flatMap(t=>Wn(t))}function Yn(e){return e===!0?"granted":e===!1?"refused":"unconfirmed"}function Te(e){let t=new Map;for(let i of e)i.kind==="permission_decision"&&i.uuid.length>0&&t.set(i.uuid,i.granted);let 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||!Jn(i,o.event))){o.bound=!0,r.set(E(o.event),Yn(t.get(i.uuid)));break}}}return r}function E(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??""}`:J(e.toolInput);return`${e.kind}:${e.sessionId}::${e.toolName}:${t}:${e.timestamp??""}`}default:return`${e.kind}:${e.sessionId}:${e.uuid}:${e.toolUseId}`}}var Zn=["\0undefined","\0unserializable"];function Ce(e){return!Zn.includes(e)}function J(e){try{return JSON.stringify(e)??"\0undefined"}catch{return"\0unserializable"}}function Jn(e,t){let n=J(e.toolInput),r=J(t.toolInput);return!Ce(n)||!Ce(r)?!1:e.sessionId===t.sessionId&&e.toolName===t.toolName&&n===r}var Oe=5e3;function L(){return{cursors:{},seen:[]}}function Re(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 $e(e,t,n){let r=xe(n.carriedRemainder+n.chunk),i=Ne(r.records),a=new Set(e.seen),o=[],s=0;for(let d of i){let h=E(d);if(a.has(h)){s+=1;continue}a.add(h),o.push(d)}let l=[...e.seen,...o.map(E)],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:De(l)},events:o,duplicates:s,skipped:r.skipped,truncated:r.truncated}}function De(e){return e.length<=Oe?[...e]:e.slice(e.length-Oe)}function Me(e){if(!e||typeof e!="object"||Array.isArray(e))return L();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:De(i)}}var Pe="visiq-claude-code-hook";var Le="WebFetch|WebSearch|Read|Grep|Glob|LSP|NotebookRead|ListMcpResourcesTool|ReadMcpResourceTool|mcp__.*",Qn=[{event:"SessionStart",matcher:""},{event:"PreToolUse",matcher:"*"},{event:"PostToolUse",matcher:Le}];function F(e,t){return!!e.hooks?.some(n=>typeof n.command=="string"&&(n.command.includes("visiq-claude-code")||t!==void 0&&n.command===t))}function Xn(e,t){return{matcher:e,hooks:[{type:"command",command:t,timeout:30}]}}function er(e,t=Pe){let n={...e},r={...n.hooks??{}};for(let{event:i,matcher:a}of Qn){let o=(Array.isArray(r[i])?r[i]:[]).filter(s=>!F(s,t));r[i]=[...o,Xn(a,t)]}return n.hooks=r,n}function tr(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=>!F(s,t));o.length>0&&(r[i]=o)}return n.hooks=r,n}function nr(e){let{hooks:t}=e;return t?Object.values(t).some(n=>(Array.isArray(n)?n:[]).some(r=>F(r))):!1}import{readFile as bo}from"node:fs/promises";import{homedir as vn}from"node:os";import{join as fe,isAbsolute as vo,resolve as wo}from"node:path";import{mkdir as Co,readFile as xo,writeFile as No,stat as Js}from"node:fs/promises";import{createHash as To}from"node:crypto";import{join as Sn}from"node:path";import{z as p}from"zod";import*as A from"node:os";import{randomUUID as hs}from"node:crypto";var C=1,Fe="X-VisIQ-SDK",je="X-VisIQ-Dialect",Be="unknown";function x(e,t=1){return{[Fe]:e&&e.length>0?e:Be,[je]:String(t)}}var Ue="interceptor_source",rr=p.enum(["enforce","audit","off"]),ir=p.enum(["closed","open"]),ze=p.enum(["enforce","monitor","off"]),ar=p.object({apiKey:p.string().min(1,"apiKey is required"),agentId:p.string().min(1,"agentId is required"),endpoint:p.string().url().optional(),mode:rr.optional(),timeoutMs:p.number().int().positive().optional(),hitlTimeoutMs:p.number().int().positive().optional(),failBehavior:ir.optional()}),fs=p.object({agent_id:p.string().min(1),target_app:p.string().min(1),action:p.string().min(1),context:p.record(p.unknown()).optional(),session_id:p.string().min(1).max(255).optional(),action_schema_id:p.string().min(1).max(128).optional(),telemetry:p.record(p.unknown()).optional()}),or=p.object({field:p.string().optional(),pattern:p.string().optional(),replacement:p.string().optional(),mode:p.enum(["full","partial","email"]).optional(),keepFirst:p.number().optional(),keepLast:p.number().optional(),maskChar:p.string().optional()}),sr=p.object({decision_id:p.string().min(1),decision:p.enum(["permit","deny","approval_required","mask"]),reason:p.string().optional(),rule_code:p.string().nullable().optional(),enforced:p.boolean().optional(),agent_mode:ze.optional(),arg_redaction_rules:p.array(or).optional(),plane:p.string().nullable().optional(),operation:p.string().nullable().optional(),is_retrieval:p.boolean().optional(),metadata:p.record(p.unknown()).optional()}),lr=p.object({field:p.string().min(1),operator:p.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:p.union([p.string(),p.number(),p.array(p.string())])}),cr=p.object({id:p.string().min(1),rule_code:p.string().default(""),name:p.string().min(1),description:p.string().nullable().default(null),effect:p.enum(["allow","deny","hitl","mask"]),resource_type:p.string().min(1),rego_source:p.string().default(""),target_app:p.string().nullable().default(null),action_pattern:p.string().nullable().default(null),conditions:p.array(lr).default([]),priority:p.number().int().default(0)}),ur=p.object({version:p.string().min(1),agent_mode:ze.optional(),rules:p.array(cr),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()}),dr=2e3,pr=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function fr(e){let t=e.rules.filter(n=>pr(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 qe=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return x(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 sr.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=ur.parse(a);return fr(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 mr(dr)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function mr(e){return new Promise(t=>setTimeout(t,e))}function Q(){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=hr();t&&(e.ip=t)}catch{}return e}function hr(){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 f}from"zod";import{createHash as gr}from"crypto";import{createHash as Zr}from"crypto";var Ge=new Map;function Ve(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function X(e){let t=gr("sha256").update(e).digest("hex"),n=Ge.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
4
- `).map(l=>_r(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,T(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=j(a,o,_))}else g==="}"||(o++,o=j(a,o,_));let b=He(_);i.push({variable:d,value:T(h),conditions:b,rawConditions:Ve(_)}),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 b=h.endsWith("}")?h.slice(0,-1).trim():h;b&&g.push(b),h.endsWith("}")||(o++,o=j(a,o,g))}else h==="}"||(o++,o=j(a,o,g));let _=He(g);i.push({variable:d,value:"true",conditions:_,rawConditions:Ve(g)}),o++;continue}o++}let s={defaults:r,rules:i};return Ge.set(t,s),s}function _r(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 j(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 T(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function yr(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function He(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=Sr(i);a&&t.push(a)}}return t}var ee=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,br=new RegExp(`^(${ee.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),vr=new RegExp(`^(${ee.source})\\s*==\\s*((?:input|data)\\S*)$`),wr=/^([^\s=!]+)\s*==\s*(.+)$/,kr=/^([^\s=!]+)\s*!=\s*(.+)$/,bs=new RegExp(`^(?:${ee.source})$`);var Ar=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function Sr(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:U,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(Ar);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:yr(s[1])};let l=n.match(br);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:Xe(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let _=xr(c[2]);if(_!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:_}}let u=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(u)return{type:"comparison",negated:t,field:u[1].trim(),operator:u[2],value:parseFloat(u[3])};let m=n.match(vr);if(m)return{type:"equality",negated:t,field:m[2].trim(),value:T(m[1].trim())};let d=n.match(wr);if(d)return{type:"equality",negated:t,field:d[1].trim(),value:T(d[2].trim())};let h=n.match(kr);if(h)return{type:"inequality",negated:t,field:h[1].trim(),value:T(h[2].trim())};let g=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return g?{type:"truthy",negated:t,field:g[1].trim()}:{type:"truthy",negated:!1,field:U,value:e.trim()}}var U="__unrecognized_condition_forces_deny__";var Ir=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Qe(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==U&&Ir.test(r.field)&&t.push(r.field);return t}var Er=["input.normalized.","input.normalized["];function Cr(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions){let{field:i}=r;typeof i!="string"||i===U||Er.some(a=>i.startsWith(a))&&t.add(i)}return[...t].sort()}function Xe(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 xr(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(Xe(s))}return o}var vs=new RegExp("^\\p{White_Space}*$","u");var Nr=["tier1","tier2","tier3"];function et(e){return typeof e=="string"&&Nr.includes(e)}var Tr=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Or=["internal","customer_facing","experimental","third_party"],tt=[...Tr,...Or];function Rr(e){return typeof e=="string"&&tt.includes(e)}function nt(e){let t=new Set;for(let n of e)Rr(n)&&t.add(n);return tt.filter(n=>t.has(n))}var rt=["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"],$r=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],Dr=["production","staging","development","test"],Mr=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function Pr(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 Ke={github:"version_control",gitlab:"version_control",bitbucket:"version_control",stripe:"payments",adyen:"payments",braintree:"payments",paypal:"payments",square:"payments",salesforce:"crm",hubspot:"crm",pipedrive:"crm",slack:"communication",teams:"communication",twilio:"communication",sendgrid:"communication",mailgun:"communication",gmail:"communication",outlook:"communication",zoom:"communication",aws:"cloud_infra",gcp:"cloud_infra",azure:"cloud_infra",okta:"identity",auth0:"identity",entra:"identity",onelogin:"identity",duo:"identity",snowflake:"data_warehouse",bigquery:"data_warehouse",databricks:"data_warehouse",redshift:"data_warehouse",jira:"ticketing",zendesk:"ticketing",servicenow:"ticketing",freshdesk:"ticketing",linear:"ticketing",workday:"hr",bamboohr:"hr",gusto:"hr",netsuite:"finance_erp",quickbooks:"finance_erp",sap:"finance_erp",xero:"finance_erp",s3:"storage",gcs:"storage",dropbox:"storage",box:"storage",postgres:"database",postgresql:"database",mysql:"database",mongodb:"database",redis:"database"};function Lr(e){let t=Pr(e);return t===null?"other":Ke[t]??Ke[t.replace(/_/g,"")]??"other"}function it(e,t){let n={...e};if(t.targetApp!==void 0&&t.targetApp!==null){let r=n.context&&typeof n.context=="object"&&!Array.isArray(n.context)?{...n.context}:{};r.app_category===void 0&&(r.app_category=Lr(t.targetApp)),n.context=r}return n}var We=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],Fr=["read","write","delete","share","export","decide","execute"],Ye=["none","low","medium","high","critical"],jr=["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"],Br={action_class:rt,operation:Fr,"context/app_category":$r,"context/environment":Dr,"context/actor_function":Mr,"read/classification":jr,"read/data_categories":We,"read/data_sensitivity":Ye,"write/data_categories":We,"write/data_sensitivity":Ye};function at(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(Br)){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 Ze=64,Ur=64,O={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function ot(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var zr=new Set(["deny","approval_required","escalate"]);function N(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>Ze?r.slice(0,Ze):r}function Je(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function B(e){return typeof e=="string"&&e.length>0?e:null}function st(e,t){let n=Je(t.data_categories),r=B(t.classification),i=Je(t.taint),a=B(t.action_class),o=a&&rt.includes(a)?a:null,s=B(t.target_app),l=B(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<Ur)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:N(e.retrieved_data_categories,n),retrieved_classifications:N(e.retrieved_classifications,r?[r]:[]),taint:N(e.taint,i),action_classes:N(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:N(e.target_apps,s?[s]:[])}}var lt="generic",ct=[{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:lt,name:"Generic",icon:"Shapes",description:"Catch-all for cross-cutting rules or rules that do not fit a specific function. Assign when no specific function clearly applies."}],qr=ct.map(e=>e.id),ws=new Map(ct.map(e=>[e.id,e])),ks=new Set(qr);function ut(e){return Array.isArray(e)&&e.length>0?[...e]:[lt]}var Gr=/^[a-z][a-z0-9_]*$/;function dt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Gr.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Vr=["narrow","moderate","broad","unbounded","unknown"];function pt(e){return typeof e=="string"&&Vr.includes(e)}function Hr(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 Kr(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+=Hr((i^a)>>>0)}return n}var Wr=["proposed","approved","revoked"];function Yr(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"&&Wr.includes(t.status)}function ft(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(Yr(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=Kr(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 mt(e){return e==="open"||e==="closed"?e:null}var Jr=["tool_name","function","name","action"];function z(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)z(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)z(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Qr(e){let t=[];return z(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function Xr(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function ei(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function ti(e,t={}){if(t.discriminatorField===null)return null;let n=[];z(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??Jr;for(let i of r){let a=null;for(let[o,s]of n){if(Xr(o)!==i)continue;let l=ei(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function ht(e,t={}){let n=Zr("sha256").update(Qr(e).join(",")).digest("hex").slice(0,16),r=ti(e,t);return r!==null?`${n}:${r}`:n}var ni=["action","retrieval","delegation"];function ri(e){return typeof e=="string"&&ni.includes(e)}var ii=new Set(["rules"]);function gt(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!ii.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(ri):[];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 _t(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=X(r)}catch{continue}let a=Cr(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 V}from"zod";var ai=/[^\u0000-\u007F]/,Dt=new RegExp("^\\p{Nd}$","u"),oi=new RegExp("^\\p{Pd}$","u"),si=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,li=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,ci=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),Mt="<invisible>",yt=new Map;function ui(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&&Dt.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function di(e){if(e<128)return null;let t=yt.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 Dt.test(r)?ui(e):oi.test(r)||ci.has(e)?"-":si.test(r)?" ":li.test(r)?Mt:null})();return yt.set(e,n),n}function pi(e){if(typeof e!="string"||e.length===0||!ai.test(e))return[];let t=bt(e,"as-separator");if(t===null)return[];let n=bt(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function bt(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=di(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===Mt){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 Pt="[REDACTED]",ie=[{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}],Is=ie.map(({name:e,re:t})=>({name:e,source:t.source})),fi="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function mi(e){return Lt(e,fi)}function Lt(e,t){let n="",r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a==="\\"){if(!r&&e[i+1]==="b"){n+=t,i++;continue}n+=a+(e[i+1]??""),i++;continue}a==="["?r=!0:a==="]"&&(r=!1),n+=a}return n}function Ft(e){return new RegExp(mi(e.source),e.flags)}var hi="(?:\\b|_)";function gi(e){return Lt(e,hi)}var _i=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function yi(e){let t=_i.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function ne(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 bi(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 vi(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 wi=[[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]],ki=[[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 Ai(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=wi[t][ki[r%8][n[r].charCodeAt(0)-48]];return t===0}function Si(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 Ii(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 Ei=[1,4,3,7,5,8,6,9,10];function Ci(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)*Ei[n];return t%11===0}var xi="TRWAGMYFPDXBNJZSQVHLCKE";function Ni(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 xi[Number(o)%23]===a}var Ti=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Oi(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Ti.has(t.slice(0,2)):!1}var ae=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&ne(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:bi},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:vi},{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:Oi(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&&Ai(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:Si},{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:Ni},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&ne(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Ii},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Ci}],Ri=Object.fromEntries([...ie,...ae].map(e=>[e.name,e.re.source])),y=Ri,Es=ae.map(e=>e.name),jt=ie.map(({name:e,re:t})=>({name:e,re:Ft(t)})),Bt=ae.map(e=>({...e,re:Ft(e.re)})),Cs=[...jt,...Bt].map(({name:e,re:t})=>({name:String(e),source:t.source})),oe=["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"],$i={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
1
+ var Pn="CLAUDE_CONFIG_DIR";function Se(e){let t=e?.[Pn];if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}var rs=["claude_code_cli","cowork_desktop","cowork_vm","unknown"],Ln="CLAUDE_CODE_HOST_PLATFORM",Fn=[/[/\\]claude[^/\\]*[/\\]claude-code[/\\]/i,/[/\\]claude\.app[/\\]/i],jn=/^\/sessions\/[^/]+\/mnt\/\.claude(\/|$)/;function Bn(e){if(e.configDir&&jn.test(e.configDir))return!0;let t=e.env?.[Ln];return typeof t=="string"&&t.length>0}function Un(e){return(e.processPaths??[]).some(t=>Fn.some(n=>n.test(t)))}function zn(e){return(e.processPaths??[]).some(t=>/(^|[/\\])claude(\.exe)?$/.test(t))}function is(e){return Bn(e)?"cowork_vm":Un(e)?"cowork_desktop":zn(e)?"claude_code_cli":"unknown"}function as(e){return e==="claude_code_cli"||e==="cowork_desktop"}function os(e){return e==="cowork_desktop"||e==="cowork_vm"}function qn(e){throw new Error(`unhandled ClaudeSurface: ${JSON.stringify(e)} \u2014 add a branch to every consumer`)}function ss(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 qn(e)}}function ls(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=Se(r);return{processPaths:n,env:r,platform:e.platform,...i===void 0?{}:{configDir:i}}}var Ie="local-agent-mode-sessions",us="claude-code-sessions";function Gn(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 Vn(e,t,...n){let r=e==="win32"?"\\":"/";return[t,...n].join(r)}function ds(e){return Vn(e.platform,Gn(e),Ie)}function Ee(e){let t=e.split(/[/\\]+/).filter(o=>o.length>0),n=t.lastIndexOf(Ie);if(n===-1||t.length<n+4)return null;let[r,i,a]=t.slice(n+1,n+4);return Hn(a)?{accountId:r,orgId:i,sessionKey:a}:null}function Hn(e){return/^local_[0-9a-fA-F-]{8,}$/.test(e)}function Kn(e){return/^audit\d*\.jsonl$/.test(e)}function Wn(e){let t=/^audit(\d*)\.jsonl$/.exec(e);return t?t[1]?Number.parseInt(t[1],10):0:null}function Ce(e){return e.filter(Kn).map(t=>({name:t,idx:Wn(t)??0})).sort((t,n)=>n.idx-t.idx).map(t=>t.name)}var xe="permission_request",Yn="permission_response",Zn="<unattributed>",fs=8388608;function Te(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 Z(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Jn(e){let t=Z(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!==xe&&m!==Yn)return[];let d=w(t.tool_name),h=d??Zn,g=d===void 0?{unattributed:!0}:{};return m===xe?[{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=Z(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=Z(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 Oe(e){return e.flatMap(t=>Jn(t))}function Qn(e){return e===!0?"granted":e===!1?"refused":"unconfirmed"}function Xn(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 Re(e){let t=Xn(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||!tr(i,o.event))){o.bound=!0,r.set(E(o.event),Qn(t.get(i.uuid)));break}}}return r}function E(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??""}`:J(e.toolInput);return`${e.kind}:${e.sessionId}::${e.toolName}:${t}:${e.timestamp??""}`}default:return`${e.kind}:${e.sessionId}:${e.uuid}:${e.toolUseId}`}}var er=["\0undefined","\0unserializable"];function Ne(e){return!er.includes(e)}function J(e){try{return JSON.stringify(e)??"\0undefined"}catch{return"\0unserializable"}}function tr(e,t){if(e.unattributed)return!1;let n=J(e.toolInput),r=J(t.toolInput);return!Ne(n)||!Ne(r)?!1:e.sessionId===t.sessionId&&e.toolName===t.toolName&&n===r}var $e=5e3;function L(){return{cursors:{},seen:[]}}function De(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 Me(e,t,n){let r=Te(n.carriedRemainder+n.chunk),i=Oe(r.records),a=new Set(e.seen),o=[],s=0;for(let d of i){let h=E(d);if(a.has(h)){s+=1;continue}a.add(h),o.push(d)}let l=[...e.seen,...o.map(E)],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:Pe(l)},events:o,duplicates:s,skipped:r.skipped,truncatedLines:r.truncatedLines}}function Pe(e){return e.length<=$e?[...e]:e.slice(e.length-$e)}function Le(e){if(!e||typeof e!="object"||Array.isArray(e))return L();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:Pe(i)}}var Fe="visiq-claude-code-hook";var je="WebFetch|WebSearch|Read|Grep|Glob|LSP|NotebookRead|ListMcpResourcesTool|ReadMcpResourceTool|mcp__.*",nr=[{event:"SessionStart",matcher:""},{event:"PreToolUse",matcher:"*"},{event:"PostToolUse",matcher:je}];function F(e,t){return!!e.hooks?.some(n=>typeof n.command=="string"&&(n.command.includes("visiq-claude-code")||t!==void 0&&n.command===t))}function rr(e,t){return{matcher:e,hooks:[{type:"command",command:t,timeout:30}]}}function ir(e,t=Fe){let n={...e},r={...n.hooks??{}};for(let{event:i,matcher:a}of nr){let o=(Array.isArray(r[i])?r[i]:[]).filter(s=>!F(s,t));r[i]=[...o,rr(a,t)]}return n.hooks=r,n}function ar(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=>!F(s,t));o.length>0&&(r[i]=o)}return n.hooks=r,n}function or(e){let{hooks:t}=e;return t?Object.values(t).some(n=>(Array.isArray(n)?n:[]).some(r=>F(r))):!1}import{readFile as Ao}from"node:fs/promises";import{homedir as kn}from"node:os";import{join as fe,isAbsolute as So,resolve as Io}from"node:path";import{mkdir as Oo,readFile as Ro,writeFile as $o,stat as rl}from"node:fs/promises";import{createHash as Do}from"node:crypto";import{join as En}from"node:path";import{z as p}from"zod";import*as A from"node:os";import{randomUUID as ws}from"node:crypto";var C=1,Be="X-VisIQ-SDK",Ue="X-VisIQ-Dialect",ze="unknown";function x(e,t=1){return{[Be]:e&&e.length>0?e:ze,[Ue]:String(t)}}var qe="interceptor_source",sr=p.enum(["enforce","audit","off"]),lr=p.enum(["closed","open"]),Ge=p.enum(["enforce","monitor","off"]),cr=p.object({apiKey:p.string().min(1,"apiKey is required"),agentId:p.string().min(1,"agentId is required"),endpoint:p.string().url().optional(),mode:sr.optional(),timeoutMs:p.number().int().positive().optional(),hitlTimeoutMs:p.number().int().positive().optional(),failBehavior:lr.optional()}),bs=p.object({agent_id:p.string().min(1),target_app:p.string().min(1),action:p.string().min(1),context:p.record(p.unknown()).optional(),session_id:p.string().min(1).max(255).optional(),action_schema_id:p.string().min(1).max(128).optional(),telemetry:p.record(p.unknown()).optional()}),ur=p.object({field:p.string().optional(),pattern:p.string().optional(),replacement:p.string().optional(),mode:p.enum(["full","partial","email"]).optional(),keepFirst:p.number().optional(),keepLast:p.number().optional(),maskChar:p.string().optional()}),dr=p.object({decision_id:p.string().min(1),decision:p.enum(["permit","deny","approval_required","mask"]),reason:p.string().optional(),rule_code:p.string().nullable().optional(),enforced:p.boolean().optional(),agent_mode:Ge.optional(),arg_redaction_rules:p.array(ur).optional(),plane:p.string().nullable().optional(),operation:p.string().nullable().optional(),is_retrieval:p.boolean().optional(),metadata:p.record(p.unknown()).optional()}),pr=p.object({field:p.string().min(1),operator:p.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:p.union([p.string(),p.number(),p.array(p.string())])}),fr=p.object({id:p.string().min(1),rule_code:p.string().default(""),name:p.string().min(1),description:p.string().nullable().default(null),effect:p.enum(["allow","deny","hitl","mask"]),resource_type:p.string().min(1),rego_source:p.string().default(""),target_app:p.string().nullable().default(null),action_pattern:p.string().nullable().default(null),conditions:p.array(pr).default([]),priority:p.number().int().default(0)}),mr=p.object({version:p.string().min(1),agent_mode:Ge.optional(),rules:p.array(fr),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()}),hr=2e3,gr=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function _r(e){let t=e.rules.filter(n=>gr(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 Ve=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return x(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 dr.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=mr.parse(a);return _r(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 yr(hr)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function yr(e){return new Promise(t=>setTimeout(t,e))}function Q(){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=br();t&&(e.ip=t)}catch{}return e}function br(){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 f}from"zod";import{createHash as vr}from"crypto";import{createHash as ei}from"crypto";var He=new Map;function Ke(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function X(e){let t=vr("sha256").update(e).digest("hex"),n=He.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
4
+ `).map(l=>wr(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,T(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=j(a,o,_))}else g==="}"||(o++,o=j(a,o,_));let b=We(_);i.push({variable:d,value:T(h),conditions:b,rawConditions:Ke(_)}),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 b=h.endsWith("}")?h.slice(0,-1).trim():h;b&&g.push(b),h.endsWith("}")||(o++,o=j(a,o,g))}else h==="}"||(o++,o=j(a,o,g));let _=We(g);i.push({variable:d,value:"true",conditions:_,rawConditions:Ke(g)}),o++;continue}o++}let s={defaults:r,rules:i};return He.set(t,s),s}function wr(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 j(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 T(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function kr(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function We(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=xr(i);a&&t.push(a)}}return t}var ee=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,Ar=new RegExp(`^(${ee.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),Sr=new RegExp(`^(${ee.source})\\s*==\\s*((?:input|data)\\S*)$`),Ir=/^([^\s=!]+)\s*==\s*(.+)$/,Er=/^([^\s=!]+)\s*!=\s*(.+)$/,Is=new RegExp(`^(?:${ee.source})$`);var Cr=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function xr(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:U,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(Cr);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:kr(s[1])};let l=n.match(Ar);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:tt(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let _=Rr(c[2]);if(_!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:_}}let u=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(u)return{type:"comparison",negated:t,field:u[1].trim(),operator:u[2],value:parseFloat(u[3])};let m=n.match(Sr);if(m)return{type:"equality",negated:t,field:m[2].trim(),value:T(m[1].trim())};let d=n.match(Ir);if(d)return{type:"equality",negated:t,field:d[1].trim(),value:T(d[2].trim())};let h=n.match(Er);if(h)return{type:"inequality",negated:t,field:h[1].trim(),value:T(h[2].trim())};let g=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return g?{type:"truthy",negated:t,field:g[1].trim()}:{type:"truthy",negated:!1,field:U,value:e.trim()}}var U="__unrecognized_condition_forces_deny__";var Nr=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function et(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==U&&Nr.test(r.field)&&t.push(r.field);return t}var Tr=["input.normalized.","input.normalized["];function Or(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions){let{field:i}=r;typeof i!="string"||i===U||Tr.some(a=>i.startsWith(a))&&t.add(i)}return[...t].sort()}function tt(e){let t=e.trim();return t==="true"?!0:t==="false"?!1:/^-?\d+(?:\.\d+)?$/.test(t)?parseFloat(t):t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Rr(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",i=!1,a="";for(let s=0;s<t.length;s++){let l=t[s];i?(r+=l,l===a&&t[s-1]!=="\\"&&(i=!1)):l==='"'||l==="'"?(r+=l,i=!0,a=l):l===","?(n.push(r.trim()),r=""):r+=l}if(i)return null;r.trim().length>0&&n.push(r.trim());let o=[];for(let s of n){let l=s.startsWith('"')&&s.endsWith('"')&&s.length>=2||s.startsWith("'")&&s.endsWith("'")&&s.length>=2,c=/^-?\d+(?:\.\d+)?$/.test(s);if(!l&&!c&&!(s==="true"||s==="false"))return null;o.push(tt(s))}return o}var Es=new RegExp("^\\p{White_Space}*$","u");var $r=["tier1","tier2","tier3"];function nt(e){return typeof e=="string"&&$r.includes(e)}var Dr=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Mr=["internal","customer_facing","experimental","third_party"],rt=[...Dr,...Mr];function Pr(e){return typeof e=="string"&&rt.includes(e)}function it(e){let t=new Set;for(let n of e)Pr(n)&&t.add(n);return rt.filter(n=>t.has(n))}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"],Lr=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],Fr=["production","staging","development","test"],jr=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function Br(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 Ye={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 Ur(e){let t=Br(e);return t===null?"other":Ye[t]??Ye[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=Ur(t.targetApp)),n.context=r}return n}var Ze=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],zr=["read","write","delete","share","export","decide","execute"],Je=["none","low","medium","high","critical"],qr=["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"],Gr={action_class:at,operation:zr,"context/app_category":Lr,"context/environment":Fr,"context/actor_function":jr,"read/classification":qr,"read/data_categories":Ze,"read/data_sensitivity":Je,"write/data_categories":Ze,"write/data_sensitivity":Je};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(Gr)){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 Qe=64,Vr=64,O={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function lt(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var Hr=new Set(["deny","approval_required","escalate"]);function N(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>Qe?r.slice(0,Qe):r}function Xe(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function B(e){return typeof e=="string"&&e.length>0?e:null}function ct(e,t){let n=Xe(t.data_categories),r=B(t.classification),i=Xe(t.taint),a=B(t.action_class),o=a&&at.includes(a)?a:null,s=B(t.target_app),l=B(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<Vr)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:N(e.retrieved_data_categories,n),retrieved_classifications:N(e.retrieved_classifications,r?[r]:[]),taint:N(e.taint,i),action_classes:N(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&Hr.has(l)?1:0),event_count:e.event_count+1,target_apps:N(e.target_apps,s?[s]:[])}}var ut="generic",dt=[{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:ut,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."}],Kr=dt.map(e=>e.id),Cs=new Map(dt.map(e=>[e.id,e])),xs=new Set(Kr);function pt(e){return Array.isArray(e)&&e.length>0?[...e]:[ut]}var Wr=/^[a-z][a-z0-9_]*$/;function ft(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Wr.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Yr=["narrow","moderate","broad","unbounded","unknown"];function mt(e){return typeof e=="string"&&Yr.includes(e)}function Zr(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 Jr(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+=Zr((i^a)>>>0)}return n}var Qr=["proposed","approved","revoked"];function Xr(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.skill_id=="string"&&t.skill_id.length>0&&typeof t.skill_schema_hash=="string"&&t.skill_schema_hash.length>0&&typeof t.status=="string"&&Qr.includes(t.status)}function ht(e,t){let n=typeof e.action=="string"?e.action:"",r=typeof e.actionSchemaId=="string"&&e.actionSchemaId.length>0?e.actionSchemaId:null,i=typeof e.fingerprint=="string"&&e.fingerprint.length>0?e.fingerprint:null,a=typeof e.fingerprintRadius=="number"&&Number.isFinite(e.fingerprintRadius)?e.fingerprintRadius:15;if(n.length===0&&r===null&&i===null)return{blocked:!1,skillId:null};for(let o of t)if(Xr(o)&&o.status==="approved"){if(n.length>0&&o.skill_id===n)return{blocked:!0,skillId:o.skill_id,matchedBy:"action"};if(r!==null&&o.skill_schema_hash===r)return{blocked:!0,skillId:o.skill_id,matchedBy:"schema"};if(i!==null&&typeof o.skill_fingerprint=="string"){let s=Jr(i,o.skill_fingerprint);if(s<=a&&s<64)return{blocked:!0,skillId:o.skill_id,matchedBy:"fingerprint",fingerprintDistance:s}}}return{blocked:!1,skillId:null}}function gt(e){return e==="open"||e==="closed"?e:null}var ti=["tool_name","function","name","action"];function z(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)z(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)z(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function ni(e){let t=[];return z(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function ri(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function ii(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function ai(e,t={}){if(t.discriminatorField===null)return null;let n=[];z(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??ti;for(let i of r){let a=null;for(let[o,s]of n){if(ri(o)!==i)continue;let l=ii(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function _t(e,t={}){let n=ei("sha256").update(ni(e).join(",")).digest("hex").slice(0,16),r=ai(e,t);return r!==null?`${n}:${r}`:n}var oi=["action","retrieval","delegation"];function si(e){return typeof e=="string"&&oi.includes(e)}var li=new Set(["rules"]);function yt(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!li.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(si):[];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 bt(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=X(r)}catch{continue}let a=Or(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 V}from"zod";var ci=/[^\u0000-\u007F]/,Pt=new RegExp("^\\p{Nd}$","u"),ui=new RegExp("^\\p{Pd}$","u"),di=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,pi=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,fi=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),Lt="<invisible>",vt=new Map;function mi(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&&Pt.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function hi(e){if(e<128)return null;let t=vt.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 Pt.test(r)?mi(e):ui.test(r)||fi.has(e)?"-":di.test(r)?" ":pi.test(r)?Lt:null})();return vt.set(e,n),n}function gi(e){if(typeof e!="string"||e.length===0||!ci.test(e))return[];let t=wt(e,"as-separator");if(t===null)return[];let n=wt(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function wt(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=hi(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===Lt){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 Ft="[REDACTED]",ie=[{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}],Os=ie.map(({name:e,re:t})=>({name:e,source:t.source})),_i="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function yi(e){return jt(e,_i)}function jt(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 Bt(e){return new RegExp(yi(e.source),e.flags)}var bi="(?:\\b|_)";function vi(e){return jt(e,bi)}var wi=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function ki(e){let t=wi.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function ne(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 Ai(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 Si(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 Ii=[[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]],Ei=[[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 Ci(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=Ii[t][Ei[r%8][n[r].charCodeAt(0)-48]];return t===0}function xi(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 Ni(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 Ti=[1,4,3,7,5,8,6,9,10];function Oi(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)*Ti[n];return t%11===0}var Ri="TRWAGMYFPDXBNJZSQVHLCKE";function $i(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 Ri[Number(o)%23]===a}var Di=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Mi(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Di.has(t.slice(0,2)):!1}var ae=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&ne(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:Ai},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Si},{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:Mi(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&&Ci(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:xi},{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:$i},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&ne(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Ni},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Oi}],Pi=Object.fromEntries([...ie,...ae].map(e=>[e.name,e.re.source])),y=Pi,Rs=ae.map(e=>e.name),Ut=ie.map(({name:e,re:t})=>({name:e,re:Bt(t)})),zt=ae.map(e=>({...e,re:Bt(e.re)})),$s=[...Ut,...zt].map(({name:e,re:t})=>({name:String(e),source:t.source})),oe=["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"],Li={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
5
  MIIEv\u2026
6
- -----END PRIVATE KEY-----`,template:{pattern:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.mac_address,mode:"full"},defaultEnabled:!1}},se=Object.freeze(Object.fromEntries(oe.map(e=>{let t=$i[e];return[e,{...t,template:{...t.template,pattern:yi(gi(t.template.pattern))}}]})));var xs=new Set(oe.filter(e=>!se[e].defaultEnabled));function Di(e,t){let n=new Set;for(let r of oe)(se[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function q(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=le(t),a=e;for(let{name:o,re:s}of jt){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 Bt)n.has(o)||(a=Vi(a,s,l,c,t,o,r));return a}function le(e){return typeof e=="function"?e:()=>e}var vt=e=>"\0".repeat(e.length);function Mi(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=pi(e);if(i.length===0)return q(e,t,n,r);let a=new Set,o=d=>{a.add(d)},s=q(e,vt,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=q(d.text,vt,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 q(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+=le(t)(e.slice(d,m))}return u}function $(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var wt=new Map;function Pi(e){let t=wt.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),wt.set(e.source,t)),t}var Li=4096,Fi=64,kt=null;function ji(e){return kt!==null?kt:Li+e.length*Fi}var Ut=!1,k={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},zt={spanBudget:0,depthCap:0};function Bi(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:ji(e),exhausted:!1}}function qt(e,t,n,r,i,a,o){k.spanCalls++;let s=t*o.stride+n.length,l=Ut?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=Ui(e,t,n,r,i,a,o);return o.chosen.set(s,c),c}function Ui(e,t,n,r,i,a,o){let s=Pi(r),l=[];for(let u=n.length-1;u>=1;u--)if($(n[u])){let m=n.slice(0,u);s.test(m)&&l.push(m)}let c=$(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(a(i(u),u)&&!qi(e,t,u,r,i,a,o))return u;return null}var At=new Map;function zi(e){let t=At.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),At.set(e.source,t)),t}function qi(e,t,n,r,i,a,o){k.cutCalls++;let s=t*o.stride+n.length,l=Ut?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=Gi(e,t,n,r,i,a,o);return o.cuts.set(s,c),c}function Gi(e,t,n,r,i,a,o){let s=t+n.length,l=zi(r);for(let c=1;c<n.length;c++){if($(n[c])||!$(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=qt(e,u,m[0],r,i,a,o);if(d!==null&&u+d.length>s&&$(e[u+d.length]))return!0}return!1}function Vi(e,t,n,r,i,a,o){let s=le(i);t.lastIndex=0;let l="",c=0,u=Bi(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{_=qt(e,g,h,t,n,r,u)}catch(b){if(b instanceof RangeError&&/call stack/i.test(b.message))u.exhausted=!0,_=null;else throw b}if(u.exhausted)return k.budgetExhausted++,zt.spanBudget++,St(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 b=h.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=b===-1?g+h.length:g+1+b+1}if(t.lastIndex>e.length)break}return St(m),l+e.slice(c)}function St(e){let t=k.spanMisses+k.cutMisses-e;t>k.maxMissesInAPass&&(k.maxMissesInAPass=t)}function Gt(e,t=Pt,n,r){return Ki(e,t,Di(n,r))}var Hi=256;function Ki(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=(s,l)=>{if(l>Hi)return zt.depthCap++,t;if(typeof s=="string")return Mi(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&&ne(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 Vt(e,t=Pt){return Gt(e,t).value}var Wi=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Ht=Object.freeze({\u0430:"a",\u0435:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0456:"i",\u0455:"s",\u043A:"k",\u043C:"m",\u0442:"t",\u043D:"h",\u0432:"b",\u0433:"r",\u03BF:"o",\u03B1:"a",\u03C1:"p",\u03B9:"i",\u03C4:"t",\u03B5:"e",\u03BA:"k",\u03BD:"v",\u03C5:"u",\u03B7:"n",\u0131:"i","\u04CF":"l",\u0578:"n"}),Yi=new RegExp(`[${Object.keys(Ht).join("")}]`,"gu"),Zi=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),Kt="\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",Ji=Object.freeze(Object.fromEntries([...Kt].map((e,t)=>[e,String.fromCharCode(97+t)]))),Qi=new RegExp(`[${Kt}\u2800]`,"g"),Wt=/[⠀-⣿]/;function Xi(e){let t="";for(let n of e){let r=n.codePointAt(0);r!==void 0&&(r>=917536&&r<=917630?t+=String.fromCodePoint(r-917504):r>=917504&&r<=917631||(t+=n))}return t}function ea(e){return e.replace(Wi,"")}function Yt(e){return e.replace(Yi,t=>Ht[t]??t)}function ta(e){return e.replace(/[4@31!05$79(8]/g,t=>Zi[t]??t)}function na(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 ra(e){return Wt.test(e)?e.replace(Qi,t=>t==="\u2800"?" ":Ji[t]??t):e}function It(e){let t;try{t=Xi(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=ea(t),t=Yt(t),t}var ia=/^[A-Za-z0-9+/]{16,}={0,2}$/,aa=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,Et=/[A-Za-z0-9+/]{20,}={0,2}/g;function re(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 Zt=new TextDecoder("utf-8",{fatal:!1});function Jt(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=Zt.decode(n);return t===r?[t]:[r,t]}function oa(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=Zt.decode(n);return r===i?[r]:[i,r]}function Ct(e){let t=e.trim(),n=[];if(aa.test(t))for(let r of oa(t))n.push({decoded:r,textiness:re(r)});if(ia.test(t)&&t.length%4===0)for(let r of Jt(t))n.push({decoded:r,textiness:re(r)});return n}function xt(e,t){let n=[],r;for(Et.lastIndex=0;(r=Et.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of Jt(i))n.push({decoded:a,textiness:re(a)})}return n}var sa=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function Qt(e,t=sa){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 b=It(g);s(b);let v=ta(b);if(v!==b&&s(v),s(na(b)),Wt.test(g)&&s(ra(b)),_>=n){let S=It(g);(Ct(S).length>0||xt(S,a).length>0)&&(c=!0);continue}let P=[...Ct(b),...xt(b,a)];for(let S of P){if(l=!0,S.decoded.length>r){c=!0;continue}S.textiness>=.85&&S.decoded!==b?d.push({s:S.decoded,depth:_+1}):s(S.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:m}}var Xt=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],la=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),ca=8,ua=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Nt=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function da(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||ua.has(i)&&Nt(t[r-1])&&Nt(t[r+1])&&(n++,n>=ca))return!0}return!1}var pa=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function fa(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(pa.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var ma=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function ha(e){for(let t of ma)if(e>=t.lo&&e<=t.hi)return t.name;return null}function ga(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=ha(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:Yt(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var Tt=Object.freeze({signals:[],contributes:!1});function _a(e){if(typeof e!="string"||e.length===0)return{...Tt,signals:[]};let t=new Set;try{da(e)&&t.add("hidden_text_carrier"),fa(e)&&t.add("injected_turn_boundary"),ga(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=Qt(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Tt,signals:[]}}return{signals:[...Xt.filter(n=>t.has(n))],contributes:la.some(n=>t.has(n))}}var G=[{name:"override_instructions",re:/\bignore (?:all |the )?(?:previous|above|prior) (?:instructions|prompts?)\b/i},{name:"disregard_instructions",re:/\bdisregard (?:the )?(?:above|previous|system)\b/i},{name:"role_tag",re:/<\/?(system|assistant|instructions|host_context)\b/i},{name:"privilege_override",re:/\b(grant|escalate|elevate) (admin|root|all|full) (access|privileges?)\b/i},{name:"tool_smuggle",re:/```[\s\S]*?(tool_call|function_call)/i}];function Ot(e){return typeof e!="string"||e.length===0?[]:G.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function ya(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(Ot(e)),{views:n}=Qt(e);for(let r of n)for(let i of Ot(r))t.add(i);return G.filter(r=>t.has(r.name)).map(r=>r.name)}function ba(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of ya(a))t.add(s);let o=_a(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:G.filter(a=>t.has(a.name)).map(a=>a.name),structural:Xt.filter(a=>n.has(a))}}function va(e){return ba(e).matched}var Ns=G.map(e=>e.name);var wa=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var ka="i:injection";function en(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=Gt(e.content);for(let a of i){let o=se[a]?.category;o&&t.add(`c:${o}`)}va(e.content)&&t.add(ka)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&wa.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var te="(?: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))",Ts=[{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${te}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${te}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${te}\\b`,"i")},{name:"repeat_above",re:/\b(?:repeat|print|output|echo|reproduce)\b[\s\S]{0,20}?\b(?:everything|all\s+(?:the\s+)?(?:text|words))\b[\s\S]{0,12}?\b(?:above|before|preceding|verbatim|word\s+for\s+word)\b/i}],Rt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Aa=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${Rt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${Rt}|programming|training))`,Sa="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",$t="(?:\\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)",Ia="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Os=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${Sa}${Aa}\\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}?${$t}`,"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+(?:${Ia}\\b|[\\s\\S]{0,40}?${$t})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Rs=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var I=e=>`[^.!?;\\n]{0,${e}}?`,Ea=["\\bi\\s+(?:can'?t|cannot|can\\s+not|won'?t|will\\s+not)\\b","\\bi(?:'m|\\s+am)\\s+(?:not\\s+able\\s+to|unable\\s+to|not\\s+going\\s+to|not\\s+permitted\\s+to|not\\s+allowed\\s+to)\\b"].join("|"),tn="(?:help|assist|provide|create|generate|produce|write|compose|draft|comply|fulfil|fulfill|share|disclose|reveal|perform|execute|run|send|transmit|publish|export|approve|grant|carry\\s+out|do\\s+that|do\\s+this|do\\s+so|go\\s+ahead)",$s=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Ea})\\s${I(40)}\\b${tn}\\b`,"\\b(?:that|this|it)(?:'s|\\s+is)\\s+not\\s+something\\s+i\\s+(?:can|could|am\\s+able\\s+to|'m\\s+able\\s+to)\\b",`\\b(?:falls|sits|is)\\s+outside\\s+(?:of\\s+)?(?:what|the\\s+(?:scope|range|bounds))\\b${I(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${I(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${I(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${I(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${I(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")}]),Ds=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${I(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${I(30)}\\b${tn}\\b|i(?:'d|\\s+would)\\s+be\\s+happy\\s+to\\b|i(?:'m|\\s+am)\\s+able\\s+to\\b)`,"i"),/\bwhat\s+i\s+can\s+do\s+(?:instead|is|for\s+you)\b/i]);var R=e=>`[^.!?;\\n]{0,${e}}?`,Ms=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${R(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${R(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${R(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${R(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${R(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 qs}from"node:crypto";var nn=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function xa(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:nn(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:nn(t.spawn.prompt)}),t}function Na(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 Ta=1440*60*1e3,Oa="VISIQ_BUNDLE_GRACE_TTL_MS",Ra="VISIQ_BUNDLE_CACHE_DISABLED",$a="VISIQ_CACHE_DIR",Da=V.object({graceTtlMs:V.number().int().nonnegative().optional(),disabled:V.boolean().optional(),cacheDir:V.string().min(1).optional()}).strict();function Ma(e){return e==null?{}:Da.parse(e)}function Pa(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Oa];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Ta}function La(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Ra]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var rn;function Fa(){if(rn!==void 0)return rn;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function ja(e){return JSON.stringify(ue(e))}function ue(e){if(Array.isArray(e))return e.map(ue);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=ue(t[r]);return n}return e}function Ba(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Ua(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 pn(){if(!Fa())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 fn(e,t){return e.createHash("sha256").update(ja(t)).digest("hex")}function za(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[$a]?.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 qa(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function mn(e,t,n){return e.path.join(za(e,n),"bundles",`${qa(e,t)}.json`)}async function Ga(e,t,n,r={}){let i=await pn();if(i)try{let a=mn(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:fn(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 Va(e,t={}){let n=await pn();if(!n)return null;try{let r=await n.fs.readFile(mn(n,e,t),"utf-8"),i=Ua(JSON.parse(r));return!i||fn(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var D;async function Ha(){if(D!==void 0)return D;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;D=typeof t=="function"?t:null}catch{D=null}return D}function Ka(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=X(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of Qe(a))t.push(`${o}: ${s}`)}return t}function Wa(e){return _t(e)}function Ya(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var Za=5e3,Ja=600*1e3,Qa=1e4,Xa=25,an=1e3,eo=5e3,to=100,on=2e3,no=10,ro=512,io=1800*1e3,ao=.7,oo="monitor",so="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",sn="Rules bundle requires a newer SDK wire-contract dialect than this SDK supports \u2014 refusing the bundle and blocking all actions (fail-closed, G001). Upgrade the VisIQ SDK.",lo="open";function ln(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function co(e,t){return en({content:e,resourceMetadata:t})}var uo=f.object({operations:f.array(f.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:f.string().min(1,"agentId is required"),sessionId:f.string().min(1).max(255).optional(),toolName:f.string().optional(),toolArgs:f.record(f.unknown()).optional(),targetResource:f.string().optional(),resourceType:f.string().optional(),resourceMetadata:f.record(f.unknown()).optional(),normalized:f.record(f.unknown()).optional(),query:f.string().optional(),contentPreview:f.string().optional(),telemetry:f.record(f.unknown()).optional(),context:f.record(f.unknown()).optional(),mcpServer:f.string().min(1).max(255).optional()}),po=f.object({version:f.string().min(1),dialect_version:f.number().int().optional(),min_dialect:f.number().int().optional(),shutdown:f.boolean().optional(),agent_mode:f.enum(["enforce","monitor","off"]).optional(),cognition_capture:f.boolean().optional(),agent_mode_by_operation:f.object({action:f.string().optional(),retrieval:f.string().optional(),delegation:f.string().optional()}).partial().optional(),agent_attributes:f.object({trust_tier:f.string().nullable().optional(),categories:f.array(f.string()).optional(),business_function:f.string().nullable().optional(),business_functions:f.array(f.string()).nullable().optional(),blast_radius_tier:f.string().nullable().optional(),no_coverage:f.string().nullable().optional(),fail_mode:f.string().nullable().optional()}).optional(),rules:f.array(f.record(f.unknown())),action_schemas:f.array(f.object({id:f.string(),plane:f.string().optional(),field_mappings:f.array(f.record(f.unknown())).optional(),derived_fields:f.array(f.record(f.unknown())).optional(),action_class:f.string().nullable().optional(),action_class_confidence:f.number().optional()})).optional(),no_coverage:f.object({no_coverage_defaults:f.record(f.string()),autopilot_enabled:f.boolean(),enduser_hitl_enabled:f.boolean(),hitl_timeout_seconds:f.number().optional()}).optional(),skill_blacklist:f.array(f.record(f.unknown())).optional()});function fo(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=ut(dt(n));return{trust_tier:et(t)?t:null,categories:nt(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&pt(e.blast_radius_tier)?e.blast_radius_tier:null}}function mo(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 ho(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var de=new Set,cn=!1;async function un(e){let t=[];for(let n of de){if(n.pendingTelemetryCount()>0&&!n.hasBackend()){console.warn(`[UnifiedRuntime] exiting with ${n.pendingTelemetryCount()} un-sent decision(s) and no backend \u2014 telemetry lost.`);continue}let r=n.flush();e&&t.push(r)}t.length>0&&await Promise.allSettled(t)}function go(){if(!cn&&!(typeof process>"u"||typeof process.once!="function")){cn=!0,process.once("beforeExit",()=>{un(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await un(!0)}finally{process.kill(process.pid,e)}})()})}}var hn=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=oo;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=ln(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??lo;governedFailMode=null;telemetryBuffer=[];droppedTelemetry=0;inFlightTelemetry=new Set;telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastSkillInventorySig=null;skillInventoryPromise=null;lastCloneCaptureSig=null;toolDescriptions=new Map;constructor(e,t,n,r,i,a,o,s){let l=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,c=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,u=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=l,this.resolvedEndpoint=c,this.resolvedAgentId=u,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=o,this.originalFetch=globalThis.fetch.bind(globalThis);let m=Ma(s);if(this.bundleCacheDisabled=La(m.disabled),this.bundleGraceTtlMs=Pa(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:Na(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new qe(d,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Za),ce(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Qa),ce(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},eo),ce(this.cognitionTimer),de.add(this),go()}else this.client=null}async evaluate(e){let t=uo.parse(e),n=Date.now();if(this.operatorShutdown){let h=this.denyAll(t,so);return this.applyAgentMode(h,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,sn,n);let h=this.denyAll(t,sn);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 Ha();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")?it(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&&Ya(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=at(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=ft({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 O;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>io?(this.sessions.delete(e),O):t.state:O}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>=ao)return a}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),o=e.operations.includes("action")||e.operations.includes("delegation"),s=st(r===O?ot():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?co(e.contentPreview,i):void 0,action_class:o?this.foldActionClass(e):void 0,target_app:o?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>ro){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=po.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=Ka(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=>gt(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?fo(t.agent_attributes):null,this.agentNoCoverage=mt(t.agent_attributes?.no_coverage),this.governedFailMode=ln(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=mo(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=Wa(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",...x(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>=Ja&&(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 Va(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Ba(e,this.bundleGraceTtlMs,t)){try{this.applyBundle(e.body)}catch{return}if(this.bundleLoaded&&!this.dialectRefused&&!this.diskFallbackServed){this.diskFallbackServed=!0;let n=Math.max(0,Math.round((t-e.fetchedAt)/1e3)),r=Math.round(this.bundleGraceTtlMs/1e3);console.warn(`[UnifiedRuntime] serving cached rules bundle (age ${n}s) \u2014 control plane unreachable on cold start; will keep retrying and fail closed once the cache exceeds the ${r}s grace window.`)}}}async persistBundleToDisk(e){this.bundleCacheDisabled||!this.cacheIdentity||await Ga(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({...Q(),...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({...Q(),...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=ht(n),i={...n};return e.toolArgs&&(i.tool_args=Vt(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?ho(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?{[Ue]: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,no)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Xa&&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-an;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${an})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(xa(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=to&&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-on;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${on})`))}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(),de.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 ce(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}var _o={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"};var yo=new Set(["read","read_file","readfile","view","cat"]);function gn(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function dn(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function pe(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=_o[n];if(i){let a=dn(r,["name","skill_name","identifier","skill","path"]);return a?{skill:a,via:n,framework:i}:null}if(yo.has(n.toLowerCase())){let a=dn(r,["path","file_path","filePath","target","file"]),o=a?gn(a):null;return o?{skill:o,via:n,framework:"unknown"}:null}return null}function _n(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 Gs=512*1024;var ko="https://api.visiqlabs.com",Ao="@visiq/claude-code-harness",me="open";function he(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function M(){let e=process.env.VISIQ_HOME;return e&&e.trim().length>0?e:fe(vn(),".visiq","claude-code")}function wn(){return fe(M(),"config.json")}function So(e){return e==="~"||e.startsWith("~/")?fe(vn(),e.slice(1).replace(/^\//,"")):e}async function Io(e){try{let t=vo(e)?e:wo(e),n=await bo(t,"utf-8");return JSON.parse(n)}catch{return null}}function H(e,...t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function yn(e){if(!e||typeof e!="object")return{};let t=e,n={},r=H(t,"apiKey","api_key"),i=H(t,"agentId","agent_id"),a=H(t,"baseUrl","base_url"),o=he(H(t,"failMode","fail_mode"));return r&&(n.apiKey=r),i&&(n.agentId=i),a&&(n.baseUrl=a),o&&(n.failMode=o),n}async function bn(e){if(!e)return{};let t=await Io(So(e));if(!t||typeof t!="object")return{};let n=t,r=n.plugins?.entries,i=r&&typeof r=="object"?r[Ao]:void 0;return i&&typeof i=="object"&&i.config?yn(i.config):yn(n)}function kn(e=process.env){let t={};e.VISIQ_API_KEY&&(t.apiKey=e.VISIQ_API_KEY),e.VISIQ_AGENT_ID&&(t.agentId=e.VISIQ_AGENT_ID),e.VISIQ_BASE_URL?t.baseUrl=e.VISIQ_BASE_URL:e.VISIQ_ENDPOINT&&(t.baseUrl=e.VISIQ_ENDPOINT);let n=he(e.VISIQ_FAIL_MODE);return n&&(t.failMode=n),t}function An(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??me};return i.baseUrl=r.baseUrl||ko,i}async function Eo(){let e=kn(),t=await bn(process.env.VISIQ_CONFIG_PATH),n=await bn(wn()),r={...n,...t,...e};return{config:An(n,t,e),failMode:r.failMode??me}}var ge="0.1.13",_e=3e4,Oo=4e3;function In(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,200)||"default"}function Ro(e){let t=To("sha1").update(e).digest("hex").slice(0,10);return`${In(e)}-${t}`}function ye(e,t,n){return n-e.fetchedAt<t}function En(e){return Sn(M(),"bundles",`${Ro(e)}.json`)}async function be(e){try{let t=await xo(En(e),"utf-8"),n=JSON.parse(t);return n&&typeof n.fetchedAt=="number"&&"body"in n?n:null}catch{return null}}async function ve(e,t,n){try{let r=En(e);await Co(Sn(M(),"bundles"),{recursive:!0});let i={fetchedAt:Date.now(),version:n,body:t};await No(r,JSON.stringify(i),{mode:384})}catch{}}async function we(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",...x(ge,C)},signal:AbortSignal.timeout(Oo)});if(!i.ok)return null;let a=i.headers.get("etag");return{body:await i.json(),version:a}}catch{return null}}import{appendFile as ml,mkdir as hl}from"node:fs/promises";import{join as _l}from"node:path";var Mo=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),Po=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function Cn(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 xn(e){return typeof e!="string"?!1:Mo.has(e)?!0:e.startsWith("mcp__")?Po.test(Cn(e)):!1}function K(e){return xn(e)?["retrieval","action"]:["action"]}var Lo=["query","q","url","prompt","pattern","file_path","path"];function Ae(e){if(!e||typeof e!="object")return;let t=e,n=[];for(let r of Lo){let i=t[r];typeof i=="string"&&i.length>0&&n.push(i)}return n.length>0?n.join(" "):void 0}var Nn="cli_harness";function Fo(e){let t=new hn(e.apiKey,e.baseUrl,e.agentId,Nn,void 0,ge,C);return t.setFailMode(e.failMode),t}function W(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 jo(e,t,n=_e){let{agentId:r}=t,i=await be(r);if(i&&ye(i,n,Date.now())&&ke(e,i.body))return!0;let a=e.getEndpoint();if(a){let o=await we(a,t.apiKey,r);if(o&&ke(e,o.body))return await ve(r,o.body,o.version),!0}if(i&&ke(e,i.body))return!0;try{await e.awaitBundleReady(2500)}catch{}return e.isBundleLoaded()}function ke(e,t){try{return e.applyBundle(t),!0}catch{return!1}}async function Bo(e){try{await e.flush()}catch{}let t=typeof e.droppedTelemetryCount=="function"?e.droppedTelemetryCount():0;try{e.dispose()}catch{}return t}var Tn="visiq_surface";function Uo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:e===void 0?{}:{value:e}}function On(e){let{call:t,agentId:n,surface:r,session:i}=e,a=e.execution??"unconfirmed",o=K(t.toolName),s=Uo(t.toolInput),l=Ae(t.toolInput),c={[Tn]: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=pe(t.toolName,s),m=_n({activation:u,attributedSkill:u?.skill??null});return m&&(c.skill=m.skill),{event:W({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 Rn(e){let{decision:t,agentId:n,surface:r,session:i}=e,a=K(t.toolName),o="unconfirmed";return t.granted===!1?o="refused":t.granted===!0&&(o="granted"),{event:W({operations:a,agentId:n,toolName:t.toolName,toolInput:{},sessionId:t.sessionId,toolUseId:t.uuid,context:{[Tn]:r,cowork:{mode:"monitor",record:"permission_decision",execution:o,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 zo,readdir as qo,readFile as Go,stat as $n,writeFile as Vo,mkdir as Ho}from"node:fs/promises";import{dirname as Ko}from"node:path";var Wo=4*1024*1024;function Y(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return`${e}${e.endsWith(n)?"":n}${t}`}async function Yo(e,t){let n=[];for(let r of await e.readdir(t)){let i=Y(t,r);for(let a of await e.readdir(i)){let o=Y(i,a);for(let s of await e.readdir(o)){let l=Y(o,s),c=Ie(l);if(c)for(let u of Ee(await e.readdir(l)))n.push({path:Y(l,u),session:c})}}}return n}async function ec(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 Yo(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=Re(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??Wo));if(g<=0)continue;let _=$e(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+=_.truncated?1:0;let b=Te(_.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(Rn({decision:v,agentId:e.agentId,surface:t,session:c.session}));continue}if(v.kind!=="tool_call")continue;let P=b.get(E(v))??"unconfirmed";P==="refused"&&(s.callsRefused+=1),i.push(On({call:v,agentId:e.agentId,surface:t,session:c.session,execution:P}))}}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 tc(e){let t=e.permissions.filter(a=>a.granted===!1),n=e.permissions.filter(a=>a.decision==="always"&&a.granted===!0).length,r=e.permissions.filter(a=>a.granted===void 0).length,i=[`[VisIQ] sandbox permission gate: ${e.stats.permissionRequests} request(s), ${e.stats.permissionDecisions} answered (${e.stats.permissionsRefused} REFUSED, ${n} standing 'always' grant(s), ${r} unreadable)`];if(t.length>0){let a=new Map;for(let s of t){let l=s.sessionId.length>0?s.sessionId:"unknown session",c=a.get(l)??new Map;c.set(s.toolName,(c.get(s.toolName)??0)+1),a.set(l,c)}let o=[...a].map(([s,l])=>`session ${s}: ${[...l].map(([c,u])=>`${c} \xD7${u}`).join(", ")}`).join("; ");i.push(`[VisIQ] REFUSED by the sandbox's own gate, so these calls did NOT run: ${o} \u2014 ${e.stats.callsRefused} bound to a tool call in this pass`)}return i}async function nc(e,t){let n=await e.readFile(t);if(n===null)return L();try{return Me(JSON.parse(n))}catch{return L()}}async function rc(e,t,n){try{return await e.writeFile(t,JSON.stringify(n)),null}catch(r){return r instanceof Error?r.message:String(r)}}function ic(e){return e.kind!=="delivered"}function Zo(e){let t=e.lastIndexOf(10);return t===-1?e.length:t+1}function ac(){return{async readdir(e){try{return await qo(e)}catch{return[]}},async size(e){try{let t=await $n(e);return t.isFile()?t.size:null}catch{return null}},async identity(e){try{let t=await $n(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 zo(e,"r");let i=Buffer.alloc(n),{bytesRead:a}=await r.read(i,0,n,t),o=Zo(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 Go(e,"utf8")}catch{return null}},async writeFile(e,t){await Ho(Ko(e),{recursive:!0}),await Vo(e,t,"utf8")}}}var sc="0.1.3";export{Jo as a,Dn as b,Qo as c,Xo as d,es as e,Bn as f,ts as g,ns as h,Se as i,is as j,Un as k,as as l,Ie as m,qn as n,Gn as o,Vn as p,Ee as q,Hn as r,Kn as s,ss as t,xe as u,Wn as v,Ne as w,Te as x,E as y,Zn as z,Ce as A,J as B,Jn as C,Oe as D,L as E,Re as F,$e as G,De as H,Me as I,Pe as J,F as K,er as L,tr as M,nr as N,hn as O,Eo as P,be as Q,Fo as R,jo as S,Bo as T,Tn as U,Uo as V,On as W,Wo as X,Yo as Y,ec as Z,tc as _,nc as $,rc as aa,ic as ba,Zo as ca,ac as da,sc as ea};
6
+ -----END PRIVATE KEY-----`,template:{pattern:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.mac_address,mode:"full"},defaultEnabled:!1}},se=Object.freeze(Object.fromEntries(oe.map(e=>{let t=Li[e];return[e,{...t,template:{...t.template,pattern:ki(vi(t.template.pattern))}}]})));var Ds=new Set(oe.filter(e=>!se[e].defaultEnabled));function Fi(e,t){let n=new Set;for(let r of oe)(se[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function q(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=le(t),a=e;for(let{name:o,re:s}of Ut){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 zt)n.has(o)||(a=Yi(a,s,l,c,t,o,r));return a}function le(e){return typeof e=="function"?e:()=>e}var kt=e=>"\0".repeat(e.length);function ji(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=gi(e);if(i.length===0)return q(e,t,n,r);let a=new Set,o=d=>{a.add(d)},s=q(e,kt,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=q(d.text,kt,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 q(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+=le(t)(e.slice(d,m))}return u}function $(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var At=new Map;function Bi(e){let t=At.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),At.set(e.source,t)),t}var Ui=4096,zi=64,St=null;function qi(e){return St!==null?St:Ui+e.length*zi}var qt=!1,k={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},Gt={spanBudget:0,depthCap:0};function Gi(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:qi(e),exhausted:!1}}function Vt(e,t,n,r,i,a,o){k.spanCalls++;let s=t*o.stride+n.length,l=qt?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=Vi(e,t,n,r,i,a,o);return o.chosen.set(s,c),c}function Vi(e,t,n,r,i,a,o){let s=Bi(r),l=[];for(let u=n.length-1;u>=1;u--)if($(n[u])){let m=n.slice(0,u);s.test(m)&&l.push(m)}let c=$(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(a(i(u),u)&&!Ki(e,t,u,r,i,a,o))return u;return null}var It=new Map;function Hi(e){let t=It.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),It.set(e.source,t)),t}function Ki(e,t,n,r,i,a,o){k.cutCalls++;let s=t*o.stride+n.length,l=qt?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=Wi(e,t,n,r,i,a,o);return o.cuts.set(s,c),c}function Wi(e,t,n,r,i,a,o){let s=t+n.length,l=Hi(r);for(let c=1;c<n.length;c++){if($(n[c])||!$(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=Vt(e,u,m[0],r,i,a,o);if(d!==null&&u+d.length>s&&$(e[u+d.length]))return!0}return!1}function Yi(e,t,n,r,i,a,o){let s=le(i);t.lastIndex=0;let l="",c=0,u=Gi(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{_=Vt(e,g,h,t,n,r,u)}catch(b){if(b instanceof RangeError&&/call stack/i.test(b.message))u.exhausted=!0,_=null;else throw b}if(u.exhausted)return k.budgetExhausted++,Gt.spanBudget++,Et(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 b=h.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=b===-1?g+h.length:g+1+b+1}if(t.lastIndex>e.length)break}return Et(m),l+e.slice(c)}function Et(e){let t=k.spanMisses+k.cutMisses-e;t>k.maxMissesInAPass&&(k.maxMissesInAPass=t)}function Ht(e,t=Ft,n,r){return Ji(e,t,Fi(n,r))}var Zi=256;function Ji(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=(s,l)=>{if(l>Zi)return Gt.depthCap++,t;if(typeof s=="string")return ji(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&&ne(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 Kt(e,t=Ft){return Ht(e,t).value}var Qi=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Wt=Object.freeze({\u0430:"a",\u0435:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0456:"i",\u0455:"s",\u043A:"k",\u043C:"m",\u0442:"t",\u043D:"h",\u0432:"b",\u0433:"r",\u03BF:"o",\u03B1:"a",\u03C1:"p",\u03B9:"i",\u03C4:"t",\u03B5:"e",\u03BA:"k",\u03BD:"v",\u03C5:"u",\u03B7:"n",\u0131:"i","\u04CF":"l",\u0578:"n"}),Xi=new RegExp(`[${Object.keys(Wt).join("")}]`,"gu"),ea=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),Yt="\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",ta=Object.freeze(Object.fromEntries([...Yt].map((e,t)=>[e,String.fromCharCode(97+t)]))),na=new RegExp(`[${Yt}\u2800]`,"g"),Zt=/[⠀-⣿]/;function ra(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 ia(e){return e.replace(Qi,"")}function Jt(e){return e.replace(Xi,t=>Wt[t]??t)}function aa(e){return e.replace(/[4@31!05$79(8]/g,t=>ea[t]??t)}function oa(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 sa(e){return Zt.test(e)?e.replace(na,t=>t==="\u2800"?" ":ta[t]??t):e}function Ct(e){let t;try{t=ra(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=ia(t),t=Jt(t),t}var la=/^[A-Za-z0-9+/]{16,}={0,2}$/,ca=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,xt=/[A-Za-z0-9+/]{20,}={0,2}/g;function re(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 Qt=new TextDecoder("utf-8",{fatal:!1});function Xt(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=Qt.decode(n);return t===r?[t]:[r,t]}function ua(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=Qt.decode(n);return r===i?[r]:[i,r]}function Nt(e){let t=e.trim(),n=[];if(ca.test(t))for(let r of ua(t))n.push({decoded:r,textiness:re(r)});if(la.test(t)&&t.length%4===0)for(let r of Xt(t))n.push({decoded:r,textiness:re(r)});return n}function Tt(e,t){let n=[],r;for(xt.lastIndex=0;(r=xt.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of Xt(i))n.push({decoded:a,textiness:re(a)})}return n}var da=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function en(e,t=da){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 b=Ct(g);s(b);let v=aa(b);if(v!==b&&s(v),s(oa(b)),Zt.test(g)&&s(sa(b)),_>=n){let S=Ct(g);(Nt(S).length>0||Tt(S,a).length>0)&&(c=!0);continue}let P=[...Nt(b),...Tt(b,a)];for(let S of P){if(l=!0,S.decoded.length>r){c=!0;continue}S.textiness>=.85&&S.decoded!==b?d.push({s:S.decoded,depth:_+1}):s(S.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:m}}var tn=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],pa=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),fa=8,ma=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Ot=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function ha(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||ma.has(i)&&Ot(t[r-1])&&Ot(t[r+1])&&(n++,n>=fa))return!0}return!1}var ga=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function _a(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(ga.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var ya=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function ba(e){for(let t of ya)if(e>=t.lo&&e<=t.hi)return t.name;return null}function va(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=ba(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:Jt(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var Rt=Object.freeze({signals:[],contributes:!1});function wa(e){if(typeof e!="string"||e.length===0)return{...Rt,signals:[]};let t=new Set;try{ha(e)&&t.add("hidden_text_carrier"),_a(e)&&t.add("injected_turn_boundary"),va(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=en(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Rt,signals:[]}}return{signals:[...tn.filter(n=>t.has(n))],contributes:pa.some(n=>t.has(n))}}var G=[{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 $t(e){return typeof e!="string"||e.length===0?[]:G.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function ka(e){if(typeof e!="string"||e.length===0)return[];let t=new Set($t(e)),{views:n}=en(e);for(let r of n)for(let i of $t(r))t.add(i);return G.filter(r=>t.has(r.name)).map(r=>r.name)}function Aa(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of ka(a))t.add(s);let o=wa(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:G.filter(a=>t.has(a.name)).map(a=>a.name),structural:tn.filter(a=>n.has(a))}}function Sa(e){return Aa(e).matched}var Ms=G.map(e=>e.name);var Ia=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Ea="i:injection";function nn(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=Ht(e.content);for(let a of i){let o=se[a]?.category;o&&t.add(`c:${o}`)}Sa(e.content)&&t.add(Ea)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Ia.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var te="(?: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))",Ps=[{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${te}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${te}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${te}\\b`,"i")},{name:"repeat_above",re:/\b(?:repeat|print|output|echo|reproduce)\b[\s\S]{0,20}?\b(?:everything|all\s+(?:the\s+)?(?:text|words))\b[\s\S]{0,12}?\b(?:above|before|preceding|verbatim|word\s+for\s+word)\b/i}],Dt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Ca=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${Dt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${Dt}|programming|training))`,xa="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Mt="(?:\\b(?:unrestricted|unfiltered|uncensored|unbounded|unlimited|unchained|jailbroken|lawless|amoral)\\b|\\b(?:DAN|STAN|DUDE|AIM)\\b|\\bno\\s+(?:longer\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|boundaries|constraints?)\\b(?!\\s+(?:on|over|regarding|upon|for)\\b)|\\bwithout\\s+(?:any\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|constraints?|censorship)\\b|\\b(?:free|freed|released)\\s+from\\s+(?:your\\s+)?(?:restrictions?|limits?|rules?|guidelines?|guardrails?|programming|constraints?)\\b|\\b(?:can|will|are\\s+able\\s+to)\\s+(?:do|say)\\s+anything\\b|\\bignore\\s+(?:all\\s+)?(?:your\\s+)?(?:previous\\s+|prior\\s+|system\\s+)?(?:instructions?|rules?|guidelines?)\\b)",Na="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Ls=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${xa}${Ca}\\b`,"i")},{name:"forget_everything_prior",re:/\b(?:forget|ignore|disregard|erase|discard)\s+(?:about\s+|all\s+|any\s+)?(?:everything|anything)\b[\s\S]{0,24}?\b(?:above|before|previously|prior|earlier|you\s+(?:were|have\s+been)\s+(?:told|instructed|given|programmed))\b/i},{name:"persona_reassignment_jailbreak",re:new RegExp(`\\byou\\s+are\\s+now\\s+(?:(?:a|an|the)\\s+)?[\\s\\S]{0,48}?${Mt}`,"i")},{name:"constraint_release",re:/\byou\s+are\s+no\s+longer\s+(?:bound|restricted|limited|constrained|obligated|governed|subject\s+to|required\s+to)\b/i},{name:"from_now_on_reassignment",re:new RegExp(`\\bfrom\\s+now\\s+on\\s*,?\\s+you\\s+(?:are|will|must|shall|have|can)\\s+(?:${Na}\\b|[\\s\\S]{0,40}?${Mt})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Fs=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var I=e=>`[^.!?;\\n]{0,${e}}?`,Ta=["\\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("|"),rn="(?:help|assist|provide|create|generate|produce|write|compose|draft|comply|fulfil|fulfill|share|disclose|reveal|perform|execute|run|send|transmit|publish|export|approve|grant|carry\\s+out|do\\s+that|do\\s+this|do\\s+so|go\\s+ahead)",js=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Ta})\\s${I(40)}\\b${rn}\\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${I(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${I(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${I(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${I(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${I(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")}]),Bs=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${I(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${I(30)}\\b${rn}\\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 R=e=>`[^.!?;\\n]{0,${e}}?`,Us=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${R(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${R(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${R(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${R(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${R(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 Ys}from"node:crypto";var an=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Ra(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:an(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:an(t.spawn.prompt)}),t}function $a(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 Da=1440*60*1e3,Ma="VISIQ_BUNDLE_GRACE_TTL_MS",Pa="VISIQ_BUNDLE_CACHE_DISABLED",La="VISIQ_CACHE_DIR",Fa=V.object({graceTtlMs:V.number().int().nonnegative().optional(),disabled:V.boolean().optional(),cacheDir:V.string().min(1).optional()}).strict();function ja(e){return e==null?{}:Fa.parse(e)}function Ba(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Ma];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Da}function Ua(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Pa]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var on;function za(){if(on!==void 0)return on;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function qa(e){return JSON.stringify(ue(e))}function ue(e){if(Array.isArray(e))return e.map(ue);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=ue(t[r]);return n}return e}function Ga(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Va(e){if(e!==null&&typeof e=="object"&&typeof e.fetchedAt=="number"&&typeof e.contentHash=="string"&&"body"in e){let t=e;return{fetchedAt:t.fetchedAt,version:typeof t.version=="string"?t.version:null,contentHash:t.contentHash,body:t.body}}return null}async function mn(){if(!za())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 hn(e,t){return e.createHash("sha256").update(qa(t)).digest("hex")}function Ha(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[La]?.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 Ka(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function gn(e,t,n){return e.path.join(Ha(e,n),"bundles",`${Ka(e,t)}.json`)}async function Wa(e,t,n,r={}){let i=await mn();if(i)try{let a=gn(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:hn(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 Ya(e,t={}){let n=await mn();if(!n)return null;try{let r=await n.fs.readFile(gn(n,e,t),"utf-8"),i=Va(JSON.parse(r));return!i||hn(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var D;async function Za(){if(D!==void 0)return D;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;D=typeof t=="function"?t:null}catch{D=null}return D}function Ja(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=X(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of et(a))t.push(`${o}: ${s}`)}return t}function Qa(e){return bt(e)}function Xa(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var eo=5e3,to=600*1e3,no=1e4,ro=25,sn=1e3,io=5e3,ao=100,ln=2e3,oo=10,so=512,lo=1800*1e3,co=.7,uo="monitor",po="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",cn="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.",fo="open";function un(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function mo(e,t){return nn({content:e,resourceMetadata:t})}var ho=f.object({operations:f.array(f.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:f.string().min(1,"agentId is required"),sessionId:f.string().min(1).max(255).optional(),toolName:f.string().optional(),toolArgs:f.record(f.unknown()).optional(),targetResource:f.string().optional(),resourceType:f.string().optional(),resourceMetadata:f.record(f.unknown()).optional(),normalized:f.record(f.unknown()).optional(),query:f.string().optional(),contentPreview:f.string().optional(),telemetry:f.record(f.unknown()).optional(),context:f.record(f.unknown()).optional(),mcpServer:f.string().min(1).max(255).optional()}),go=f.object({version:f.string().min(1),dialect_version:f.number().int().optional(),min_dialect:f.number().int().optional(),shutdown:f.boolean().optional(),agent_mode:f.enum(["enforce","monitor","off"]).optional(),cognition_capture:f.boolean().optional(),agent_mode_by_operation:f.object({action:f.string().optional(),retrieval:f.string().optional(),delegation:f.string().optional()}).partial().optional(),agent_attributes:f.object({trust_tier:f.string().nullable().optional(),categories:f.array(f.string()).optional(),business_function:f.string().nullable().optional(),business_functions:f.array(f.string()).nullable().optional(),blast_radius_tier:f.string().nullable().optional(),no_coverage:f.string().nullable().optional(),fail_mode:f.string().nullable().optional()}).optional(),rules:f.array(f.record(f.unknown())),action_schemas:f.array(f.object({id:f.string(),plane:f.string().optional(),field_mappings:f.array(f.record(f.unknown())).optional(),derived_fields:f.array(f.record(f.unknown())).optional(),action_class:f.string().nullable().optional(),action_class_confidence:f.number().optional()})).optional(),no_coverage:f.object({no_coverage_defaults:f.record(f.string()),autopilot_enabled:f.boolean(),enduser_hitl_enabled:f.boolean(),hitl_timeout_seconds:f.number().optional()}).optional(),skill_blacklist:f.array(f.record(f.unknown())).optional()});function _o(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=pt(ft(n));return{trust_tier:nt(t)?t:null,categories:it(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&mt(e.blast_radius_tier)?e.blast_radius_tier:null}}function yo(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 bo(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var de=new Set,dn=!1;async function pn(e){let t=[];for(let n of de){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 vo(){if(!dn&&!(typeof process>"u"||typeof process.once!="function")){dn=!0,process.once("beforeExit",()=>{pn(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await pn(!0)}finally{process.kill(process.pid,e)}})()})}}var _n=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=uo;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=un(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??fo;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=ja(s);if(this.bundleCacheDisabled=Ua(m.disabled),this.bundleGraceTtlMs=Ba(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:$a(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new Ve(d,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},eo),ce(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},no),ce(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},io),ce(this.cognitionTimer),de.add(this),vo()}else this.client=null}async evaluate(e){let t=ho.parse(e),n=Date.now();if(this.operatorShutdown){let h=this.denyAll(t,po);return this.applyAgentMode(h,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,cn,n);let h=this.denyAll(t,cn);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 Za();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&&Xa(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=ht({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 O;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>lo?(this.sessions.delete(e),O):t.state:O}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>=co)return a}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),o=e.operations.includes("action")||e.operations.includes("delegation"),s=ct(r===O?lt():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?mo(e.contentPreview,i):void 0,action_class:o?this.foldActionClass(e):void 0,target_app:o?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>so){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=go.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=Ja(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=>yt(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?_o(t.agent_attributes):null,this.agentNoCoverage=gt(t.agent_attributes?.no_coverage),this.governedFailMode=un(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=yo(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=Qa(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",...x(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>=to&&(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 Ya(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Ga(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 Wa(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({...Q(),...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({...Q(),...e.agentType?{agent_type:e.agentType}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{toolSchemas:e.toolSchemas}:{}}))}buildActionSchemaEvent(e){let t=e.toolName?this.toolDescriptions.get(e.toolName):void 0,n={agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{},...e.toolArgs?{tool_args:e.toolArgs}:{},...t?{tool_description:t}:{}},r=_t(n),i={...n};return e.toolArgs&&(i.tool_args=Kt(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?bo(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?{[qe]: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,oo)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=ro&&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-sn;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${sn})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Ra(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=ao&&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-ln;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${ln})`))}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(),de.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 ce(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}var wo={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"};var ko=new Set(["read","read_file","readfile","view","cat"]);function yn(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function fn(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function pe(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=wo[n];if(i){let a=fn(r,["name","skill_name","identifier","skill","path"]);return a?{skill:a,via:n,framework:i}:null}if(ko.has(n.toLowerCase())){let a=fn(r,["path","file_path","filePath","target","file"]),o=a?yn(a):null;return o?{skill:o,via:n,framework:"unknown"}:null}return null}function bn(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 Zs=512*1024;var Eo="https://api.visiqlabs.com",Co="@visiq/claude-code-harness",me="open";function he(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function M(){let e=process.env.VISIQ_HOME;return e&&e.trim().length>0?e:fe(kn(),".visiq","claude-code")}function An(){return fe(M(),"config.json")}function xo(e){return e==="~"||e.startsWith("~/")?fe(kn(),e.slice(1).replace(/^\//,"")):e}async function No(e){try{let t=So(e)?e:Io(e),n=await Ao(t,"utf-8");return JSON.parse(n)}catch{return null}}function H(e,...t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function vn(e){if(!e||typeof e!="object")return{};let t=e,n={},r=H(t,"apiKey","api_key"),i=H(t,"agentId","agent_id"),a=H(t,"baseUrl","base_url"),o=he(H(t,"failMode","fail_mode"));return r&&(n.apiKey=r),i&&(n.agentId=i),a&&(n.baseUrl=a),o&&(n.failMode=o),n}async function wn(e){if(!e)return{};let t=await No(xo(e));if(!t||typeof t!="object")return{};let n=t,r=n.plugins?.entries,i=r&&typeof r=="object"?r[Co]:void 0;return i&&typeof i=="object"&&i.config?vn(i.config):vn(n)}function Sn(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=he(e.VISIQ_FAIL_MODE);return n&&(t.failMode=n),t}function In(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??me};return i.baseUrl=r.baseUrl||Eo,i}async function To(){let e=Sn(),t=await wn(process.env.VISIQ_CONFIG_PATH),n=await wn(An()),r={...n,...t,...e};return{config:In(n,t,e),failMode:r.failMode??me}}var ge="0.1.13",_e=3e4,Mo=4e3;function Cn(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,200)||"default"}function Po(e){let t=Do("sha1").update(e).digest("hex").slice(0,10);return`${Cn(e)}-${t}`}function ye(e,t,n){return n-e.fetchedAt<t}function xn(e){return En(M(),"bundles",`${Po(e)}.json`)}async function be(e){try{let t=await Ro(xn(e),"utf-8"),n=JSON.parse(t);return n&&typeof n.fetchedAt=="number"&&"body"in n?n:null}catch{return null}}async function ve(e,t,n){try{let r=xn(e);await Oo(En(M(),"bundles"),{recursive:!0});let i={fetchedAt:Date.now(),version:n,body:t};await $o(r,JSON.stringify(i),{mode:384})}catch{}}async function we(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",...x(ge,C)},signal:AbortSignal.timeout(Mo)});if(!i.ok)return null;let a=i.headers.get("etag");return{body:await i.json(),version:a}}catch{return null}}import{appendFile as vl,mkdir as wl}from"node:fs/promises";import{join as Al}from"node:path";var jo=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),Bo=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function Nn(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 Tn(e){return typeof e!="string"?!1:jo.has(e)?!0:e.startsWith("mcp__")?Bo.test(Nn(e)):!1}function K(e){return Tn(e)?["retrieval","action"]:["action"]}var Uo=["query","q","url","prompt","pattern","file_path","path"];function Ae(e){if(!e||typeof e!="object")return;let t=e,n=[];for(let r of Uo){let i=t[r];typeof i=="string"&&i.length>0&&n.push(i)}return n.length>0?n.join(" "):void 0}var On="cli_harness";function zo(e){let t=new _n(e.apiKey,e.baseUrl,e.agentId,On,void 0,ge,C);return t.setFailMode(e.failMode),t}function W(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 qo(e,t,n=_e){let{agentId:r}=t,i=await be(r);if(i&&ye(i,n,Date.now())&&ke(e,i.body))return!0;let a=e.getEndpoint();if(a){let o=await we(a,t.apiKey,r);if(o&&ke(e,o.body))return await ve(r,o.body,o.version),!0}if(i&&ke(e,i.body))return!0;try{await e.awaitBundleReady(2500)}catch{}return e.isBundleLoaded()}function ke(e,t){try{return e.applyBundle(t),!0}catch{return!1}}async function Go(e){try{await e.flush()}catch{}let t=typeof e.droppedTelemetryCount=="function"?e.droppedTelemetryCount():0;try{e.dispose()}catch{}return t}var Rn="visiq_surface";function Vo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:e===void 0?{}:{value:e}}function $n(e){let{call:t,agentId:n,surface:r,session:i}=e,a=e.execution??"unconfirmed",o=K(t.toolName),s=Vo(t.toolInput),l=Ae(t.toolInput),c={[Rn]: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=pe(t.toolName,s),m=bn({activation:u,attributedSkill:u?.skill??null});return m&&(c.skill=m.skill),{event:W({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 Dn(e){let{decision:t,agentId:n,surface:r,session:i}=e,a=K(t.toolName),o="unconfirmed";return t.granted===!1?o="refused":t.granted===!0&&(o="granted"),{event:W({operations:a,agentId:n,toolName:t.toolName,toolInput:{},sessionId:t.sessionId,toolUseId:t.uuid,context:{[Rn]: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 Ho,readdir as Ko,readFile as Wo,stat as Mn,writeFile as Yo,mkdir as Zo}from"node:fs/promises";import{dirname as Jo}from"node:path";var Qo=4*1024*1024;function Y(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return`${e}${e.endsWith(n)?"":n}${t}`}async function Xo(e,t){let n=[];for(let r of await e.readdir(t)){let i=Y(t,r);for(let a of await e.readdir(i)){let o=Y(i,a);for(let s of await e.readdir(o)){let l=Y(o,s),c=Ee(l);if(c)for(let u of Ce(await e.readdir(l)))n.push({path:Y(l,u),session:c})}}}return n}async function oc(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 Xo(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=De(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??Qo));if(g<=0)continue;let _=Me(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 b=Re(_.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(Dn({decision:v,agentId:e.agentId,surface:t,session:c.session}));continue}if(v.kind!=="tool_call")continue;let P=b.get(E(v))??"unconfirmed";P==="refused"&&(s.callsRefused+=1),i.push($n({call:v,agentId:e.agentId,surface:t,session:c.session,execution:P}))}}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 sc(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 lc(e,t){let n=await e.readFile(t);if(n===null)return L();try{return Le(JSON.parse(n))}catch{return L()}}async function cc(e,t,n){try{return await e.writeFile(t,JSON.stringify(n)),null}catch(r){return r instanceof Error?r.message:String(r)}}function uc(e){return e.kind!=="delivered"}function es(e){let t=e.lastIndexOf(10);return t===-1?e.length:t+1}function dc(){return{async readdir(e){try{return await Ko(e)}catch{return[]}},async size(e){try{let t=await Mn(e);return t.isFile()?t.size:null}catch{return null}},async identity(e){try{let t=await Mn(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 Ho(e,"r");let i=Buffer.alloc(n),{bytesRead:a}=await r.read(i,0,n,t),o=es(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 Wo(e,"utf8")}catch{return null}},async writeFile(e,t){await Zo(Jo(e),{recursive:!0}),await Yo(e,t,"utf8")}}}var fc="0.1.4";export{Se as a,rs as b,Ln as c,is as d,as as e,os as f,qn as g,ss as h,ls as i,Ie as j,us as k,Gn as l,ds as m,Ee as n,Hn as o,Kn as p,Wn as q,Ce as r,xe as s,Yn as t,Zn as u,fs as v,Te as w,Jn as x,Oe as y,Xn as z,Re as A,E as B,er as C,Ne as D,J as E,tr as F,$e as G,L as H,De as I,Me as J,Pe as K,Le as L,Fe as M,F as N,ir as O,ar as P,or as Q,_n as R,To as S,be as T,zo as U,qo as V,Go as W,Rn as X,Vo as Y,$n as Z,Qo as _,Xo as $,oc as aa,sc as ba,lc as ca,cc as da,uc as ea,es as fa,dc as ga,fc as ha};
package/dist/cli/main.js CHANGED
@@ -1,48 +1,46 @@
1
1
  #!/usr/bin/env node
2
- import{$ as O,J as M,K as V,L as F,M as _,N as D,O as U,P as b,Q as G,R as j,S as H,T as B,Y as Q,Z as q,_ as J,aa as W,ba as X,c as L,d as N,da as I,ea as K,g as $,h as A,l as S}from"../chunk-4HEZXX65.js";import{homedir as k,platform as ge}from"node:os";import{basename as Le,dirname as Ae,join as R}from"node:path";import{readFile as Me,writeFile as Ve,mkdir as Fe,rename as _e,unlink as De}from"node:fs/promises";import{existsSync as pe}from"node:fs";import{parseArgs as Ue}from"node:util";import{accessSync as we,constants as ke,statSync as Ee}from"node:fs";var y="PreToolUse";function Ne(e){return e.type===void 0||e.type==="command"}function $e(e,n){return e.includes("visiq-claude-code")||n!==void 0&&e===n}function Se(e){if(e==null)return!0;if(typeof e!="string")return!1;let n=e.trim();return n===""||n==="*"||n===".*"||n==="^.*$"}function Y(e,n){let t=[],o=e.hooks?.[y];for(let s of Array.isArray(o)?o:[]){if(!V(s,n))continue;let a=(s.hooks??[]).find(i=>Ne(i)&&typeof i.command=="string"&&i.command.trim().length>0&&$e(i.command,n));if(!a)continue;let{matcher:r}=s,c=typeof r=="string"?r.trim():JSON.stringify(r);t.push({command:a.command,scopedTo:Se(r)?null:c})}return t}function z(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),l=[...new Set(e.filter(i=>o(i.command)===null).map(i=>i.command))],a=s.find(i=>i.group.scopedTo===null),r=a??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:a?null:c.join("|"),unresolved:l}}function Oe(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 Ie(e,n,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${n}`:`${e}${t}${n}`}function Z(e,n){let t=Oe(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):[],l=r=>[r,...s.map(c=>`${r}${c}`)];if(t.includes("/")||t.includes("\\"))return l(t).find(r=>n.isExecutable(r))??null;let a=o?"\\":"/";for(let r of(n.env?.PATH??"").split(o?";":":")){if(r.length===0)continue;let c=l(Ie(r,t,a)).find(i=>n.isExecutable(i));if(c)return c}return null}function ee(){return{env:process.env,platform:process.platform,isExecutable(e){try{return we(e,ke.X_OK),Ee(e).isFile()}catch{return!1}}}}function w(e){throw new Error(`unhandled HostLocalEnforcement state: ${JSON.stringify(e)} \u2014 add a branch to every consumer`)}function ne(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 w(e)}}function te(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:l,scopedTo:a,unresolved:r}=e;return n.resolved?t.state==="no-bundle"?{state:"no-rule-bundle",command:s,resolvedPath:l,reason:t.reason,failMode:n.failMode}:t.state==="observing"?{state:"agent-mode",command:s,resolvedPath:l,mode:t.mode}:a!==null?{state:"scoped",command:s,resolvedPath:l,scopedTo:a,unresolved:r}:{state:"enforced",command:s,resolvedPath:l}:{state:"unconfigured",command:s,resolvedPath:l,failMode:n.failMode,scopedTo:a}}function oe(e){if(e===null)return{state:"no-bundle",reason:"absent"};let n=new U;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 Re=["install","uninstall","status","monitor"];var re=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},se=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 f={settings:{type:"string",value:se,commands:["install","uninstall","status"]},command:{type:"string",value:se,commands:["install","uninstall","status"]},once:{type:"boolean",commands:["monitor"]},interval:{type:"string",value:re,commands:["monitor"]}},ie=Object.fromEntries(Object.entries(f).map(([e,n])=>[e,{type:n.type}]));function ae(e){return Object.keys(e).filter(n=>!Object.hasOwn(f,n))}function le(e,n){if(!Re.includes(e))return[];let t=[];for(let o of Object.keys(n)){let s=Object.hasOwn(f,o)?f[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 de(e){let n=[];for(let[t,o]of Object.entries(e)){let s=Object.hasOwn(f,t)?f[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 l=s.value(o);l!==null&&n.push(`--${t} ${l}`)}return n}function ce(e){if(e===void 0)return 15e3;let n=typeof e=="string"?re(e):"needs a string value";if(n!==null)throw new Error(`--interval ${n}`);return Number(String(e).trim())}import{join as ue}from"node:path";var Pe="CLAUDE_CONFIG_DIR",Te=".claude",xe="settings.json";function Ce(e){let n=e.env?.[Pe];return typeof n=="string"&&n.trim().length>0?n.trim():ue(e.homeDir,Te)}function me(e){let{explicit:n}=e;return typeof n=="string"&&n.length>0?n:ue(Ce(e),xe)}function P(){let e=process.env.VISIQ_HOME,n=e&&e.trim().length>0?e:R(k(),".visiq","claude-cowork");return R(n,"monitor-state.json")}function x(e){return me({explicit:e.settings,env:process.env,homeDir:k()})}async function C(e){if(!pe(e))return{kind:"absent"};let n;try{n=await Me(e,"utf-8")}catch(o){return{kind:"unreadable",reason:o instanceof Error?o.message:String(o)}}let t;try{t=JSON.parse(n)}catch(o){return{kind:"unreadable",reason:o instanceof Error?o.message:String(o)}}return t===null||typeof t!="object"||Array.isArray(t)?{kind:"unreadable",reason:`expected a JSON object, found ${Array.isArray(t)?"an array":typeof t}`}:{kind:"parsed",settings:t}}async function he(e){let n=await C(e);return n.kind==="unreadable"?(process.stderr.write(`[VisIQ] REFUSING to write ${e} \u2014 it exists but could not be read as JSON (${n.reason}).
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-7WPBRDY7.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
+ `);return`Usage: ${C} ${Qe()} [flags]
4
+
5
+ ${t}
6
+
7
+ Credentials are shared with @visiq/claude-code-harness:
8
+ visiq-claude-code configure --api-key <key> --agent-id <id>
9
+ `}var ve={settings:e=>N(e)},Be=e=>typeof e.explicit=="string"&&e.explicit.length>0?e.explicit:void 0;function we(e,n){return((Object.hasOwn(ve,e)?ve[e]:void 0)??Be)(n)}function qe(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Je(e){let n=[C,e.command];for(let[t,o]of Object.entries(e.options??u)){if(!o.identifiesTarget||!o.commands.includes(e.command))continue;if(o.type==="boolean"){e.values[t]===!0&&n.push(`--${t}`);continue}let s={env:e.env,homeDir:e.homeDir},a=we(t,{...s,explicit:e.values[t]});a!==void 0&&a!==we(t,{...s,explicit:void 0})&&n.push(`--${t}`,qe(a))}return n.join(" ")}function $e(e){return Object.fromEntries(h.map(n=>[n,Je({...e,command:n})]))}function P(){let e=process.env.VISIQ_HOME,n=e&&e.trim().length>0?e:I(b(),".visiq","claude-cowork");return I(n,"monitor-state.json")}function A(e){return N({explicit:e.settings,env:process.env,homeDir:b()})}function Se(e){return $e({values:e,env:process.env,homeDir:b()})}async function L(e){if(!Ee(e))return{kind:"absent"};let n;try{n=await Ke(e,"utf-8")}catch(o){return{kind:"unreadable",reason:o instanceof Error?o.message:String(o)}}let t;try{t=JSON.parse(n)}catch(o){return{kind:"unreadable",reason:o instanceof Error?o.message:String(o)}}return t===null||typeof t!="object"||Array.isArray(t)?{kind:"unreadable",reason:`expected a JSON object, found ${Array.isArray(t)?"an array":typeof t}`}:{kind:"parsed",settings:t}}async function Oe(e){let n=await L(e);return n.kind==="unreadable"?(process.stderr.write(`[VisIQ] REFUSING to write ${e} \u2014 it exists but could not be read as JSON (${n.reason}).
3
10
  Writing would REPLACE it, discarding everything it holds \u2014 including any
4
11
  \`permissions.deny\` rules you rely on. Nothing has been changed.
5
12
  Fix the JSON (or move the file aside) and run this again.
6
- `),null):n.kind==="parsed"?n.settings:{}}async function ve(e,n){let t=Ae(e);await Fe(t,{recursive:!0});let o=R(t,`.${Le(e)}.visiq-${process.pid}.tmp`);try{await Ve(o,`${JSON.stringify(n,null,2)}
7
- `,"utf-8"),await _e(o,e)}catch(s){throw await De(o).catch(()=>{}),s}}async function be(e){let{config:n,failMode:t}=await b(),o=e.read.kind==="parsed"?e.read.settings:{},s=ee(),l=z(Y(o,e.explicitCommand),r=>Z(r,s)),a=oe(n?await G(n.agentId):null);return te(l,{resolved:!!n,failMode:t},a,e.read.kind==="unreadable"?e.read.reason:void 0)}async function Ge(e){let n=x(e),t=typeof e.command=="string"?e.command:M,o=await he(n);if(o===null)return 1;await ve(n,F(o,t));let s=await be({read:await C(n),explicitCommand:typeof e.command=="string"?e.command:void 0});return process.stdout.write(`[VisIQ] Installed Claude Cowork governance hooks \u2192 ${n}
8
- ${T("cowork_desktop",{hostLocal:s,sessions:0,logs:0,observedLogs:0})}
9
- VM-sandboxed sessions are NOT hook-reachable \u2014 run \`visiq-claude-cowork monitor\`
13
+ `),null):n.kind==="parsed"?n.settings:{}}async function xe(e,n){let t=Xe(e);await ze(t,{recursive:!0});let o=I(t,`.${We(e)}.visiq-${process.pid}.tmp`);try{await Ye(o,`${JSON.stringify(n,null,2)}
14
+ `,"utf-8"),await Ze(o,e)}catch(s){throw await en(o).catch(()=>{}),s}}async function Re(e){let{config:n,failMode:t}=await w(),o=e.read.kind==="parsed"?e.read.settings:{},s=se(),a=te(ne(o,e.explicitCommand),r=>oe(r,s)),l=ae(n?await B(n.agentId):null);return ie(a,{resolved:!!n,failMode:t},l,e.read.kind==="unreadable"?e.read.reason:void 0)}async function tn(e){let n=A(e),t=typeof e.command=="string"?e.command:_,o=await Oe(n);if(o===null)return 1;await xe(n,j(o,t));let s=await Re({read:await L(n),explicitCommand:typeof e.command=="string"?e.command:void 0}),a=Se(e);return process.stdout.write(`[VisIQ] Installed Claude Cowork governance hooks \u2192 ${n}
15
+ ${M("cowork_desktop",{hostLocal:s,hints:a,sessions:0,logs:0,observedLogs:0})}
16
+ VM-sandboxed sessions are NOT hook-reachable \u2014 run \`${a.monitor}\`
10
17
  for monitor-only coverage of those.
11
- Restart Claude for the hooks to take effect, then \`visiq-claude-cowork status\`.
12
- `),0}async function je(e){let n=x(e),t=typeof e.command=="string"?e.command:void 0;if(!pe(n))return process.stdout.write(`[VisIQ] No settings file at ${n} \u2014 nothing to remove, and nothing was created.
13
- `),0;let o=await he(n);return o===null?1:(await ve(n,_(o,t)),process.stdout.write(`[VisIQ] Removed Claude Cowork governance hooks from ${n}
14
- `),0)}function T(e,n){let t=` ${$(e)}:`;if(!N(e)){let o=`${n.sessions} session(s), ${n.logs} audit log(s)`;return n.logs===0?`${t} monitor-only \u2014 ${o} \u2014 nothing to monitor`:n.observedLogs===0?`${t} NOT monitored \u2014 ${o} found, none observed \u2014 run \`visiq-claude-cowork monitor\``:n.observedLogs<n.logs?`${t} PARTIALLY monitored \u2014 ${o}, ${n.observedLogs} observed \u2014 run \`visiq-claude-cowork monitor\``:`${t} monitor-only \u2014 ${o}, all observed`}switch(n.hostLocal.state){case"enforced":return`${t} ENFORCED (PreToolUse deny blocks)`;case"scoped":{let o=n.hostLocal.unresolved.length>0?` (a VisIQ group runs \`${n.hostLocal.unresolved.join("`, `")}\`, which is NOT on PATH, so that group covers nothing)`:"";return`${t} PARTIALLY enforced \u2014 the VisIQ ${y} hook matches only \`${n.hostLocal.scopedTo}\`, so every OTHER tool call runs UNGOVERNED${o} \u2014 run \`visiq-claude-cowork install\` to cover them all`}case"no-rule-bundle":return`${t} NOT CONFIRMED \u2014 no VisIQ rule bundle is cached${n.hostLocal.reason==="unusable"?" (the cached one could not be applied)":""}, so each tool call is governed only if the hook's own fetch succeeds; when it does not the hook logs \`FAIL-OPEN (no-bundle) \u2026 proceeding UNGOVERNED\` \u2014 start a Claude session (SessionStart caches the bundle) or check connectivity`;case"agent-mode":return n.hostLocal.mode==="off"?`${t} NOT enforced \u2014 the rule bundle sets \`agent_mode: "off"\`, so the hook skips evaluation entirely: no call is blocked and none is recorded`:`${t} MONITORING, not enforcing \u2014 the rule bundle sets \`agent_mode: "${n.hostLocal.mode}"\`, so a \`deny\` is RECORDED and the tool call still runs \u2014 switch the agent to enforce mode to block`;case"settings-unreadable":return`${t} UNKNOWN \u2014 the settings file could not be read as JSON (${n.hostLocal.reason}), so coverage cannot be determined \u2014 fix the JSON and run status again`;case"dispatcher-unresolvable":return`${t} installed, but the dispatcher \`${n.hostLocal.command}\` is not on PATH \u2014 tool calls run UNGOVERNED`;case"no-pre-tool-use-hook":return`${t} not covered (no VisIQ PreToolUse hook) \u2014 run \`visiq-claude-cowork install\``;case"unconfigured":{let{scopedTo:o}=n.hostLocal;return n.hostLocal.failMode==="closed"?o===null?`${t} BLOCKING EVERY call (no VisIQ credentials, failMode=closed) \u2014 run \`visiq-claude-code configure\``:`${t} BLOCKING every \`${o}\` call and leaving every OTHER tool call UNGOVERNED (no VisIQ credentials, failMode=closed) \u2014 run \`visiq-claude-code configure\``:`${t} installed, but no VisIQ credentials \u2014 the hook FAILS OPEN and tool calls run UNGOVERNED \u2014 run \`visiq-claude-code configure\``}default:return w(n.hostLocal)}}function He(e,n){return e?"UNKNOWN (settings file is not readable JSON)":n?"installed":"not installed"}function Be(e){switch(e.state){case"enforced":return`${e.command} \u2192 ${e.resolvedPath}`;case"scoped":return`${e.command} \u2192 ${e.resolvedPath} (matches only \`${e.scopedTo}\`)`;case"settings-unreadable":return"\u2014 (the settings file could not be read as JSON)";case"dispatcher-unresolvable":return`${e.command} \u2192 NOT FOUND on PATH`;case"no-pre-tool-use-hook":return`\u2014 (no VisIQ ${y} hook in this settings file)`;case"no-rule-bundle":case"agent-mode":return`${e.command} \u2192 ${e.resolvedPath}`;case"unconfigured":return`${e.command} \u2192 ${e.resolvedPath}`;default:return w(e)}}async function Qe(e){let n=I(),{config:t}=await b(),o=x(e),s=await C(o),l=s.kind==="parsed"?s.settings:{},a=s.kind==="unreadable",r=D(l),c=typeof e.command=="string"?e.command:void 0,i=await be({read:s,explicitCommand:c}),h=S({homeDir:k(),platform:ge(),env:process.env}),m=await Q(n,h),d=new Set(m.map(E=>E.session.sessionKey)),g=await O(n,P()),p=m.filter(E=>g.cursors[E.path]!==void 0).length,u={hostLocal:i,sessions:d.size,logs:m.length,observedLogs:p},v=L(A()),ye=[`[VisIQ] Claude Cowork harness ${K} \u2014 status`,` this process: ${$(v)}${N(v)?"":" (cannot enforce)"}`,` credentials: ${t?"resolved":"MISSING (run `visiq-claude-code configure`)"}`,` agent id: ${t?.agentId??"\u2014"}`,` hooks: ${He(a,r)} \u2014 ${o}`,` dispatcher: ${Be(i)}`,T("cowork_desktop",u),T("cowork_vm",u),` session tree: ${h}`,` monitor state: ${P()}`];return process.stdout.write(`${ye.join(`
18
+ Restart Claude for the hooks to take effect, then \`${a.status}\`.
19
+ `),0}async function on(e){let n=A(e),t=typeof e.command=="string"?e.command:void 0;if(!Ee(n))return process.stdout.write(`[VisIQ] No settings file at ${n} \u2014 nothing to remove, and nothing was created.
20
+ `),0;let o=await Oe(n);return o===null?1:(await xe(n,H(o,t)),process.stdout.write(`[VisIQ] Removed Claude Cowork governance hooks from ${n}
21
+ `),0)}function M(e,n){let t=` ${O(e)}:`;if(!S(e)){let o=`${n.sessions} session(s), ${n.logs} audit log(s)`;return n.logs===0?`${t} monitor-only \u2014 ${o} \u2014 nothing to monitor`:n.observedLogs===0?`${t} NOT monitored \u2014 ${o} found, none observed \u2014 run \`${n.hints.monitor}\``:n.observedLogs<n.logs?`${t} PARTIALLY monitored \u2014 ${o}, ${n.observedLogs} observed \u2014 run \`${n.hints.monitor}\``:`${t} monitor-only \u2014 ${o}, all observed`}switch(n.hostLocal.state){case"enforced":return`${t} ENFORCED (PreToolUse deny blocks)`;case"scoped":{let o=n.hostLocal.unresolved.length>0?` (a VisIQ group runs \`${n.hostLocal.unresolved.join("`, `")}\`, which is NOT on PATH, so that group covers nothing)`:"";return`${t} PARTIALLY enforced \u2014 the VisIQ ${$} hook matches only \`${n.hostLocal.scopedTo}\`, so every OTHER tool call runs UNGOVERNED${o} \u2014 run \`${n.hints.install}\` to cover them all`}case"no-rule-bundle":return`${t} NOT CONFIRMED \u2014 no VisIQ rule bundle is cached${n.hostLocal.reason==="unusable"?" (the cached one could not be applied)":""}, so each tool call is governed only if the hook's own fetch succeeds; when it does not the hook logs \`FAIL-OPEN (no-bundle) \u2026 proceeding UNGOVERNED\` \u2014 start a Claude session (SessionStart caches the bundle) or check connectivity`;case"agent-mode":return n.hostLocal.mode==="off"?`${t} NOT enforced \u2014 the rule bundle sets \`agent_mode: "off"\`, so the hook skips evaluation entirely: no call is blocked and none is recorded`:`${t} MONITORING, not enforcing \u2014 the rule bundle sets \`agent_mode: "${n.hostLocal.mode}"\`, so a \`deny\` is RECORDED and the tool call still runs \u2014 switch the agent to enforce mode to block`;case"settings-unreadable":return`${t} UNKNOWN \u2014 the settings file could not be read as JSON (${n.hostLocal.reason}), so coverage cannot be determined \u2014 fix the JSON and run \`${n.hints.status}\` again`;case"dispatcher-unresolvable":return`${t} installed, but the dispatcher \`${n.hostLocal.command}\` is not on PATH \u2014 tool calls run UNGOVERNED`;case"no-pre-tool-use-hook":return`${t} not covered (no VisIQ PreToolUse hook) \u2014 run \`${n.hints.install}\``;case"unconfigured":{let{scopedTo:o}=n.hostLocal;return n.hostLocal.failMode==="closed"?o===null?`${t} BLOCKING EVERY call (no VisIQ credentials, failMode=closed) \u2014 run \`visiq-claude-code configure\``:`${t} BLOCKING every \`${o}\` call and leaving every OTHER tool call UNGOVERNED (no VisIQ credentials, failMode=closed) \u2014 run \`visiq-claude-code configure\``:`${t} installed, but no VisIQ credentials \u2014 the hook FAILS OPEN and tool calls run UNGOVERNED \u2014 run \`visiq-claude-code configure\``}default:return k(n.hostLocal)}}function sn(e,n){return e?"UNKNOWN (settings file is not readable JSON)":n?"installed":"not installed"}function rn(e){switch(e.state){case"enforced":return`${e.command} \u2192 ${e.resolvedPath}`;case"scoped":return`${e.command} \u2192 ${e.resolvedPath} (matches only \`${e.scopedTo}\`)`;case"settings-unreadable":return"\u2014 (the settings file could not be read as JSON)";case"dispatcher-unresolvable":return`${e.command} \u2192 NOT FOUND on PATH`;case"no-pre-tool-use-hook":return`\u2014 (no VisIQ ${$} hook in this settings file)`;case"no-rule-bundle":case"agent-mode":return`${e.command} \u2192 ${e.resolvedPath}`;case"unconfigured":return`${e.command} \u2192 ${e.resolvedPath}`;default:return k(e)}}async function an(e){let n=T(),{config:t}=await w(),o=A(e),s=await L(o),a=s.kind==="parsed"?s.settings:{},l=s.kind==="unreadable",r=G(a),c=typeof e.command=="string"?e.command:void 0,i=await Re({read:s,explicitCommand:c}),y=x({homeDir:b(),platform:Ne(),env:process.env}),g=await X(n,y),d=new Set(g.map(E=>E.session.sessionKey)),f=await R(n,P()),p=g.filter(E=>f.cursors[E.path]!==void 0).length,m={hostLocal:i,hints:Se(e),sessions:d.size,logs:g.length,observedLogs:p},v=V(D()),Te=[`[VisIQ] Claude Cowork harness ${ee} \u2014 status`,` this process: ${O(v)}${S(v)?"":" (cannot enforce)"}`,` credentials: ${t?"resolved":"MISSING (run `visiq-claude-code configure`)"}`,` agent id: ${t?.agentId??"\u2014"}`,` hooks: ${sn(l,r)} \u2014 ${o}`,` dispatcher: ${rn(i)}`,M("cowork_desktop",m),M("cowork_vm",m),` session tree: ${y}`,` monitor state: ${P()}`];return process.stdout.write(`${Te.join(`
15
22
  `)}
16
- `),ne(i)?0:1}async function qe(e){let{config:n}=await b();if(!n)return process.stderr.write("[VisIQ] monitor needs credentials \u2014 run `visiq-claude-code configure` first.\n"),1;let t=I(),o=S({homeDir:k(),platform:ge(),env:process.env}),s=P(),l=e.once===!0,a=ce(e.interval);process.stdout.write(`[VisIQ] Monitoring Claude Cowork sandbox sessions (monitor-only; hooks cover host-local).
23
+ `),re(i)?0:1}async function ln(e){let{config:n}=await w();if(!n)return process.stderr.write("[VisIQ] monitor needs credentials \u2014 run `visiq-claude-code configure` first.\n"),1;let t=T(),o=x({homeDir:b(),platform:Ne(),env:process.env}),s=P(),a=e.once===!0,l=he(e.interval);process.stdout.write(`[VisIQ] Monitoring Claude Cowork sandbox sessions (monitor-only; hooks cover host-local).
17
24
  tree: ${o}
18
- `);let r=!1,c=!1,i=m=>{c=X(m)||c},h=()=>{r=!0};process.on("SIGINT",h),process.on("SIGTERM",h);do{let m=await O(t,s);try{let d=await q({fs:t,root:o,agentId:n.agentId,state:m});({state:m}=d);let g=[...d.observations,...d.permissionObservations],p=0;if(g.length>0){let u=j(n);try{await H(u,n);for(let v of g)await u.evaluate(v.event)}finally{p=await B(u)}}if(p>0)process.stderr.write(`[VisIQ] monitor pass NOT committed: ${p} event(s) failed to reach the control plane. The cursor was left where it was, so the next pass re-reads them.
19
- `),i({kind:"undelivered",dropped:p});else{let u=await W(t,s,m);u===null?i({kind:"delivered"}):(process.stderr.write(`[VisIQ] monitor pass delivered but NOT PERSISTED: ${s} could not be written (${u}). The cursor did not move, so the next pass re-reads and re-delivers everything this one just sent \u2014 and will keep doing so until the write succeeds.
20
- `),i({kind:"not-persisted",reason:u}))}process.stdout.write(`[VisIQ] scanned ${d.stats.logsScanned} log(s): ${d.observations.length} new tool call(s), ${d.stats.duplicates} duplicate(s), ${d.stats.corruptLines} corrupt line(s), ${d.stats.truncatedLines} truncated line(s)
21
- `),process.stdout.write(`${J(d).join(`
25
+ `);let r=!1,c=!1,i=g=>{c=Z(g)||c},y=()=>{r=!0};process.on("SIGINT",y),process.on("SIGTERM",y);do{let g=await R(t,s);try{let d=await K({fs:t,root:o,agentId:n.agentId,state:g});({state:g}=d);let f=[...d.observations,...d.permissionObservations],p=0;if(f.length>0){let m=q(n);try{await J(m,n);for(let v of f)await m.evaluate(v.event)}finally{p=await W(m)}}if(p>0)process.stderr.write(`[VisIQ] monitor pass NOT committed: ${p} event(s) failed to reach the control plane. The cursor was left where it was, so the next pass re-reads them.
26
+ `),i({kind:"undelivered",dropped:p});else{let m=await z(t,s,g);m===null?i({kind:"delivered"}):(process.stderr.write(`[VisIQ] monitor pass delivered but NOT PERSISTED: ${s} could not be written (${m}). The cursor did not move, so the next pass re-reads and re-delivers everything this one just sent \u2014 and will keep doing so until the write succeeds.
27
+ `),i({kind:"not-persisted",reason:m}))}process.stdout.write(`[VisIQ] scanned ${d.stats.logsScanned} log(s): ${d.observations.length} new tool call(s), ${d.stats.duplicates} duplicate(s), ${d.stats.corruptLines} corrupt line(s), ${d.stats.truncatedLines} truncated line(s)
28
+ `),process.stdout.write(`${Y(d).join(`
22
29
  `)}
23
- `)}catch(d){let g=d instanceof Error?d.message:String(d);process.stderr.write(`[VisIQ] monitor pass failed (continuing): ${g}
24
- `),i({kind:"threw",error:g})}if(l||r)break;await new Promise(d=>{setTimeout(d,a)})}while(!r);return c?1:0}function fe(){process.stdout.write(`Usage: visiq-claude-cowork <install|uninstall|status|monitor> [flags]
25
-
26
- install [--settings <path>] [--command <cmd>] host-local enforcement
27
- uninstall [--settings <path>]
28
- status what is covered, and how
29
- monitor [--once] [--interval <ms>] sandbox monitor-only coverage
30
-
31
- Credentials are shared with @visiq/claude-code-harness:
32
- visiq-claude-code configure --api-key <key> --agent-id <id>
33
- `)}async function Je(){let{positionals:e,values:n}=Ue({args:process.argv.slice(2),options:ie,strict:!1,allowPositionals:!0}),t=n,o=ae(t);if(o.length>0){process.stderr.write(`[VisIQ] unknown option(s): ${o.map(r=>`--${r}`).join(", ")}
34
- known options: ${Object.keys(f).map(r=>`--${r}`).join(", ")}
30
+ `)}catch(d){let f=d instanceof Error?d.message:String(d);process.stderr.write(`[VisIQ] monitor pass failed (continuing): ${f}
31
+ `),i({kind:"threw",error:f})}if(a||r)break;await new Promise(d=>{setTimeout(d,l)})}while(!r);return c?1:0}function ke(){process.stdout.write(be())}async function dn(){let{positionals:e,values:n}=nn({args:process.argv.slice(2),options:me,strict:!1,allowPositionals:!0}),t=n,o=ge(t);if(o.length>0){process.stderr.write(`[VisIQ] unknown option(s): ${o.map(r=>`--${r}`).join(", ")}
32
+ known options: ${Object.keys(u).map(r=>`--${r}`).join(", ")}
35
33
  Refusing to continue: an ignored flag has silently written the real
36
34
  ~/.claude/settings.json when a different path was intended.
37
- `),process.exitCode=2;return}let s=de(t);if(s.length>0){process.stderr.write(`[VisIQ] bad option value(s):
35
+ `),process.exitCode=2;return}let s=pe(t);if(s.length>0){process.stderr.write(`[VisIQ] bad option value(s):
38
36
  ${s.map(r=>` ${r}
39
37
  `).join("")} Refusing to continue: a flag whose value cannot be honoured used to be
40
38
  DROPPED \u2014 \`--once=true\` looped forever, an empty --settings wrote the
41
39
  real ~/.claude/settings.json, and \`--interval 30s\` became a 1000 ms poll.
42
- `),process.exitCode=2;return}let l=le(String(e[0]??""),t);if(l.length>0){process.stderr.write(`[VisIQ] flag(s) that do not apply to \`${String(e[0])}\`:
43
- ${l.map(r=>` ${r}
40
+ `),process.exitCode=2;return}let a=fe(String(e[0]??""),t);if(a.length>0){process.stderr.write(`[VisIQ] flag(s) that do not apply to \`${String(e[0])}\`:
41
+ ${a.map(r=>` ${r}
44
42
  `).join("")} Refusing to continue: a flag this command cannot honour is indistinguishable,
45
43
  to the person who typed it, from one that was applied.
46
- `),process.exitCode=2;return}let a=0;switch(e[0]){case"install":a=await Ge(t);break;case"uninstall":a=await je(t);break;case"status":a=await Qe(t);break;case"monitor":a=await qe(t);break;case"help":case void 0:fe();break;default:process.stderr.write(`[VisIQ] Unknown command: ${e[0]}
47
- `),fe(),a=1}process.exit(a)}Je().catch(e=>{process.stderr.write(`[VisIQ] ${e instanceof Error?e.message:String(e)}
44
+ `),process.exitCode=2;return}let l=0;switch(e[0]){case"install":l=await tn(t);break;case"uninstall":l=await on(t);break;case"status":l=await an(t);break;case"monitor":l=await ln(t);break;case"help":case void 0:ke();break;default:process.stderr.write(`[VisIQ] Unknown command: ${e[0]}
45
+ `),ke(),l=1}process.exit(l)}dn().catch(e=>{process.stderr.write(`[VisIQ] ${e instanceof Error?e.message:String(e)}
48
46
  `),process.exit(1)});export{P as monitorStatePath};
package/dist/index.d.ts CHANGED
@@ -234,6 +234,20 @@ export declare function orderAuditLogs(names: readonly string[]): string[];
234
234
  * `system` record used to return zero events, which discarded the user's own
235
235
  * allow/deny answer for each call, and every standing `always` grant.
236
236
  *
237
+ * AND THEN A NARROWER VERSION OF THE SAME DROP SURVIVED THE FIX: a permission
238
+ * record whose `tool_name` was absent, empty, or not a string returned zero
239
+ * events under the rule "it governs nothing identifiable". MEASURED against the
240
+ * BUILT CLI in all three of those shapes, over a `permission_response` carrying
241
+ * `granted:false`: `0 request(s), 0 answered (0 REFUSED …)` and exit 0, while
242
+ * the same record with `tool_name:"Bash"` printed `1 REFUSED` and exited
243
+ * non-zero because it had something to deliver. Exit 0 is the damning half — the
244
+ * pass committed its cursor, so those bytes are never read again. For a RESPONSE
245
+ * the record is the ONLY evidence the user's refusal ever happened, so dropping
246
+ * it erases an explicit denial rather than merely losing a tool name. Both halves
247
+ * of the pair are now emitted with {@link UNATTRIBUTED_TOOL_NAME} and the
248
+ * `unattributed` mark, counted, and reported; what they may NOT do is bind to a
249
+ * tool call, because the tool name is the binding evidence and there is none.
250
+ *
237
251
  * (This paragraph used to quote a count and a percentage of the source session
238
252
  * that those `system` records made up. The session's TOTAL is bound —
239
253
  * `manifest.recording.sourceRecordCount`, asserted by audit-corpus-drift.test.ts —
@@ -306,8 +320,19 @@ export interface CoworkPermissionRequestEvent {
306
320
  kind: "permission_request";
307
321
  uuid: string;
308
322
  sessionId: string;
323
+ /** The gated tool, or {@link UNATTRIBUTED_TOOL_NAME} when `unattributed`. */
309
324
  toolName: string;
310
325
  toolInput: unknown;
326
+ /**
327
+ * Set (and only ever `true`) when the vendor's record carried no readable
328
+ * `tool_name`, so {@link toolName} is a placeholder rather than a tool.
329
+ *
330
+ * A FLAG rather than a comparison against the placeholder string: the rule that
331
+ * matters — such a record may never bind to a tool call — has to hold whatever
332
+ * the placeholder is spelled, including against a hypothetical tool that
333
+ * happens to be named like it.
334
+ */
335
+ unattributed?: true | undefined;
311
336
  timestamp?: string | undefined;
312
337
  }
313
338
  /** The user's answer to a {@link CoworkPermissionRequestEvent}. */
@@ -316,7 +341,16 @@ export interface CoworkPermissionDecisionEvent {
316
341
  /** The REQUEST's uuid — the vendor reuses it on the response, and it is the join. */
317
342
  uuid: string;
318
343
  sessionId: string;
344
+ /** The answered tool, or {@link UNATTRIBUTED_TOOL_NAME} when `unattributed`. */
319
345
  toolName: string;
346
+ /**
347
+ * Set (and only ever `true`) when the vendor's record carried no readable
348
+ * `tool_name`. The ANSWER is still readable, and an unattributable refusal is
349
+ * reported rather than dropped — see the header. It cannot mark a call by
350
+ * NAME; it can still mark one through the uuid the vendor shares with the
351
+ * request, which is where the name comes from in that case.
352
+ */
353
+ unattributed?: true | undefined;
320
354
  /**
321
355
  * `true` = allowed to run. `false` = REFUSED, so the tool never executed even
322
356
  * though its `tool_use` record is already in the stream.
@@ -336,6 +370,17 @@ export type CoworkAuditEvent = CoworkToolCallEvent | CoworkToolResultEvent | Cow
336
370
  export declare const PERMISSION_REQUEST_SUBTYPE = "permission_request";
337
371
  /** Subtype of a `system` record that answers it. */
338
372
  export declare const PERMISSION_RESPONSE_SUBTYPE = "permission_response";
373
+ /**
374
+ * Stand-in tool name for a permission record the vendor wrote without a readable
375
+ * `tool_name`.
376
+ *
377
+ * Not the empty string, which would read downstream as a tool called `''` and is
378
+ * why the record used to be dropped instead; not a plausible tool name either,
379
+ * so an operator reading the refusal line sees the gap rather than a fiction. The
380
+ * machine-readable form of the same fact is the `unattributed` flag on the event,
381
+ * and that — never this string — is what the binding rule consults.
382
+ */
383
+ export declare const UNATTRIBUTED_TOOL_NAME = "<unattributed>";
339
384
  /**
340
385
  * Ceiling on the partial line CARRIED BETWEEN CHUNKS. A live `audit.jsonl` is
341
386
  * appended to while we read it, so a partial trailing line is NORMAL and gets
@@ -365,8 +410,26 @@ export interface NdjsonChunkResult {
365
410
  remainder: string;
366
411
  /** Lines that were present but unparseable (corrupt JSON). Observability only. */
367
412
  skipped: number;
368
- /** True when an over-long partial line was dropped to bound memory. */
369
- truncated: boolean;
413
+ /**
414
+ * Over-long partial lines DROPPED from this chunk to bound memory — 0 or 1,
415
+ * because a chunk carries at most one partial line (everything before the last
416
+ * newline is a complete record).
417
+ *
418
+ * A COUNT, not the boolean it used to be, and the difference is the whole
419
+ * point of the name. The monitor's `stats.truncatedLines` folded that boolean
420
+ * with `truncated ? 1 : 0`, so the figure it reported under the label
421
+ * "truncated line(s)" was the number of READS that dropped something. Summing a
422
+ * per-chunk LINE count says what it means, and the two agree only because this
423
+ * value can never exceed 1.
424
+ *
425
+ * WHAT ONE UNIT IS, precisely, since it is not "one distinct over-long line":
426
+ * an over-long line spanning several chunks is dropped once per chunk whose
427
+ * carry crossed the ceiling — this function cannot tell the tail of a line it
428
+ * already dropped from a fresh one, and reporting 1 for a line that cost
429
+ * several drops would understate the loss. So: dropped line FRAGMENTS, one per
430
+ * drop, never fewer than the number of distinct lines lost.
431
+ */
432
+ truncatedLines: number;
370
433
  }
371
434
  /**
372
435
  * Split a chunk into whole NDJSON records, carrying any trailing partial line.
@@ -394,6 +457,35 @@ export declare function normalizeAuditRecords(records: readonly unknown[]): Cowo
394
457
  * observation without this mark reports one that did.
395
458
  */
396
459
  export type CallExecutionStatus = "unconfirmed" | "granted" | "refused";
460
+ /**
461
+ * The uuid → `granted` index the call/gate join reads, keyed on the uuid the
462
+ * vendor REUSES across a request and its response.
463
+ *
464
+ * A UUID-LESS ROW HAS NO JOIN, and joining on `''` is not a weak join — it is
465
+ * a WRONG one. `normalizeAuditRecord` coerces a missing `uuid` to the empty
466
+ * string, so every uuid-less request and response collapses onto one key: PROVEN
467
+ * by probe, a `permission_response` for tool `SomethingElse` with no uuid marked
468
+ * an unrelated `Bash` call `refused`. That is precisely the error this module's
469
+ * own docblock forbids — "inventing a denial the vendor did not write is the same
470
+ * class of error as the drop this event exists to fix" — committed by the JOIN
471
+ * rather than by the parser. Such a record is still emitted, counted and reported
472
+ * in its own right; it is only barred from marking a CALL.
473
+ *
474
+ * THE PROBE PROVED THE DEFECT, NOT THIS LINE, and conflating the two is what this
475
+ * function exists to stop. The empty-uuid skip below used to live inline in
476
+ * {@link resolveCallExecution} under that same "PROVEN by probe" note — and
477
+ * REMOVING IT REDDED NOTHING (600/600 unit specs green), because the guard on the
478
+ * REQUEST side already bars the only lookup that could reach an `''` entry. The
479
+ * property that survives mutation is the request-side one, and its named test is
480
+ * "does NOT let a uuid-less response mark an unrelated call refused".
481
+ *
482
+ * So the skip is kept — a join index with a bogus key is a loaded gun for the next
483
+ * edit of the consumer — but it is kept where its own effect is OBSERVABLE, and
484
+ * "the join index never keys a record on the empty string" is asserted directly by
485
+ * "keeps a uuid-less decision OUT of the join index". Delete the skip and that
486
+ * test reds. A guard nothing can red is not a guard, it is a comment.
487
+ */
488
+ export declare function permissionDecisionIndex(events: readonly CoworkAuditEvent[]): Map<string, boolean | undefined>;
397
489
  /**
398
490
  * Resolve execution status for every tool call in an event window, by pairing
399
491
  * each permission request with the OLDEST unbound call it matches and then with
@@ -537,8 +629,13 @@ export interface AdvanceResult {
537
629
  duplicates: number;
538
630
  /** Corrupt lines skipped in this chunk. */
539
631
  skipped: number;
540
- /** True when an over-long partial line was DROPPED to bound memory. */
541
- truncated: boolean;
632
+ /**
633
+ * Over-long partial lines DROPPED to bound memory in this chunk (0 or 1).
634
+ * Passed through from {@link parseNdjsonChunk}, whose docstring defines what
635
+ * one unit is — it is a dropped FRAGMENT, so a line spanning several reads
636
+ * counts once per read that dropped part of it.
637
+ */
638
+ truncatedLines: number;
542
639
  }
543
640
  /**
544
641
  * Fold one read of `path` into the state: parse, normalize, drop duplicates and
@@ -741,16 +838,38 @@ export interface ScanResult {
741
838
  corruptLines: number;
742
839
  restarts: number;
743
840
  /**
744
- * Over-long lines DROPPED to bound memory. Previously produced by the parser
745
- * and consumed by nothing — so discarding up to 8 MiB of governance records
746
- * was invisible while the far milder `corruptLines` was reported.
841
+ * Over-long line fragments DROPPED to bound memory, summed over this pass's
842
+ * reads. Previously produced by the parser and consumed by nothing — so
843
+ * discarding up to 8 MiB of governance records was invisible while the far
844
+ * milder `corruptLines` was reported.
845
+ *
846
+ * THE ARITHMETIC AND THE NAME NOW AGREE. This was `+= result.truncated ? 1 : 0`
847
+ * over a boolean, which counts READS that dropped a partial line, under a
848
+ * docstring that said "Over-long lines DROPPED" — a different quantity with
849
+ * the same value only because one read can drop at most one partial line. The
850
+ * parser now returns a line COUNT and this sums it. One unit is a dropped
851
+ * FRAGMENT: a single over-long line spanning several reads is counted once per
852
+ * read that dropped part of it, because nothing in the stream can tell those
853
+ * fragments were one line, and reporting 1 would understate the loss. So this
854
+ * is a floor on lines lost, never an over-count of bytes-lost events.
747
855
  */
748
856
  truncatedLines: number;
749
- /** Permission gates opened (a `system/permission_request` record). */
857
+ /**
858
+ * Permission gates opened (a `system/permission_request` record), INCLUDING
859
+ * the ones whose `tool_name` was unreadable. Those used to be dropped before
860
+ * the subtype was consulted, so they reached no counter at all.
861
+ */
750
862
  permissionRequests: number;
751
863
  /** Permission gates answered (a `system/permission_response` record). */
752
864
  permissionDecisions: number;
753
- /** …of which the user REFUSED. These calls never executed. */
865
+ /**
866
+ * …of which the user REFUSED. These calls never executed.
867
+ *
868
+ * A refusal counts here whether or not the record named its tool: an
869
+ * unattributable denial is still a denial, and dropping it was the seventh
870
+ * silent-drop shape (see audit-stream.ts). `permissionReportLines` prints how
871
+ * many of the pass's answers were unattributed alongside this count.
872
+ */
754
873
  permissionsRefused: number;
755
874
  /**
756
875
  * Tool calls this pass could bind to a REFUSAL. Distinct from
@@ -897,6 +1016,6 @@ export declare function nodeFs(): MonitorFs;
897
1016
  * (package-relative on purpose: a bare `__tests__/…` path reads as a monorepo leak to
898
1017
  * the publish-bundle validator, because this JSDoc ships inside the published .d.ts).
899
1018
  */
900
- export declare const HARNESS_VERSION = "0.1.3";
1019
+ export declare const HARNESS_VERSION = "0.1.4";
901
1020
 
902
1021
  export {};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as h,A as I,B as k,C as P,D as L,E as M,F as w,G as x,H as D,I as F,U,V as g,W as B,X as K,Y,Z as b,_ as X,a as e,aa as j,b as o,ba as q,c as t,ca as z,d as r,da as H,e as s,ea as V,f as S,g as a,h as n,i,j as E,k as p,l as u,m as c,n as R,o as l,p as d,q as y,r as C,s as _,t as N,u as A,v as f,w as m,x as O,y as T,z as v}from"./chunk-4HEZXX65.js";export{e as CLAUDE_SURFACES,i as COWORK_SESSIONS_DIRNAME,E as DESKTOP_SESSIONS_DIRNAME,V as HARNESS_VERSION,o as HOST_PLATFORM_ENV,v as INPUT_SIGNATURE_SENTINELS,N as MAX_BUFFERED_LINE_BYTES,K as MAX_READ_BYTES,L as MAX_SEEN_KEYS,C as PERMISSION_REQUEST_SUBTYPE,_ as PERMISSION_RESPONSE_SUBTYPE,U as SURFACE_CONTEXT_KEY,x as advance,z as alignToRecordBoundary,S as assertNeverSurface,T as auditEventKey,d as auditLogIndex,B as buildCoworkObservation,t as classifySurface,p as claudeSupportDir,u as coworkSessionsRoot,Y as discoverAuditLogs,M as emptyState,l as isAuditLogName,s as isCoworkSurface,I as isRepresentedInput,R as isSessionKey,h as loadState,q as monitorPassLost,H as nodeFs,f as normalizeAuditRecord,m as normalizeAuditRecords,y as orderAuditLogs,A as parseNdjsonChunk,c as parseSessionDir,F as parseState,X as permissionReportLines,P as permissionRequestMatchesCall,w as planRead,D as pruneSeen,O as resolveCallExecution,j as saveState,b as scanOnce,n as surfaceFactsFromProcess,a as surfaceLabel,r as surfaceSupportsEnforcement,g as toolArgsOf,k as toolInputSignature};
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-7WPBRDY7.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",
3
+ "version": "0.1.4",
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",