@visiq/harness 0.2.12 → 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -4
- package/package.json +8 -2
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{randomUUID as ys}from"node:crypto";import*as tt from"node:fs";import*as nt from"node:path";import*as Fr from"node:os";import{AsyncLocalStorage as bs}from"node:async_hooks";import{z as m}from"zod";import*as P from"node:os";import{randomUUID as pe}from"node:crypto";var ot=1,$t="X-VisIQ-SDK",Pt="X-VisIQ-Dialect",jt="unknown";function H(e,t=1){return{[$t]:e&&e.length>0?e:jt,[Pt]:String(t)}}var Ut="interceptor_source",Gr=m.enum(["enforce","audit","off"]),Hr=m.enum(["closed","open"]),Bt=m.enum(["enforce","monitor","off"]),Wr=m.object({apiKey:m.string().min(1,"apiKey is required"),agentId:m.string().min(1,"agentId is required"),endpoint:m.string().url().optional(),mode:Gr.optional(),timeoutMs:m.number().int().positive().optional(),hitlTimeoutMs:m.number().int().positive().optional(),failBehavior:Hr.optional()}),Bs=m.object({agent_id:m.string().min(1),target_app:m.string().min(1),action:m.string().min(1),context:m.record(m.unknown()).optional(),session_id:m.string().min(1).max(255).optional(),action_schema_id:m.string().min(1).max(128).optional(),telemetry:m.record(m.unknown()).optional()}),Qr=m.object({field:m.string().optional(),pattern:m.string().optional(),replacement:m.string().optional(),mode:m.enum(["full","partial","email"]).optional(),keepFirst:m.number().optional(),keepLast:m.number().optional(),maskChar:m.string().optional()}),Yr=m.object({decision_id:m.string().min(1),decision:m.enum(["permit","deny","approval_required","mask"]),reason:m.string().optional(),rule_code:m.string().nullable().optional(),enforced:m.boolean().optional(),agent_mode:Bt.optional(),arg_redaction_rules:m.array(Qr).optional(),plane:m.string().nullable().optional(),operation:m.string().nullable().optional(),is_retrieval:m.boolean().optional(),metadata:m.record(m.unknown()).optional()}),Zr=m.object({field:m.string().min(1),operator:m.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:m.union([m.string(),m.number(),m.array(m.string())])}),Jr=m.object({id:m.string().min(1),rule_code:m.string().default(""),name:m.string().min(1),description:m.string().nullable().default(null),effect:m.enum(["allow","deny","hitl","mask"]),resource_type:m.string().min(1),rego_source:m.string().default(""),target_app:m.string().nullable().default(null),action_pattern:m.string().nullable().default(null),conditions:m.array(Zr).default([]),priority:m.number().int().default(0)}),Xr=m.object({version:m.string().min(1),agent_mode:Bt.optional(),rules:m.array(Jr),no_coverage:m.object({no_coverage_defaults:m.record(m.string()),autopilot_enabled:m.boolean(),enduser_hitl_enabled:m.boolean(),hitl_timeout_seconds:m.number()}).optional()}),eo=2e3,it=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return H(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 o=await r.json();return Yr.parse(o)}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),o;try{o=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json",...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!o.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${o.status} ${o.statusText}`);let i=await o.json();return Xr.parse(i)}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 o=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})});o.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${o.status}`)}catch(o){console.warn("[ALLOW] Execution result report failed:",o)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),o;try{o=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(!o.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${o.status} ${o.statusText}`);let i=await o.json();if(typeof i!="object"||i===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let a=i,s=a.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 a.reason=="string"?a.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await to(eo)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function to(e){return new Promise(t=>setTimeout(t,e))}function Le(){let e={};try{let t=`${P.platform()} ${P.release()}`.trim();t&&(e.os=t)}catch{}try{let t=P.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=P.userInfo();t&&(e.username=t)}catch{}try{let t=no();t&&(e.ip=t)}catch{}return e}function no(){let e=P.networkInterfaces();for(let t of Object.keys(e))for(let n of e[t]??[])if((n.family==="IPv4"||n.family===4)&&!n.internal&&n.address)return n.address}function ro(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Me(e,...t){for(let n of t){let r=ro(e[n]);if(r)return r}}function De(e){if(Me(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(Me(e,"user_id","userId"))return"user";if(Me(e,"agent_id","agentId"))return"agent";if(Me(e,"org_id","orgId","namespace"))return"org"}var oo=[{framework:"mem0",matches:e=>/^(mem0[_-])?(add|search|get|retrieve|update|delete)[_-]memor(y|ies)$/i.test(e),extract:(e,t)=>{let n=/^(?:mem0[_-])?([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"||n==="update"?r="write":r="read";let o=De(t);return{op:r,store:"mem0",framework:"mem0",...o?{scope:o}:{}}}},{framework:"letta",matches:e=>/^(core_memory_(append|replace)|archival_memory_(insert|search)|conversation_search)$/i.test(e),extract:e=>{let t=e.toLowerCase();return t.startsWith("core_memory_")?{op:"write",store:"letta-core",scope:"agent",framework:"letta"}:t==="archival_memory_insert"?{op:"write",store:"letta-archival",scope:"agent",framework:"letta"}:t==="archival_memory_search"?{op:"search",store:"letta-archival",scope:"agent",framework:"letta"}:{op:"search",store:"letta-conversation",scope:"session",framework:"letta"}}},{framework:"langgraph",matches:e=>/^(upsert_memory|save_recall_memory|search_recall_memories)$/i.test(e),extract:(e,t)=>{let n=/^search_/i.test(e),r=De(t);return{op:n?"search":"write",store:"langgraph-store",framework:"langgraph",...r?{scope:r}:{}}}},{framework:"zep",matches:e=>/^zep[_-](add|search|get|delete)[_-]memory$/i.test(e),extract:(e,t)=>{let n=/^zep[_-]([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"?r="write":r="read";let o=De(t)??"session";return{op:r,store:"zep",scope:o,framework:"zep"}}},{framework:"mcp-memory",matches:e=>/^(create_entities|create_relations|add_observations|delete_entities|delete_relations|delete_observations|search_nodes|open_nodes|read_graph)$/i.test(e),extract:e=>{let t=e.toLowerCase(),n;return t.startsWith("delete_")?n="delete":t==="search_nodes"?n="search":t==="open_nodes"||t==="read_graph"?n="read":n="write",{op:n,store:"mcp-memory",scope:"agent",framework:"mcp-memory"}}},{framework:"generic",matches:e=>/(^|[_\-.])(memory|memories|mem0|recall)([_\-.]|$)/i.test(e),extract:(e,t)=>{let n=e.toLowerCase(),r;/(^|[_\-.])(search|query|find|lookup|retrieve)([_\-.]|$)/.test(n)?r="search":/(^|[_\-.])(delete|remove|forget|clear|purge)([_\-.]|$)/.test(n)?r="delete":/(^|[_\-.])(add|save|write|store|upsert|put|set|update|insert|append|remember)([_\-.]|$)/.test(n)?r="write":r="read";let o=De(t);return{op:r,store:"memory",framework:"generic",...o?{scope:o}:{}}}}];function de(e,t){if(!e)return null;let n=t??{};for(let r of oo)try{if(r.matches(e)){let o=r.extract(e,n);if(o)return o}}catch{}return null}function at(e,t){let n=typeof t?.itemCount=="number"&&Number.isFinite(t.itemCount)&&t.itemCount>=0?Math.round(t.itemCount):void 0,r=typeof t?.bytes=="number"&&Number.isFinite(t.bytes)&&t.bytes>=0?Math.round(t.bytes):void 0,o=e.op==="read"||e.op==="search";return{op:e.op,store:e.store,...e.scope?{scope:e.scope}:{},...n!==void 0?{itemCount:n}:{},...r!==void 0?{bytes:r}:{},...o&&n!==void 0?{hit:n>0}:{}}}var Ft=new Map;function fe(e){let t=(Ft.get(e)??0)+1;return Ft.set(e,t),t}function qt(e){if(!e||typeof e!="object")return;let t={};for(let n of["tokensIn","tokensOut","cacheRead","cacheWrite"]){let r=e[n];typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[n]=Math.round(r))}return Object.keys(t).length>0?t:void 0}function st(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,o=Array.isArray(n.texts)?n.texts.filter(a=>typeof a=="string"&&a.length>0).join(`
|
|
1
|
+
import{randomUUID as Vs}from"node:crypto";import*as rt from"node:fs";import*as it from"node:path";import*as Gr from"node:os";import{AsyncLocalStorage as zs}from"node:async_hooks";import{z as g}from"zod";import*as j from"node:os";import{randomUUID as fe}from"node:crypto";var at=1,Ut="X-VisIQ-SDK",qt="X-VisIQ-Dialect",Vt="unknown";function W(e,t=1){return{[Ut]:e&&e.length>0?e:Vt,[qt]:String(t)}}var zt="interceptor_source",ni=g.enum(["enforce","audit","off"]),ri=g.enum(["closed","open"]),Kt=g.enum(["enforce","monitor","off"]),ii=g.object({apiKey:g.string().min(1,"apiKey is required"),agentId:g.string().min(1,"agentId is required"),endpoint:g.string().url().optional(),mode:ni.optional(),timeoutMs:g.number().int().positive().optional(),hitlTimeoutMs:g.number().int().positive().optional(),failBehavior:ri.optional()}),pl=g.object({agent_id:g.string().min(1),target_app:g.string().min(1),action:g.string().min(1),context:g.record(g.unknown()).optional(),session_id:g.string().min(1).max(255).optional(),action_schema_id:g.string().min(1).max(128).optional(),telemetry:g.record(g.unknown()).optional()}),oi=g.object({field:g.string().optional(),pattern:g.string().optional(),replacement:g.string().optional(),mode:g.enum(["full","partial","email"]).optional(),keepFirst:g.number().optional(),keepLast:g.number().optional(),maskChar:g.string().optional()}),ai=g.object({decision_id:g.string().min(1),decision:g.enum(["permit","deny","approval_required","mask"]),reason:g.string().optional(),rule_code:g.string().nullable().optional(),enforced:g.boolean().optional(),agent_mode:Kt.optional(),arg_redaction_rules:g.array(oi).optional(),plane:g.string().nullable().optional(),operation:g.string().nullable().optional(),is_retrieval:g.boolean().optional(),metadata:g.record(g.unknown()).optional()}),si=g.object({field:g.string().min(1),operator:g.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:g.union([g.string(),g.number(),g.array(g.string())])}),li=g.object({id:g.string().min(1),rule_code:g.string().default(""),name:g.string().min(1),description:g.string().nullable().default(null),effect:g.enum(["allow","deny","hitl","mask"]),resource_type:g.string().min(1),rego_source:g.string().default(""),target_app:g.string().nullable().default(null),action_pattern:g.string().nullable().default(null),conditions:g.array(si).default([]),priority:g.number().int().default(0)}),ci=g.object({version:g.string().min(1),agent_mode:Kt.optional(),rules:g.array(li),no_coverage:g.object({no_coverage_defaults:g.record(g.string()),autopilot_enabled:g.boolean(),enduser_hitl_enabled:g.boolean(),hitl_timeout_seconds:g.number()}).optional()}),ui=2e3,st=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return W(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 ai.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 o=await i.json();return ci.parse(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 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 o=await i.json();if(typeof o!="object"||o===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let a=o,s=a.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 a.reason=="string"?a.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await di(ui)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function di(e){return new Promise(t=>setTimeout(t,e))}function $e(){let e={};try{let t=`${j.platform()} ${j.release()}`.trim();t&&(e.os=t)}catch{}try{let t=j.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=j.userInfo();t&&(e.username=t)}catch{}try{let t=pi();t&&(e.ip=t)}catch{}return e}function pi(){let e=j.networkInterfaces();for(let t of Object.keys(e))for(let n of e[t]??[])if((n.family==="IPv4"||n.family===4)&&!n.internal&&n.address)return n.address}function fi(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Le(e,...t){for(let n of t){let r=fi(e[n]);if(r)return r}}function Fe(e){if(Le(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(Le(e,"user_id","userId"))return"user";if(Le(e,"agent_id","agentId"))return"agent";if(Le(e,"org_id","orgId","namespace"))return"org"}var mi=[{framework:"mem0",matches:e=>/^(mem0[_-])?(add|search|get|retrieve|update|delete)[_-]memor(y|ies)$/i.test(e),extract:(e,t)=>{let n=/^(?:mem0[_-])?([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"||n==="update"?r="write":r="read";let i=Fe(t);return{op:r,store:"mem0",framework:"mem0",...i?{scope:i}:{}}}},{framework:"letta",matches:e=>/^(core_memory_(append|replace)|archival_memory_(insert|search)|conversation_search)$/i.test(e),extract:e=>{let t=e.toLowerCase();return t.startsWith("core_memory_")?{op:"write",store:"letta-core",scope:"agent",framework:"letta"}:t==="archival_memory_insert"?{op:"write",store:"letta-archival",scope:"agent",framework:"letta"}:t==="archival_memory_search"?{op:"search",store:"letta-archival",scope:"agent",framework:"letta"}:{op:"search",store:"letta-conversation",scope:"session",framework:"letta"}}},{framework:"langgraph",matches:e=>/^(upsert_memory|save_recall_memory|search_recall_memories)$/i.test(e),extract:(e,t)=>{let n=/^search_/i.test(e),r=Fe(t);return{op:n?"search":"write",store:"langgraph-store",framework:"langgraph",...r?{scope:r}:{}}}},{framework:"zep",matches:e=>/^zep[_-](add|search|get|delete)[_-]memory$/i.test(e),extract:(e,t)=>{let n=/^zep[_-]([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"?r="write":r="read";let i=Fe(t)??"session";return{op:r,store:"zep",scope:i,framework:"zep"}}},{framework:"mcp-memory",matches:e=>/^(create_entities|create_relations|add_observations|delete_entities|delete_relations|delete_observations|search_nodes|open_nodes|read_graph)$/i.test(e),extract:e=>{let t=e.toLowerCase(),n;return t.startsWith("delete_")?n="delete":t==="search_nodes"?n="search":t==="open_nodes"||t==="read_graph"?n="read":n="write",{op:n,store:"mcp-memory",scope:"agent",framework:"mcp-memory"}}},{framework:"generic",matches:e=>/(^|[_\-.])(memory|memories|mem0|recall)([_\-.]|$)/i.test(e),extract:(e,t)=>{let n=e.toLowerCase(),r;/(^|[_\-.])(search|query|find|lookup|retrieve)([_\-.]|$)/.test(n)?r="search":/(^|[_\-.])(delete|remove|forget|clear|purge)([_\-.]|$)/.test(n)?r="delete":/(^|[_\-.])(add|save|write|store|upsert|put|set|update|insert|append|remember)([_\-.]|$)/.test(n)?r="write":r="read";let i=Fe(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function pe(e,t){if(!e)return null;let n=t??{};for(let r of mi)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function lt(e,t){let n=typeof t?.itemCount=="number"&&Number.isFinite(t.itemCount)&&t.itemCount>=0?Math.round(t.itemCount):void 0,r=typeof t?.bytes=="number"&&Number.isFinite(t.bytes)&&t.bytes>=0?Math.round(t.bytes):void 0,i=e.op==="read"||e.op==="search";return{op:e.op,store:e.store,...e.scope?{scope:e.scope}:{},...n!==void 0?{itemCount:n}:{},...r!==void 0?{bytes:r}:{},...i&&n!==void 0?{hit:n>0}:{}}}var Bt=new Map;function me(e){let t=(Bt.get(e)??0)+1;return Bt.set(e,t),t}function Gt(e){if(!e||typeof e!="object")return;let t={};for(let n of["tokensIn","tokensOut","cacheRead","cacheWrite"]){let r=e[n];typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[n]=Math.round(r))}return Object.keys(t).length>0?t:void 0}function ct(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=Array.isArray(n.texts)?n.texts.filter(a=>typeof a=="string"&&a.length>0).join(`
|
|
2
2
|
|
|
3
|
-
`):"",
|
|
4
|
-
`).map(l=>ao(l)).filter(l=>l.trim().length>0),a=0;for(;a<i.length;){let l=i[a].trim();if(l.startsWith("package ")||l.startsWith("import ")){a++;continue}let c=l.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(c){let _=c[1],f=c[2].trim();r.set(_,ye(f)),a++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let _=u[1],f=u[2].trim(),g=u[3].trim(),p=[];if(g&&g!=="}"){let x=g.endsWith("}")?g.slice(0,-1).trim():g;x&&p.push(x),g.endsWith("}")||(a++,a=Fe(i,a,p))}else g==="}"||(a++,a=Fe(i,a,p));let y=Kt(p);o.push({variable:_,value:ye(f),conditions:y,rawConditions:zt(p)}),a++;continue}let d=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(d){let _=d[1],f=d[2].trim(),g=[];if(f&&f!=="}"){let y=f.endsWith("}")?f.slice(0,-1).trim():f;y&&g.push(y),f.endsWith("}")||(a++,a=Fe(i,a,g))}else f==="}"||(a++,a=Fe(i,a,g));let p=Kt(g);o.push({variable:_,value:"true",conditions:p,rawConditions:zt(g)}),a++;continue}a++}let s={defaults:r,rules:o};return Vt.set(t,s),s}function ao(e){let t=!1,n="";for(let r=0;r<e.length;r++){let o=e[r];if(t)o===n&&e[r-1]!=="\\"&&(t=!1);else if(o==='"'||o==="'")t=!0,n=o;else if(o==="#")return e.slice(0,r)}return e}function Fe(e,t,n){let r=1,o=t;for(;o<e.length&&r>0;){let i=e[o].trim();for(let a of i)a==="{"&&r++,a==="}"&&r--;if(r>0)n.push(i),o++;else{let a=i.slice(0,i.lastIndexOf("}")).trim();return a&&n.push(a),o}}return o}function ye(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function so(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Kt(e){let t=[];for(let n of e){let r=n.split(";").map(o=>o.trim()).filter(o=>o.length>0);for(let o of r){let i=lo(o);i&&t.push(i)}}return t}function lo(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:Pe,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 o=n.match(/^startswith\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"startswith",negated:t,field:o[1].trim(),value:o[2]};let i=n.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(i)return{type:"endswith",negated:t,field:i[1].trim(),value:i[2]};let a=n.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(a)return{type:"contains",negated:t,field:a[1].trim(),value:a[2]};let s=n.match(/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:so(s[1])};let l=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s+in\s+((?:input|data)[^\s]*)$/);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:Xt(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let p=po(c[2]);if(p!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:p}}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 d=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s*==\s*((?:input|data)\S*)$/);if(d)return{type:"equality",negated:t,field:d[2].trim(),value:ye(d[1].trim())};let _=n.match(/^([^\s=!]+)\s*==\s*(.+)$/);if(_)return{type:"equality",negated:t,field:_[1].trim(),value:ye(_[2].trim())};let f=n.match(/^([^\s=!]+)\s*!=\s*(.+)$/);if(f)return{type:"inequality",negated:t,field:f[1].trim(),value:ye(f[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:Pe,value:e.trim()}}var Pe="__unrecognized_condition_forces_deny__";var co=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Zt(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==Pe&&co.test(r.field)&&t.push(r.field);return t}var uo=["input.normalized.","input.normalized["];function Jt(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions){let{field:o}=r;typeof o!="string"||o===Pe||uo.some(i=>o.startsWith(i))&&t.add(o)}return[...t].sort()}function Xt(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 po(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",o=!1,i="";for(let s=0;s<t.length;s++){let l=t[s];o?(r+=l,l===i&&t[s-1]!=="\\"&&(o=!1)):l==='"'||l==="'"?(r+=l,o=!0,i=l):l===","?(n.push(r.trim()),r=""):r+=l}if(o)return null;r.trim().length>0&&n.push(r.trim());let a=[];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;a.push(Xt(s))}return a}var fo=["tier1","tier2","tier3"];function en(e){return typeof e=="string"&&fo.includes(e)}var mo=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],go=["internal","customer_facing","experimental","third_party"],tn=[...mo,...go];function ho(e){return typeof e=="string"&&tn.includes(e)}function nn(e){let t=new Set;for(let n of e)ho(n)&&t.add(n);return tn.filter(n=>t.has(n))}var rn=["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"],_o=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],yo=["production","staging","development","test"],bo=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function vo(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 Gt={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 wo(e){let t=vo(e);return t===null?"other":Gt[t]??Gt[t.replace(/_/g,"")]??"other"}function on(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=wo(t.targetApp)),n.context=r}return n}var Ht=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],ko=["read","write","delete","share","export","decide","execute"],Wt=["none","low","medium","high","critical"],Ao=["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"],Io={action_class:rn,operation:ko,"context/app_category":_o,"context/environment":yo,"context/actor_function":bo,"read/classification":Ao,"read/data_categories":Ht,"read/data_sensitivity":Wt,"write/data_categories":Ht,"write/data_sensitivity":Wt};function an(e){if(e===null||typeof e!="object")return[];let t=e,n=new Set,r=(o,i,a)=>{let s=Array.isArray(i)?i:[i];for(let l of s)typeof l!="string"||l.length===0||a.includes(l)||n.add(`${o}=${l}`)};for(let[o,i]of Object.entries(Io)){Object.prototype.hasOwnProperty.call(t,o)&&r(o,t[o],i);let a=o.indexOf("/");if(a===-1)continue;let s=t[o.slice(0,a)];if(s!==null&&typeof s=="object"&&!Array.isArray(s)){let l=o.slice(a+1),c=s;Object.prototype.hasOwnProperty.call(c,l)&&r(o,c[l],i)}}return[...n].sort()}var Qt=64,So=64,be={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function sn(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var Eo=new Set(["deny","approval_required","escalate"]);function _e(e,t){if(t.length===0)return[...e];let n=new Set(e);for(let o of t)n.add(o);let r=[...n].sort();return r.length>Qt?r.slice(0,Qt):r}function Yt(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function $e(e){return typeof e=="string"&&e.length>0?e:null}function ln(e,t){let n=Yt(t.data_categories),r=$e(t.classification),o=Yt(t.taint),i=$e(t.action_class),a=i&&rn.includes(i)?i:null,s=$e(t.target_app),l=$e(t.decision),c={...e.action_counts};if(a)if(a in c)c[a]=(c[a]??0)+1;else if(Object.keys(c).length<So)c[a]=1;else{let u=Object.keys(c).sort(),d=u[u.length-1];d!==void 0&&a<d&&(delete c[d],c[a]=1)}return{retrieved_data_categories:_e(e.retrieved_data_categories,n),retrieved_classifications:_e(e.retrieved_classifications,r?[r]:[]),taint:_e(e.taint,o),action_classes:_e(e.action_classes,a?[a]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&Eo.has(l)?1:0),event_count:e.event_count+1,target_apps:_e(e.target_apps,s?[s]:[])}}var cn="generic",un=[{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:cn,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."}],To=un.map(e=>e.id),Gs=new Map(un.map(e=>[e.id,e])),Hs=new Set(To);function dn(e){return Array.isArray(e)&&e.length>0?[...e]:[cn]}var Ro=/^[a-z][a-z0-9_]*$/;function pn(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Ro.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Co=["narrow","moderate","broad","unbounded","unknown"];function fn(e){return typeof e=="string"&&Co.includes(e)}function mn(e){return e==="open"||e==="closed"?e:null}var Oo=["tool_name","function","name","action"];function je(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)je(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[o,i]of r)je(i,t?`${t}.${o}`:o,n);return}t&&n.push([t,e])}function No(e){let t=[];return je(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function Mo(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function Do(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function Lo(e,t={}){if(t.discriminatorField===null)return null;let n=[];je(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??Oo;for(let o of r){let i=null;for(let[a,s]of n){if(Mo(a)!==o)continue;let l=Do(s);l!==null&&(i===null||a<i.path)&&(i={path:a,value:l})}if(i)return i.value}return null}function gn(e,t={}){let n=xo("sha256").update(No(e).join(",")).digest("hex").slice(0,16),r=Lo(e,t);return r!==null?`${n}:${r}`:n}var Fo=["action","retrieval","delegation"];function $o(e){return typeof e=="string"&&Fo.includes(e)}var Po=new Set(["rules"]);function hn(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Po.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter($o):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{z as Ve}from"zod";var En="[REDACTED]",Tn=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"in_pan_tax",re:/\b[A-Z]{3}[ABCFGHJLPTE][A-Z]\d{4}[A-Z]\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"date_of_birth",re:/\b(?:\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])|(?:0[1-9]|[12]\d|3[01])[/.](?:0[1-9]|1[0-2])[/.]\d{4}|(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12]\d|3[01])\/\d{4})\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];function ut(e){if(!/^\d+$/.test(e))return!1;let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let o=e.charCodeAt(r)-48;n&&(o*=2,o>9&&(o-=9)),t+=o,n=!n}return t%10===0}function jo(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 o=0;o<n.length;o++){let i=n[o],a=i>="A"&&i<="Z"?String(i.charCodeAt(0)-55):i;for(let s=0;s<a.length;s++)r=(r*10+(a.charCodeAt(s)-48))%97}return r===1}function Uo(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 Bo=[[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]],qo=[[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 Vo(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=Bo[t][qo[r%8][n[r].charCodeAt(0)-48]];return t===0}function zo(e){if(!/^\d{11}$/.test(e)||/^(\d)\1{10}$/.test(e))return!1;let t=n=>{let r=0;for(let i=0;i<n;i++)r+=(e.charCodeAt(i)-48)*(n+1-i);let o=r*10%11;return o===10?0:o};return t(9)===e.charCodeAt(9)-48&&t(10)===e.charCodeAt(10)-48}function Ko(e){if(!/^\d{10}$/.test(e))return!1;let t=0;for(let o=0;o<9;o++)t+=(e.charCodeAt(o)-48)*(10-o);let n=11-t%11,r=n===11?0:n;return r!==10&&r===e.charCodeAt(9)-48}var Go=[1,4,3,7,5,8,6,9,10];function Ho(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)*Go[n];return t%11===0}var Wo="TRWAGMYFPDXBNJZSQVHLCKE";function Qo(e){let t=e.replace(/[\s-]/g,"").toUpperCase(),n=/^([XYZ]?)(\d{7,8})([A-Z])$/.exec(t);if(!n)return!1;let[,r,o,i]=n;if(r===""&&o.length!==8||r!==""&&o.length!==7)return!1;let a=r===""?o:String("XYZ".indexOf(r))+o;return Wo[Number(a)%23]===i}var Yo=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Zo(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Yo.has(t.slice(0,2)):!1}var pt=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&ut(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:jo},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Uo},{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:Zo(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&&Vo(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:zo},{name:"es_dni_nie",re:/\b[XYZxyz]?\d{7,8}[ -]?[A-Za-z]\b/g,normalize:e=>e.replace(/[\s-]/g,"").toUpperCase(),validate:Qo},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&ut(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Ko},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Ho}],Jo=Object.fromEntries([...Tn,...pt].map(e=>[e.name,e.re.source])),I=Jo,Ys=pt.map(e=>e.name),Rn=["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"],Be={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
3
|
+
`):"",o=Gt(n.usage);e.emitCognition({clientEventId:fe(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:me(r),ts:Date.now(),kind:n.final?"speech":"thought",visibility:"shown",provenance:"narration",...i?{content:{text:i}}:{},...o?{cost:o}:{},...n.model?{model:n.model}:{},...typeof n.durationMs=="number"&&Number.isFinite(n.durationMs)?{durationMs:Math.max(0,Math.round(n.durationMs))}:{},...t.framework?{framework:t.framework}:{}})}function ge(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId:fe(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:me(r),ts:Date.now(),kind:"spawn",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},spawn:{childAgentId:n.childAgentId,childName:n.childName,kind:n.kind,...n.model?{model:n.model}:{},...n.task?{prompt:n.task}:{}}})}function he(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=n.memory?lt(n.memory):void 0;e.emitCognition({clientEventId:fe(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:me(r),ts:Date.now(),kind:i?"memory":"action",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},tool:{name:n.toolName,...n.verb?{verb:n.verb}:{},...n.argSummary?{argSummary:n.argSummary}:{}},...i?{memory:i}:{}})}function _e(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.round(c):void 0,o=i(n.bytes),a=i(n.itemCount),s=i(n.durationMs),l;n.memory&&(l=lt(n.memory,{itemCount:a,bytes:o})),e.emitCognition({clientEventId:fe(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:me(r),ts:Date.now(),kind:"observation",visibility:"shown",provenance:"parsed",...s!==void 0?{durationMs:s}:{},...t.framework?{framework:t.framework}:{},tool:{name:n.toolName},result:{ok:n.ok,...o!==void 0?{bytes:o}:{},...a!==void 0?{itemCount:a}:{}},...l?{memory:l}:{}})}function te(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId:fe(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:me(r),ts:Date.now(),kind:"intervention",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},tool:{name:n.toolName},governance:{decision:n.decision,enforced:n.enforced,...n.ruleCode?{ruleCode:n.ruleCode}:{},...n.ruleLabel?{ruleLabel:n.ruleLabel}:{},...n.harnessMessage?{harnessMessage:n.harnessMessage}:{}}})}function Q(e){try{let t=JSON.stringify(e);return typeof t=="string"?t.length:void 0}catch{return}}function Y(e){try{return Array.isArray(e)?e.length:void 0}catch{return}}import{z as _}from"zod";import{createHash as gi}from"crypto";import{createHash as Vi}from"crypto";var Ht=new Map;function Wt(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function ut(e){let t=gi("sha256").update(e).digest("hex"),n=Ht.get(t);if(n)return n;let r=new Map,i=[],o=e.split(`
|
|
4
|
+
`).map(l=>hi(l)).filter(l=>l.trim().length>0),a=0;for(;a<o.length;){let l=o[a].trim();if(l.startsWith("package ")||l.startsWith("import ")){a++;continue}let c=l.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(c){let h=c[1],f=c[2].trim();r.set(h,be(f)),a++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let h=u[1],f=u[2].trim(),m=u[3].trim(),p=[];if(m&&m!=="}"){let x=m.endsWith("}")?m.slice(0,-1).trim():m;x&&p.push(x),m.endsWith("}")||(a++,a=Pe(o,a,p))}else m==="}"||(a++,a=Pe(o,a,p));let y=Qt(p);i.push({variable:h,value:be(f),conditions:y,rawConditions:Wt(p)}),a++;continue}let d=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(d){let h=d[1],f=d[2].trim(),m=[];if(f&&f!=="}"){let y=f.endsWith("}")?f.slice(0,-1).trim():f;y&&m.push(y),f.endsWith("}")||(a++,a=Pe(o,a,m))}else f==="}"||(a++,a=Pe(o,a,m));let p=Qt(m);i.push({variable:h,value:"true",conditions:p,rawConditions:Wt(m)}),a++;continue}a++}let s={defaults:r,rules:i};return Ht.set(t,s),s}function hi(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 Pe(e,t,n){let r=1,i=t;for(;i<e.length&&r>0;){let o=e[i].trim();for(let a of o)a==="{"&&r++,a==="}"&&r--;if(r>0)n.push(o),i++;else{let a=o.slice(0,o.lastIndexOf("}")).trim();return a&&n.push(a),i}}return i}function be(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function _i(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Qt(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 o=ki(i);o&&t.push(o)}}return t}var dt=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,yi=new RegExp(`^(${dt.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),bi=new RegExp(`^(${dt.source})\\s*==\\s*((?:input|data)\\S*)$`),vi=/^([^\s=!]+)\s*==\s*(.+)$/,wi=/^([^\s=!]+)\s*!=\s*(.+)$/,_l=new RegExp(`^(?:${dt.source})$`);function ki(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:Be,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 o=n.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"endswith",negated:t,field:o[1].trim(),value:o[2]};let a=n.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(a)return{type:"contains",negated:t,field:a[1].trim(),value:a[2]};let s=n.match(/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:_i(s[1])};let l=n.match(yi);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:rn(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let p=Si(c[2]);if(p!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:p}}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 d=n.match(bi);if(d)return{type:"equality",negated:t,field:d[2].trim(),value:be(d[1].trim())};let h=n.match(vi);if(h)return{type:"equality",negated:t,field:h[1].trim(),value:be(h[2].trim())};let f=n.match(wi);if(f)return{type:"inequality",negated:t,field:f[1].trim(),value:be(f[2].trim())};let m=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return m?{type:"truthy",negated:t,field:m[1].trim()}:{type:"truthy",negated:!1,field:Be,value:e.trim()}}var Be="__unrecognized_condition_forces_deny__";var Ai=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function tn(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==Be&&Ai.test(r.field)&&t.push(r.field);return t}var Ii=["input.normalized.","input.normalized["];function nn(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===Be||Ii.some(o=>i.startsWith(o))&&t.add(i)}return[...t].sort()}function rn(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 Si(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",i=!1,o="";for(let s=0;s<t.length;s++){let l=t[s];i?(r+=l,l===o&&t[s-1]!=="\\"&&(i=!1)):l==='"'||l==="'"?(r+=l,i=!0,o=l):l===","?(n.push(r.trim()),r=""):r+=l}if(i)return null;r.trim().length>0&&n.push(r.trim());let a=[];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;a.push(rn(s))}return a}var Ei=["tier1","tier2","tier3"];function on(e){return typeof e=="string"&&Ei.includes(e)}var Ti=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Ri=["internal","customer_facing","experimental","third_party"],an=[...Ti,...Ri];function Ci(e){return typeof e=="string"&&an.includes(e)}function sn(e){let t=new Set;for(let n of e)Ci(n)&&t.add(n);return an.filter(n=>t.has(n))}var ln=["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"],xi=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],Oi=["production","staging","development","test"],Ni=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function Mi(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 Yt={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 Di(e){let t=Mi(e);return t===null?"other":Yt[t]??Yt[t.replace(/_/g,"")]??"other"}function cn(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=Di(t.targetApp)),n.context=r}return n}var Zt=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],Li=["read","write","delete","share","export","decide","execute"],Jt=["none","low","medium","high","critical"],Fi=["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"],$i={action_class:ln,operation:Li,"context/app_category":xi,"context/environment":Oi,"context/actor_function":Ni,"read/classification":Fi,"read/data_categories":Zt,"read/data_sensitivity":Jt,"write/data_categories":Zt,"write/data_sensitivity":Jt};function un(e){if(e===null||typeof e!="object")return[];let t=e,n=new Set,r=(i,o,a)=>{let s=Array.isArray(o)?o:[o];for(let l of s)typeof l!="string"||l.length===0||a.includes(l)||n.add(`${i}=${l}`)};for(let[i,o]of Object.entries($i)){Object.prototype.hasOwnProperty.call(t,i)&&r(i,t[i],o);let a=i.indexOf("/");if(a===-1)continue;let s=t[i.slice(0,a)];if(s!==null&&typeof s=="object"&&!Array.isArray(s)){let l=i.slice(a+1),c=s;Object.prototype.hasOwnProperty.call(c,l)&&r(i,c[l],o)}}return[...n].sort()}var Xt=64,Pi=64,ve={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function dn(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var ji=new Set(["deny","approval_required","escalate"]);function ye(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>Xt?r.slice(0,Xt):r}function en(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function je(e){return typeof e=="string"&&e.length>0?e:null}function pn(e,t){let n=en(t.data_categories),r=je(t.classification),i=en(t.taint),o=je(t.action_class),a=o&&ln.includes(o)?o:null,s=je(t.target_app),l=je(t.decision),c={...e.action_counts};if(a)if(a in c)c[a]=(c[a]??0)+1;else if(Object.keys(c).length<Pi)c[a]=1;else{let u=Object.keys(c).sort(),d=u[u.length-1];d!==void 0&&a<d&&(delete c[d],c[a]=1)}return{retrieved_data_categories:ye(e.retrieved_data_categories,n),retrieved_classifications:ye(e.retrieved_classifications,r?[r]:[]),taint:ye(e.taint,i),action_classes:ye(e.action_classes,a?[a]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&ji.has(l)?1:0),event_count:e.event_count+1,target_apps:ye(e.target_apps,s?[s]:[])}}var fn="generic",mn=[{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:fn,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."}],Bi=mn.map(e=>e.id),yl=new Map(mn.map(e=>[e.id,e])),bl=new Set(Bi);function gn(e){return Array.isArray(e)&&e.length>0?[...e]:[fn]}var Ui=/^[a-z][a-z0-9_]*$/;function hn(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Ui.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var qi=["narrow","moderate","broad","unbounded","unknown"];function _n(e){return typeof e=="string"&&qi.includes(e)}function yn(e){return e==="open"||e==="closed"?e:null}var zi=["tool_name","function","name","action"];function Ue(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)Ue(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,o]of r)Ue(o,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Ki(e){let t=[];return Ue(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function Gi(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function Hi(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function Wi(e,t={}){if(t.discriminatorField===null)return null;let n=[];Ue(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??zi;for(let i of r){let o=null;for(let[a,s]of n){if(Gi(a)!==i)continue;let l=Hi(s);l!==null&&(o===null||a<o.path)&&(o={path:a,value:l})}if(o)return o.value}return null}function bn(e,t={}){let n=Vi("sha256").update(Ki(e).join(",")).digest("hex").slice(0,16),r=Wi(e,t);return r!==null?`${n}:${r}`:n}var Qi=["action","retrieval","delegation"];function Yi(e){return typeof e=="string"&&Qi.includes(e)}var Zi=new Set(["rules"]);function vn(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Zi.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Yi):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{z as Ke}from"zod";var Dn="[REDACTED]",gt=[{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}],kl=gt.map(({name:e,re:t})=>({name:e,source:t.source}));function ft(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 Ji(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 o=n[i],a=o>="A"&&o<="Z"?String(o.charCodeAt(0)-55):o;for(let s=0;s<a.length;s++)r=(r*10+(a.charCodeAt(s)-48))%97}return r===1}function Xi(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 eo=[[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]],to=[[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 no(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=eo[t][to[r%8][n[r].charCodeAt(0)-48]];return t===0}function ro(e){if(!/^\d{11}$/.test(e)||/^(\d)\1{10}$/.test(e))return!1;let t=n=>{let r=0;for(let o=0;o<n;o++)r+=(e.charCodeAt(o)-48)*(n+1-o);let i=r*10%11;return i===10?0:i};return t(9)===e.charCodeAt(9)-48&&t(10)===e.charCodeAt(10)-48}function io(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 oo=[1,4,3,7,5,8,6,9,10];function ao(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)*oo[n];return t%11===0}var so="TRWAGMYFPDXBNJZSQVHLCKE";function lo(e){let t=e.replace(/[\s.-]/g,"").toUpperCase(),n=/^([XYZ]?)(\d{7,8})([A-Z])$/.exec(t);if(!n)return!1;let[,r,i,o]=n;if(r===""&&i.length!==8||r!==""&&i.length!==7)return!1;let a=r===""?i:String("XYZ".indexOf(r))+i;return so[Number(a)%23]===o}var co=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function uo(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!co.has(t.slice(0,2)):!1}var ht=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&ft(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:Ji},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Xi},{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:uo(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&&no(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:ro},{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:lo},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&ft(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:io},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:ao}],po=Object.fromEntries([...gt,...ht].map(e=>[e.name,e.re.source])),I=po,Al=ht.map(e=>e.name),Ln=["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"],Ve={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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:.896}},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:I.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:.991}},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:I.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:I.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:I.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:I.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:I.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:I.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.",examples:["12345678A","X1234567H"],measuredOverMaskRate:.973}},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:I.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:I.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:I.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:I.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:I.mac_address,mode:"full"},defaultEnabled:!1}};var Zs=new Set(Rn.filter(e=>!Be[e].defaultEnabled));function Xo(e,t){let n=new Set;for(let r of Rn)(Be[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function ei(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let o=e;for(let{name:i,re:a}of Tn){let s=i;n.has(s)||(o=o.replace(a,()=>(r?.(s),t)))}for(let{name:i,re:a,normalize:s,validate:l}of pt)n.has(i)||(o=o.replace(a,c=>l(s(c),c)?(r?.(i),t):c));return o}function ft(e,t=En,n,r){return ti(e,t,Xo(n,r))}function ti(e,t,n){let r=new Set,o=!n.has("pan"),i=s=>{r.add(s)},a=s=>{if(typeof s=="string")return ei(s,t,n,i);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!o)return s;let l=String(s);return l.length>=13&&l.length<=19&&ut(l)?(r.add("pan"),t):s}if(Array.isArray(s))return s.map(l=>a(l));if(s!==null&&typeof s=="object"){let l=s,c={};for(let u of Object.keys(l))c[u]=a(l[u]);return c}return s};return{value:a(e),detectors:[...r].sort()}}function Cn(e,t=En){return ft(e,t).value}function ni(e){let{value:t,detectors:n}=ft(e),r=n.some(o=>Be[o].category==="secret");return{detectors:n,blocked:r,redacted:t}}function ri(e,t){let{blocked:n,redacted:r,detectors:o}=ni(e);return n?t.failMode==="closed"?{verdict:"block",redacted:r,detectors:o}:{verdict:"redact",redacted:r,detectors:o}:{verdict:"allow",redacted:r,detectors:o}}function oi(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var ii=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function ai(e){return ii.has(oi(e))}function ne(e,t,n){return n.enforced&&ai(e)?ri(t,{failMode:n.failMode}):{verdict:"allow",redacted:t,detectors:[]}}var si=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,xn=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"}),li=new RegExp(`[${Object.keys(xn).join("")}]`,"gu"),ci=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),On="\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",ui=Object.freeze(Object.fromEntries([...On].map((e,t)=>[e,String.fromCharCode(97+t)]))),di=new RegExp(`[${On}\u2800]`,"g"),Nn=/[⠀-⣿]/;function pi(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 fi(e){return e.replace(si,"")}function Mn(e){return e.replace(li,t=>xn[t]??t)}function mi(e){return e.replace(/[4@31!05$79(8]/g,t=>ci[t]??t)}function gi(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 hi(e){return Nn.test(e)?e.replace(di,t=>t==="\u2800"?" ":ui[t]??t):e}function _n(e){let t;try{t=pi(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=fi(t),t=Mn(t),t}var _i=/^[A-Za-z0-9+/]{16,}={0,2}$/,yi=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,yn=/[A-Za-z0-9+/]{20,}={0,2}/g;function dt(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 Dn=new TextDecoder("utf-8",{fatal:!1});function Ln(e){let t;try{t=atob(e)}catch{return[]}let n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o)&255;let r=Dn.decode(n);return t===r?[t]:[r,t]}function bi(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 i=0;i<n.length;i++){let a=Number.parseInt(t.slice(i*2,i*2+2),16);if(Number.isNaN(a))return[];n[i]=a}let r="";for(let i=0;i<n.length;i++)r+=String.fromCharCode(n[i]);let o=Dn.decode(n);return r===o?[r]:[o,r]}function bn(e){let t=e.trim(),n=[];if(yi.test(t))for(let r of bi(t))n.push({decoded:r,textiness:dt(r)});if(_i.test(t)&&t.length%4===0)for(let r of Ln(t))n.push({decoded:r,textiness:dt(r)});return n}function vn(e,t){let n=[],r;for(yn.lastIndex=0;(r=yn.exec(e))!==null&&n.length<t;){let o=r[0];if(o.length%4===0)for(let i of Ln(o))n.push({decoded:i,textiness:dt(i)})}return n}var vi=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function Fn(e,t=vi){if(typeof e!="string"||e.length===0)return{views:[],anyDecoded:!1,truncated:!1,nodes:0,maxDepthSeen:0};let{maxDepth:n,byteCap:r,maxNodes:o,maxBlobsPerNode:i}=t,a=new Set,s=f=>{f.length>0&&f.length<=r&&a.add(f)},l=!1,c=!1,u=0,d=0,_=[{s:e,depth:0}];for(;_.length>0;){if(u>=o){c=!0;break}let f=_.pop();if(f===void 0)break;let{s:g,depth:p}=f;if(g.length>r){c=!0;continue}u++,p>d&&(d=p);let y=_n(g);s(y);let x=mi(y);if(x!==y&&s(x),s(gi(y)),Nn.test(g)&&s(hi(y)),p>=n){let T=_n(g);(bn(T).length>0||vn(T,i).length>0)&&(c=!0);continue}let A=[...bn(y),...vn(y,i)];for(let T of A){if(l=!0,T.decoded.length>r){c=!0;continue}T.textiness>=.85&&T.decoded!==y?_.push({s:T.decoded,depth:p+1}):s(T.decoded)}}return{views:[...a],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:d}}var $n=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],wi=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),ki=8,Ai=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),wn=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function Ii(e){let t=[...e].map(r=>r.codePointAt(0)),n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o>=917504&&o<=917631||Ai.has(o)&&wn(t[r-1])&&wn(t[r+1])&&(n++,n>=ki))return!0}return!1}var Si=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function Ei(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(Si.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Ti=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Ri(e){for(let t of Ti)if(e>=t.lo&&e<=t.hi)return t.name;return null}function Ci(e){for(let t of e.split(/\s+/)){if(t.length<4)continue;let n=0,r=0,o=!0;for(let i of t){let a=Ri(i.codePointAt(0));if(a===null){o=!1;break}a==="latin"?n++:Mn(i)!==i&&r++}if(o&&n>0&&r>0)return!0}return!1}var kn=Object.freeze({signals:[],contributes:!1});function xi(e){if(typeof e!="string"||e.length===0)return{...kn,signals:[]};let t=new Set;try{Ii(e)&&t.add("hidden_text_carrier"),Ei(e)&&t.add("injected_turn_boundary"),Ci(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:o}=Fn(e);n&&(r>=2||o)&&t.add("nested_encoding_payload")}catch{return{...kn,signals:[]}}return{signals:[...$n.filter(n=>t.has(n))],contributes:wi.some(n=>t.has(n))}}var qe=[{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 An(e){return typeof e!="string"||e.length===0?[]:qe.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function Oi(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(An(e)),{views:n}=Fn(e);for(let r of n)for(let o of An(r))t.add(o);return qe.filter(r=>t.has(r.name)).map(r=>r.name)}function Ni(e){let t=new Set,n=new Set,r=!1,o=i=>{if(i!=null){if(typeof i=="string"){for(let s of Oi(i))t.add(s);let a=xi(i);for(let s of a.signals)n.add(s);a.contributes&&(r=!0);return}if(Array.isArray(i)){for(let a of i)o(a);return}if(typeof i=="object")for(let a of Object.values(i))o(a)}};return o(e),{matched:t.size>0||r,signatures:qe.filter(i=>t.has(i.name)).map(i=>i.name),structural:$n.filter(i=>n.has(i))}}function Mi(e){return Ni(e).matched}var Js=qe.map(e=>e.name);var Di=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Li="i:injection";function Pn(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:o}=ft(e.content);for(let i of o){let a=Be[i]?.category;a&&t.add(`c:${a}`)}Mi(e.content)&&t.add(Li)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Di.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var ct="(?: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))",Xs=[{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${ct}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${ct}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${ct}\\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}],In="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Fi=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${In}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${In}|programming|training))`,$i="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Sn="(?:\\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)",Pi="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",el=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${$i}${Fi}\\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}?${Sn}`,"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+(?:${Pi}\\b|[\\s\\S]{0,40}?${Sn})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var tl=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var q=e=>`[^.!?;\\n]{0,${e}}?`,ji=["\\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("|"),jn="(?: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)",nl=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${ji})\\s${q(40)}\\b${jn}\\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${q(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${q(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${q(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${q(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${q(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")}]),rl=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${q(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${q(30)}\\b${jn}\\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 ve=e=>`[^.!?;\\n]{0,${e}}?`,ol=Object.freeze([{id:"vulnerability_scanning",objectPatterns:[/\b(?:vulnerability|vuln|security)\s+(?:scan|scans|scanning|assessment|audit|test|testing)\b/i,/\bpen(?:etration)?[\s-]?test(?:ing)?\b/i,/\bport\s+scan(?:ning)?\b/i,/\b(?:exploit|nmap|metasploit|nessus|burp\s+suite)\b/i,/\bCVE-\d{4}-\d{4,7}\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|vulnerability|incident\s+respon\w{0,4}|threat|soc|red\s+team|phishing|malware)\b/i]},{id:"credential_access",objectPatterns:[/\b(?:credential|password|passphrase|api\s+key|access\s+key|secret|token|private\s+key|ssh\s+key)s?\b/i,/\b(?:vault|secrets?\s+manager|keychain|keystore)\b/i,/\bservice\s+account\s+key\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|identity|iam|credential|secrets?\s+manage\w{0,4}|vault|platform|devops)\b/i]},{id:"financial_transaction",objectPatterns:[/\b(?:wire\s+transfer|bank\s+transfer|payout|disbursement|chargeback)\b/i,new RegExp(`\\b(?:approve|issue|initiate|process|release)\\s${ve(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${ve(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${ve(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${ve(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${ve(30)}\\b(?:external|customer|customers|public|press|social\\s+media|third[\\s-]party|prospect|prospects)\\b`,"i"),/\b(?:cold\s+outreach|marketing\s+blast|phishing\s+email|press\s+release)\b/i],purposeFunctions:["marketing","sales","customer_support"],purposePatterns:[/\b(?:marketing|campaign|outreach|email\s+assistant|support|customer|sales|lead|leads|communication|communications)\b/i]}]);var mt="[REDACTED]",te="\u2022",Ue=e=>/[A-Za-z0-9]/.test(e);function Un(e,t,n,r){let o=Array.from(e),i=o.length,a=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:te,c=a+s>=i;return o.map((u,d)=>!c&&(d<a||d>=i-s)?u:Ue(u)?l:u).join("")}function Ui(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Un(e,0,0,t);let r=e.slice(0,n),o=e.slice(n),i=t.length>0?t:te;return(r.length<=1?i:r[0]+Array.from(r.slice(1)).map(a=>Ue(a)?i:a).join(""))+o}function Bi(e,t,n){let r=n.length>0?n:te,o=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let c=new RegExp(t,"g"),u;for(;(u=c.exec(e))!==null;){if(u[0].length===0){c.lastIndex++;continue}for(let d=u.index;d<u.index+u[0].length;d++)o[d]=!0}}catch{}let i=!1,a=!0;for(let c=0;c<e.length;c++)if(Ue(e[c])&&(i=!0,!o[c])){a=!1;break}let s=i&&a,l="";for(let c=0;c<e.length;c++){let u=e[c];!s&&o[c]||!Ue(u)?l+=u:l+=r}return l}function Bn(e,t){let n=t.mode??"full";return n==="partial"?Un(e,t.keepFirst??0,t.keepLast??0,t.maskChar??te):n==="email"?Ui(e,t.maskChar??te):n==="custom"?Bi(e,t.keepPattern,t.maskChar??te):t.replacement??mt}function qi(e,t){return typeof e=="string"?Bn(e,t):t.replacement??mt}function qn(e){let t=[],n=e.replacement??mt;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:o}=r;typeof o!="string"||o.length===0||t.push({source:o,replacer:i=>Bn(i,r)})}return t}function Vn(e,t){let n=e;for(let{source:r,replacer:o}of t){let i;try{i=new RegExp(r,"g")}catch(a){let s=a instanceof Error?a.message:String(a);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(i,a=>o(a))}return n}function M(e,t){return e==null?e:typeof e=="string"?Vi(e,t):typeof e=="object"?zi(e,t):e}function Vi(e,t){if(typeof e!="string")return e;let n=qn(t);return n.length===0?e:Vn(e,n)}function zi(e,t){let n=new Map;for(let s of t.fields??[])typeof s=="string"&&s.length>0&&n.set(s,{field:s,mode:"full",replacement:t.replacement});for(let s of t.directives??[])typeof s.field=="string"&&s.field.length>0&&n.set(s.field,s);let r=qn(t),o=n.size>0,i=r.length>0,a=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>a(l));if(typeof s=="object"){let l=s,c=Object.create(Object.getPrototypeOf(l));for(let u of Object.keys(l)){let d=o?n.get(u):void 0;if(d){c[u]=qi(l[u],d);continue}c[u]=a(l[u])}return c}return typeof s=="string"&&i?Vn(s,r):s};return a(e)}var zn=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Ki(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:zn(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:zn(t.spawn.prompt)}),t}function Gi(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 Hi=1440*60*1e3,Wi="VISIQ_BUNDLE_GRACE_TTL_MS",Qi="VISIQ_BUNDLE_CACHE_DISABLED",Yi="VISIQ_CACHE_DIR",Zi=Ve.object({graceTtlMs:Ve.number().int().nonnegative().optional(),disabled:Ve.boolean().optional(),cacheDir:Ve.string().min(1).optional()}).strict();function Ji(e){return e==null?{}:Zi.parse(e)}function Xi(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Wi];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Hi}function ea(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Qi]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var Kn;function ta(){if(Kn!==void 0)return Kn;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function na(e){return JSON.stringify(ht(e))}function ht(e){if(Array.isArray(e))return e.map(ht);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=ht(t[r]);return n}return e}function ra(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function oa(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 Zn(){if(!ta())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 Jn(e,t){return e.createHash("sha256").update(na(t)).digest("hex")}function ia(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Yi]?.trim();if(r)return r;let o=process.env.XDG_CACHE_HOME?.trim();if(o)return e.path.join(o,"visiq");let i="";try{i=e.os.homedir()}catch{i=""}return i?e.path.join(i,".cache","visiq"):e.path.join(e.os.tmpdir(),"visiq-cache")}function aa(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function Xn(e,t,n){return e.path.join(ia(e,n),"bundles",`${aa(e,t)}.json`)}async function sa(e,t,n,r={}){let o=await Zn();if(o)try{let i=Xn(o,e,r),a=o.path.dirname(i);await o.fs.mkdir(a,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:Jn(o.crypto,t),body:t},l=`${i}.tmp-${process.pid}-${o.crypto.randomBytes(6).toString("hex")}`;await o.fs.writeFile(l,JSON.stringify(s),{mode:384});try{await o.fs.rename(l,i)}catch(c){throw await o.fs.rm(l,{force:!0}).catch(()=>{}),c}}catch{}}async function la(e,t={}){let n=await Zn();if(!n)return null;try{let r=await n.fs.readFile(Xn(n,e,t),"utf-8"),o=oa(JSON.parse(r));return!o||Jn(n.crypto,o.body)!==o.contentHash?null:o}catch{return null}}var we;async function ca(){if(we!==void 0)return we;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;we=typeof t=="function"?t:null}catch{we=null}return we}function ua(e){let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,o=r.rego_source;if(typeof o!="string"||o.length===0)continue;let i;try{i=lt(o)}catch{continue}let a=typeof r.id=="string"?r.id:"<rule>";for(let s of Zt(i))t.push(`${a}: ${s}`)}return t}function da(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 o;try{o=lt(r)}catch{continue}let i=Jt(o);if(i.length!==0)for(let a of n.appliesTo){let s=t[a];if(s)for(let l of i)s.add(`${n.id}: ${l}`)}}return{retrieval:[...t.retrieval].sort(),action:[...t.action].sort(),delegation:[...t.delegation].sort()}}function pa(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var fa=5e3,ma=600*1e3,ga=1e4,ha=25,Gn=1e3,_a=5e3,ya=100,Hn=2e3,ba=10,va=512,wa=1800*1e3,ka=.7,Aa="monitor",Ia="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",Wn="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.",ze="open";function ke(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Sa(e,t){return Pn({content:e,resourceMetadata:t})}var Ea=h.object({operations:h.array(h.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:h.string().min(1,"agentId is required"),sessionId:h.string().min(1).max(255).optional(),toolName:h.string().optional(),toolArgs:h.record(h.unknown()).optional(),targetResource:h.string().optional(),resourceType:h.string().optional(),resourceMetadata:h.record(h.unknown()).optional(),normalized:h.record(h.unknown()).optional(),query:h.string().optional(),contentPreview:h.string().optional(),telemetry:h.record(h.unknown()).optional(),context:h.record(h.unknown()).optional(),mcpServer:h.string().min(1).max(255).optional()}),Ta=h.object({version:h.string().min(1),dialect_version:h.number().int().optional(),min_dialect:h.number().int().optional(),shutdown:h.boolean().optional(),agent_mode:h.enum(["enforce","monitor","off"]).optional(),cognition_capture:h.boolean().optional(),agent_mode_by_operation:h.object({action:h.string().optional(),retrieval:h.string().optional(),delegation:h.string().optional()}).partial().optional(),agent_attributes:h.object({trust_tier:h.string().nullable().optional(),categories:h.array(h.string()).optional(),business_function:h.string().nullable().optional(),business_functions:h.array(h.string()).nullable().optional(),blast_radius_tier:h.string().nullable().optional(),no_coverage:h.string().nullable().optional(),fail_mode:h.string().nullable().optional()}).optional(),rules:h.array(h.record(h.unknown())),action_schemas:h.array(h.object({id:h.string(),plane:h.string().optional(),field_mappings:h.array(h.record(h.unknown())).optional(),derived_fields:h.array(h.record(h.unknown())).optional(),action_class:h.string().nullable().optional(),action_class_confidence:h.number().optional()})).optional(),no_coverage:h.object({no_coverage_defaults:h.record(h.string()),autopilot_enabled:h.boolean(),enduser_hitl_enabled:h.boolean(),hitl_timeout_seconds:h.number().optional()}).optional()});function Ra(e){let t=e.trust_tier??null,n=[];Array.isArray(e.business_functions)&&e.business_functions.length>0?n=e.business_functions:typeof e.business_function=="string"&&e.business_function!==""&&(n=[e.business_function]);let r=dn(pn(n));return{trust_tier:en(t)?t:null,categories:nn(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&fn(e.blast_radius_tier)?e.blast_radius_tier:null}}function Ca(e){if(!e)return null;let t={};for(let n of["action","retrieval","delegation"]){let r=e[n];(r==="enforce"||r==="monitor"||r==="off")&&(t[n]=r)}return Object.keys(t).length>0?t:null}function xa(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var _t=new Set,Qn=!1;async function Yn(e){let t=[];for(let n of _t){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 Oa(){if(!Qn&&!(typeof process>"u"||typeof process.once!="function")){Qn=!0,process.once("beforeExit",()=>{Yn(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await Yn(!0)}finally{process.kill(process.pid,e)}})()})}}var er=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;cacheIdentity;bundleCacheDisabled;bundleGraceTtlMs;bundleCacheDirOverride;diskFallbackServed=!1;agentMode=Aa;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=ke(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??ze;governedFailMode=null;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastCloneCaptureSig=null;toolDescriptions=new Map;constructor(e,t,n,r,o,i,a,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=i,this.sdkDialect=a,this.originalFetch=globalThis.fetch.bind(globalThis);let d=Ji(s);if(this.bundleCacheDisabled=ea(d.disabled),this.bundleGraceTtlMs=Xi(d.graceTtlMs),this.bundleCacheDirOverride=d.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let _={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:Gi(o),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...i!==void 0?{sdkVersion:i}:{},...a!==void 0?{sdkDialect:a}:{}};this.client=new it(_,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},fa),gt(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},ga),gt(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},_a),gt(this.cognitionTimer),_t.add(this),Oa()}else this.client=null}async evaluate(e){let t=Ea.parse(e),n=Date.now();if(this.operatorShutdown){let f=this.denyAll(t,Ia);return this.applyAgentMode(f,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,Wn,n);let f=this.denyAll(t,Wn);return this.applyAgentMode(f,"enforce",t,n)}if(t.operations.every(f=>this.modeFor(f)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let f;if(this.agentModeConfirmed?f=this.agentMode:this.bundleApplyFailed?f="enforce":f="monitor",f==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let g=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(g,f,t,n)}let r=this.readSession(t.sessionId),o=await ca();if(!o||!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 i=t.operations.includes("action")||t.operations.includes("delegation")?on(t.normalized??{},{targetApp:t.targetResource??t.toolName??""}):t.normalized,a=this.buildActionSchemaEvent(t),s=t.mcpServer?{...i??{},mcp_server:t.mcpServer}:i,l={...t,normalized:s,session:r,at:Date.now(),action_schema_id:a.id,action_schema_raw:a.canonical},c={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},u;try{u=o(l,c)}catch(f){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${f instanceof Error?f.message:String(f)}`,n);throw f}let d=[...new Set(t.operations.flatMap(f=>this.normalizedRefs[f]??[]))].sort();d.length>0&&pa(t.normalized)&&(u.normalizedColdStart=d,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${d.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: ${d.slice(0,5).join("; ")}${d.length>5?`; +${d.length-5} more`:""}`)));let _=an(t.normalized);return _.length>0&&(u.normalizedDrift=_,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${_.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: ${_.slice(0,5).join("; ")}${_.length>5?`; +${_.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}readSession(e){if(!e)return be;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>wa?(this.sessions.delete(e),be):t.state:be}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),o=n.find(s=>s?.id===r);if(!o)return;let i=o.action_class,a=typeof o.action_class_confidence=="number"?o.action_class_confidence:0;if(typeof i=="string"&&i.length>0&&a>=ka)return i}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),o=e.resourceMetadata??{},i=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=ln(r===be?sn():r,{data_categories:i&&Array.isArray(o.data_categories)?o.data_categories:void 0,classification:i?o.classification:void 0,taint:i?Sa(e.contentPreview,o):void 0,action_class:a?this.foldActionClass(e):void 0,target_app:a?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>va){let l=this.sessions.keys().next().value;l!==void 0&&this.sessions.delete(l)}}applyAgentMode(e,t,n,r){let o=Date.now()-r;if(t==="enforce"){let a={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,a,o,!0),a}let i={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,i,o,!1),i}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 o=e.operations.includes("action")||e.operations.includes("delegation"),i=e.operations.includes("retrieval"),a={decision:"permit",allowed:!0,reason:r,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:o?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:i?{action:"allow"}:{action:null},failOpen:!0};return this.bufferTelemetry(e,a,Date.now()-n,!1,!0),a}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=Ta.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=ua(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(o=>hn(o)).filter(o=>o!==null),this.agentAttributes=t.agent_attributes?Ra(t.agent_attributes):null,this.agentNoCoverage=mn(t.agent_attributes?.no_coverage),this.governedFailMode=ke(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=Ca(t.agent_mode_by_operation),process.env.VISIQ_COGNITION_CAPTURE==="1"?this.cognitionEnabled=!0:typeof t.cognition_capture=="boolean"&&(this.cognitionEnabled=t.cognition_capture),this.operatorShutdown=t.shutdown===!0,this.normalizedRefs=da(this.rules),this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1,this.lastNormalizedWarnRearmMs=Date.now(),this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json",...H(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 a=Date.now();a-this.lastNormalizedWarnRearmMs>=ma&&(this.lastNormalizedWarnRearmMs=a,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"),o=await n.json();this.applyBundle(o);let i=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&i?this.bundleEtag=r:i||(this.bundleEtag=null),i&&await this.persistBundleToDisk(o)}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 la(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(ra(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 sa(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}isBundleLoaded(){return this.bundleLoaded}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e,t){this.registerEnvironment({...Le(),...e?{agent_type:e}:{},...t?.model?{model:t.model}:{},...t?.systemPrompt?{systemPrompt:t.systemPrompt}:{},...t?.toolSchemas&&t.toolSchemas.length>0?{toolSchemas:t.toolSchemas}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));for(let n of e)n.description&&this.toolDescriptions.set(n.name,n.description);t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}captureCloneMetadata(e){if(!this.client||!this.resolvedAgentId||!(e.model||e.systemPrompt||(e.toolSchemas?.length??0)>0))return;let t=JSON.stringify({m:e.model??"",s:e.systemPrompt??"",t:e.toolSchemas??[]});t!==this.lastCloneCaptureSig&&(this.lastCloneCaptureSig=t,this.client.registerEnvironment({...Le(),...e.agentType?{agent_type:e.agentType}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{toolSchemas:e.toolSchemas}:{}}))}buildActionSchemaEvent(e){let t=e.toolName?this.toolDescriptions.get(e.toolName):void 0,n={agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{},...e.toolArgs?{tool_args:e.toolArgs}:{},...t?{tool_description:t}:{}},r=gn(n),o={...n};return e.toolArgs&&(o.tool_args=Cn(e.toolArgs)),{canonical:n,id:r,rawEventForWire:o}}bufferTelemetry(e,t,n,r,o=!1){let i=this.buildActionSchemaEvent(e);this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:r?xa(t.decision):"permit",reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:i.rawEventForWire,action_schema_id:i.id,...this.harnessKind||e.context||o||t.normalizedColdStart||t.normalizedDrift?{context:{...this.harnessKind?{[Ut]:this.harnessKind}:{},...e.context??{},...o?{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,ba)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=ha&&this.flushTelemetry()}pendingTelemetryCount(){return this.telemetryBuffer.length}hasBackend(){return this.client!==null}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0);try{await this.client.sendTelemetry(e)}catch(t){console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",t)}}enforceTelemetryCap(){let e=this.telemetryBuffer.length-Gn;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Gn})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Ki(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=ya&&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-Hn;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Hn})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),_t.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 gt(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function Na(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function F(e,...t){for(let n of t){let r=Na(e[n]);if(r)return r}}var Ma=[{framework:"openai-agents",matches:e=>/^transfer_to_.+/.test(e),extract:(e,t)=>{let n=e.replace(/^transfer_to_/,"");return{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"teammate",task:F(t,"task","input","reason","message"),source:"structural"}}},{framework:"voltagent",matches:e=>e==="delegate_task",extract:(e,t)=>{let n=F(t,"targetAgent","agent","subAgent","agentName","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:F(t,"task","message","input"),description:F(t,"purpose"),source:"structural"}:null}},{framework:"crewai",matches:e=>/delegate work to (co-?worker|.+)/i.test(e),extract:(e,t)=>{let n=F(t,"coworker","agent","role");return n?{childAgentId:n,childName:n,kind:"teammate",agentType:n,task:F(t,"task","question"),description:F(t,"context"),source:"structural"}:null}},{framework:"llamaindex",matches:e=>e==="handoff"||/handoff/i.test(e),extract:(e,t)=>{let n=F(t,"to_agent","toAgent","agent_name","agentName","agent","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:F(t,"reason","task","message"),source:"structural"}:null}},{framework:"generic",matches:e=>/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)([_-].+)?$/i.test(e),extract:(e,t)=>{let n=F(t,"agent","agentName","agentId","target","targetAgent","to","to_agent","coworker","name")??(/[_-]/.test(e)?e.replace(/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)[_-]/i,""):void 0);return n?{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"subagent",task:F(t,"task","message","input","reason","prompt"),source:"heuristic"}:null}}];function Ke(e,t){if(!e)return null;let n=t??{};for(let r of Ma)try{if(r.matches(e)){let o=r.extract(e,n);if(o)return o}}catch{}return null}function Ge(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}function yt(e){if(e===null||typeof e!="object"||Array.isArray(e))return{input:e===void 0?"":String(e)};let t=e,n=Object.keys(t);return n.length===1&&n[0]==="context"&&t.context!==null&&typeof t.context=="object"?t.context:t}function tr(e){if(typeof e=="string"){try{let t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{input:e}}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{input:e===void 0?"":String(e)}}function D(e){let t=[],n=[],r,o=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let l={mode:a.mode};a.field&&(l.field=a.field),a.pattern&&(l.pattern=a.pattern),typeof a.keepFirst=="number"&&(l.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(l.keepLast=a.keepLast),a.maskChar&&(l.maskChar=a.maskChar),a.keepPattern&&(l.keepPattern=a.keepPattern),a.replacement!==void 0&&(l.replacement=a.replacement),o.push(l);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:s}=a;s&&r===void 0&&(r=s)}let i={};return t.length>0&&(i.fields=t),n.length>0&&(i.patterns=n),r!==void 0&&(i.replacement=r),o.length>0&&(i.directives=o),i}var V="0.2.12";import{AsyncLocalStorage as Da}from"node:async_hooks";var C=new Da,La=5120,nr=50;function Fa(e,t){if(typeof e!="string")return"";let n=new TextEncoder,r=n.encode(e);if(r.length<=t)return e;let i=`\u2026[truncated ${Math.ceil(r.length/1024)}KB]`,a=n.encode(i).length,s=Math.max(0,t-a),l=r.subarray(0,s);return new TextDecoder("utf-8",{fatal:!1}).decode(l)+i}function z(e){if(!e)return;let t=r=>r.length<=nr?r.slice():r.slice(r.length-nr),n=r=>Fa(r,La);return{session_id:e.session_id,llm_prompts:t(e.llm_prompts).map(n),llm_responses:t(e.llm_responses).map(n),agent_reasoning:t(e.agent_reasoning).map(n)}}var bt=12e4,rr=2e3,or=3,$a=5e3;function Ae(e,t){return e==="mask"&&(t?.length??0)>0}var Pa=new Set(["approved","resolved"]),ja=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function Ua(e){return new Promise(t=>setTimeout(t,e))}function Ba(e){if(typeof e!="object"||e===null)return null;let t=e,n=t.hitl_result;if(typeof n=="string"&&n.length>0)return n;let{hitl:r}=t;if(r&&typeof r=="object"){let{status:o}=r;if(typeof o=="string"&&o.length>0)return o==="pending"?null:o}return null}async function Ie(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:o=bt,maskFallback:i=!1,sdkVersion:a,fetchImpl:s=globalThis.fetch,sleep:l=Ua,log:c=p=>console.warn(p)}=e,u=p=>i?{resolution:"mask",reason:p}:{resolution:"block",reason:p};if(!t)return u("HITL approval cannot be confirmed (no backend endpoint) \u2014 fail-closed (G001)");if(!r)return u("HITL approval cannot be confirmed (no decision id) \u2014 fail-closed (G001)");let d=`${t.replace(/\/$/,"")}/v1/allow/decisions/${encodeURIComponent(r)}`,_={Accept:"application/json",...H(a)};n&&(_.Authorization=`Bearer ${n}`);let f=Date.now()+Math.max(0,o),g=0;for(c(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${o}ms)`);;){if(Date.now()>=f)return c(`[VisIQ HITL] Decision ${r} timed out after ${o}ms \u2014 ${i?"masking":"blocking"} (G001)`),u("HITL approval timed out");let p=null;try{let y=new AbortController,x=setTimeout(()=>y.abort(),$a),A;try{A=await s(d,{method:"GET",headers:_,signal:y.signal})}finally{clearTimeout(x)}if(!A.ok)throw new Error(`HTTP ${A.status} ${A.statusText}`);let T=await A.json();p=Ba(T),g=0}catch(y){g+=1;let x=y instanceof Error?y.message:String(y);if(c(`[VisIQ HITL] Poll failed for decision ${r} (${g}/${or}): ${x}`),g>=or)return u(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${x}`);await l(rr);continue}if(p!==null){let y=p.toLowerCase();return Pa.has(y)?(c(`[VisIQ HITL] Decision ${r} approved (${p}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${p})`}):ja.has(y)?(c(`[VisIQ HITL] Decision ${r} resolved as ${p} \u2014 ${i?"masking":"blocking"}`),u(`Not approved by human reviewer (${p})`)):(c(`[VisIQ HITL] Decision ${r} returned unknown status '${p}' \u2014 ${i?"masking":"blocking"} (G001)`),u(`HITL returned unknown status '${p}' \u2014 fail-closed (G001)`))}await l(rr)}}function K(e){return e??ke(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??ze}function v(e,t){try{console.error(`[VisIQ] FAIL-OPEN (${e}): ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`)}catch{}}function U(e,t){try{console.error(`[VisIQ] TRACE-DEGRADED (${e}): ${t} \u2014 the governance decision was still made and enforced; only the execution-trace beat was lost.`)}catch{}}function re(e){let t=e.getFailMode;return(typeof t=="function"?t.call(e):void 0)??K()}function Y(e){return e.enforced?{allowed:e.action.allowed,decision:e.action.decision,...e.action.decisionId!==void 0?{decisionId:e.action.decisionId}:{},...e.ruleCode!==null?{ruleCode:e.ruleCode}:{},reason:e.reason,argRedactionRules:e.action.argRedactionRules??[],...e.action.hitlFallback?{hitlFallback:e.action.hitlFallback}:{}}:{allowed:!0,decision:"permit",reason:e.reason,argRedactionRules:[]}}function ar(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&Ae(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}var ir=new Set;function At(e){ir.has(e)||(ir.add(e),console.warn(`[VisIQ] unrecognized retrieval outcome "${e}" \u2014 failing closed (withholding content). Upgrade @visiq/harness if a newer control plane introduced this outcome.`))}async function We(e,t,n){let r=C.getStore(),o=z(r),i=await e.evaluate({operations:["retrieval"],agentId:t,...r?.session_id?{sessionId:r.session_id}:{},resourceType:n.resourceType??"document",resourceMetadata:n.resourceMetadata??{},...n.query!==void 0?{query:n.query}:{},...n.contentPreview!==void 0?{contentPreview:n.contentPreview}:{},...o?{telemetry:o}:{}});return ar(i)}async function Qe(e,t,n){return await e.awaitBundleReady(),We(e,t,n)}function sr(e,t,n=K()){switch(t.action){case"allow":case"escalate":return e;case"deny":return null;case"redact":{if(t.redactionRules.length===0)return e;try{return M(e,D(t.redactionRules))}catch{return n==="closed"?null:(v("redact-error","document redaction failed \u2014 document passed UNREDACTED"),e)}}default:return At(String(t.action)),n==="closed"?null:(v("unknown-retrieval-verb",`unrecognized outcome "${String(t.action)}" \u2014 document passed through`),e)}}async function lr(e,t,n,r){if(!Array.isArray(e)||e.length===0)return e;await r.awaitBundleReady();let o=[];for(let i of e){let a=i,s=String(a.pageContent??a.text??a.content??""),l=a.metadata??{},c=await We(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s.slice(0,500)}),u=sr(i,c,re(r));u!==null&&o.push(u)}return o}async function cr(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await We(n,t,{resourceType:"document",resourceMetadata:{content_preview:e.slice(0,500)},contentPreview:e.slice(0,500)})}catch(o){return re(n)==="closed"?"[RECALL] Retrieved context blocked \u2014 policy evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":(v("eval-error",`retrieval evaluation failed \u2014 text passed through: ${o instanceof Error?o.message:String(o)}`),e)}switch(r.action){case"allow":case"escalate":return e;case"deny":return"[RECALL] Retrieved context was blocked by policy.";case"redact":{if(r.redactionRules.length===0)return e;try{return M(e,D(r.redactionRules))}catch{return re(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(v("redact-error","text redaction failed \u2014 text passed UNREDACTED"),e)}}default:return At(String(r.action)),re(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(v("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 text passed through`),e)}}var ur=4,dr=1e3;function He(e){return e.length===0?!1:e.some(t=>t!==null&&typeof t=="object"&&(typeof t.pageContent=="string"||typeof t.text=="string"||typeof t.content=="string"))}async function pr(e,t,n){let r=[];for(let o of e){let i=o,a=String(i.pageContent??i.text??i.content??""),s={...i.metadata??{},content_preview:a.slice(0,500)},l;try{l=await We(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:a.slice(0,500)})}catch(u){if(re(n)==="closed")continue;v("eval-error",`document retrieval evaluation failed \u2014 document passed through: ${u instanceof Error?u.message:String(u)}`),r.push(o);continue}let c=sr(o,l,re(n));c!==null&&r.push(c)}return r}async function wt(e,t,n,r,o){if(r>ur||o.nodes++>dr)return e;if(Array.isArray(e)){if(He(e))return o.matched=!0,pr(e,t,n);let i=[];for(let a of e)i.push(await wt(a,t,n,r+1,o));return i}if(e!==null&&typeof e=="object"){let i=e,a={...i};for(let s of Object.keys(i))a[s]=await wt(i[s],t,n,r+1,o);return a}return e}async function Ye(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&He(e))return pr(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},o=await wt(e,t,n,0,r);if(r.matched)return o}return e}var qa={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function kt(e,t,n){if(t>ur||n.n++>dr)return e;if(Array.isArray(e))return He(e)?[]:e.map(r=>kt(r,t+1,n));if(e!==null&&typeof e=="object"){if(He([e]))return{...qa};let r=e,o={};for(let i of Object.keys(r))o[i]=kt(r[i],t+1,n);return o}return e}function vt(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?kt(e,0,{n:0}):e}function fr(e,t,n=K()){let r=ar(t);switch(r.action){case"allow":case"escalate":return e;case"deny":return vt(e);case"redact":{if(r.redactionRules.length===0)return e;try{return M(e,D(r.redactionRules))}catch{return n==="closed"?vt(e):(v("redact-error","result redaction failed \u2014 result passed UNREDACTED"),e)}}default:return At(String(r.action)),n==="closed"?vt(e):(v("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 result passed through`),e)}}function O(e){return typeof e=="object"&&e!==null?e:null}function mr(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}function Va(e,t){let n=O(e.metadata),r=n&&typeof n.name=="string"?n.name:void 0;return mr(e.name,e.id,r,t)}function za(e){let t=O(e.metadata),n=t&&typeof t.description=="string"?t.description:void 0,r=mr(e.description,n);return r===void 0?void 0:r.slice(0,4e3)}function Ka(e){let t=O(e);return t!==null&&("type"in t||"properties"in t||"$schema"in t)}function Ga(e){let t=O(e);if(t===null||!("_def"in t))return;let{shape:n}=t;if(typeof n=="function")try{n=n.call(t)}catch{n=void 0}let r=O(n);if(r===null)return{type:"object"};let o={};for(let i of Object.keys(r))o[i]={};return{type:"object",properties:o}}var Ha=new Set(["default","const","enum","examples","example"]);function It(e){if(Array.isArray(e))return e.map(It);let t=O(e);if(t===null)return e;let n={};for(let[r,o]of Object.entries(t))Ha.has(r)||(n[r]=It(o));return n}function Wa(e){let t;if(Ka(e))t=e;else{let n=Ga(e);if(n===void 0)return;t=n}try{let n=JSON.stringify(t);if(n.length>2e4){let r=O(t),o=r&&O(r.properties);if(o){let i={};for(let a of Object.keys(o))i[a]={};return{type:"object",properties:i}}return{type:"object"}}return It(JSON.parse(n))}catch{return}}function Qa(e){let t=O(e.metadata),n=e.input_schema??e.inputSchema??e.parameters??e.schema??e.args_schema??e.tool_call_schema??(t?t.parameters:void 0);return n===void 0?void 0:Wa(n)}function Ya(e,t){let n=O(e);if(n===null)return null;let r=Va(n,t);if(r===void 0)return null;let o={name:r.slice(0,255)},i=za(n);i!==void 0&&(o.description=i);let a=Qa(n);return a!==void 0&&(o.input_schema=a),o}function Se(e){let t=[],n=new Set,r=(o,i)=>{try{let a=Ya(o,i);a!==null&&!n.has(a.name)&&(n.add(a.name),t.push(a))}catch{}};if(Array.isArray(e)){for(let o of e)if(r(o),t.length>=200)break}else if(e instanceof Map){for(let[o,i]of e.entries())if(r(i,typeof o=="string"?o:void 0),t.length>=200)break}else{let o=O(e);if(o!==null){for(let i of Object.keys(o))if(r(o[i],i),t.length>=200)break}}return t}function St(e){try{let t=O(e);if(t===null)return[];let n=[],r=new Set,o=l=>{for(let c of l)!r.has(c.name)&&n.length<200&&(r.add(c.name),n.push(c))};t.tools!==void 0&&o(Se(t.tools));let i=O(t.settings);i&&i.tools!==void 0&&o(Se(i.tools));for(let l of["getTools","listTools"]){let c=t[l];if(typeof c=="function")try{o(Se(c.call(t)))}catch{}}let a=O(t.nodes);if(a)for(let l of Object.keys(a)){let c=O(a[l]);c&&c.tools!==void 0&&o(Se(c.tools))}let{agents:s}=t;if(s instanceof Map)for(let l of s.values()){let c=O(l);c&&c.tools!==void 0&&o(Se(c.tools))}return n}catch{return[]}}import{z as Ze}from"zod";var Za=Ze.object({decision:Ze.enum(["permit","deny"]),reason:Ze.string(),handoff_event_id:Ze.string().nullable()}),j=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},Z=class extends j{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},Ja="https://api.visiqlabs.com",Xa=1e4,oe=class{config;fetch;constructor(e,t=globalThis.fetch){this.config={agentId:e.agentId,apiKey:e.apiKey??process.env.VISIQ_API_KEY??"",endpoint:e.endpoint??process.env.VISIQ_ENDPOINT??Ja,timeoutMs:e.timeoutMs??Xa},this.fetch=t}get headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Agent-ID":this.config.agentId}}async post(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),o;try{o=await this.fetch(`${this.config.endpoint}${e}`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:n.signal})}finally{clearTimeout(r)}let i=await o.json();if(!o.ok){let a=i?.error??`HTTP ${o.status}`;throw new j(a,"API_ERROR",o.status)}return i}async requestGrant(e){let t=await this.post("/orchestrate/grants",{parent_agent_id:e.parentAgentId,child_agent_id:e.childAgentId,tool_scope:e.toolScope??null,context_scope:e.contextScope??null,purpose:e.purpose,duration_seconds:e.durationSeconds,max_depth:e.maxDepth,parent_grant_token:e.parentGrantToken});return{grantId:t.grant_id,status:"pending",effectiveToolScope:t.effective_tool_scope,effectiveContextScope:t.effective_context_scope,acceptDeadline:t.accept_deadline}}async acceptGrant(e){let t=await this.post(`/orchestrate/grants/${e}/accept`,{});return{grantToken:t.grant_token,toolScope:t.tool_scope,contextScope:t.context_scope,expiresAt:t.expires_at}}async evaluate(e){let t=await this.post("/orchestrate/evaluate",{grant_token:e.grantToken,action:e.action,resource_type:e.resourceType,resource_metadata:e.resourceMetadata??{}}),n=Za.parse(t);return{decision:n.decision,reason:n.reason,handoffEventId:n.handoff_event_id}}async revokeGrant(e,t){return{revokedCount:(await this.post(`/orchestrate/grants/${e}/revoke`,{reason:t})).revoked_count}}};var gr=new Map;async function hr(e,t){if(!e||e.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: agentId is required");if(!t||t.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: grantId is required");let n=gr.get(e);if(n)return n;let r=process.env.VISIQ_API_KEY;if(!r)throw new Error("[ORCHESTRATE] bootstrapGrant: VISIQ_API_KEY env var is required");let o=process.env.VISIQ_ENDPOINT,i=(await new oe({agentId:e,apiKey:r,...o?{endpoint:o}:{}}).acceptGrant(t)).grantToken;if(!i||i.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: backend returned empty grant token");return gr.set(e,i),i}var Ee=Symbol.for("visiq.orchestrate.wrapped");function es(e){return e instanceof j&&typeof e.status=="number"&&e.status>=400&&e.status<500}function _r(e,t){if(!t.agentId||t.agentId.trim()==="")throw new j("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new j("grantToken is required","CONFIG_ERROR");if(e[Ee]===!0)return e;let n=new oe(t),r=t.failBehavior??(process.env.VISIQ_FAIL_MODE?.trim().toLowerCase()==="closed"?"deny":"permit"),o=async(i,a)=>{let s;try{s=await n.evaluate({grantToken:t.grantToken,action:i,resourceType:a})}catch(l){if(es(l))throw l;if(r==="permit"){console.warn('[VisIQ] FAIL-OPEN (orchestrate-eval-error): evaluate failed \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed (or failBehavior:"deny") to block instead.',l);return}throw new j(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new Z(s.reason,s.handoffEventId)};return new Proxy(e,{get(i,a,s){let l=Reflect.get(i,a,s);return a===Ee?!0:a==="_call"&&typeof l=="function"?async function(c,...u){let d=i.name;return await o(d??"_call"),l.call(this??i,c,...u)}:(a==="call"||a==="execute"||a==="run")&&typeof l=="function"?async function(c,...u){let d=i.name;return await o(d??String(a)),l.call(this??i,c,...u)}:l}})}import{randomUUID as Ar}from"node:crypto";var yr=Symbol.for("visiq.semantickernel.instrumented");function wr(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.useFunctionInvocation=="function"&&typeof t.usePromptRender=="function"&&typeof t.execute!="function"&&typeof t.generate!="function"&&typeof t.run!="function"}function br(e){let t=e.arguments;return t&&typeof t=="object"&&"arguments"in t&&t.arguments&&typeof t.arguments=="object"?t.arguments:t??{}}function vr(e,t){let n=e.arguments;if(n&&typeof n=="object"&&"arguments"in n&&n.arguments&&typeof n.arguments=="object"){let r=n.arguments;for(let o of Object.keys(r))delete r[o];Object.assign(r,t);return}e.arguments=t}function B(e,t){e.result&&typeof e.result=="object"?e.result.value=t:e.result={value:t}}function ts(e){return e.result?.value}function ns(e){let{agentId:t,unified:n,failMode:r}=e;return async function(i,a){let s=i.function?.metadata?.name??"unknown",l=i.function?.metadata?.pluginName,c=br(i),u=l;try{let p=await n.evaluate({operations:["action"],agentId:t,toolName:s,toolArgs:c,...u!==void 0?{targetResource:u}:{}}),y=Y(p);if(!y.allowed){B(i,R({outcome:"deny",code:y.ruleCode??"DENY",reason:y.reason}));return}y.decision==="mask"&&y.argRedactionRules.length>0&&vr(i,M(c,D(y.argRedactionRules)));let x=br(i),A=ne(s,x,{failMode:r==="closed"?"closed":"open",enforced:p.enforced});if(A.verdict==="block"){B(i,R({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${A.detectors.join(",")})`}));return}A.verdict==="redact"&&(vr(i,A.redacted),v("outbound-secret-redacted",`outbound secret screen redacted ${A.detectors.length} detector(s): ${A.detectors.join(",")}`))}catch(p){if(r==="closed"){B(i,R({outcome:"error",code:"EVAL-ERROR",mechanism:`evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${p instanceof Error?p.message:String(p)}`}));return}v("eval-error",`SK action pre-gate failed for "${s}": ${p instanceof Error?p.message:String(p)}`)}try{let p=await Qe(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l}});if(p.action==="deny"||p.action==="escalate"){B(i,`[RECALL: access denied \u2014 ${p.reason}]`);return}}catch(p){if(r==="closed"){B(i,`[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${p instanceof Error?p.message:String(p)}.`);return}v("eval-error",`SK retrieval pre-gate failed for "${s}": ${p instanceof Error?p.message:String(p)}`)}await a(i);let d=ts(i),f=(typeof d=="string"?d:(()=>{try{return JSON.stringify(d)??String(d)}catch{return String(d)}})()).slice(0,500),g;try{g=await Qe(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l,content_preview:f},contentPreview:f})}catch(p){r==="closed"?B(i,"[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):v("eval-error",`SK post-result retrieval eval failed for "${s}": ${p instanceof Error?p.message:String(p)}`);return}if(g.action==="deny"||g.action==="escalate"){B(i,`[RECALL: access denied \u2014 ${g.reason}]`);return}if(g.action==="redact"&&g.redactionRules&&g.redactionRules.length>0&&d!==null&&d!==void 0)try{B(i,M(d,D(g.redactionRules)))}catch(p){r==="closed"?B(i,"[RECALL] Result withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):v("redact-error",`SK result redaction failed for "${s}" \u2014 result passed UNREDACTED: ${p instanceof Error?p.message:String(p)}`)}}}function rs(e){return async function(n,r){await r(n);let o=n.renderedPrompt;if(typeof o!="string"||o.length===0)return;let i;try{i=await Qe(e.unified,e.agentId,{resourceType:"prompt",resourceMetadata:{},contentPreview:o.slice(0,500)})}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":v("eval-error",`SK prompt-render eval failed: ${a instanceof Error?a.message:String(a)}`);return}if(i.action==="redact"&&i.redactionRules&&i.redactionRules.length>0){try{n.renderedPrompt=M(o,D(i.redactionRules))}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed).":v("redact-error",`SK prompt redaction failed \u2014 prompt passed UNREDACTED: ${a instanceof Error?a.message:String(a)}`)}return}(i.action==="deny"||i.action==="escalate")&&(n.renderedPrompt=`[RECALL: prompt suppressed \u2014 ${i.reason}]`)}}function kr(e,t){let n=e;if(n[yr]===!0)return t.onWrap?.(),e;let r=ns(t),o=rs(t),i=!1;return Array.isArray(n._functionInvocationFilters)?(n._functionInvocationFilters.unshift(r),i=!0):typeof n.useFunctionInvocation=="function"&&(n.useFunctionInvocation(r),i=!0),typeof n.usePromptRender=="function"?n.usePromptRender(o):Array.isArray(n._promptRenderFilters)&&n._promptRenderFilters.push(o),i&&(n[yr]=!0,t.onWrap?.()),e}function R(e){let t=/^D-/.test(e.code),n;e.outcome==="approval_required"?n="requires human approval, which was not granted":e.outcome==="error"?n="was blocked (fail-closed) after a policy-evaluation error":n="was denied by policy";let r=e.reason?.trim(),o;r?o=r:t?o="no policy rule covers this action, so the organization default applied":e.outcome==="approval_required"?o="this action is routed to a human for approval":o="denied by policy";let i=e.mechanism?.trim()?` \u2014 ${e.mechanism.trim()}`:"";return`[VisIQ decision=${e.outcome} code=${e.code}] This tool call was NOT executed: it ${n} (${o})${i}. VisIQ is a security harness installed by your developer. Report this reason to the user verbatim; do not invent a different one.`}function Je(e){return e instanceof Error?e.message:String(e)}var os=/https?:\/\/[^\s"'`,)}\]]+/;function Et(e){let t=e.match(os);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var ie=Symbol.for("visiq.toolexec.instrumented");function is(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}var Tt={vercel:"Vercel AI SDK agent",mastra:"Mastra Agent",openai:"OpenAI Agents SDK agent",llamaindex:"LlamaIndex.TS agent",voltagent:"VoltAgent agent","semantic-kernel":"Semantic Kernel"};function Ir(e){if(e===null||typeof e!="object")return null;let t=e;if(is(t))return null;if(wr(e))return"semantic-kernel";if(typeof t.generateText=="function"&&(typeof t.getTools=="function"||t.toolManager!==void 0))return"voltagent";if(typeof t.run=="function"&&typeof t.runStream=="function"&&t.agents!==void 0)return"llamaindex";if(Array.isArray(t.tools)&&t.handoffs!==void 0&&(typeof t.on=="function"||t.eventEmitter!==void 0))return"openai";if(typeof t.generate=="function"&&typeof t.getLLM=="function"&&(typeof t.listTools=="function"||typeof t.getTools=="function"))return"mastra";if(typeof t.generate=="function"){let n=t.settings;if(n&&typeof n=="object"&&n.tools!==void 0||t.tools!==void 0)return"vercel"}return null}async function as(e,t,n,r,o,i){let{agentId:a,unified:s}=e,l=z(o),c,u=!1;try{await s.awaitBundleReady();let p=await s.evaluate({operations:i?["action","delegation"]:["action"],agentId:a,toolName:t,toolArgs:n,...i?{context:Ge(i,a)}:{},...o?.session_id?{sessionId:o.session_id}:{},...r!==void 0?{targetResource:r}:{},...l?{telemetry:l}:{}});({enforced:u}=p),c=Y(p)}catch(p){let y=p instanceof Error?p.message:String(p);return e.failMode==="closed"?{block:R({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${y} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})}:(v("eval-error",`policy evaluation failed for tool "${t}": ${y}`),{block:null})}if(c.decision==="approval_required"&&c.decisionId){let p=s.getApiKey()??e.apiKey,y=await Ie({endpoint:s.getEndpoint()??e.endpoint??"",...p?{apiKey:p}:{},decisionId:c.decisionId,timeoutMs:e.hitlTimeoutMs,sdkVersion:V});return y.resolution!=="proceed"?{block:R({outcome:"approval_required",code:c.ruleCode??"HITL-BLOCK",reason:c.reason,mechanism:y.reason}),decision:c}:{block:null}}if(!c.allowed)return{block:R({outcome:"deny",code:c.ruleCode??"DENY",reason:c.reason}),decision:c};let d=n,_=!1,f;if(c.decision==="mask"&&c.argRedactionRules&&c.argRedactionRules.length>0)try{let p=D(c.argRedactionRules);d=M(n,p),_=!0,f=c}catch(p){let y=p instanceof Error?p.message:String(p);if(e.failMode==="closed")return{block:R({outcome:"error",code:"MASK-ERROR",mechanism:`argument masking failed: ${y} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})};v("mask-error",`argument masking failed for tool "${t}" \u2014 running with UNMASKED args: ${y}`)}let g=ne(t,d,{failMode:e.failMode==="closed"?"closed":"open",enforced:u});return g.verdict==="block"?{block:R({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${g.detectors.join(",")})`}),decision:{allowed:!1,decision:"deny",ruleCode:"OUTPUT-BLOCK",reason:"outbound content carried a live secret",argRedactionRules:[]}}:(g.verdict==="redact"&&(d=g.redacted,_=!0,v("outbound-secret-redacted",`outbound secret screen redacted ${g.detectors.length} detector(s): ${g.detectors.join(",")}`),f??={allowed:!0,decision:"mask",ruleCode:"OUTPUT-BLOCK",reason:"outbound secret redacted before egress",argRedactionRules:[]}),_?{block:null,maskedArgs:d,decision:f}:{block:null})}async function Rt(e,t,n,r,o){let i=C.getStore()??e.telemetry,a=Ke(t,n);a&&me(e.unified,{agentId:e.agentId,sessionId:i?.session_id,...e.framework?{framework:e.framework}:{}},a);let s={agentId:e.agentId,sessionId:i?.session_id,...e.framework?{framework:e.framework}:{}},l=de(t,n);try{ge(e.unified,s,{toolName:t,...l?{memory:l}:{},argSummary:r.slice(0,512)})}catch(g){U("step-beat",`emit failed for tool "${t}": ${Je(g)}`)}let c=Date.now(),u=await as(e,t,n,Et(r),i,a);if(u.block!==null){try{u.decision&&ee(e.unified,s,{toolName:t,decision:u.decision.decision??"deny",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0,harnessMessage:u.block})}catch(g){U("intervention-beat",`emit failed for tool "${t}": ${Je(g)}`)}return u.block}if(u.maskedArgs!==void 0&&u.decision)try{ee(e.unified,s,{toolName:t,decision:u.decision.decision??"mask",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0})}catch(g){U("intervention-beat",`emit failed for tool "${t}": ${Je(g)}`)}let d=u.maskedArgs??n,_=await o(d),f=await Ye(_,e.agentId,e.unified);try{he(e.unified,s,{toolName:t,ok:!0,durationMs:Date.now()-c,...W(f)!==void 0?{bytes:W(f)}:{},...Q(f)!==void 0?{itemCount:Q(f)}:{},...l?{memory:l}:{}})}catch(g){U("observation-beat",`emit failed for tool "${t}": ${Je(g)}`)}return f}function Xe(e,t,n){let r=e;if(r[ie]){n.onWrap?.();return}if(typeof r.execute!="function")return;let o=r.execute;xt(r,"execute",async function(...a){let s=yt(a[0]);return Rt(n,t,s,Re(s),l=>Promise.resolve(o.apply(this,[l,...a.slice(1)])))}),r[ie]=!0,n.onWrap?.()}function ss(e,t,n){let r=e;if(r[ie]){n.onWrap?.();return}if(typeof r.invoke!="function")return;let o=r.invoke;xt(r,"invoke",async function(...a){let s=a[1],l=tr(s),c=typeof s=="string"?s:Re(l);return Rt(n,t,l,c,u=>{let d=typeof s=="string"?JSON.stringify(u):u;return Promise.resolve(o.apply(this,[a[0],d,...a.slice(2)]))})}),r[ie]=!0,n.onWrap?.()}function ls(e,t){let n=e;if(n[ie]){t.onWrap?.();return}if(typeof n.call!="function")return;let r=n.metadata,o=typeof r?.name=="string"?r.name:"unknown",i=n.call;xt(n,"call",async function(...s){let l=yt(s[0]);return Rt(t,o,l,Re(l),c=>Promise.resolve(i.apply(this,[c,...s.slice(1)])))}),n[ie]=!0,t.onWrap?.()}function Sr(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&Xe(r,n,t);return e}function Er(e,t,n){let r={...t,framework:n};switch(n){case"vercel":return cs(e,r);case"mastra":return us(e,r);case"openai":return fs(e,r);case"llamaindex":return ps(e,r);case"voltagent":return ds(e,r);case"semantic-kernel":return kr(e,r);default:return e}}function cs(e,t){let n=e,r=n.settings&&typeof n.settings=="object"?n.settings:void 0,o=r?.tools??n.tools;return o&&typeof o=="object"&&Sr(o,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=Ct(r.onStepFinish)),et(e,["generate","stream"],async(i,a)=>(Te(a,i[0]),i)),e}function us(e,t){let r=_s(e);return r&&Sr(r,t),et(e,["generate","stream","generateVNext","streamVNext"],async(o,i)=>{Te(i,o[0]);let a=o[1]&&typeof o[1]=="object"?{...o[1]}:{};a.onStepFinish=Ct(a.onStepFinish);let s=[...o];return s[1]=a,s}),e}function ds(e,t){let n=gs(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:o}=r;Xe(r,typeof o=="string"?o:"unknown",t)}}return et(e,["generateText","streamText","generateObject","streamObject"],async(r,o)=>{Te(o,r[0]);let i=r[1]&&typeof r[1]=="object"?{...r[1]}:{};i.onStepFinish=Ct(i.onStepFinish);let a=[...r];return a[1]=i,a}),e}function ps(e,t){let n=e,r=i=>{let a=i?.tools;if(Array.isArray(a))for(let s of a)s!==null&&typeof s=="object"&&ls(s,t)},{agents:o}=n;if(o instanceof Map)for(let i of o.values())r(i);else Array.isArray(n.tools)&&r(n);return et(e,["run"],async(i,a)=>(Te(a,i[0]),i)),hs(e,"runStream",(i,a,s)=>{s||Te(a,i[0])}),e}function fs(e,t){let n=e,{tools:r}=n;if(Array.isArray(r)){for(let o of r)if(o!==null&&typeof o=="object"){let{name:i}=o;ss(o,typeof i=="string"?i:"unknown",t)}}return ms(e,t),e}function ms(e,t){let n=e;if(n.__visiq_openai_hooks||typeof n.on!="function")return;let r=n.on,{telemetry:o}=t;r.call(e,"agent_start",(...i)=>{o.session_id=Ar(),o.llm_prompts=[],o.llm_responses=[],o.agent_reasoning=[],o.retrieverQueries=new Map;let a=i[2];a!=null&&o.llm_prompts.push(Re(a).slice(0,5120))}),r.call(e,"agent_end",(...i)=>{let a=i[1];typeof a=="string"&&a&&o.llm_responses.push(a.slice(0,5120))}),n.__visiq_openai_hooks=!0}function gs(e){let t=r=>Array.isArray(r)&&r.some(o=>o!==null&&typeof o.execute=="function");if(typeof e.getTools=="function")try{let r=e.getTools();if(t(r))return r}catch{}let n=e.toolManager;if(n&&typeof n.getAllBaseTools=="function")try{let r=n.getAllBaseTools();if(t(r))return r}catch{}return t(e.tools)?e.tools:null}function et(e,t,n){let r=e;for(let o of t){if(typeof r[o]!="function")continue;let i=`__visiq_wrapped_${o}`;if(r[i])continue;let a=r[o];r[o]=function(...s){let l=Tr();return C.run(l,async()=>{let c=await n(s,l);return a.apply(e,c)})},r[i]=!0}}function hs(e,t,n){let r=e;if(typeof r[t]!="function")return;let o=`__visiq_wrapped_${t}`;if(r[o])return;let i=r[t];r[t]=function(...a){let s=C.getStore(),l=s??Tr();return n(a,l,s!==void 0),C.run(l,()=>i.apply(e,a))},r[o]=!0}function Ct(e){return t=>{let n=C.getStore(),r=t;if(n&&typeof r?.text=="string"&&r.text&&n.llm_responses.push(r.text.slice(0,5120)),typeof e=="function")return e(t)}}function Te(e,t){if(t==null)return;let n=t;if(typeof t=="object"){let r=t;n=r.prompt??r.messages??t}e.llm_prompts.push(Re(n).slice(0,5120))}function _s(e){for(let t of["listTools","getTools"])if(typeof e[t]=="function")try{let n=e[t]();if(n&&typeof n=="object"&&typeof n.then!="function")return n}catch{}return null}function Tr(){return{session_id:Ar(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function xt(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function Re(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function $r(e,t){let n=As(t);if(e[Ee]===!0)return e;let r=Ts(e);if(r==="langchain-executor"||r==="langchain-graph")return se(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,Cr(r,null),n.failMode,{model:xr(e)}),Nr(e,n),Rs(e,n);let o=Ir(e);if(o){se(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,Cr("unknown",o),n.failMode,{model:xr(e)}),Nr(e,n);let i=0,a=qr(n);a.onWrap=()=>{i+=1};let s=Er(e,a,o);if(i===0){let l=0;try{l=St(e).length}catch{l=0}if(l>0){let c=`[VisIQ] Detected a ${Tt[o]} that ADVERTISES ${String(l)} tool(s) but instrumented ZERO of them \u2014 its tool calls run UN-GOVERNED while this SDK appears correctly wired. This is almost always a tool bag that moved/renamed on a framework version bump. Upgrade @visiq/harness, or pass the tools through visiq() directly (visiq(tools, \u2026)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw / VISIQ_FAIL_MODE=closed) to refuse to run ungoverned.`;if(n.onInstrumentFailure!==void 0?n.onInstrumentFailure==="throw":n.failMode==="closed")throw new Error(c);v("zero-instrument",`advertised ${String(l)} tool(s), instrumented none`),console.warn(c)}else{let c=`[VisIQ] Detected a ${Tt[o]} with no tools to instrument (the agent advertises none). If it is intentionally tool-less (LLM-only) this is safe to ignore; otherwise its tool bag is not where this SDK looks for it \u2014 upgrade @visiq/harness or pass the tools through visiq() (visiq(tools, \u2026)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw) to fail closed here.`;if(n.onInstrumentFailure==="throw")throw new Error(c);console.warn(c)}}return s}if(Ls(e)){let i=process.env.VISIQ_GRANT_ID;return i?$s(e,n,i):Ps(e,n)}throw new Error("[VisIQ] Cannot detect agentic framework. Pass a LangChain AgentExecutor, LangGraph CompiledGraph, or a tool with one of: _call, execute, call, run, invoke.")}var vs="https://api.visiqlabs.com",ws="\0",Rr=new Map;function Cr(e,t){if(e==="langchain-executor"||e==="langchain-graph")return"langchain";switch(t){case"vercel":return"vercel_ai";case"mastra":return"mastra";case"openai":return"openai_agents";case"llamaindex":return"llamaindex";case"voltagent":return"voltagent";case"semantic-kernel":return"semantic_kernel";default:return}}function xr(e){try{if(typeof e!="object"||e===null)return;let t=e,n=ae(t.model);if(n)return n;let{settings:r}=t;if(typeof r=="object"&&r!==null){let a=ae(r.model);if(a)return a}let{llm:o}=t;if(typeof o=="object"&&o!==null){let a=Or(o);if(a)return a}let{agents:i}=t;if(i instanceof Map){for(let a of i.values())if(typeof a=="object"&&a!==null){let s=a,l=s.llm,c=ae(s.model)??(typeof l=="object"&&l!==null?Or(l):void 0);if(c)return c}}return}catch{return}}function Or(e){return ae(e.model)??ae(e.modelId)??ae(e.model_name)}function ae(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null){let t=e;for(let n of["modelId","model_id","id","model","modelName","model_name"]){let r=t[n];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}}function se(e,t,n,r,o,i,a){let s=[e??"",t??"",n??"",r??"",i??""].join(ws),l=Rr.get(s);return l||(l=new er(e,t,n,void 0,r,V,ot),l.registerHostEnvironment(o,a),Rr.set(s,l)),i!==void 0&&l.setFailMode(i),l}function Nr(e,t){try{let n=St(e);n.length>0&&se(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode).reportToolSurface(n)}catch{}}function ks(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let t=process.env.VISIQ_TIMEOUT_MS;if(t!==void 0){let n=Number.parseInt(t,10);if(Number.isFinite(n)&&n>0)return n}}function As(e){let t=e?.agentId??process.env.VISIQ_AGENT_ID??Ss(),n=e?.apiKey??process.env.VISIQ_API_KEY,r=e?.endpoint??process.env.VISIQ_ENDPOINT??(n?vs:void 0);return{agentId:t,apiKey:n,endpoint:r,hitlTimeoutMs:Es(e?.hitlTimeoutMs),timeoutMs:ks(e?.timeoutMs),onInstrumentFailure:e?.onInstrumentFailure??Is(),failMode:K(e?.failMode)}}function Is(){let e=process.env.VISIQ_ON_INSTRUMENT_FAILURE;if(e==="throw")return"throw";if(e==="warn")return"warn"}function Ss(){let e=t=>t.toLowerCase().replace(/^@[^/]+\//,"").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,255);try{let t=process.cwd();for(let n=0;n<64;n++){let r=nt.join(t,"package.json");if(tt.existsSync(r)){let i=JSON.parse(tt.readFileSync(r,"utf8"));if(typeof i.name=="string"&&i.name.trim()){let a=e(i.name);if(a)return a}break}let o=nt.dirname(t);if(o===t)break;t=o}}catch{}try{let t=e(Fr.hostname());if(t)return t}catch{}return"agent"}function Es(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let t=process.env.VISIQ_HITL_TIMEOUT_MS;if(t){let n=Number(t);if(Number.isFinite(n)&&n>0)return n}return bt}function Ts(e){let t=e;return typeof t.invoke=="function"&&t.agent&&Array.isArray(t.tools)?"langchain-executor":typeof t.invoke=="function"&&t.nodes&&(t.edges||t.lg_is_pregel===!0||typeof t.builder=="object"&&t.builder!==null&&t.builder.edges)?"langchain-graph":"unknown"}function Rs(e,t){let n=e,r=se(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),o=Cs(n);for(let l of o)Mt(l,t.agentId,r),Ns(l,t.agentId,r,t),Ur(l,r,t);let{nodes:i}=n;if(!!i&&typeof i=="object"&&"tools"in i&&o.length===0){let l="[VisIQ] Detected a LangGraph agent whose compiled graph carries a ToolNode, but resolved ZERO tools from it \u2014 its tool calls run UN-GOVERNED while this SDK appears correctly wired. This is almost always a compiled-graph tool bag that moved on a @langchain/langgraph version bump. Upgrade @visiq/harness, or pass the tools through visiq() directly (visiq(tools, \u2026)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw / VISIQ_FAIL_MODE=closed) to refuse to run ungoverned.";if(t.onInstrumentFailure!==void 0?t.onInstrumentFailure==="throw":t.failMode==="closed")throw new Error(l);v("zero-instrument","langgraph compiled-graph ToolNode present, resolved no tools"),console.warn(l)}let s=n.invoke;if(n.invoke=function(l,c){let u=Nt(),d=Lr(t.agentId,r),_=c?.callbacks??[];return C.run(u,()=>s.call(this,l,{...c,callbacks:[..._,d]}))},typeof n.stream=="function"){let l=n.stream;n.stream=function(c,u){let d=Nt(),_=Lr(t.agentId,r),f=u?.callbacks??[];return C.run(d,()=>l.call(this,c,{...u,callbacks:[...f,_]}))}}return e}function Cs(e){let t=[],n=new Set,r=i=>{if(Array.isArray(i))for(let a of i)a&&typeof a=="object"&&!n.has(a)&&(n.add(a),t.push(a))};r(e.tools);let{nodes:o}=e;if(o&&typeof o=="object"){for(let i of Object.values(o))if(i&&typeof i=="object"){let a=i;r(a.tools);let{bound:s}=a;s&&typeof s=="object"&&r(s.tools)}}return t}function Nt(){return{session_id:ys(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Mt(e,t,n){let r=e,o=Symbol.for("visiq.recall.instrumented");if(!r[o]){if(typeof r._getRelevantDocuments=="function"){let i=r._getRelevantDocuments;r._getRelevantDocuments=async function(a,s){let l=await i.call(this,a,s);return Mr(l,t,a,n)},r[o]=!0}if(typeof r.retrieve=="function"&&!r._getRelevantDocuments){let i=r.retrieve;r.retrieve=async function(a){let s=await i.call(this,a);return Mr(s,t,String(a),n)},r[o]=!0}r.retriever&&typeof r.retriever=="object"&&Mt(r.retriever,t,n)}}var xs=Symbol.for("visiq.operations"),Os=new Set(["action","retrieval","delegation"]);function Pr(e){if(typeof e!="object"||e===null)return;let t=e[xs]??e.visiqOperations;if(!Array.isArray(t))return;let n=t.filter(r=>typeof r=="string"&&Os.has(r));return n.length>0?Array.from(new Set(n)):void 0}function Ns(e,t,n,r){let o=e,i=Symbol.for("visiq.recall.tool-instrumented");if(o[i]||typeof o.func!="function")return;let a=typeof o.name=="string"?o.name:"",s=typeof o.retriever=="object"&&o.retriever!==null,l=a.split(/[^a-zA-Z0-9]+|(?<=[a-z])(?=[A-Z])/).map(S=>S.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),d=l.some(S=>c.has(S)),_=u.has(l[0]??""),f=d||_,g=["update","delete","create","archive","insert","remove"],p=l.some(S=>g.some(b=>S.length>b.length&&S.endsWith(b))),x=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!f&&!p,A=Pr(o),T=A?.includes("retrieval")??!1;if(A!==void 0&&!T||!(s||x||T))return;let Ne=A?T&&A.includes("action"):d||p;if(!Ne)if(s)Mt(o.retriever,t,n);else{let S=globalThis,b=Symbol.for("visiq.recall.closureRetrieverWarned"),$=S[b]??=new Set;$.has(a)||($.add(a),console.warn(`[VisIQ] Retriever tool "${a||"(unnamed)"}" exposes no reachable retriever (e.g. LangChain createRetrieverTool returns a joined string). RECALL masks its output via value-shape + whole-result rules, but PER-DOCUMENT metadata/classification rules cannot apply to a metadata-less joined string. For full per-doc governance, pass the retriever to visiq() directly, or use a tool that returns a Document[].`))}let G=o.func;Ne?(o[jr]=!0,o.func=async function(...S){await n.awaitBundleReady();let b=S[0],$=typeof b=="object"&&b!==null?b:{input:b},ce=typeof $.query=="string"?$.query:void 0,w=C.getStore(),k=z(w),N;try{N=await n.evaluate({operations:["retrieval","action"],agentId:t,...w?.session_id?{sessionId:w.session_id}:{},toolName:a||"unknown",toolArgs:$,resourceType:"document",resourceMetadata:{},...ce!==void 0?{query:ce}:{},...k?{telemetry:k}:{}})}catch(L){let ue=L instanceof Error?L.message:String(L);return K(r?.failMode)==="closed"?R({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${ue} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(v("eval-error",`policy evaluation failed for hybrid tool "${a||"unknown"}": ${ue}`),G.apply(this,S))}let E=Y(N),rt=Ae(E.hitlFallback,E.argRedactionRules),Dt=S,Lt=()=>{try{return Dt=[M($,D(E.argRedactionRules)),...S.slice(1)],null}catch{return K(r?.failMode)==="closed"?R({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(v("mask-error",`argument masking failed for tool "${a||"unknown"}" \u2014 running with UNMASKED args`),null)}};if(E.decision==="approval_required"&&E.decisionId&&r){let L=await Ie({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:E.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:rt,sdkVersion:V});if(L.resolution==="mask"){let ue=Lt();if(ue)return ue}else if(L.resolution!=="proceed")return R({outcome:"approval_required",code:E.ruleCode??"HITL-BLOCK",reason:E.reason,mechanism:L.reason})}else if(!E.allowed)return R({outcome:"deny",code:E.ruleCode??"DENY",reason:E.reason});if(E.decision==="mask"&&E.argRedactionRules.length>0){let L=Lt();if(L)return L}let Kr=await G.apply(this,Dt);return fr(Kr,N,r?.failMode)}):o.func=async function(...S){let b=await G.apply(this,S);return typeof b=="string"?cr(b,t,n):Ye(b,t,n)},o[i]=!0}var jr=Symbol.for("visiq.hybrid.instrumented");async function Mr(e,t,n,r){return lr(e,t,n,r)}var Dr=["invoke","call","_call"],J=new bs;function Ur(e,t,n){let r=e,o=Symbol.for("visiq.allow.instrumented");if(r[o]||typeof r._getRelevantDocuments=="function"||r[jr]||Pr(r)?.every(c=>c==="retrieval")||!Dr.some(c=>typeof r[c]=="function"))return;let{agentId:i}=n,a=typeof r.name=="string"?r.name:"unknown",s=Symbol("visiq.gate"),l=async(c,u,d,_,f)=>{let g=J.getStore();if(g!==void 0&&g.gateKey===s&&!g.entered.has(f))return g.entered.add(f),c.call(u,d,..._);let p;if(typeof d=="string")p=d;else{let w=d?.input;p=w!=null?String(w):JSON.stringify(d)??""}let y=C.getStore(),x=z(y),A=typeof d=="object"&&d!==null?d:{input:p},T=Ke(a,A);T&&me(t,{agentId:i,sessionId:y?.session_id,framework:"langchain"},T);let Oe={agentId:i,sessionId:y?.session_id,framework:"langchain"},le=de(a,A);try{ge(t,Oe,{toolName:a,...le?{memory:le}:{},argSummary:p.slice(0,512)})}catch(w){U("step-beat",`emit failed for tool "${a}": ${Ot(w)}`)}let Ne=Date.now(),G=async w=>{let k=await w();try{he(t,Oe,{toolName:a,ok:!0,durationMs:Date.now()-Ne,...W(k)!==void 0?{bytes:W(k)}:{},...Q(k)!==void 0?{itemCount:Q(k)}:{},...le?{memory:le}:{}})}catch(N){U("observation-beat",`emit failed for tool "${a}": ${Ot(N)}`)}return k},S=(w,k,N,E)=>{try{ee(t,Oe,{toolName:a,decision:w,...k?{ruleCode:k}:{},...N?{ruleLabel:N}:{},enforced:!0,...E?{harnessMessage:E}:{}})}catch(rt){U("intervention-beat",`emit failed for tool "${a}": ${Ot(rt)}`)}};await t.awaitBundleReady();let b,$=!1;try{let w=await t.evaluate({operations:T?["action","delegation"]:["action"],agentId:i,...y?.session_id?{sessionId:y.session_id}:{},toolName:a,toolArgs:A,targetResource:Et(p),...x?{telemetry:x}:{},...T?{context:Ge(T,i)}:{}});({enforced:$}=w),b=Y(w)}catch(w){let k=w instanceof Error?w.message:String(w);return n.failMode==="closed"?R({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${k} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(v("eval-error",`policy evaluation failed for tool "${a}": ${k}`),J.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,..._)))}let ce=w=>{let k=ne(a,w,{failMode:n.failMode==="closed"?"closed":"open",enforced:$});if(k.verdict==="block"){let E=R({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${k.detectors.join(",")})`});return S("deny","OUTPUT-BLOCK","outbound content carried a live secret",E),E}let N=w;return k.verdict==="redact"&&(N=k.redacted,v("outbound-secret-redacted",`outbound secret screen redacted ${k.detectors.length} detector(s): ${k.detectors.join(",")}`),S("mask","OUTPUT-BLOCK","outbound secret redacted before egress")),G(()=>J.run({gateKey:s,entered:new Set([f])},()=>c.call(u,N,..._)))};if(b.decision==="approval_required"&&b.decisionId){let w=Ae(b.hitlFallback,b.argRedactionRules),k=await Ie({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:b.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:w,sdkVersion:V});if(k.resolution==="proceed")return G(()=>J.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,..._)));if(k.resolution==="mask")try{let E=M(d,D(b.argRedactionRules));return S("mask",b.ruleCode,b.reason),G(()=>J.run({gateKey:s,entered:new Set([f])},()=>c.call(u,E,..._)))}catch{return n.failMode==="closed"?R({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(v("mask-error",`HITL mask fallback failed for tool "${a}" \u2014 running with UNMASKED args`),J.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,..._)))}let N=R({outcome:"approval_required",code:b.ruleCode??"HITL-BLOCK",reason:b.reason,mechanism:k.reason});return S("approval_required",b.ruleCode,b.reason,N),N}if(!b.allowed){let w=R({outcome:"deny",code:b.ruleCode??"DENY",reason:b.reason});return S("deny",b.ruleCode,b.reason,w),w}if(b.decision==="mask"&&b.argRedactionRules.length>0)try{let w=M(d,D(b.argRedactionRules));return S("mask",b.ruleCode,b.reason),ce(w)}catch{return n.failMode==="closed"?R({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(v("mask-error",`argument masking failed for tool "${a}" \u2014 running with UNMASKED args`),J.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,..._)))}return ce(d)};for(let c of Dr){if(typeof r[c]!="function")continue;let u=r[c];r[c]=function(d,..._){return l(u,this,d,_,c)}}r[o]=!0}function Ot(e){return e instanceof Error?e.message:String(e)}function Ms(e,t,n){let r=(a,s)=>{if(!a||typeof a!="object")return;let l=a[s];return typeof l=="string"&&l.length>0?l:void 0},o=t?.invocation_params,i=e&&typeof e=="object"?e.kwargs:void 0;return r(o,"model")??r(o,"model_name")??r(n,"ls_model_name")??r(i,"model")??r(i,"model_name")}function Ds(e,t){let n=(f,g)=>{if(!f||typeof f!="object")return;let p=f[g];return typeof p=="number"&&Number.isFinite(p)?p:void 0},r=e?.tokenUsage,o=n(r,"promptTokens"),i=n(r,"completionTokens");if(o!==void 0||i!==void 0)return{...o!==void 0?{tokensIn:o}:{},...i!==void 0?{tokensOut:i}:{}};let a=t?.usage_metadata,s=n(a,"input_tokens"),l=n(a,"output_tokens");if(s===void 0&&l===void 0)return;let c=a&&typeof a=="object"?a.input_token_details:void 0,u=n(c,"cache_read"),d=n(c,"cache_creation"),_=s!==void 0?Math.max(0,s-(u??0)-(d??0)):void 0;return{..._!==void 0?{tokensIn:_}:{},...l!==void 0?{tokensOut:l}:{},...u!==void 0?{cacheRead:u}:{},...d!==void 0?{cacheWrite:d}:{}}}function Lr(e,t){return{name:"VisiqHandler",handleLLMStart:async(n,r,o,i,a,s,l)=>{let c=C.getStore();if(!c)return;c.llm_prompts.push(...r);let u=Ms(n,a,l);u&&(c.llm_model=u,t.captureCloneMetadata({model:u,agentType:"langchain"}))},handleLLMEnd:async n=>{let r=C.getStore();if(!r)return;let i=n?.generations?.[0]?.[0],a=typeof i?.text=="string"?i.text:"";a&&r.llm_responses.push(a);try{let s=n?.llmOutput,l=i?.message&&typeof i.message=="object"?i.message:void 0,c=Ds(s,l);if(!c&&!a)return;let u=l?.tool_calls,d=typeof s?.model=="string"?s.model:void 0,_=r.llm_model??d;await t.awaitBundleReady(),st(t,{agentId:e,sessionId:r.session_id,framework:"langchain"},{...a?{texts:[a]}:{},...c?{usage:c}:{},..._?{model:_}:{},final:!(Array.isArray(u)&&u.length>0)})}catch{}},handleAgentAction:async n=>{let r=C.getStore();if(!r)return;let o=typeof n.log=="string"?n.log:"";o&&r.agent_reasoning.push(o)},handleRetrieverStart:async(n,r,o)=>{let i=C.getStore();i&&i.retrieverQueries.set(o,r??"")},handleRetrieverEnd:async(n,r)=>{let o=C.getStore();if(!o)return;let i=o.retrieverQueries.get(r)??"";if(o.retrieverQueries.delete(r),!Array.isArray(n))return;let a=z(o);for(let s of n){let l=s,c=String(l.pageContent??l.text??l.content??""),u=l.metadata??{};await t.evaluate({operations:["retrieval"],agentId:e,resourceType:"document",resourceMetadata:u,query:i,contentPreview:c.slice(0,500),...a?{telemetry:a}:{}})}},handleRetrieverError:async(n,r)=>{let o=C.getStore();o&&o.retrieverQueries.delete(r)}}}var Br=["_call","execute","call","run","invoke"];function Ls(e){let t=e;for(let n of Br)if(typeof t[n]=="function")return!0;return!1}function Fs(e){return e instanceof Z?!0:e instanceof j?typeof e.status=="number"&&e.status>=400&&e.status<500:!1}function $s(e,t,n){let r=null,o=null,i=!1,a=async()=>{if(r)return r;if(o)throw new Z(`Failed to bootstrap grant ${n}: ${o.message}`,null);let s;try{s=await hr(t.agentId,n)}catch(l){throw i=Fs(l),i&&(o=l instanceof Error?l:new Error(String(l))),new Z(`Failed to bootstrap grant ${n}: ${l instanceof Error?l.message:String(l)}`,null)}return r=_r(e,{agentId:t.agentId,grantToken:s,failBehavior:t.failMode==="closed"?"deny":"permit",...t.apiKey?{apiKey:t.apiKey}:{},...t.endpoint?{endpoint:t.endpoint}:{}}),r};return new Proxy(e,{get(s,l,c){if(l===Ee)return!0;let u=Reflect.get(s,l,c);return typeof u!="function"||typeof l!="string"||!Br.includes(l)?u:async function(...d){let _;try{_=await a()}catch(g){if(i||t.failMode==="closed")throw g;return v("grant-bootstrap",`grant ${n} bootstrap failed: ${g instanceof Error?g.message:String(g)}`),u.call(this,...d)}return _[l].call(_,...d)}}})}function Ps(e,t){let n=se(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode);Ur(e,n,t);let r=e;if(typeof r.execute=="function"){let o=typeof r.name=="string"&&r.name||typeof r.id=="string"&&r.id||"unknown";Xe(e,o,qr(t))}return e}function qr(e){return{agentId:e.agentId,unified:se(e.apiKey,e.endpoint,e.agentId,e.timeoutMs,void 0,e.failMode),hitlTimeoutMs:e.hitlTimeoutMs,failMode:e.failMode,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:Nt()}}async function Vr(e,t={}){if(!e||e.trim()==="")throw new Error("[VisIQ] visiq.delegate: childAgentId is required");let n=process.env.VISIQ_AGENT_ID;if(!n)throw new Error("[VisIQ] visiq.delegate: VISIQ_AGENT_ID env var is required. Set it to the parent agent ID before calling delegate.");let r=process.env.VISIQ_API_KEY;if(!r)throw new Error("[VisIQ] visiq.delegate: VISIQ_API_KEY env var is required");let o=process.env.VISIQ_ENDPOINT;return{VISIQ_GRANT_ID:(await new oe({agentId:n,apiKey:r,...o?{endpoint:o}:{}}).requestGrant({parentAgentId:n,childAgentId:e,toolScope:t.toolScope??null,contextScope:t.contextScope??null,durationSeconds:t.durationSeconds??3600,purpose:t.purpose??`Delegated to ${e}`,...t.maxDepth!==void 0?{maxDepth:t.maxDepth}:{},...t.parentGrantToken!==void 0?{parentGrantToken:t.parentGrantToken}:{}})).grantId}}var Ce=class{constructor(t){this.transport=t}transport;deploy(t={}){let n={include_mac:t.includeMac??!1};return t.autoInstallHarness!==void 0&&(n.auto_install_harness=t.autoInstallHarness),X(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return X(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return X(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return X(this.transport,"POST","/api/discovery/fleet/stop")}};var xe=class{constructor(t){this.transport=t}transport;connectAws(t){return X(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function js(e){if(!e.baseUrl||e.baseUrl.length===0)throw new Error("[VisIQ] createVisiqClient: baseUrl is required");if(!e.accessToken&&!e.cookieHeader)throw new Error("[VisIQ] createVisiqClient: one of accessToken or cookieHeader is required");let t=e.baseUrl.replace(/\/$/,""),n=e.fetchImpl??globalThis.fetch.bind(globalThis),r={baseUrl:t,accessToken:e.accessToken,cookieHeader:e.cookieHeader,fetchImpl:n};return{fleet:new Ce(r),integrations:new xe(r)}}async function X(e,t,n,r){let o=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,i={...H(V)};e.cookieHeader&&(i.Cookie=e.cookieHeader),e.accessToken&&(i.Authorization=`Bearer ${e.accessToken}`);let a;r!==void 0&&(i["Content-Type"]="application/json",a=JSON.stringify(r));let s=await e.fetchImpl(o,{method:t,headers:i,body:a});if(!s.ok){let l="";try{l=await s.text()}catch{}throw new Error(`[VisIQ] ${t} ${n} failed (${s.status}): ${l||s.statusText}`)}return await s.json()}var zr=$r;zr.delegate=Vr;var Cc=zr;export{ze as DEFAULT_FAIL_MODE,Ce as FleetClient,xe as IntegrationsClient,js as createVisiqClient,Vr as delegate,ke as normalizeFailMode,Cc as visiq};
|
|
6
|
+
-----END PRIVATE KEY-----`,template:{pattern:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.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:I.mac_address,mode:"full"},defaultEnabled:!1}};var Il=new Set(Ln.filter(e=>!Ve[e].defaultEnabled));function fo(e,t){let n=new Set;for(let r of Ln)(Ve[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function mo(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=e;for(let{name:o,re:a}of gt){let s=o;n.has(s)||(i=i.replace(a,()=>(r?.(s),t)))}for(let{name:o,re:a,normalize:s,validate:l}of ht)n.has(o)||(i=Io(i,a,s,l,t,o,r));return i}function ke(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var wn=new Map;function go(e){let t=wn.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),wn.set(e.source,t)),t}var ho=4096,_o=64,kn=null;function yo(e){return kn!==null?kn:ho+e.length*_o}var Fn=!1,F={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},$n={spanBudget:0,depthCap:0};function bo(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:yo(e),exhausted:!1}}function Pn(e,t,n,r,i,o,a){F.spanCalls++;let s=t*a.stride+n.length,l=Fn?void 0:a.chosen.get(s);if(l!==void 0)return l;if(a.budget<=0)return a.exhausted=!0,null;a.budget--,F.spanMisses++;let c=vo(e,t,n,r,i,o,a);return a.chosen.set(s,c),c}function vo(e,t,n,r,i,o,a){let s=go(r),l=[];for(let u=n.length-1;u>=1;u--)if(ke(n[u])){let d=n.slice(0,u);s.test(d)&&l.push(d)}let c=ke(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(o(i(u),u)&&!ko(e,t,u,r,i,o,a))return u;return null}var An=new Map;function wo(e){let t=An.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),An.set(e.source,t)),t}function ko(e,t,n,r,i,o,a){F.cutCalls++;let s=t*a.stride+n.length,l=Fn?void 0:a.cuts.get(s);if(l!==void 0)return l;if(a.budget<=0)return a.exhausted=!0,!0;a.budget--,F.cutMisses++;let c=Ao(e,t,n,r,i,o,a);return a.cuts.set(s,c),c}function Ao(e,t,n,r,i,o,a){let s=t+n.length,l=wo(r);for(let c=1;c<n.length;c++){if(ke(n[c])||!ke(n[c-1]))continue;let u=t+c;l.lastIndex=u;let d=l.exec(e);if(d===null||d[0].length===0)continue;let h=Pn(e,u,d[0],r,i,o,a);if(h!==null&&u+h.length>s&&ke(e[u+h.length]))return!0}return!1}function Io(e,t,n,r,i,o,a){t.lastIndex=0;let s="",l=0,c=bo(e),u=F.spanMisses+F.cutMisses,d;for(;(d=t.exec(e))!==null;){let h=d[0],f=d.index;if(h.length===0){t.lastIndex=f+1;continue}let m;try{m=Pn(e,f,h,t,n,r,c)}catch(p){if(p instanceof RangeError&&/call stack/i.test(p.message))c.exhausted=!0,m=null;else throw p}if(c.exhausted)return F.budgetExhausted++,$n.spanBudget++,In(u),s+e.slice(l,f)+i;if(m!==null)a?.(o),s+=e.slice(l,f)+i,l=f+m.length,t.lastIndex=l;else{let p=h.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=p===-1?f+h.length:f+1+p+1}if(t.lastIndex>e.length)break}return In(u),s+e.slice(l)}function In(e){let t=F.spanMisses+F.cutMisses-e;t>F.maxMissesInAPass&&(F.maxMissesInAPass=t)}function _t(e,t=Dn,n,r){return Eo(e,t,fo(n,r))}var So=256;function Eo(e,t,n){let r=new Set,i=!n.has("pan"),o=s=>{r.add(s)},a=(s,l)=>{if(l>So)return $n.depthCap++,t;if(typeof s=="string")return mo(s,t,n,o);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!i)return s;let c=String(s);return c.length>=13&&c.length<=19&&ft(c)?(r.add("pan"),t):s}if(Array.isArray(s))return s.map(c=>a(c,l+1));if(s!==null&&typeof s=="object"){let c=s,u={};for(let d of Object.keys(c))u[d]=a(c[d],l+1);return u}return s};return{value:a(e,0),detectors:[...r].sort()}}function jn(e,t=Dn){return _t(e,t).value}function To(e){let{value:t,detectors:n}=_t(e),r=n.some(i=>Ve[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function Ro(e,t){let{blocked:n,redacted:r,detectors:i}=To(e);return n?t.failMode==="closed"?{verdict:"block",redacted:r,detectors:i}:{verdict:"redact",redacted:r,detectors:i}:{verdict:"allow",redacted:r,detectors:i}}function Co(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var xo=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function Oo(e){return xo.has(Co(e))}function re(e,t,n){return n.enforced&&Oo(e)?Ro(t,{failMode:n.failMode}):{verdict:"allow",redacted:t,detectors:[]}}var No=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Bn=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"}),Mo=new RegExp(`[${Object.keys(Bn).join("")}]`,"gu"),Do=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),Un="\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",Lo=Object.freeze(Object.fromEntries([...Un].map((e,t)=>[e,String.fromCharCode(97+t)]))),Fo=new RegExp(`[${Un}\u2800]`,"g"),qn=/[⠀-⣿]/;function $o(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 Po(e){return e.replace(No,"")}function Vn(e){return e.replace(Mo,t=>Bn[t]??t)}function jo(e){return e.replace(/[4@31!05$79(8]/g,t=>Do[t]??t)}function Bo(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 Uo(e){return qn.test(e)?e.replace(Fo,t=>t==="\u2800"?" ":Lo[t]??t):e}function Sn(e){let t;try{t=$o(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=Po(t),t=Vn(t),t}var qo=/^[A-Za-z0-9+/]{16,}={0,2}$/,Vo=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,En=/[A-Za-z0-9+/]{20,}={0,2}/g;function mt(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 zn=new TextDecoder("utf-8",{fatal:!1});function Kn(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=zn.decode(n);return t===r?[t]:[r,t]}function zo(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 o=0;o<n.length;o++){let a=Number.parseInt(t.slice(o*2,o*2+2),16);if(Number.isNaN(a))return[];n[o]=a}let r="";for(let o=0;o<n.length;o++)r+=String.fromCharCode(n[o]);let i=zn.decode(n);return r===i?[r]:[i,r]}function Tn(e){let t=e.trim(),n=[];if(Vo.test(t))for(let r of zo(t))n.push({decoded:r,textiness:mt(r)});if(qo.test(t)&&t.length%4===0)for(let r of Kn(t))n.push({decoded:r,textiness:mt(r)});return n}function Rn(e,t){let n=[],r;for(En.lastIndex=0;(r=En.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let o of Kn(i))n.push({decoded:o,textiness:mt(o)})}return n}var Ko=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function Gn(e,t=Ko){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:o}=t,a=new Set,s=f=>{f.length>0&&f.length<=r&&a.add(f)},l=!1,c=!1,u=0,d=0,h=[{s:e,depth:0}];for(;h.length>0;){if(u>=i){c=!0;break}let f=h.pop();if(f===void 0)break;let{s:m,depth:p}=f;if(m.length>r){c=!0;continue}u++,p>d&&(d=p);let y=Sn(m);s(y);let x=jo(y);if(x!==y&&s(x),s(Bo(y)),qn.test(m)&&s(Uo(y)),p>=n){let T=Sn(m);(Tn(T).length>0||Rn(T,o).length>0)&&(c=!0);continue}let A=[...Tn(y),...Rn(y,o)];for(let T of A){if(l=!0,T.decoded.length>r){c=!0;continue}T.textiness>=.85&&T.decoded!==y?h.push({s:T.decoded,depth:p+1}):s(T.decoded)}}return{views:[...a],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:d}}var Hn=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],Go=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),Ho=8,Wo=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Cn=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function Qo(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||Wo.has(i)&&Cn(t[r-1])&&Cn(t[r+1])&&(n++,n>=Ho))return!0}return!1}var Yo=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function Zo(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(Yo.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Jo=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Xo(e){for(let t of Jo)if(e>=t.lo&&e<=t.hi)return t.name;return null}function ea(e){for(let t of e.split(/\s+/)){if(t.length<4)continue;let n=0,r=0,i=!0;for(let o of t){let a=Xo(o.codePointAt(0));if(a===null){i=!1;break}a==="latin"?n++:Vn(o)!==o&&r++}if(i&&n>0&&r>0)return!0}return!1}var xn=Object.freeze({signals:[],contributes:!1});function ta(e){if(typeof e!="string"||e.length===0)return{...xn,signals:[]};let t=new Set;try{Qo(e)&&t.add("hidden_text_carrier"),Zo(e)&&t.add("injected_turn_boundary"),ea(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=Gn(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...xn,signals:[]}}return{signals:[...Hn.filter(n=>t.has(n))],contributes:Go.some(n=>t.has(n))}}var ze=[{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 On(e){return typeof e!="string"||e.length===0?[]:ze.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function na(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(On(e)),{views:n}=Gn(e);for(let r of n)for(let i of On(r))t.add(i);return ze.filter(r=>t.has(r.name)).map(r=>r.name)}function ra(e){let t=new Set,n=new Set,r=!1,i=o=>{if(o!=null){if(typeof o=="string"){for(let s of na(o))t.add(s);let a=ta(o);for(let s of a.signals)n.add(s);a.contributes&&(r=!0);return}if(Array.isArray(o)){for(let a of o)i(a);return}if(typeof o=="object")for(let a of Object.values(o))i(a)}};return i(e),{matched:t.size>0||r,signatures:ze.filter(o=>t.has(o.name)).map(o=>o.name),structural:Hn.filter(o=>n.has(o))}}function ia(e){return ra(e).matched}var Sl=ze.map(e=>e.name);var oa=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var aa="i:injection";function Wn(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=_t(e.content);for(let o of i){let a=Ve[o]?.category;a&&t.add(`c:${a}`)}ia(e.content)&&t.add(aa)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&oa.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var pt="(?: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))",El=[{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${pt}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${pt}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${pt}\\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}],Nn="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",sa=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${Nn}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${Nn}|programming|training))`,la="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Mn="(?:\\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)",ca="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Tl=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${la}${sa}\\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}?${Mn}`,"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+(?:${ca}\\b|[\\s\\S]{0,40}?${Mn})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Rl=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var V=e=>`[^.!?;\\n]{0,${e}}?`,ua=["\\bi\\s+(?:can'?t|cannot|can\\s+not|won'?t|will\\s+not)\\b","\\bi(?:'m|\\s+am)\\s+(?:not\\s+able\\s+to|unable\\s+to|not\\s+going\\s+to|not\\s+permitted\\s+to|not\\s+allowed\\s+to)\\b"].join("|"),Qn="(?: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)",Cl=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${ua})\\s${V(40)}\\b${Qn}\\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${V(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${V(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${V(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${V(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${V(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")}]),xl=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${V(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${V(30)}\\b${Qn}\\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 we=e=>`[^.!?;\\n]{0,${e}}?`,Ol=Object.freeze([{id:"vulnerability_scanning",objectPatterns:[/\b(?:vulnerability|vuln|security)\s+(?:scan|scans|scanning|assessment|audit|test|testing)\b/i,/\bpen(?:etration)?[\s-]?test(?:ing)?\b/i,/\bport\s+scan(?:ning)?\b/i,/\b(?:exploit|nmap|metasploit|nessus|burp\s+suite)\b/i,/\bCVE-\d{4}-\d{4,7}\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|vulnerability|incident\s+respon\w{0,4}|threat|soc|red\s+team|phishing|malware)\b/i]},{id:"credential_access",objectPatterns:[/\b(?:credential|password|passphrase|api\s+key|access\s+key|secret|token|private\s+key|ssh\s+key)s?\b/i,/\b(?:vault|secrets?\s+manager|keychain|keystore)\b/i,/\bservice\s+account\s+key\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|identity|iam|credential|secrets?\s+manage\w{0,4}|vault|platform|devops)\b/i]},{id:"financial_transaction",objectPatterns:[/\b(?:wire\s+transfer|bank\s+transfer|payout|disbursement|chargeback)\b/i,new RegExp(`\\b(?:approve|issue|initiate|process|release)\\s${we(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${we(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${we(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${we(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${we(30)}\\b(?:external|customer|customers|public|press|social\\s+media|third[\\s-]party|prospect|prospects)\\b`,"i"),/\b(?:cold\s+outreach|marketing\s+blast|phishing\s+email|press\s+release)\b/i],purposeFunctions:["marketing","sales","customer_support"],purposePatterns:[/\b(?:marketing|campaign|outreach|email\s+assistant|support|customer|sales|lead|leads|communication|communications)\b/i]}]);var yt="[REDACTED]",ne="\u2022",qe=e=>/[A-Za-z0-9]/.test(e);function Yn(e,t,n,r){let i=Array.from(e),o=i.length,a=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:ne,c=a+s>=o;return i.map((u,d)=>!c&&(d<a||d>=o-s)?u:qe(u)?l:u).join("")}function da(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Yn(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:ne;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>qe(a)?o:a).join(""))+i}function pa(e,t,n){let r=n.length>0?n:ne,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let c=new RegExp(t,"g"),u;for(;(u=c.exec(e))!==null;){if(u[0].length===0){c.lastIndex++;continue}for(let d=u.index;d<u.index+u[0].length;d++)i[d]=!0}}catch{}let o=!1,a=!0;for(let c=0;c<e.length;c++)if(qe(e[c])&&(o=!0,!i[c])){a=!1;break}let s=o&&a,l="";for(let c=0;c<e.length;c++){let u=e[c];!s&&i[c]||!qe(u)?l+=u:l+=r}return l}function Zn(e,t){let n=t.mode??"full";return n==="partial"?Yn(e,t.keepFirst??0,t.keepLast??0,t.maskChar??ne):n==="email"?da(e,t.maskChar??ne):n==="custom"?pa(e,t.keepPattern,t.maskChar??ne):t.replacement??yt}function fa(e,t){return typeof e=="string"?Zn(e,t):t.replacement??yt}function Jn(e){let t=[],n=e.replacement??yt;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:o=>Zn(o,r)})}return t}function Xn(e,t){let n=e;for(let{source:r,replacer:i}of t){let o;try{o=new RegExp(r,"g")}catch(a){let s=a instanceof Error?a.message:String(a);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(o,a=>i(a))}return n}function M(e,t){return e==null?e:typeof e=="string"?ma(e,t):typeof e=="object"?ga(e,t):e}function ma(e,t){if(typeof e!="string")return e;let n=Jn(t);return n.length===0?e:Xn(e,n)}function ga(e,t){let n=new Map;for(let s of t.fields??[])typeof s=="string"&&s.length>0&&n.set(s,{field:s,mode:"full",replacement:t.replacement});for(let s of t.directives??[])typeof s.field=="string"&&s.field.length>0&&n.set(s.field,s);let r=Jn(t),i=n.size>0,o=r.length>0,a=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>a(l));if(typeof s=="object"){let l=s,c=Object.create(Object.getPrototypeOf(l));for(let u of Object.keys(l)){let d=i?n.get(u):void 0;if(d){c[u]=fa(l[u],d);continue}c[u]=a(l[u])}return c}return typeof s=="string"&&o?Xn(s,r):s};return a(e)}var er=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function ha(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:er(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:er(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 ya=1440*60*1e3,ba="VISIQ_BUNDLE_GRACE_TTL_MS",va="VISIQ_BUNDLE_CACHE_DISABLED",wa="VISIQ_CACHE_DIR",ka=Ke.object({graceTtlMs:Ke.number().int().nonnegative().optional(),disabled:Ke.boolean().optional(),cacheDir:Ke.string().min(1).optional()}).strict();function Aa(e){return e==null?{}:ka.parse(e)}function Ia(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[ba];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return ya}function Sa(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[va]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var tr;function Ea(){if(tr!==void 0)return tr;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Ta(e){return JSON.stringify(vt(e))}function vt(e){if(Array.isArray(e))return e.map(vt);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=vt(t[r]);return n}return e}function Ra(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Ca(e){if(e!==null&&typeof e=="object"&&typeof e.fetchedAt=="number"&&typeof e.contentHash=="string"&&"body"in e){let t=e;return{fetchedAt:t.fetchedAt,version:typeof t.version=="string"?t.version:null,contentHash:t.contentHash,body:t.body}}return null}async function sr(){if(!Ea())return null;try{let[e,t,n,r]=await Promise.all([import("node:fs/promises"),import("node:path"),import("node:os"),import("node:crypto")]);return{fs:e,path:t,os:n,crypto:r}}catch{return null}}function lr(e,t){return e.createHash("sha256").update(Ta(t)).digest("hex")}function xa(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[wa]?.trim();if(r)return r;let i=process.env.XDG_CACHE_HOME?.trim();if(i)return e.path.join(i,"visiq");let o="";try{o=e.os.homedir()}catch{o=""}return o?e.path.join(o,".cache","visiq"):e.path.join(e.os.tmpdir(),"visiq-cache")}function Oa(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function cr(e,t,n){return e.path.join(xa(e,n),"bundles",`${Oa(e,t)}.json`)}async function Na(e,t,n,r={}){let i=await sr();if(i)try{let o=cr(i,e,r),a=i.path.dirname(o);await i.fs.mkdir(a,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:lr(i.crypto,t),body:t},l=`${o}.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,o)}catch(c){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),c}}catch{}}async function Ma(e,t={}){let n=await sr();if(!n)return null;try{let r=await n.fs.readFile(cr(n,e,t),"utf-8"),i=Ca(JSON.parse(r));return!i||lr(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var Ae;async function Da(){if(Ae!==void 0)return Ae;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;Ae=typeof t=="function"?t:null}catch{Ae=null}return Ae}function La(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 o;try{o=ut(i)}catch{continue}let a=typeof r.id=="string"?r.id:"<rule>";for(let s of tn(o))t.push(`${a}: ${s}`)}return t}function Fa(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=ut(r)}catch{continue}let o=nn(i);if(o.length!==0)for(let a of n.appliesTo){let s=t[a];if(s)for(let l of o)s.add(`${n.id}: ${l}`)}}return{retrieval:[...t.retrieval].sort(),action:[...t.action].sort(),delegation:[...t.delegation].sort()}}function $a(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var Pa=5e3,ja=600*1e3,Ba=1e4,Ua=25,nr=1e3,qa=5e3,Va=100,rr=2e3,za=10,Ka=512,Ga=1800*1e3,Ha=.7,Wa="monitor",Qa="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",ir="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.",Ge="open";function Ie(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Ya(e,t){return Wn({content:e,resourceMetadata:t})}var Za=_.object({operations:_.array(_.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:_.string().min(1,"agentId is required"),sessionId:_.string().min(1).max(255).optional(),toolName:_.string().optional(),toolArgs:_.record(_.unknown()).optional(),targetResource:_.string().optional(),resourceType:_.string().optional(),resourceMetadata:_.record(_.unknown()).optional(),normalized:_.record(_.unknown()).optional(),query:_.string().optional(),contentPreview:_.string().optional(),telemetry:_.record(_.unknown()).optional(),context:_.record(_.unknown()).optional(),mcpServer:_.string().min(1).max(255).optional()}),Ja=_.object({version:_.string().min(1),dialect_version:_.number().int().optional(),min_dialect:_.number().int().optional(),shutdown:_.boolean().optional(),agent_mode:_.enum(["enforce","monitor","off"]).optional(),cognition_capture:_.boolean().optional(),agent_mode_by_operation:_.object({action:_.string().optional(),retrieval:_.string().optional(),delegation:_.string().optional()}).partial().optional(),agent_attributes:_.object({trust_tier:_.string().nullable().optional(),categories:_.array(_.string()).optional(),business_function:_.string().nullable().optional(),business_functions:_.array(_.string()).nullable().optional(),blast_radius_tier:_.string().nullable().optional(),no_coverage:_.string().nullable().optional(),fail_mode:_.string().nullable().optional()}).optional(),rules:_.array(_.record(_.unknown())),action_schemas:_.array(_.object({id:_.string(),plane:_.string().optional(),field_mappings:_.array(_.record(_.unknown())).optional(),derived_fields:_.array(_.record(_.unknown())).optional(),action_class:_.string().nullable().optional(),action_class_confidence:_.number().optional()})).optional(),no_coverage:_.object({no_coverage_defaults:_.record(_.string()),autopilot_enabled:_.boolean(),enduser_hitl_enabled:_.boolean(),hitl_timeout_seconds:_.number().optional()}).optional()});function Xa(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=gn(hn(n));return{trust_tier:on(t)?t:null,categories:sn(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&_n(e.blast_radius_tier)?e.blast_radius_tier:null}}function es(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 ts(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var wt=new Set,or=!1;async function ar(e){let t=[];for(let n of wt){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 ns(){if(!or&&!(typeof process>"u"||typeof process.once!="function")){or=!0,process.once("beforeExit",()=>{ar(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await ar(!0)}finally{process.kill(process.pid,e)}})()})}}var ur=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;cacheIdentity;bundleCacheDisabled;bundleGraceTtlMs;bundleCacheDirOverride;diskFallbackServed=!1;agentMode=Wa;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=Ie(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Ge;governedFailMode=null;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastCloneCaptureSig=null;toolDescriptions=new Map;constructor(e,t,n,r,i,o,a,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=o,this.sdkDialect=a,this.originalFetch=globalThis.fetch.bind(globalThis);let d=Aa(s);if(this.bundleCacheDisabled=Sa(d.disabled),this.bundleGraceTtlMs=Ia(d.graceTtlMs),this.bundleCacheDirOverride=d.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let h={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:_a(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...o!==void 0?{sdkVersion:o}:{},...a!==void 0?{sdkDialect:a}:{}};this.client=new st(h,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Pa),bt(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Ba),bt(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},qa),bt(this.cognitionTimer),wt.add(this),ns()}else this.client=null}async evaluate(e){let t=Za.parse(e),n=Date.now();if(this.operatorShutdown){let f=this.denyAll(t,Qa);return this.applyAgentMode(f,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,ir,n);let f=this.denyAll(t,ir);return this.applyAgentMode(f,"enforce",t,n)}if(t.operations.every(f=>this.modeFor(f)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let f;if(this.agentModeConfirmed?f=this.agentMode:this.bundleApplyFailed?f="enforce":f="monitor",f==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let m=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(m,f,t,n)}let r=this.readSession(t.sessionId),i=await Da();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 o=t.operations.includes("action")||t.operations.includes("delegation")?cn(t.normalized??{},{targetApp:t.targetResource??t.toolName??""}):t.normalized,a=this.buildActionSchemaEvent(t),s=t.mcpServer?{...o??{},mcp_server:t.mcpServer}:o,l={...t,normalized:s,session:r,at:Date.now(),action_schema_id:a.id,action_schema_raw:a.canonical},c={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},u;try{u=i(l,c)}catch(f){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${f instanceof Error?f.message:String(f)}`,n);throw f}let d=[...new Set(t.operations.flatMap(f=>this.normalizedRefs[f]??[]))].sort();d.length>0&&$a(t.normalized)&&(u.normalizedColdStart=d,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${d.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: ${d.slice(0,5).join("; ")}${d.length>5?`; +${d.length-5} more`:""}`)));let h=un(t.normalized);return h.length>0&&(u.normalizedDrift=h,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${h.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: ${h.slice(0,5).join("; ")}${h.length>5?`; +${h.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}readSession(e){if(!e)return ve;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Ga?(this.sessions.delete(e),ve):t.state:ve}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 o=i.action_class,a=typeof i.action_class_confidence=="number"?i.action_class_confidence:0;if(typeof o=="string"&&o.length>0&&a>=Ha)return o}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=pn(r===ve?dn():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,taint:o?Ya(e.contentPreview,i):void 0,action_class:a?this.foldActionClass(e):void 0,target_app:a?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>Ka){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 a={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,a,i,!0),a}let o={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,o,i,!1),o}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"),o=e.operations.includes("retrieval"),a={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:o?{action:"allow"}:{action:null},failOpen:!0};return this.bufferTelemetry(e,a,Date.now()-n,!1,!0),a}reportFailOpen(e,t){try{let n={operations:["action"],agentId:this.resolvedAgentId,...t?.toolName?{toolName:t.toolName}:{},...t?.sessionId?{sessionId:t.sessionId}:{}},r={decision:"permit",allowed:!0,reason:`fail-open: ${e} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:{decision:"permit",allowed:!0},retrieval:{action:null},failOpen:!0};this.bufferTelemetry(n,r,0,!1,!0)}catch{}}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},action_schema_id:this.buildActionSchemaEvent(e).id,...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=Ja.parse(e);this.bundleApplyFailed=!1;let n=this.sdkDialect??1;if(t.min_dialect!==void 0&&t.min_dialect>n){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle requires dialect ${t.min_dialect} but this SDK speaks ${n} \u2014 refusing the bundle and failing closed (deny-all, G001). Upgrade the VisIQ SDK.`);return}let r=La(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=>vn(i)).filter(i=>i!==null),this.agentAttributes=t.agent_attributes?Xa(t.agent_attributes):null,this.agentNoCoverage=yn(t.agent_attributes?.no_coverage),this.governedFailMode=Ie(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=es(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=Fa(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",...W(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 a=Date.now();a-this.lastNormalizedWarnRearmMs>=ja&&(this.lastNormalizedWarnRearmMs=a,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 o=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&o?this.bundleEtag=r:o||(this.bundleEtag=null),o&&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 Ma(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Ra(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 Na(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}isBundleLoaded(){return this.bundleLoaded}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e,t){this.registerEnvironment({...$e(),...e?{agent_type:e}:{},...t?.model?{model:t.model}:{},...t?.systemPrompt?{systemPrompt:t.systemPrompt}:{},...t?.toolSchemas&&t.toolSchemas.length>0?{toolSchemas:t.toolSchemas}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));for(let n of e)n.description&&this.toolDescriptions.set(n.name,n.description);t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}captureCloneMetadata(e){if(!this.client||!this.resolvedAgentId||!(e.model||e.systemPrompt||(e.toolSchemas?.length??0)>0))return;let t=JSON.stringify({m:e.model??"",s:e.systemPrompt??"",t:e.toolSchemas??[]});t!==this.lastCloneCaptureSig&&(this.lastCloneCaptureSig=t,this.client.registerEnvironment({...$e(),...e.agentType?{agent_type:e.agentType}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{toolSchemas:e.toolSchemas}:{}}))}buildActionSchemaEvent(e){let t=e.toolName?this.toolDescriptions.get(e.toolName):void 0,n={agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{},...e.toolArgs?{tool_args:e.toolArgs}:{},...t?{tool_description:t}:{}},r=bn(n),i={...n};return e.toolArgs&&(i.tool_args=jn(e.toolArgs)),{canonical:n,id:r,rawEventForWire:i}}bufferTelemetry(e,t,n,r,i=!1){let o=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?ts(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:o.rawEventForWire,action_schema_id:o.id,...this.harnessKind||e.context||i||t.normalizedColdStart||t.normalizedDrift?{context:{...this.harnessKind?{[zt]:this.harnessKind}:{},...e.context??{},...i?{fail_open:!0}:{},...t.normalizedColdStart?{normalized_cold_start:!0,normalized_inert_conditions:t.normalizedColdStart.length}:{},...t.normalizedDrift?{normalized_drift:!0,normalized_drift_values:t.normalizedDrift.length,normalized_drift_fields:t.normalizedDrift.slice(0,za)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Ua&&this.flushTelemetry()}pendingTelemetryCount(){return this.telemetryBuffer.length}hasBackend(){return this.client!==null}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0);try{await this.client.sendTelemetry(e)}catch(t){console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",t)}}enforceTelemetryCap(){let e=this.telemetryBuffer.length-nr;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${nr})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(ha(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Va&&this.flushCognition())}async flushCognition(){if(this.cognitionBuffer.length===0||!this.client)return;let e=this.cognitionBuffer.splice(0);try{await this.client.sendCognition(void 0,e)}catch(t){console.error("[UnifiedRuntime] cognition flush failed (non-fatal):",t)}}enforceCognitionCap(){let e=this.cognitionBuffer.length-rr;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${rr})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),wt.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 bt(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function rs(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function $(e,...t){for(let n of t){let r=rs(e[n]);if(r)return r}}var is=[{framework:"openai-agents",matches:e=>/^transfer_to_.+/.test(e),extract:(e,t)=>{let n=e.replace(/^transfer_to_/,"");return{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"teammate",task:$(t,"task","input","reason","message"),source:"structural"}}},{framework:"voltagent",matches:e=>e==="delegate_task",extract:(e,t)=>{let n=$(t,"targetAgent","agent","subAgent","agentName","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:$(t,"task","message","input"),description:$(t,"purpose"),source:"structural"}:null}},{framework:"crewai",matches:e=>/delegate work to (co-?worker|.+)/i.test(e),extract:(e,t)=>{let n=$(t,"coworker","agent","role");return n?{childAgentId:n,childName:n,kind:"teammate",agentType:n,task:$(t,"task","question"),description:$(t,"context"),source:"structural"}:null}},{framework:"llamaindex",matches:e=>e==="handoff"||/handoff/i.test(e),extract:(e,t)=>{let n=$(t,"to_agent","toAgent","agent_name","agentName","agent","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:$(t,"reason","task","message"),source:"structural"}:null}},{framework:"generic",matches:e=>/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)([_-].+)?$/i.test(e),extract:(e,t)=>{let n=$(t,"agent","agentName","agentId","target","targetAgent","to","to_agent","coworker","name")??(/[_-]/.test(e)?e.replace(/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)[_-]/i,""):void 0);return n?{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"subagent",task:$(t,"task","message","input","reason","prompt"),source:"heuristic"}:null}}];function He(e,t){if(!e)return null;let n=t??{};for(let r of is)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function We(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}function kt(e){if(e===null||typeof e!="object"||Array.isArray(e))return{input:e===void 0?"":String(e)};let t=e,n=Object.keys(t);return n.length===1&&n[0]==="context"&&t.context!==null&&typeof t.context=="object"?t.context:t}function dr(e){if(typeof e=="string"){try{let t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{input:e}}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{input:e===void 0?"":String(e)}}function D(e){let t=[],n=[],r,i=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let l={mode:a.mode};a.field&&(l.field=a.field),a.pattern&&(l.pattern=a.pattern),typeof a.keepFirst=="number"&&(l.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(l.keepLast=a.keepLast),a.maskChar&&(l.maskChar=a.maskChar),a.keepPattern&&(l.keepPattern=a.keepPattern),a.replacement!==void 0&&(l.replacement=a.replacement),i.push(l);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:s}=a;s&&r===void 0&&(r=s)}let o={};return t.length>0&&(o.fields=t),n.length>0&&(o.patterns=n),r!==void 0&&(o.replacement=r),i.length>0&&(o.directives=i),o}var z="0.2.13";import{AsyncLocalStorage as os}from"node:async_hooks";var C=new os,as=5120,pr=50;function ss(e,t){if(typeof e!="string")return"";let n=new TextEncoder,r=n.encode(e);if(r.length<=t)return e;let o=`\u2026[truncated ${Math.ceil(r.length/1024)}KB]`,a=n.encode(o).length,s=Math.max(0,t-a),l=r.subarray(0,s);return new TextDecoder("utf-8",{fatal:!1}).decode(l)+o}function K(e){if(!e)return;let t=r=>r.length<=pr?r.slice():r.slice(r.length-pr),n=r=>ss(r,as);return{session_id:e.session_id,llm_prompts:t(e.llm_prompts).map(n),llm_responses:t(e.llm_responses).map(n),agent_reasoning:t(e.agent_reasoning).map(n)}}var At=12e4,fr=2e3,mr=3,ls=5e3;function Se(e,t){return e==="mask"&&(t?.length??0)>0}var cs=new Set(["approved","resolved"]),us=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function ds(e){return new Promise(t=>setTimeout(t,e))}function ps(e){if(typeof e!="object"||e===null)return null;let t=e,n=t.hitl_result;if(typeof n=="string"&&n.length>0)return n;let{hitl:r}=t;if(r&&typeof r=="object"){let{status:i}=r;if(typeof i=="string"&&i.length>0)return i==="pending"?null:i}return null}async function Ee(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=At,maskFallback:o=!1,sdkVersion:a,fetchImpl:s=globalThis.fetch,sleep:l=ds,log:c=p=>console.warn(p)}=e,u=p=>o?{resolution:"mask",reason:p}:{resolution:"block",reason:p};if(!t)return u("HITL approval cannot be confirmed (no backend endpoint) \u2014 fail-closed (G001)");if(!r)return u("HITL approval cannot be confirmed (no decision id) \u2014 fail-closed (G001)");let d=`${t.replace(/\/$/,"")}/v1/allow/decisions/${encodeURIComponent(r)}`,h={Accept:"application/json",...W(a)};n&&(h.Authorization=`Bearer ${n}`);let f=Date.now()+Math.max(0,i),m=0;for(c(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=f)return c(`[VisIQ HITL] Decision ${r} timed out after ${i}ms \u2014 ${o?"masking":"blocking"} (G001)`),u("HITL approval timed out");let p=null;try{let y=new AbortController,x=setTimeout(()=>y.abort(),ls),A;try{A=await s(d,{method:"GET",headers:h,signal:y.signal})}finally{clearTimeout(x)}if(!A.ok)throw new Error(`HTTP ${A.status} ${A.statusText}`);let T=await A.json();p=ps(T),m=0}catch(y){m+=1;let x=y instanceof Error?y.message:String(y);if(c(`[VisIQ HITL] Poll failed for decision ${r} (${m}/${mr}): ${x}`),m>=mr)return u(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${x}`);await l(fr);continue}if(p!==null){let y=p.toLowerCase();return cs.has(y)?(c(`[VisIQ HITL] Decision ${r} approved (${p}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${p})`}):us.has(y)?(c(`[VisIQ HITL] Decision ${r} resolved as ${p} \u2014 ${o?"masking":"blocking"}`),u(`Not approved by human reviewer (${p})`)):(c(`[VisIQ HITL] Decision ${r} returned unknown status '${p}' \u2014 ${o?"masking":"blocking"} (G001)`),u(`HITL returned unknown status '${p}' \u2014 fail-closed (G001)`))}await l(fr)}}function G(e){return e??Ie(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Ge}function v(e,t){try{console.error(`[VisIQ] FAIL-OPEN (${e}): ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`)}catch{}}function U(e,t){try{console.error(`[VisIQ] TRACE-DEGRADED (${e}): ${t} \u2014 the governance decision was still made and enforced; only the execution-trace beat was lost.`)}catch{}}function ie(e){let t=e.getFailMode;return(typeof t=="function"?t.call(e):void 0)??G()}function Z(e){return e.enforced?{allowed:e.action.allowed,decision:e.action.decision,...e.action.decisionId!==void 0?{decisionId:e.action.decisionId}:{},...e.ruleCode!==null?{ruleCode:e.ruleCode}:{},reason:e.reason,argRedactionRules:e.action.argRedactionRules??[],...e.action.hitlFallback?{hitlFallback:e.action.hitlFallback}:{}}:{allowed:!0,decision:"permit",reason:e.reason,argRedactionRules:[]}}function hr(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&Se(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}var gr=new Set;function Tt(e){gr.has(e)||(gr.add(e),console.warn(`[VisIQ] unrecognized retrieval outcome "${e}" \u2014 failing closed (withholding content). Upgrade @visiq/harness if a newer control plane introduced this outcome.`))}async function Ye(e,t,n){let r=C.getStore(),i=K(r),o=await e.evaluate({operations:["retrieval"],agentId:t,...r?.session_id?{sessionId:r.session_id}:{},resourceType:n.resourceType??"document",resourceMetadata:n.resourceMetadata??{},...n.query!==void 0?{query:n.query}:{},...n.contentPreview!==void 0?{contentPreview:n.contentPreview}:{},...i?{telemetry:i}:{}});return hr(o)}async function Ze(e,t,n){return await e.awaitBundleReady(),Ye(e,t,n)}function _r(e,t,n=G()){switch(t.action){case"allow":case"escalate":return e;case"deny":return null;case"redact":{if(t.redactionRules.length===0)return e;try{return M(e,D(t.redactionRules))}catch{return n==="closed"?null:(v("redact-error","document redaction failed \u2014 document passed UNREDACTED"),e)}}default:return Tt(String(t.action)),n==="closed"?null:(v("unknown-retrieval-verb",`unrecognized outcome "${String(t.action)}" \u2014 document passed through`),e)}}async function yr(e,t,n,r){if(!Array.isArray(e)||e.length===0)return e;await r.awaitBundleReady();let i=[];for(let o of e){let a=o,s=String(a.pageContent??a.text??a.content??""),l=a.metadata??{},c=await Ye(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s.slice(0,500)}),u=_r(o,c,ie(r));u!==null&&i.push(u)}return i}async function br(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await Ye(n,t,{resourceType:"document",resourceMetadata:{content_preview:e.slice(0,500)},contentPreview:e.slice(0,500)})}catch(i){return ie(n)==="closed"?"[RECALL] Retrieved context blocked \u2014 policy evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":(v("eval-error",`retrieval evaluation failed \u2014 text passed through: ${i instanceof Error?i.message:String(i)}`),e)}switch(r.action){case"allow":case"escalate":return e;case"deny":return"[RECALL] Retrieved context was blocked by policy.";case"redact":{if(r.redactionRules.length===0)return e;try{return M(e,D(r.redactionRules))}catch{return ie(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(v("redact-error","text redaction failed \u2014 text passed UNREDACTED"),e)}}default:return Tt(String(r.action)),ie(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(v("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 text passed through`),e)}}var vr=4,wr=1e3;function Qe(e){return e.length===0?!1:e.some(t=>t!==null&&typeof t=="object"&&(typeof t.pageContent=="string"||typeof t.text=="string"||typeof t.content=="string"))}async function kr(e,t,n){let r=[];for(let i of e){let o=i,a=String(o.pageContent??o.text??o.content??""),s={...o.metadata??{},content_preview:a.slice(0,500)},l;try{l=await Ye(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:a.slice(0,500)})}catch(u){if(ie(n)==="closed")continue;v("eval-error",`document retrieval evaluation failed \u2014 document passed through: ${u instanceof Error?u.message:String(u)}`),r.push(i);continue}let c=_r(i,l,ie(n));c!==null&&r.push(c)}return r}async function St(e,t,n,r,i){if(r>vr||i.nodes++>wr)return e;if(Array.isArray(e)){if(Qe(e))return i.matched=!0,kr(e,t,n);let o=[];for(let a of e)o.push(await St(a,t,n,r+1,i));return o}if(e!==null&&typeof e=="object"){let o=e,a={...o};for(let s of Object.keys(o))a[s]=await St(o[s],t,n,r+1,i);return a}return e}async function Je(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&Qe(e))return kr(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await St(e,t,n,0,r);if(r.matched)return i}return e}var fs={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function Et(e,t,n){if(t>vr||n.n++>wr)return e;if(Array.isArray(e))return Qe(e)?[]:e.map(r=>Et(r,t+1,n));if(e!==null&&typeof e=="object"){if(Qe([e]))return{...fs};let r=e,i={};for(let o of Object.keys(r))i[o]=Et(r[o],t+1,n);return i}return e}function It(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?Et(e,0,{n:0}):e}function Ar(e,t,n=G()){let r=hr(t);switch(r.action){case"allow":case"escalate":return e;case"deny":return It(e);case"redact":{if(r.redactionRules.length===0)return e;try{return M(e,D(r.redactionRules))}catch{return n==="closed"?It(e):(v("redact-error","result redaction failed \u2014 result passed UNREDACTED"),e)}}default:return Tt(String(r.action)),n==="closed"?It(e):(v("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 result passed through`),e)}}function O(e){return typeof e=="object"&&e!==null?e:null}function Ir(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}function ms(e,t){let n=O(e.metadata),r=n&&typeof n.name=="string"?n.name:void 0;return Ir(e.name,e.id,r,t)}function gs(e){let t=O(e.metadata),n=t&&typeof t.description=="string"?t.description:void 0,r=Ir(e.description,n);return r===void 0?void 0:r.slice(0,4e3)}function hs(e){let t=O(e);return t!==null&&("type"in t||"properties"in t||"$schema"in t)}function _s(e){let t=O(e);if(t===null||!("_def"in t))return;let{shape:n}=t;if(typeof n=="function")try{n=n.call(t)}catch{n=void 0}let r=O(n);if(r===null)return{type:"object"};let i={};for(let o of Object.keys(r))i[o]={};return{type:"object",properties:i}}var ys=new Set(["default","const","enum","examples","example"]);function Rt(e){if(Array.isArray(e))return e.map(Rt);let t=O(e);if(t===null)return e;let n={};for(let[r,i]of Object.entries(t))ys.has(r)||(n[r]=Rt(i));return n}function bs(e){let t;if(hs(e))t=e;else{let n=_s(e);if(n===void 0)return;t=n}try{let n=JSON.stringify(t);if(n.length>2e4){let r=O(t),i=r&&O(r.properties);if(i){let o={};for(let a of Object.keys(i))o[a]={};return{type:"object",properties:o}}return{type:"object"}}return Rt(JSON.parse(n))}catch{return}}function vs(e){let t=O(e.metadata),n=e.input_schema??e.inputSchema??e.parameters??e.schema??e.args_schema??e.tool_call_schema??(t?t.parameters:void 0);return n===void 0?void 0:bs(n)}function ws(e,t){let n=O(e);if(n===null)return null;let r=ms(n,t);if(r===void 0)return null;let i={name:r.slice(0,255)},o=gs(n);o!==void 0&&(i.description=o);let a=vs(n);return a!==void 0&&(i.input_schema=a),i}function Te(e){let t=[],n=new Set,r=(i,o)=>{try{let a=ws(i,o);a!==null&&!n.has(a.name)&&(n.add(a.name),t.push(a))}catch{}};if(Array.isArray(e)){for(let i of e)if(r(i),t.length>=200)break}else if(e instanceof Map){for(let[i,o]of e.entries())if(r(o,typeof i=="string"?i:void 0),t.length>=200)break}else{let i=O(e);if(i!==null){for(let o of Object.keys(i))if(r(i[o],o),t.length>=200)break}}return t}function Ct(e){try{let t=O(e);if(t===null)return[];let n=[],r=new Set,i=l=>{for(let c of l)!r.has(c.name)&&n.length<200&&(r.add(c.name),n.push(c))};t.tools!==void 0&&i(Te(t.tools));let o=O(t.settings);o&&o.tools!==void 0&&i(Te(o.tools));for(let l of["getTools","listTools"]){let c=t[l];if(typeof c=="function")try{i(Te(c.call(t)))}catch{}}let a=O(t.nodes);if(a)for(let l of Object.keys(a)){let c=O(a[l]);c&&c.tools!==void 0&&i(Te(c.tools))}let{agents:s}=t;if(s instanceof Map)for(let l of s.values()){let c=O(l);c&&c.tools!==void 0&&i(Te(c.tools))}return n}catch{return[]}}import{z as Xe}from"zod";var ks=Xe.object({decision:Xe.enum(["permit","deny"]),reason:Xe.string(),handoff_event_id:Xe.string().nullable()}),B=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},J=class extends B{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},As="https://api.visiqlabs.com",Is=1e4,oe=class{config;fetch;constructor(e,t=globalThis.fetch){this.config={agentId:e.agentId,apiKey:e.apiKey??process.env.VISIQ_API_KEY??"",endpoint:e.endpoint??process.env.VISIQ_ENDPOINT??As,timeoutMs:e.timeoutMs??Is},this.fetch=t}get headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Agent-ID":this.config.agentId}}async post(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.fetch(`${this.config.endpoint}${e}`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:n.signal})}finally{clearTimeout(r)}let o=await i.json();if(!i.ok){let a=o?.error??`HTTP ${i.status}`;throw new B(a,"API_ERROR",i.status)}return o}async requestGrant(e){let t=await this.post("/orchestrate/grants",{parent_agent_id:e.parentAgentId,child_agent_id:e.childAgentId,tool_scope:e.toolScope??null,context_scope:e.contextScope??null,purpose:e.purpose,duration_seconds:e.durationSeconds,max_depth:e.maxDepth,parent_grant_token:e.parentGrantToken});return{grantId:t.grant_id,status:"pending",effectiveToolScope:t.effective_tool_scope,effectiveContextScope:t.effective_context_scope,acceptDeadline:t.accept_deadline}}async acceptGrant(e){let t=await this.post(`/orchestrate/grants/${e}/accept`,{});return{grantToken:t.grant_token,toolScope:t.tool_scope,contextScope:t.context_scope,expiresAt:t.expires_at}}async evaluate(e){let t=await this.post("/orchestrate/evaluate",{grant_token:e.grantToken,action:e.action,resource_type:e.resourceType,resource_metadata:e.resourceMetadata??{}}),n=ks.parse(t);return{decision:n.decision,reason:n.reason,handoffEventId:n.handoff_event_id}}async revokeGrant(e,t){return{revokedCount:(await this.post(`/orchestrate/grants/${e}/revoke`,{reason:t})).revoked_count}}};var Sr=new Map;async function Er(e,t){if(!e||e.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: agentId is required");if(!t||t.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: grantId is required");let n=Sr.get(e);if(n)return n;let r=process.env.VISIQ_API_KEY;if(!r)throw new Error("[ORCHESTRATE] bootstrapGrant: VISIQ_API_KEY env var is required");let i=process.env.VISIQ_ENDPOINT,o=(await new oe({agentId:e,apiKey:r,...i?{endpoint:i}:{}}).acceptGrant(t)).grantToken;if(!o||o.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: backend returned empty grant token");return Sr.set(e,o),o}var Re=Symbol.for("visiq.orchestrate.wrapped");function Ss(e){return e instanceof B&&typeof e.status=="number"&&e.status>=400&&e.status<500}function Tr(e,t){if(!t.agentId||t.agentId.trim()==="")throw new B("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new B("grantToken is required","CONFIG_ERROR");if(e[Re]===!0)return e;let n=new oe(t),r=t.failBehavior??(process.env.VISIQ_FAIL_MODE?.trim().toLowerCase()==="closed"?"deny":"permit"),i=async(o,a)=>{let s;try{s=await n.evaluate({grantToken:t.grantToken,action:o,resourceType:a})}catch(l){if(Ss(l))throw l;if(r==="permit"){console.warn('[VisIQ] FAIL-OPEN (orchestrate-eval-error): evaluate failed \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed (or failBehavior:"deny") to block instead.',l);return}throw new B(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new J(s.reason,s.handoffEventId)};return new Proxy(e,{get(o,a,s){let l=Reflect.get(o,a,s);return a===Re?!0:a==="_call"&&typeof l=="function"?async function(c,...u){let d=o.name;return await i(d??"_call"),l.call(this??o,c,...u)}:(a==="call"||a==="execute"||a==="run")&&typeof l=="function"?async function(c,...u){let d=o.name;return await i(d??String(a)),l.call(this??o,c,...u)}:l}})}import{randomUUID as Mr}from"node:crypto";var Rr=Symbol.for("visiq.semantickernel.instrumented");function Or(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.useFunctionInvocation=="function"&&typeof t.usePromptRender=="function"&&typeof t.execute!="function"&&typeof t.generate!="function"&&typeof t.run!="function"}function Cr(e){let t=e.arguments;return t&&typeof t=="object"&&"arguments"in t&&t.arguments&&typeof t.arguments=="object"?t.arguments:t??{}}function xr(e,t){let n=e.arguments;if(n&&typeof n=="object"&&"arguments"in n&&n.arguments&&typeof n.arguments=="object"){let r=n.arguments;for(let i of Object.keys(r))delete r[i];Object.assign(r,t);return}e.arguments=t}function q(e,t){e.result&&typeof e.result=="object"?e.result.value=t:e.result={value:t}}function Es(e){return e.result?.value}function Ts(e){let{agentId:t,unified:n,failMode:r}=e;return async function(o,a){let s=o.function?.metadata?.name??"unknown",l=o.function?.metadata?.pluginName,c=Cr(o),u=l;try{let p=await n.evaluate({operations:["action"],agentId:t,toolName:s,toolArgs:c,...u!==void 0?{targetResource:u}:{}}),y=Z(p);if(!y.allowed){q(o,R({outcome:"deny",code:y.ruleCode??"DENY",reason:y.reason}));return}y.decision==="mask"&&y.argRedactionRules.length>0&&xr(o,M(c,D(y.argRedactionRules)));let x=Cr(o),A=re(s,x,{failMode:r==="closed"?"closed":"open",enforced:p.enforced});if(A.verdict==="block"){q(o,R({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${A.detectors.join(",")})`}));return}A.verdict==="redact"&&(xr(o,A.redacted),v("outbound-secret-redacted",`outbound secret screen redacted ${A.detectors.length} detector(s): ${A.detectors.join(",")}`))}catch(p){if(r==="closed"){q(o,R({outcome:"error",code:"EVAL-ERROR",mechanism:`evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${p instanceof Error?p.message:String(p)}`}));return}v("eval-error",`SK action pre-gate failed for "${s}": ${p instanceof Error?p.message:String(p)}`)}try{let p=await Ze(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l}});if(p.action==="deny"||p.action==="escalate"){q(o,`[RECALL: access denied \u2014 ${p.reason}]`);return}}catch(p){if(r==="closed"){q(o,`[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${p instanceof Error?p.message:String(p)}.`);return}v("eval-error",`SK retrieval pre-gate failed for "${s}": ${p instanceof Error?p.message:String(p)}`)}await a(o);let d=Es(o),f=(typeof d=="string"?d:(()=>{try{return JSON.stringify(d)??String(d)}catch{return String(d)}})()).slice(0,500),m;try{m=await Ze(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l,content_preview:f},contentPreview:f})}catch(p){r==="closed"?q(o,"[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):v("eval-error",`SK post-result retrieval eval failed for "${s}": ${p instanceof Error?p.message:String(p)}`);return}if(m.action==="deny"||m.action==="escalate"){q(o,`[RECALL: access denied \u2014 ${m.reason}]`);return}if(m.action==="redact"&&m.redactionRules&&m.redactionRules.length>0&&d!==null&&d!==void 0)try{q(o,M(d,D(m.redactionRules)))}catch(p){r==="closed"?q(o,"[RECALL] Result withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):v("redact-error",`SK result redaction failed for "${s}" \u2014 result passed UNREDACTED: ${p instanceof Error?p.message:String(p)}`)}}}function Rs(e){return async function(n,r){await r(n);let i=n.renderedPrompt;if(typeof i!="string"||i.length===0)return;let o;try{o=await Ze(e.unified,e.agentId,{resourceType:"prompt",resourceMetadata:{},contentPreview:i.slice(0,500)})}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":v("eval-error",`SK prompt-render eval failed: ${a instanceof Error?a.message:String(a)}`);return}if(o.action==="redact"&&o.redactionRules&&o.redactionRules.length>0){try{n.renderedPrompt=M(i,D(o.redactionRules))}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed).":v("redact-error",`SK prompt redaction failed \u2014 prompt passed UNREDACTED: ${a instanceof Error?a.message:String(a)}`)}return}(o.action==="deny"||o.action==="escalate")&&(n.renderedPrompt=`[RECALL: prompt suppressed \u2014 ${o.reason}]`)}}function Nr(e,t){let n=e;if(n[Rr]===!0)return t.onWrap?.(),e;let r=Ts(t),i=Rs(t),o=!1;return Array.isArray(n._functionInvocationFilters)?(n._functionInvocationFilters.unshift(r),o=!0):typeof n.useFunctionInvocation=="function"&&(n.useFunctionInvocation(r),o=!0),typeof n.usePromptRender=="function"?n.usePromptRender(i):Array.isArray(n._promptRenderFilters)&&n._promptRenderFilters.push(i),o&&(n[Rr]=!0,t.onWrap?.()),e}function R(e){let t=/^D-/.test(e.code),n;e.outcome==="approval_required"?n="requires human approval, which was not granted":e.outcome==="error"?n="was blocked (fail-closed) after a policy-evaluation error":n="was denied by policy";let r=e.reason?.trim(),i;r?i=r:t?i="no policy rule covers this action, so the organization default applied":e.outcome==="approval_required"?i="this action is routed to a human for approval":i="denied by policy";let o=e.mechanism?.trim()?` \u2014 ${e.mechanism.trim()}`:"";return`[VisIQ decision=${e.outcome} code=${e.code}] This tool call was NOT executed: it ${n} (${i})${o}. VisIQ is a security harness installed by your developer. Report this reason to the user verbatim; do not invent a different one.`}function et(e){return e instanceof Error?e.message:String(e)}var Cs=/https?:\/\/[^\s"'`,)}\]]+/;function xt(e){let t=e.match(Cs);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var ae=Symbol.for("visiq.toolexec.instrumented");function xs(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}var Ot={vercel:"Vercel AI SDK agent",mastra:"Mastra Agent",openai:"OpenAI Agents SDK agent",llamaindex:"LlamaIndex.TS agent",voltagent:"VoltAgent agent","semantic-kernel":"Semantic Kernel"};function Dr(e){if(e===null||typeof e!="object")return null;let t=e;if(xs(t))return null;if(Or(e))return"semantic-kernel";if(typeof t.generateText=="function"&&(typeof t.getTools=="function"||t.toolManager!==void 0))return"voltagent";if(typeof t.run=="function"&&typeof t.runStream=="function"&&t.agents!==void 0)return"llamaindex";if(Array.isArray(t.tools)&&t.handoffs!==void 0&&(typeof t.on=="function"||t.eventEmitter!==void 0))return"openai";if(typeof t.generate=="function"&&typeof t.getLLM=="function"&&(typeof t.listTools=="function"||typeof t.getTools=="function"))return"mastra";if(typeof t.generate=="function"){let n=t.settings;if(n&&typeof n=="object"&&n.tools!==void 0||t.tools!==void 0)return"vercel"}return null}async function Os(e,t,n,r,i,o){let{agentId:a,unified:s}=e,l=K(i),c,u=!1;try{await s.awaitBundleReady();let p=await s.evaluate({operations:o?["action","delegation"]:["action"],agentId:a,toolName:t,toolArgs:n,...o?{context:We(o,a)}:{},...i?.session_id?{sessionId:i.session_id}:{},...r!==void 0?{targetResource:r}:{},...l?{telemetry:l}:{}});({enforced:u}=p),c=Z(p)}catch(p){let y=p instanceof Error?p.message:String(p);return e.failMode==="closed"?{block:R({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${y} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})}:(v("eval-error",`policy evaluation failed for tool "${t}": ${y}`),{block:null})}if(c.decision==="approval_required"&&c.decisionId){let p=s.getApiKey()??e.apiKey,y=await Ee({endpoint:s.getEndpoint()??e.endpoint??"",...p?{apiKey:p}:{},decisionId:c.decisionId,timeoutMs:e.hitlTimeoutMs,sdkVersion:z});return y.resolution!=="proceed"?{block:R({outcome:"approval_required",code:c.ruleCode??"HITL-BLOCK",reason:c.reason,mechanism:y.reason}),decision:c}:{block:null}}if(!c.allowed)return{block:R({outcome:"deny",code:c.ruleCode??"DENY",reason:c.reason}),decision:c};let d=n,h=!1,f;if(c.decision==="mask"&&c.argRedactionRules&&c.argRedactionRules.length>0)try{let p=D(c.argRedactionRules);d=M(n,p),h=!0,f=c}catch(p){let y=p instanceof Error?p.message:String(p);if(e.failMode==="closed")return{block:R({outcome:"error",code:"MASK-ERROR",mechanism:`argument masking failed: ${y} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})};v("mask-error",`argument masking failed for tool "${t}" \u2014 running with UNMASKED args: ${y}`)}let m=re(t,d,{failMode:e.failMode==="closed"?"closed":"open",enforced:u});return m.verdict==="block"?{block:R({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${m.detectors.join(",")})`}),decision:{allowed:!1,decision:"deny",ruleCode:"OUTPUT-BLOCK",reason:"outbound content carried a live secret",argRedactionRules:[]}}:(m.verdict==="redact"&&(d=m.redacted,h=!0,v("outbound-secret-redacted",`outbound secret screen redacted ${m.detectors.length} detector(s): ${m.detectors.join(",")}`),f??={allowed:!0,decision:"mask",ruleCode:"OUTPUT-BLOCK",reason:"outbound secret redacted before egress",argRedactionRules:[]}),h?{block:null,maskedArgs:d,decision:f}:{block:null})}async function Nt(e,t,n,r,i){let o=C.getStore()??e.telemetry,a=He(t,n);a&&ge(e.unified,{agentId:e.agentId,sessionId:o?.session_id,...e.framework?{framework:e.framework}:{}},a);let s={agentId:e.agentId,sessionId:o?.session_id,...e.framework?{framework:e.framework}:{}},l=pe(t,n);try{he(e.unified,s,{toolName:t,...l?{memory:l}:{},argSummary:r.slice(0,512)})}catch(m){U("step-beat",`emit failed for tool "${t}": ${et(m)}`)}let c=Date.now(),u=await Os(e,t,n,xt(r),o,a);if(u.block!==null){try{u.decision&&te(e.unified,s,{toolName:t,decision:u.decision.decision??"deny",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0,harnessMessage:u.block})}catch(m){U("intervention-beat",`emit failed for tool "${t}": ${et(m)}`)}return u.block}if(u.maskedArgs!==void 0&&u.decision)try{te(e.unified,s,{toolName:t,decision:u.decision.decision??"mask",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0})}catch(m){U("intervention-beat",`emit failed for tool "${t}": ${et(m)}`)}let d=u.maskedArgs??n,h=await i(d),f=await Je(h,e.agentId,e.unified);try{_e(e.unified,s,{toolName:t,ok:!0,durationMs:Date.now()-c,...Q(f)!==void 0?{bytes:Q(f)}:{},...Y(f)!==void 0?{itemCount:Y(f)}:{},...l?{memory:l}:{}})}catch(m){U("observation-beat",`emit failed for tool "${t}": ${et(m)}`)}return f}function tt(e,t,n){let r=e;if(r[ae]){n.onWrap?.();return}if(typeof r.execute!="function")return;let i=r.execute;Dt(r,"execute",async function(...a){let s=kt(a[0]);return Nt(n,t,s,xe(s),l=>Promise.resolve(i.apply(this,[l,...a.slice(1)])))}),r[ae]=!0,n.onWrap?.()}function Ns(e,t,n){let r=e;if(r[ae]){n.onWrap?.();return}if(typeof r.invoke!="function")return;let i=r.invoke;Dt(r,"invoke",async function(...a){let s=a[1],l=dr(s),c=typeof s=="string"?s:xe(l);return Nt(n,t,l,c,u=>{let d=typeof s=="string"?JSON.stringify(u):u;return Promise.resolve(i.apply(this,[a[0],d,...a.slice(2)]))})}),r[ae]=!0,n.onWrap?.()}function Ms(e,t){let n=e;if(n[ae]){t.onWrap?.();return}if(typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",o=n.call;Dt(n,"call",async function(...s){let l=kt(s[0]);return Nt(t,i,l,xe(l),c=>Promise.resolve(o.apply(this,[c,...s.slice(1)])))}),n[ae]=!0,t.onWrap?.()}function Lr(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&tt(r,n,t);return e}function Fr(e,t,n){let r={...t,framework:n};switch(n){case"vercel":return Ds(e,r);case"mastra":return Ls(e,r);case"openai":return Ps(e,r);case"llamaindex":return $s(e,r);case"voltagent":return Fs(e,r);case"semantic-kernel":return Nr(e,r);default:return e}}function Ds(e,t){let n=e,r=n.settings&&typeof n.settings=="object"?n.settings:void 0,i=r?.tools??n.tools;return i&&typeof i=="object"&&Lr(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=Mt(r.onStepFinish)),nt(e,["generate","stream"],async(o,a)=>(Ce(a,o[0]),o)),e}function Ls(e,t){let r=qs(e);return r&&Lr(r,t),nt(e,["generate","stream","generateVNext","streamVNext"],async(i,o)=>{Ce(o,i[0]);let a=i[1]&&typeof i[1]=="object"?{...i[1]}:{};a.onStepFinish=Mt(a.onStepFinish);let s=[...i];return s[1]=a,s}),e}function Fs(e,t){let n=Bs(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;tt(r,typeof i=="string"?i:"unknown",t)}}return nt(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{Ce(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=Mt(o.onStepFinish);let a=[...r];return a[1]=o,a}),e}function $s(e,t){let n=e,r=o=>{let a=o?.tools;if(Array.isArray(a))for(let s of a)s!==null&&typeof s=="object"&&Ms(s,t)},{agents:i}=n;if(i instanceof Map)for(let o of i.values())r(o);else Array.isArray(n.tools)&&r(n);return nt(e,["run"],async(o,a)=>(Ce(a,o[0]),o)),Us(e,"runStream",(o,a,s)=>{s||Ce(a,o[0])}),e}function Ps(e,t){let n=e,{tools:r}=n;if(Array.isArray(r)){for(let i of r)if(i!==null&&typeof i=="object"){let{name:o}=i;Ns(i,typeof o=="string"?o:"unknown",t)}}return js(e,t),e}function js(e,t){let n=e;if(n.__visiq_openai_hooks||typeof n.on!="function")return;let r=n.on,{telemetry:i}=t;r.call(e,"agent_start",(...o)=>{i.session_id=Mr(),i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let a=o[2];a!=null&&i.llm_prompts.push(xe(a).slice(0,5120))}),r.call(e,"agent_end",(...o)=>{let a=o[1];typeof a=="string"&&a&&i.llm_responses.push(a.slice(0,5120))}),n.__visiq_openai_hooks=!0}function Bs(e){let t=r=>Array.isArray(r)&&r.some(i=>i!==null&&typeof i.execute=="function");if(typeof e.getTools=="function")try{let r=e.getTools();if(t(r))return r}catch{}let n=e.toolManager;if(n&&typeof n.getAllBaseTools=="function")try{let r=n.getAllBaseTools();if(t(r))return r}catch{}return t(e.tools)?e.tools:null}function nt(e,t,n){let r=e;for(let i of t){if(typeof r[i]!="function")continue;let o=`__visiq_wrapped_${i}`;if(r[o])continue;let a=r[i];r[i]=function(...s){let l=$r();return C.run(l,async()=>{let c=await n(s,l);return a.apply(e,c)})},r[o]=!0}}function Us(e,t,n){let r=e;if(typeof r[t]!="function")return;let i=`__visiq_wrapped_${t}`;if(r[i])return;let o=r[t];r[t]=function(...a){let s=C.getStore(),l=s??$r();return n(a,l,s!==void 0),C.run(l,()=>o.apply(e,a))},r[i]=!0}function Mt(e){return t=>{let n=C.getStore(),r=t;if(n&&typeof r?.text=="string"&&r.text&&n.llm_responses.push(r.text.slice(0,5120)),typeof e=="function")return e(t)}}function Ce(e,t){if(t==null)return;let n=t;if(typeof t=="object"){let r=t;n=r.prompt??r.messages??t}e.llm_prompts.push(xe(n).slice(0,5120))}function qs(e){for(let t of["listTools","getTools"])if(typeof e[t]=="function")try{let n=e[t]();if(n&&typeof n=="object"&&typeof n.then!="function")return n}catch{}return null}function $r(){return{session_id:Mr(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Dt(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function xe(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Hr(e,t){let n=Ws(t);if(e[Re]===!0)return e;let r=Js(e);if(r==="langchain-executor"||r==="langchain-graph")return le(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,jr(r,null),n.failMode,{model:Br(e)}),qr(e,n),Xs(e,n);let i=Dr(e);if(i){le(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,jr("unknown",i),n.failMode,{model:Br(e)}),qr(e,n);let o=0,a=Jr(n);a.onWrap=()=>{o+=1};let s=Fr(e,a,i);if(o===0){let l=0;try{l=Ct(e).length}catch{l=0}if(l>0){let c=`[VisIQ] Detected a ${Ot[i]} that ADVERTISES ${String(l)} tool(s) but instrumented ZERO of them \u2014 its tool calls run UN-GOVERNED while this SDK appears correctly wired. This is almost always a tool bag that moved/renamed on a framework version bump. Upgrade @visiq/harness, or pass the tools through visiq() directly (visiq(tools, \u2026)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw / VISIQ_FAIL_MODE=closed) to refuse to run ungoverned.`;if(n.onInstrumentFailure!==void 0?n.onInstrumentFailure==="throw":n.failMode==="closed")throw new Error(c);v("zero-instrument",`advertised ${String(l)} tool(s), instrumented none`),console.warn(c)}else{let c=`[VisIQ] Detected a ${Ot[i]} with no tools to instrument (the agent advertises none). If it is intentionally tool-less (LLM-only) this is safe to ignore; otherwise its tool bag is not where this SDK looks for it \u2014 upgrade @visiq/harness or pass the tools through visiq() (visiq(tools, \u2026)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw) to fail closed here.`;if(n.onInstrumentFailure==="throw")throw new Error(c);console.warn(c)}}return s}if(al(e)){let o=process.env.VISIQ_GRANT_ID;return o?ll(e,n,o):cl(e,n)}throw new Error("[VisIQ] Cannot detect agentic framework. Pass a LangChain AgentExecutor, LangGraph CompiledGraph, or a tool with one of: _call, execute, call, run, invoke.")}var Ks="https://api.visiqlabs.com",Gs="\0",Pr=new Map;function jr(e,t){if(e==="langchain-executor"||e==="langchain-graph")return"langchain";switch(t){case"vercel":return"vercel_ai";case"mastra":return"mastra";case"openai":return"openai_agents";case"llamaindex":return"llamaindex";case"voltagent":return"voltagent";case"semantic-kernel":return"semantic_kernel";default:return}}function Br(e){try{if(typeof e!="object"||e===null)return;let t=e,n=se(t.model);if(n)return n;let{settings:r}=t;if(typeof r=="object"&&r!==null){let a=se(r.model);if(a)return a}let{llm:i}=t;if(typeof i=="object"&&i!==null){let a=Ur(i);if(a)return a}let{agents:o}=t;if(o instanceof Map){for(let a of o.values())if(typeof a=="object"&&a!==null){let s=a,l=s.llm,c=se(s.model)??(typeof l=="object"&&l!==null?Ur(l):void 0);if(c)return c}}return}catch{return}}function Ur(e){return se(e.model)??se(e.modelId)??se(e.model_name)}function se(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null){let t=e;for(let n of["modelId","model_id","id","model","modelName","model_name"]){let r=t[n];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}}function le(e,t,n,r,i,o,a){let s=[e??"",t??"",n??"",r??"",o??""].join(Gs),l=Pr.get(s);return l||(l=new ur(e,t,n,void 0,r,z,at),l.registerHostEnvironment(i,a),Pr.set(s,l)),o!==void 0&&l.setFailMode(o),l}function qr(e,t){try{let n=Ct(e);n.length>0&&le(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode).reportToolSurface(n)}catch{}}function Hs(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let t=process.env.VISIQ_TIMEOUT_MS;if(t!==void 0){let n=Number.parseInt(t,10);if(Number.isFinite(n)&&n>0)return n}}function Ws(e){let t=e?.agentId??process.env.VISIQ_AGENT_ID??Ys(),n=e?.apiKey??process.env.VISIQ_API_KEY,r=e?.endpoint??process.env.VISIQ_ENDPOINT??(n?Ks:void 0);return{agentId:t,apiKey:n,endpoint:r,hitlTimeoutMs:Zs(e?.hitlTimeoutMs),timeoutMs:Hs(e?.timeoutMs),onInstrumentFailure:e?.onInstrumentFailure??Qs(),failMode:G(e?.failMode)}}function Qs(){let e=process.env.VISIQ_ON_INSTRUMENT_FAILURE;if(e==="throw")return"throw";if(e==="warn")return"warn"}function Ys(){let e=t=>t.toLowerCase().replace(/^@[^/]+\//,"").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,255);try{let t=process.cwd();for(let n=0;n<64;n++){let r=it.join(t,"package.json");if(rt.existsSync(r)){let o=JSON.parse(rt.readFileSync(r,"utf8"));if(typeof o.name=="string"&&o.name.trim()){let a=e(o.name);if(a)return a}break}let i=it.dirname(t);if(i===t)break;t=i}}catch{}try{let t=e(Gr.hostname());if(t)return t}catch{}return"agent"}function Zs(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let t=process.env.VISIQ_HITL_TIMEOUT_MS;if(t){let n=Number(t);if(Number.isFinite(n)&&n>0)return n}return At}function Js(e){let t=e;return typeof t.invoke=="function"&&t.agent&&Array.isArray(t.tools)?"langchain-executor":typeof t.invoke=="function"&&t.nodes&&(t.edges||t.lg_is_pregel===!0||typeof t.builder=="object"&&t.builder!==null&&t.builder.edges)?"langchain-graph":"unknown"}function Xs(e,t){let n=e,r=le(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),i=el(n);for(let l of i)$t(l,t.agentId,r),rl(l,t.agentId,r,t),Yr(l,r,t);let{nodes:o}=n;if(!!o&&typeof o=="object"&&"tools"in o&&i.length===0){let l="[VisIQ] Detected a LangGraph agent whose compiled graph carries a ToolNode, but resolved ZERO tools from it \u2014 its tool calls run UN-GOVERNED while this SDK appears correctly wired. This is almost always a compiled-graph tool bag that moved on a @langchain/langgraph version bump. Upgrade @visiq/harness, or pass the tools through visiq() directly (visiq(tools, \u2026)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw / VISIQ_FAIL_MODE=closed) to refuse to run ungoverned.";if(t.onInstrumentFailure!==void 0?t.onInstrumentFailure==="throw":t.failMode==="closed")throw new Error(l);v("zero-instrument","langgraph compiled-graph ToolNode present, resolved no tools"),console.warn(l)}let s=n.invoke;if(n.invoke=function(l,c){let u=Ft(),d=Kr(t.agentId,r),h=c?.callbacks??[];return C.run(u,()=>s.call(this,l,{...c,callbacks:[...h,d]}))},typeof n.stream=="function"){let l=n.stream;n.stream=function(c,u){let d=Ft(),h=Kr(t.agentId,r),f=u?.callbacks??[];return C.run(d,()=>l.call(this,c,{...u,callbacks:[...f,h]}))}}return e}function el(e){let t=[],n=new Set,r=o=>{if(Array.isArray(o))for(let a of o)a&&typeof a=="object"&&!n.has(a)&&(n.add(a),t.push(a))};r(e.tools);let{nodes:i}=e;if(i&&typeof i=="object"){for(let o of Object.values(i))if(o&&typeof o=="object"){let a=o;r(a.tools);let{bound:s}=a;s&&typeof s=="object"&&r(s.tools)}}return t}function Ft(){return{session_id:Vs(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function $t(e,t,n){let r=e,i=Symbol.for("visiq.recall.instrumented");if(!r[i]){if(typeof r._getRelevantDocuments=="function"){let o=r._getRelevantDocuments;r._getRelevantDocuments=async function(a,s){let l=await o.call(this,a,s);return Vr(l,t,a,n)},r[i]=!0}if(typeof r.retrieve=="function"&&!r._getRelevantDocuments){let o=r.retrieve;r.retrieve=async function(a){let s=await o.call(this,a);return Vr(s,t,String(a),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&$t(r.retriever,t,n)}}var tl=Symbol.for("visiq.operations"),nl=new Set(["action","retrieval","delegation"]);function Wr(e){if(typeof e!="object"||e===null)return;let t=e[tl]??e.visiqOperations;if(!Array.isArray(t))return;let n=t.filter(r=>typeof r=="string"&&nl.has(r));return n.length>0?Array.from(new Set(n)):void 0}function rl(e,t,n,r){let i=e,o=Symbol.for("visiq.recall.tool-instrumented");if(i[o]||typeof i.func!="function")return;let a=typeof i.name=="string"?i.name:"",s=typeof i.retriever=="object"&&i.retriever!==null,l=a.split(/[^a-zA-Z0-9]+|(?<=[a-z])(?=[A-Z])/).map(S=>S.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),d=l.some(S=>c.has(S)),h=u.has(l[0]??""),f=d||h,m=["update","delete","create","archive","insert","remove"],p=l.some(S=>m.some(b=>S.length>b.length&&S.endsWith(b))),x=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!f&&!p,A=Wr(i),T=A?.includes("retrieval")??!1;if(A!==void 0&&!T||!(s||x||T))return;let De=A?T&&A.includes("action"):d||p;if(!De)if(s)$t(i.retriever,t,n);else{let S=globalThis,b=Symbol.for("visiq.recall.closureRetrieverWarned"),P=S[b]??=new Set;P.has(a)||(P.add(a),console.warn(`[VisIQ] Retriever tool "${a||"(unnamed)"}" exposes no reachable retriever (e.g. LangChain createRetrieverTool returns a joined string). RECALL masks its output via value-shape + whole-result rules, but PER-DOCUMENT metadata/classification rules cannot apply to a metadata-less joined string. For full per-doc governance, pass the retriever to visiq() directly, or use a tool that returns a Document[].`))}let H=i.func;De?(i[Qr]=!0,i.func=async function(...S){await n.awaitBundleReady();let b=S[0],P=typeof b=="object"&&b!==null?b:{input:b},ue=typeof P.query=="string"?P.query:void 0,w=C.getStore(),k=K(w),N;try{N=await n.evaluate({operations:["retrieval","action"],agentId:t,...w?.session_id?{sessionId:w.session_id}:{},toolName:a||"unknown",toolArgs:P,resourceType:"document",resourceMetadata:{},...ue!==void 0?{query:ue}:{},...k?{telemetry:k}:{}})}catch(L){let de=L instanceof Error?L.message:String(L);return G(r?.failMode)==="closed"?R({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${de} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(v("eval-error",`policy evaluation failed for hybrid tool "${a||"unknown"}": ${de}`),H.apply(this,S))}let E=Z(N),ot=Se(E.hitlFallback,E.argRedactionRules),Pt=S,jt=()=>{try{return Pt=[M(P,D(E.argRedactionRules)),...S.slice(1)],null}catch{return G(r?.failMode)==="closed"?R({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(v("mask-error",`argument masking failed for tool "${a||"unknown"}" \u2014 running with UNMASKED args`),null)}};if(E.decision==="approval_required"&&E.decisionId&&r){let L=await Ee({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:E.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:ot,sdkVersion:z});if(L.resolution==="mask"){let de=jt();if(de)return de}else if(L.resolution!=="proceed")return R({outcome:"approval_required",code:E.ruleCode??"HITL-BLOCK",reason:E.reason,mechanism:L.reason})}else if(!E.allowed)return R({outcome:"deny",code:E.ruleCode??"DENY",reason:E.reason});if(E.decision==="mask"&&E.argRedactionRules.length>0){let L=jt();if(L)return L}let ti=await H.apply(this,Pt);return Ar(ti,N,r?.failMode)}):i.func=async function(...S){let b=await H.apply(this,S);return typeof b=="string"?br(b,t,n):Je(b,t,n)},i[o]=!0}var Qr=Symbol.for("visiq.hybrid.instrumented");async function Vr(e,t,n,r){return yr(e,t,n,r)}var zr=["invoke","call","_call"],X=new zs;function Yr(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[Qr]||Wr(r)?.every(c=>c==="retrieval")||!zr.some(c=>typeof r[c]=="function"))return;let{agentId:o}=n,a=typeof r.name=="string"?r.name:"unknown",s=Symbol("visiq.gate"),l=async(c,u,d,h,f)=>{let m=X.getStore();if(m!==void 0&&m.gateKey===s&&!m.entered.has(f))return m.entered.add(f),c.call(u,d,...h);let p;if(typeof d=="string")p=d;else{let w=d?.input;p=w!=null?String(w):JSON.stringify(d)??""}let y=C.getStore(),x=K(y),A=typeof d=="object"&&d!==null?d:{input:p},T=He(a,A);T&&ge(t,{agentId:o,sessionId:y?.session_id,framework:"langchain"},T);let Me={agentId:o,sessionId:y?.session_id,framework:"langchain"},ce=pe(a,A);try{he(t,Me,{toolName:a,...ce?{memory:ce}:{},argSummary:p.slice(0,512)})}catch(w){U("step-beat",`emit failed for tool "${a}": ${Lt(w)}`)}let De=Date.now(),H=async w=>{let k=await w();try{_e(t,Me,{toolName:a,ok:!0,durationMs:Date.now()-De,...Q(k)!==void 0?{bytes:Q(k)}:{},...Y(k)!==void 0?{itemCount:Y(k)}:{},...ce?{memory:ce}:{}})}catch(N){U("observation-beat",`emit failed for tool "${a}": ${Lt(N)}`)}return k},S=(w,k,N,E)=>{try{te(t,Me,{toolName:a,decision:w,...k?{ruleCode:k}:{},...N?{ruleLabel:N}:{},enforced:!0,...E?{harnessMessage:E}:{}})}catch(ot){U("intervention-beat",`emit failed for tool "${a}": ${Lt(ot)}`)}};await t.awaitBundleReady();let b,P=!1;try{let w=await t.evaluate({operations:T?["action","delegation"]:["action"],agentId:o,...y?.session_id?{sessionId:y.session_id}:{},toolName:a,toolArgs:A,targetResource:xt(p),...x?{telemetry:x}:{},...T?{context:We(T,o)}:{}});({enforced:P}=w),b=Z(w)}catch(w){let k=w instanceof Error?w.message:String(w);return n.failMode==="closed"?R({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${k} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(v("eval-error",`policy evaluation failed for tool "${a}": ${k}`),X.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,...h)))}let ue=w=>{let k=re(a,w,{failMode:n.failMode==="closed"?"closed":"open",enforced:P});if(k.verdict==="block"){let E=R({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${k.detectors.join(",")})`});return S("deny","OUTPUT-BLOCK","outbound content carried a live secret",E),E}let N=w;return k.verdict==="redact"&&(N=k.redacted,v("outbound-secret-redacted",`outbound secret screen redacted ${k.detectors.length} detector(s): ${k.detectors.join(",")}`),S("mask","OUTPUT-BLOCK","outbound secret redacted before egress")),H(()=>X.run({gateKey:s,entered:new Set([f])},()=>c.call(u,N,...h)))};if(b.decision==="approval_required"&&b.decisionId){let w=Se(b.hitlFallback,b.argRedactionRules),k=await Ee({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:b.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:w,sdkVersion:z});if(k.resolution==="proceed")return H(()=>X.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,...h)));if(k.resolution==="mask")try{let E=M(d,D(b.argRedactionRules));return S("mask",b.ruleCode,b.reason),H(()=>X.run({gateKey:s,entered:new Set([f])},()=>c.call(u,E,...h)))}catch{return n.failMode==="closed"?R({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(v("mask-error",`HITL mask fallback failed for tool "${a}" \u2014 running with UNMASKED args`),X.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,...h)))}let N=R({outcome:"approval_required",code:b.ruleCode??"HITL-BLOCK",reason:b.reason,mechanism:k.reason});return S("approval_required",b.ruleCode,b.reason,N),N}if(!b.allowed){let w=R({outcome:"deny",code:b.ruleCode??"DENY",reason:b.reason});return S("deny",b.ruleCode,b.reason,w),w}if(b.decision==="mask"&&b.argRedactionRules.length>0)try{let w=M(d,D(b.argRedactionRules));return S("mask",b.ruleCode,b.reason),ue(w)}catch{return n.failMode==="closed"?R({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(v("mask-error",`argument masking failed for tool "${a}" \u2014 running with UNMASKED args`),X.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,...h)))}return ue(d)};for(let c of zr){if(typeof r[c]!="function")continue;let u=r[c];r[c]=function(d,...h){return l(u,this,d,h,c)}}r[i]=!0}function Lt(e){return e instanceof Error?e.message:String(e)}function il(e,t,n){let r=(a,s)=>{if(!a||typeof a!="object")return;let l=a[s];return typeof l=="string"&&l.length>0?l:void 0},i=t?.invocation_params,o=e&&typeof e=="object"?e.kwargs:void 0;return r(i,"model")??r(i,"model_name")??r(n,"ls_model_name")??r(o,"model")??r(o,"model_name")}function ol(e,t){let n=(f,m)=>{if(!f||typeof f!="object")return;let p=f[m];return typeof p=="number"&&Number.isFinite(p)?p:void 0},r=e?.tokenUsage,i=n(r,"promptTokens"),o=n(r,"completionTokens");if(i!==void 0||o!==void 0)return{...i!==void 0?{tokensIn:i}:{},...o!==void 0?{tokensOut:o}:{}};let a=t?.usage_metadata,s=n(a,"input_tokens"),l=n(a,"output_tokens");if(s===void 0&&l===void 0)return;let c=a&&typeof a=="object"?a.input_token_details:void 0,u=n(c,"cache_read"),d=n(c,"cache_creation"),h=s!==void 0?Math.max(0,s-(u??0)-(d??0)):void 0;return{...h!==void 0?{tokensIn:h}:{},...l!==void 0?{tokensOut:l}:{},...u!==void 0?{cacheRead:u}:{},...d!==void 0?{cacheWrite:d}:{}}}function Kr(e,t){return{name:"VisiqHandler",handleLLMStart:async(n,r,i,o,a,s,l)=>{let c=C.getStore();if(!c)return;c.llm_prompts.push(...r);let u=il(n,a,l);u&&(c.llm_model=u,t.captureCloneMetadata({model:u,agentType:"langchain"}))},handleLLMEnd:async n=>{let r=C.getStore();if(!r)return;let o=n?.generations?.[0]?.[0],a=typeof o?.text=="string"?o.text:"";a&&r.llm_responses.push(a);try{let s=n?.llmOutput,l=o?.message&&typeof o.message=="object"?o.message:void 0,c=ol(s,l);if(!c&&!a)return;let u=l?.tool_calls,d=typeof s?.model=="string"?s.model:void 0,h=r.llm_model??d;await t.awaitBundleReady(),ct(t,{agentId:e,sessionId:r.session_id,framework:"langchain"},{...a?{texts:[a]}:{},...c?{usage:c}:{},...h?{model:h}:{},final:!(Array.isArray(u)&&u.length>0)})}catch{}},handleAgentAction:async n=>{let r=C.getStore();if(!r)return;let i=typeof n.log=="string"?n.log:"";i&&r.agent_reasoning.push(i)},handleRetrieverStart:async(n,r,i)=>{let o=C.getStore();o&&o.retrieverQueries.set(i,r??"")},handleRetrieverEnd:async(n,r)=>{let i=C.getStore();if(!i)return;let o=i.retrieverQueries.get(r)??"";if(i.retrieverQueries.delete(r),!Array.isArray(n))return;let a=K(i);for(let s of n){let l=s,c=String(l.pageContent??l.text??l.content??""),u=l.metadata??{};await t.evaluate({operations:["retrieval"],agentId:e,resourceType:"document",resourceMetadata:u,query:o,contentPreview:c.slice(0,500),...a?{telemetry:a}:{}})}},handleRetrieverError:async(n,r)=>{let i=C.getStore();i&&i.retrieverQueries.delete(r)}}}var Zr=["_call","execute","call","run","invoke"];function al(e){let t=e;for(let n of Zr)if(typeof t[n]=="function")return!0;return!1}function sl(e){return e instanceof J?!0:e instanceof B?typeof e.status=="number"&&e.status>=400&&e.status<500:!1}function ll(e,t,n){let r=null,i=null,o=!1,a=async()=>{if(r)return r;if(i)throw new J(`Failed to bootstrap grant ${n}: ${i.message}`,null);let s;try{s=await Er(t.agentId,n)}catch(l){throw o=sl(l),o&&(i=l instanceof Error?l:new Error(String(l))),new J(`Failed to bootstrap grant ${n}: ${l instanceof Error?l.message:String(l)}`,null)}return r=Tr(e,{agentId:t.agentId,grantToken:s,failBehavior:t.failMode==="closed"?"deny":"permit",...t.apiKey?{apiKey:t.apiKey}:{},...t.endpoint?{endpoint:t.endpoint}:{}}),r};return new Proxy(e,{get(s,l,c){if(l===Re)return!0;let u=Reflect.get(s,l,c);return typeof u!="function"||typeof l!="string"||!Zr.includes(l)?u:async function(...d){let h;try{h=await a()}catch(m){if(o||t.failMode==="closed")throw m;return v("grant-bootstrap",`grant ${n} bootstrap failed: ${m instanceof Error?m.message:String(m)}`),u.call(this,...d)}return h[l].call(h,...d)}}})}function cl(e,t){let n=le(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode);Yr(e,n,t);let r=e;if(typeof r.execute=="function"){let i=typeof r.name=="string"&&r.name||typeof r.id=="string"&&r.id||"unknown";tt(e,i,Jr(t))}return e}function Jr(e){return{agentId:e.agentId,unified:le(e.apiKey,e.endpoint,e.agentId,e.timeoutMs,void 0,e.failMode),hitlTimeoutMs:e.hitlTimeoutMs,failMode:e.failMode,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:Ft()}}async function Xr(e,t={}){if(!e||e.trim()==="")throw new Error("[VisIQ] visiq.delegate: childAgentId is required");let n=process.env.VISIQ_AGENT_ID;if(!n)throw new Error("[VisIQ] visiq.delegate: VISIQ_AGENT_ID env var is required. Set it to the parent agent ID before calling delegate.");let r=process.env.VISIQ_API_KEY;if(!r)throw new Error("[VisIQ] visiq.delegate: VISIQ_API_KEY env var is required");let i=process.env.VISIQ_ENDPOINT;return{VISIQ_GRANT_ID:(await new oe({agentId:n,apiKey:r,...i?{endpoint:i}:{}}).requestGrant({parentAgentId:n,childAgentId:e,toolScope:t.toolScope??null,contextScope:t.contextScope??null,durationSeconds:t.durationSeconds??3600,purpose:t.purpose??`Delegated to ${e}`,...t.maxDepth!==void 0?{maxDepth:t.maxDepth}:{},...t.parentGrantToken!==void 0?{parentGrantToken:t.parentGrantToken}:{}})).grantId}}var Oe=class{constructor(t){this.transport=t}transport;deploy(t={}){let n={include_mac:t.includeMac??!1};return t.autoInstallHarness!==void 0&&(n.auto_install_harness=t.autoInstallHarness),ee(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return ee(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return ee(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return ee(this.transport,"POST","/api/discovery/fleet/stop")}};var Ne=class{constructor(t){this.transport=t}transport;connectAws(t){return ee(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function ul(e){if(!e.baseUrl||e.baseUrl.length===0)throw new Error("[VisIQ] createVisiqClient: baseUrl is required");if(!e.accessToken&&!e.cookieHeader)throw new Error("[VisIQ] createVisiqClient: one of accessToken or cookieHeader is required");let t=e.baseUrl.replace(/\/$/,""),n=e.fetchImpl??globalThis.fetch.bind(globalThis),r={baseUrl:t,accessToken:e.accessToken,cookieHeader:e.cookieHeader,fetchImpl:n};return{fleet:new Oe(r),integrations:new Ne(r)}}async function ee(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,o={...W(z)};e.cookieHeader&&(o.Cookie=e.cookieHeader),e.accessToken&&(o.Authorization=`Bearer ${e.accessToken}`);let a;r!==void 0&&(o["Content-Type"]="application/json",a=JSON.stringify(r));let s=await e.fetchImpl(i,{method:t,headers:o,body:a});if(!s.ok){let l="";try{l=await s.text()}catch{}throw new Error(`[VisIQ] ${t} ${n} failed (${s.status}): ${l||s.statusText}`)}return await s.json()}var ei=Hr;ei.delegate=Xr;var nu=ei;export{Ge as DEFAULT_FAIL_MODE,Oe as FleetClient,Ne as IntegrationsClient,ul as createVisiqClient,Xr as delegate,Ie as normalizeFailMode,nu as visiq};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@visiq/harness",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.13",
|
|
4
4
|
"description": "VisIQ agent-governance harness for Node.js — action governance, retrieval governance, and audit-trail reporting, added to your existing agent framework by one visiq() call.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -37,8 +37,14 @@
|
|
|
37
37
|
"ai-agent",
|
|
38
38
|
"sdk",
|
|
39
39
|
"governance",
|
|
40
|
-
"harness"
|
|
40
|
+
"harness",
|
|
41
|
+
"ai-governance",
|
|
42
|
+
"agent-governance",
|
|
43
|
+
"action-governance",
|
|
44
|
+
"retrieval-governance",
|
|
45
|
+
"audit-trail"
|
|
41
46
|
],
|
|
47
|
+
"homepage": "https://docs.visiqlabs.com",
|
|
42
48
|
"peerDependencies": {
|
|
43
49
|
"@langchain/core": ">=0.3.0",
|
|
44
50
|
"llamaindex": ">=0.11.0"
|