@visiq/harness 0.2.22 → 0.2.25

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.
Files changed (2) hide show
  1. package/dist/index.js +8 -4
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,10 @@
1
- import{randomUUID as Mi}from"node:crypto";import*as dt from"node:fs";import*as pt from"node:path";import*as Di from"node:os";import{AsyncLocalStorage as vc}from"node:async_hooks";import{z as y}from"zod";import*as q from"node:os";import{randomUUID as be}from"node:crypto";var mt=1,rn="X-VisIQ-SDK",on="X-VisIQ-Dialect",an="unknown";function ee(e,t=1){return{[rn]:e&&e.length>0?e:an,[on]:String(t)}}var sn="interceptor_source",Ki=y.enum(["enforce","audit","off"]),Gi=y.enum(["closed","open"]),ln=y.enum(["enforce","monitor","off"]),Hi=y.object({apiKey:y.string().min(1,"apiKey is required"),agentId:y.string().min(1,"agentId is required"),endpoint:y.string().url().optional(),mode:Ki.optional(),timeoutMs:y.number().int().positive().optional(),hitlTimeoutMs:y.number().int().positive().optional(),failBehavior:Gi.optional()}),Hc=y.object({agent_id:y.string().min(1),target_app:y.string().min(1),action:y.string().min(1),context:y.record(y.unknown()).optional(),session_id:y.string().min(1).max(255).optional(),action_schema_id:y.string().min(1).max(128).optional(),telemetry:y.record(y.unknown()).optional()}),Wi=y.object({field:y.string().optional(),pattern:y.string().optional(),replacement:y.string().optional(),mode:y.enum(["full","partial","email"]).optional(),keepFirst:y.number().optional(),keepLast:y.number().optional(),maskChar:y.string().optional()}),Qi=y.object({decision_id:y.string().min(1),decision:y.enum(["permit","deny","approval_required","mask"]),reason:y.string().optional(),rule_code:y.string().nullable().optional(),enforced:y.boolean().optional(),agent_mode:ln.optional(),arg_redaction_rules:y.array(Wi).optional(),plane:y.string().nullable().optional(),operation:y.string().nullable().optional(),is_retrieval:y.boolean().optional(),metadata:y.record(y.unknown()).optional()}),Yi=y.object({field:y.string().min(1),operator:y.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:y.union([y.string(),y.number(),y.array(y.string())])}),Zi=y.object({id:y.string().min(1),rule_code:y.string().default(""),name:y.string().min(1),description:y.string().nullable().default(null),effect:y.enum(["allow","deny","hitl","mask"]),resource_type:y.string().min(1),rego_source:y.string().default(""),target_app:y.string().nullable().default(null),action_pattern:y.string().nullable().default(null),conditions:y.array(Yi).default([]),priority:y.number().int().default(0)}),Ji=y.object({version:y.string().min(1),agent_mode:ln.optional(),rules:y.array(Zi),no_coverage:y.object({no_coverage_defaults:y.record(y.string()),autopilot_enabled:y.boolean(),enduser_hitl_enabled:y.boolean(),hitl_timeout_seconds:y.number()}).optional()}),Xi=2e3,eo=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function to(e){let t=e.rules.filter(n=>eo(n.rego_source)).map(n=>n.id);return t.length>0&&console.warn(`[VISIQ] ${t.length} bundle rule(s) carry an EMPTY rego body and will be evaluated as an UNCONDITIONAL PERMIT credited to their own rule id: ${t.join(", ")}. If any of these is meant to deny, it is not denying. Fix the rule body at the control plane; the SDK cannot tell an intentional stub from a dropped column.`),t}var gt=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return ee(this.config.sdkVersion,this.config.sdkDialect)}async boundedFetch(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs);try{return await this.originalFetch(e,{...t,signal:n.signal})}finally{clearTimeout(r)}}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return Qi.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(),a=Ji.parse(o);return to(a),a}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.boundedFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.boundedFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.boundedFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.boundedFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.boundedFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async reportSkillInventory(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/skills`;try{let n=await this.boundedFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,skills:e})});n.ok||console.warn(`[ALLOW] Skill-inventory report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Skill-inventory report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let 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 no(Xi)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function no(e){return new Promise(t=>setTimeout(t,e))}function ze(){let e={};try{let t=`${q.platform()} ${q.release()}`.trim();t&&(e.os=t)}catch{}try{let t=q.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=q.userInfo();t&&(e.username=t)}catch{}try{let t=ro();t&&(e.ip=t)}catch{}return e}function ro(){let e=q.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 io(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Ue(e,...t){for(let n of t){let r=io(e[n]);if(r)return r}}function qe(e){if(Ue(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(Ue(e,"user_id","userId"))return"user";if(Ue(e,"agent_id","agentId"))return"agent";if(Ue(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 i=qe(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=qe(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=qe(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=qe(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function _e(e,t){if(!e)return null;let n=t??{};for(let r of oo)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function ht(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 nn=new Map;function ve(e){let t=(nn.get(e)??0)+1;return nn.set(e,t),t}function cn(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 yt(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(`
1
+ import{randomUUID as Qi}from"node:crypto";import*as _t from"node:fs";import*as bt from"node:path";import*as Zi from"node:os";import{AsyncLocalStorage as lu}from"node:async_hooks";import{z as y}from"zod";import*as z from"node:os";import{randomUUID as ve}from"node:crypto";var wt=1,gn="X-VisIQ-SDK",hn="X-VisIQ-Dialect",yn="unknown";function ne(e,t=1){return{[gn]:e&&e.length>0?e:yn,[hn]:String(t)}}var _n="interceptor_source",lo=y.enum(["enforce","audit","off"]),co=y.enum(["closed","open"]),bn=y.enum(["enforce","monitor","off"]),uo=y.object({apiKey:y.string().min(1,"apiKey is required"),agentId:y.string().min(1,"agentId is required"),endpoint:y.string().url().optional(),mode:lo.optional(),timeoutMs:y.number().int().positive().optional(),hitlTimeoutMs:y.number().int().positive().optional(),failBehavior:co.optional()}),Lu=y.object({agent_id:y.string().min(1),target_app:y.string().min(1),action:y.string().min(1),context:y.record(y.unknown()).optional(),session_id:y.string().min(1).max(255).optional(),action_schema_id:y.string().min(1).max(128).optional(),telemetry:y.record(y.unknown()).optional()}),fo=y.object({field:y.string().optional(),pattern:y.string().optional(),replacement:y.string().optional(),mode:y.enum(["full","partial","email"]).optional(),keepFirst:y.number().optional(),keepLast:y.number().optional(),maskChar:y.string().optional()}),po=y.object({decision_id:y.string().min(1),decision:y.enum(["permit","deny","approval_required","mask"]),reason:y.string().optional(),rule_code:y.string().nullable().optional(),enforced:y.boolean().optional(),agent_mode:bn.optional(),arg_redaction_rules:y.array(fo).optional(),plane:y.string().nullable().optional(),operation:y.string().nullable().optional(),is_retrieval:y.boolean().optional(),metadata:y.record(y.unknown()).optional()}),mo=y.object({field:y.string().min(1),operator:y.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:y.union([y.string(),y.number(),y.array(y.string())])}),go=y.object({id:y.string().min(1),rule_code:y.string().default(""),name:y.string().min(1),description:y.string().nullable().default(null),effect:y.enum(["allow","deny","hitl","mask"]),resource_type:y.string().min(1),rego_source:y.string().default(""),target_app:y.string().nullable().default(null),action_pattern:y.string().nullable().default(null),conditions:y.array(mo).default([]),priority:y.number().int().default(0)}),ho=y.object({version:y.string().min(1),agent_mode:bn.optional(),rules:y.array(go),no_coverage:y.object({no_coverage_defaults:y.record(y.string()),autopilot_enabled:y.boolean(),enduser_hitl_enabled:y.boolean(),hitl_timeout_seconds:y.number()}).optional()}),yo=2e3,_o=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function bo(e){let t=e.rules.filter(n=>_o(n.rego_source)).map(n=>n.id);return t.length>0&&console.warn(`[VISIQ] ${t.length} bundle rule(s) carry an EMPTY rego body and will be evaluated as an UNCONDITIONAL PERMIT credited to their own rule id: ${t.join(", ")}. If any of these is meant to deny, it is not denying. Fix the rule body at the control plane; the SDK cannot tell an intentional stub from a dropped column.`),t}var kt=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return ne(this.config.sdkVersion,this.config.sdkDialect)}async boundedFetch(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs);try{return await this.originalFetch(e,{...t,signal:n.signal})}finally{clearTimeout(r)}}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return po.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(),a=ho.parse(o);return bo(a),a}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.boundedFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.boundedFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.boundedFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.boundedFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.boundedFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async reportSkillInventory(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/skills`;try{let n=await this.boundedFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,skills:e})});n.ok||console.warn(`[ALLOW] Skill-inventory report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Skill-inventory report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let 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 vo(yo)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function vo(e){return new Promise(t=>setTimeout(t,e))}function Ye(){let e={};try{let t=`${z.platform()} ${z.release()}`.trim();t&&(e.os=t)}catch{}try{let t=z.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=z.userInfo();t&&(e.username=t)}catch{}try{let t=wo();t&&(e.ip=t)}catch{}return e}function wo(){let e=z.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 ko(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function He(e,...t){for(let n of t){let r=ko(e[n]);if(r)return r}}function We(e){if(He(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(He(e,"user_id","userId"))return"user";if(He(e,"agent_id","agentId"))return"agent";if(He(e,"org_id","orgId","namespace"))return"org"}var Ao=[{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=We(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=We(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=We(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=We(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function be(e,t){if(!e)return null;let n=t??{};for(let r of Ao)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}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,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 mn=new Map;function we(e){let t=(mn.get(e)??0)+1;return mn.set(e,t),t}function vn(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 It(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=Array.isArray(n.texts)?n.texts.filter(a=>typeof a=="string"&&a.length>0).join(`
2
2
 
3
- `):"",o=cn(n.usage);e.emitCognition({clientEventId:be(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:ve(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 we(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:be(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:ve(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 ke(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?ht(n.memory):void 0;e.emitCognition({clientEventId:be(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:ve(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 Ae(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=ht(n.memory,{itemCount:a,bytes:o})),e.emitCognition({clientEventId:be(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:ve(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 ue(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:be(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:ve(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 te(e){try{let t=JSON.stringify(e);return typeof t=="string"?t.length:void 0}catch{return}}function ne(e){try{return Array.isArray(e)?e.length:void 0}catch{return}}import{z as h}from"zod";import{createHash as ao}from"crypto";import{createHash as Ho}from"crypto";var un=new Map;function dn(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function _t(e){let t=ao("sha256").update(e).digest("hex"),n=un.get(t);if(n)return n;let r=new Map,i=[],o=e.split(`
4
- `).map(l=>so(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 f=c[1],m=c[2].trim();r.set(f,Se(m)),a++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let f=u[1],m=u[2].trim(),g=u[3].trim(),p=[];if(g&&g!=="}"){let I=g.endsWith("}")?g.slice(0,-1).trim():g;I&&p.push(I),g.endsWith("}")||(a++,a=Ve(o,a,p))}else g==="}"||(a++,a=Ve(o,a,p));let _=pn(p);i.push({variable:f,value:Se(m),conditions:_,rawConditions:dn(p)}),a++;continue}let d=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(d){let f=d[1],m=d[2].trim(),g=[];if(m&&m!=="}"){let _=m.endsWith("}")?m.slice(0,-1).trim():m;_&&g.push(_),m.endsWith("}")||(a++,a=Ve(o,a,g))}else m==="}"||(a++,a=Ve(o,a,g));let p=pn(g);i.push({variable:f,value:"true",conditions:p,rawConditions:dn(g)}),a++;continue}a++}let s={defaults:r,rules:i};return un.set(t,s),s}function so(e){let t=!1,n="";for(let r=0;r<e.length;r++){let i=e[r];if(t)i===n&&e[r-1]!=="\\"&&(t=!1);else if(i==='"'||i==="'")t=!0,n=i;else if(i==="#")return e.slice(0,r)}return e}function Ve(e,t,n){let r=1,i=t;for(;i<e.length&&r>0;){let 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 Se(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function lo(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function pn(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=yo(i);o&&t.push(o)}}return t}var bt=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,co=new RegExp(`^(${bt.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),uo=new RegExp(`^(${bt.source})\\s*==\\s*((?:input|data)\\S*)$`),Ke=/(?:input|data)(?:\.[A-Za-z0-9_]+|\["[^"]+"\]|\['[^']+'\])+/,po=new RegExp(`^(${Ke.source})\\s*(==|!=)\\s*(${Ke.source})$`),fo=new RegExp(`^(${Ke.source})\\s+in\\s+(${Ke.source})$`),mo=/^([^\s=!]+)\s*==\s*(.+)$/,go=/^([^\s=!]+)\s*!=\s*(.+)$/,Jc=new RegExp(`^(?:${bt.source})$`);var ho=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function yo(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:Te,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(ho);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:lo(s[1])};let l=n.match(fo);if(l)return{type:"field_in_set",negated:t,field:l[1].trim(),rightField:l[2].trim()};let c=n.match(po);if(c)return{type:"field_equality",negated:c[2]==="!="?!t:t,field:c[1].trim(),rightField:c[3].trim()};let u=n.match(co);if(u)return{type:"array_includes",negated:t,field:u[2].trim(),value:bn(u[1])};let d=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(d){let I=ko(d[2]);if(I!==null)return{type:"in_set",negated:t,field:d[1].trim(),values:I}}let f=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(f)return{type:"comparison",negated:t,field:f[1].trim(),operator:f[2],value:parseFloat(f[3])};let m=n.match(uo);if(m)return{type:"equality",negated:t,field:m[2].trim(),value:Se(m[1].trim())};let g=n.match(mo);if(g)return{type:"equality",negated:t,field:g[1].trim(),value:Se(g[2].trim())};let p=n.match(go);if(p)return{type:"inequality",negated:t,field:p[1].trim(),value:Se(p[2].trim())};let _=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return _?{type:"truthy",negated:t,field:_[1].trim()}:{type:"truthy",negated:!1,field:Te,value:e.trim()}}var Te="__unrecognized_condition_forces_deny__";var _o=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function _n(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==Te&&_o.test(r.field)&&t.push(r.field);return t}var bo=["input.normalized.","input.normalized["];function vo(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions)for(let i of wo(r))typeof i!="string"||i===Te||bo.some(o=>i.startsWith(o))&&t.add(i);return[...t].sort()}var fn=/\binput\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/g;function wo(e){let{field:t,rightField:n}=e;if(t!==Te){let i=typeof t=="string"?[t]:[];return typeof n=="string"&&n.length>0&&i.push(n),i}let r=typeof e.value=="string"?e.value:"";return fn.lastIndex=0,[...r.matchAll(fn)].map(i=>i[0])}function bn(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 ko(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(bn(s))}return a}var vn=["read_only","record_create","record_update","record_delete","data_export","data_share","data_subject_request","consent_change","funds_transfer","funds_disbursement","payroll_run","trade_execution","ledger_mutation","credit_decision","decision_adverse","account_restriction","account_closure","card_management","purchase_commitment","vendor_management","deal_management","pricing_change","contract_execution","legal_hold","regulatory_filing","personnel_action","employment_termination","compensation_change","campaign_send","content_publish","inventory_adjustment","order_fulfillment","account_servicing","credential_reset","access_grant","permission_change","credential_management","auth_policy_change","security_config_change","logging_change","alert_management","code_change","infrastructure_provision","deployment_change","communication_send","other"],Ao=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],Io=["production","staging","development","test"],So=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function To(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 mn={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 Eo(e){let t=To(e);return t===null?"other":mn[t]??mn[t.replace(/_/g,"")]??"other"}function wn(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=Eo(t.targetApp)),n.context=r}return n}var gn=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],Ro=["read","write","delete","share","export","decide","execute"],hn=["none","low","medium","high","critical"],Co=["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"],xo={action_class:vn,operation:Ro,"context/app_category":Ao,"context/environment":Io,"context/actor_function":So,"read/classification":Co,"read/data_categories":gn,"read/data_sensitivity":hn,"write/data_categories":gn,"write/data_sensitivity":hn};function kn(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(xo)){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 yn=64,Oo=64,Ee={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}};function We(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:In()}}var No=new Set(["deny","approval_required","escalate"]);function H(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>yn?r.slice(0,yn):r}function Ge(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Ie(e){return typeof e=="string"&&e.length>0?e:null}function An(e,t){let n=Ge(t.data_categories),r=Ie(t.classification),i=Ge(t.taint),o=Ie(t.action_class),a=o&&vn.includes(o)?o:null,s=Ie(t.target_app),l=Ie(t.decision),c={...e.action_counts};if(a)if(a in c)c[a]=(c[a]??0)+1;else if(Object.keys(c).length<Oo)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:H(e.retrieved_data_categories,n),retrieved_classifications:H(e.retrieved_classifications,r?[r]:[]),taint:H(e.taint,i),action_classes:H(e.action_classes,a?[a]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&No.has(l)?1:0),event_count:e.event_count+1,target_apps:H(e.target_apps,s?[s]:[]),identity:Mo(e.identity,t)}}function Mo(e,t){let n=e??In(),r=Ge(t.attested_subjects),i=H(n.attested_subjects,r),o=Ie(t.subject_id);return{attested_subjects:i,claimed_subjects:H(n.claimed_subjects,Ge(t.claimed_subjects)),acted_subjects:H(n.acted_subjects,o?[o]:[])}}function In(){return{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}}var Do=["tier1","tier2","tier3"];function Sn(e){return typeof e=="string"&&Do.includes(e)}var Fo=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Lo=["internal","customer_facing","experimental","third_party"],Tn=[...Fo,...Lo];function $o(e){return typeof e=="string"&&Tn.includes(e)}function En(e){let t=new Set;for(let n of e)$o(n)&&t.add(n);return Tn.filter(n=>t.has(n))}var Po={trust_tier:null,categories:[],business_functions:[],business_function:null,blast_radius_tier:null};function Rn(e,t,n){if(t.length>0&&n.add(t),!(e===null||typeof e!="object"||Array.isArray(e)))for(let[r,i]of Object.entries(e))Rn(i,t.length>0?`${t}.${r}`:r,n)}function Cn(e){let t=new Set;return Rn(e,"",t),t}var Xc=Cn(We()),eu=Cn(Po),jo=["action_counts"];for(let e of jo){let t=We()[e];if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`closed-input-paths: session.${e} is no longer a dynamic map \u2014 remove it from DYNAMIC_SESSION_MAPS or the carve-out admits every spelling under it.`)}var tu=new RegExp("^\\p{White_Space}*$","u");var xn="generic",On=[{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:xn,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."}],Bo=On.map(e=>e.id),nu=new Map(On.map(e=>[e.id,e])),ru=new Set(Bo);function Nn(e){return Array.isArray(e)&&e.length>0?[...e]:[xn]}var Uo=/^[a-z][a-z0-9_]*$/;function Mn(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Uo.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var qo=["narrow","moderate","broad","unbounded","unknown"];function Dn(e){return typeof e=="string"&&qo.includes(e)}function zo(e){let t=e-(e>>>1&1431655765);return t=(t&858993459)+(t>>>2&858993459),t=t+(t>>>4)&252645135,Math.imul(t,16843009)>>>24&255}function Vo(e,t){if(typeof e!="string"||typeof t!="string"||e.length!==16||t.length!==16)return 64;let n=0;for(let r=0;r<16;r+=8){let i=parseInt(e.slice(r,r+8),16),o=parseInt(t.slice(r,r+8),16);if(!Number.isFinite(i)||!Number.isFinite(o))return 64;n+=zo((i^o)>>>0)}return n}var Ko=["proposed","approved","revoked"];function Go(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.skill_id=="string"&&t.skill_id.length>0&&typeof t.skill_schema_hash=="string"&&t.skill_schema_hash.length>0&&typeof t.status=="string"&&Ko.includes(t.status)}function Fn(e,t){let n=typeof e.action=="string"?e.action:"",r=typeof e.actionSchemaId=="string"&&e.actionSchemaId.length>0?e.actionSchemaId:null,i=typeof e.fingerprint=="string"&&e.fingerprint.length>0?e.fingerprint:null,o=typeof e.fingerprintRadius=="number"&&Number.isFinite(e.fingerprintRadius)?e.fingerprintRadius:15;if(n.length===0&&r===null&&i===null)return{blocked:!1,skillId:null};for(let a of t)if(Go(a)&&a.status==="approved"){if(n.length>0&&a.skill_id===n)return{blocked:!0,skillId:a.skill_id,matchedBy:"action"};if(r!==null&&a.skill_schema_hash===r)return{blocked:!0,skillId:a.skill_id,matchedBy:"schema"};if(i!==null&&typeof a.skill_fingerprint=="string"){let s=Vo(i,a.skill_fingerprint);if(s<=o&&s<64)return{blocked:!0,skillId:a.skill_id,matchedBy:"fingerprint",fingerprintDistance:s}}}return{blocked:!1,skillId:null}}function Ln(e){return e==="open"||e==="closed"?e:null}var Wo=["tool_name","function","name","action"];function He(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)He(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)He(o,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Qo(e){let t=[];return He(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function Yo(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function Zo(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function Jo(e,t={}){if(t.discriminatorField===null)return null;let n=[];He(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??Wo;for(let i of r){let o=null;for(let[a,s]of n){if(Yo(a)!==i)continue;let l=Zo(s);l!==null&&(o===null||a<o.path)&&(o={path:a,value:l})}if(o)return o.value}return null}function $n(e,t={}){let n=Ho("sha256").update(Qo(e).join(",")).digest("hex").slice(0,16),r=Jo(e,t);return r!==null?`${n}:${r}`:n}var Xo=["action","retrieval","delegation"];function ea(e){return typeof e=="string"&&Xo.includes(e)}var ta=new Set(["rules"]);function Pn(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!ta.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(ea):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}function jn(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=_t(r)}catch{continue}let o=vo(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()}}import{z as Xe}from"zod";var na=/[^\u0000-\u007F]/,rr=new RegExp("^\\p{Nd}$","u"),ra=new RegExp("^\\p{Pd}$","u"),ia=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,oa=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,aa=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),ir="<invisible>",Bn=new Map;function sa(e){let t=String.fromCodePoint(e).normalize("NFKC");if(t.length===1&&t>="0"&&t<="9")return t;let n=e;for(let i=0;i<256&&n>0&&rr.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function la(e){if(e<128)return null;let t=Bn.get(e);if(t!==void 0)return t;let n=(()=>{if(e>=65281&&e<=65374)return String.fromCharCode(e-65248);let r=String.fromCodePoint(e);return rr.test(r)?sa(e):ra.test(r)||aa.has(e)?"-":ia.test(r)?" ":oa.test(r)?ir:null})();return Bn.set(e,n),n}function It(e){if(typeof e!="string"||e.length===0||!na.test(e))return[];let t=Un(e,"as-separator");if(t===null)return[];let n=Un(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function Un(e,t){let n=[],r=[],i=!1;for(let o=0;o<e.length;){let a=e.codePointAt(o),s=a>65535?2:1,l=la(a);if(l===null){for(let c=0;c<s;c++)n.push(e[o+c]),r.push(o+c);o+=s;continue}if(i=!0,l===ir){t==="as-separator"&&(n.push(" "),r.push(o)),o+=s;continue}n.push(l),r.push(o),o+=s}return i?(r.push(e.length),{label:t,text:n.join(""),offsets:Int32Array.from(r)}):null}function ca(e,t){return{start:e.offsets[t.start],end:e.offsets[t.end]}}function ua(e){if(e.length<=1)return[...e];let t=[...e].sort((i,o)=>i.start-o.start||i.end-o.end),n=[],r={start:t[0].start,end:t[0].end};for(let i=1;i<t.length;i++){let o=t[i];o.start<=r.end?o.end>r.end&&(r={start:r.start,end:o.end}):(n.push(r),r={start:o.start,end:o.end})}return n.push(r),n}function qn(e,t){let n=[];e.lastIndex=0;let r;for(;(r=e.exec(t))!==null;){if(r[0].length===0){e.lastIndex++;continue}n.push({start:r.index,end:r.index+r[0].length})}return n}var or="[REDACTED]",St=[{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}],au=St.map(({name:e,re:t})=>({name:e,source:t.source})),da="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function pa(e){return ar(e,da)}function ar(e,t){let n="",r=!1;for(let i=0;i<e.length;i++){let o=e[i];if(o==="\\"){if(!r&&e[i+1]==="b"){n+=t,i++;continue}n+=o+(e[i+1]??""),i++;continue}o==="["?r=!0:o==="]"&&(r=!1),n+=o}return n}function sr(e){return new RegExp(pa(e.source),e.flags)}var fa="(?:\\b|_)";function wt(e){return ar(e,fa)}var ma=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function ga(e){let t=ma.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function kt(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 ha(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 ya(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 _a=[[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]],ba=[[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 va(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=_a[t][ba[r%8][n[r].charCodeAt(0)-48]];return t===0}function wa(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 ka(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 Aa=[1,4,3,7,5,8,6,9,10];function Ia(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)*Aa[n];return t%11===0}var Sa="TRWAGMYFPDXBNJZSQVHLCKE";function Ta(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 Sa[Number(a)%23]===o}var Ea=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Ra(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Ea.has(t.slice(0,2)):!1}var Tt=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&kt(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:ha},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:ya},{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:Ra(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&&va(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:wa},{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:Ta},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&kt(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:ka},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Ia}],Ca=Object.fromEntries([...St,...Tt].map(e=>[e.name,e.re.source])),E=Ca,su=Tt.map(e=>e.name),lr=St.map(({name:e,re:t})=>({name:e,re:sr(t)})),cr=Tt.map(e=>({...e,re:sr(e.re)})),lu=[...lr,...cr].map(({name:e,re:t})=>({name:String(e),source:t.source})),Et=["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"],xa={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=vn(n.usage);e.emitCognition({clientEventId:ve(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:we(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 ke(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:ve(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:we(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 Ae(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?At(n.memory):void 0;e.emitCognition({clientEventId:ve(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:we(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 Ie(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=At(n.memory,{itemCount:a,bytes:o})),e.emitCognition({clientEventId:ve(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:we(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 fe(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:ve(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:we(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 re(e){try{let t=JSON.stringify(e);return typeof t=="string"?t.length:void 0}catch{return}}function ie(e){try{return Array.isArray(e)?e.length:void 0}catch{return}}import{z as h}from"zod";import{createHash as Io}from"crypto";import{createHash as Ia}from"crypto";var wn=new Map;function kn(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function Et(e){let t=Io("sha256").update(e).digest("hex"),n=wn.get(t);if(n)return n;let r=new Map,i=[],o=e.split(`
4
+ `).map(l=>So(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 f=c[1],p=c[2].trim();r.set(f,Ee(p)),a++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let f=u[1],p=u[2].trim(),m=u[3].trim(),g=[];if(m&&m!=="}"){let w=m.endsWith("}")?m.slice(0,-1).trim():m;w&&g.push(w),m.endsWith("}")||(a++,a=Qe(o,a,g))}else m==="}"||(a++,a=Qe(o,a,g));let _=An(g);i.push({variable:f,value:Ee(p),conditions:_,rawConditions:kn(g)}),a++;continue}let d=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(d){let f=d[1],p=d[2].trim(),m=[];if(p&&p!=="}"){let _=p.endsWith("}")?p.slice(0,-1).trim():p;_&&m.push(_),p.endsWith("}")||(a++,a=Qe(o,a,m))}else p==="}"||(a++,a=Qe(o,a,m));let g=An(m);i.push({variable:f,value:"true",conditions:g,rawConditions:kn(m)}),a++;continue}a++}let s={defaults:r,rules:i};return wn.set(t,s),s}function So(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 Qe(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 Ee(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function To(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function An(e){let t=[];for(let n of e){let r=n.split(";").map(i=>i.trim()).filter(i=>i.length>0);for(let i of r){let o=Mo(i);o&&t.push(o)}}return t}var Rt=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,Eo=new RegExp(`^(${Rt.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),Ro=new RegExp(`^(${Rt.source})\\s*==\\s*((?:input|data)\\S*)$`),Ze=/(?:input|data)(?:\.[A-Za-z0-9_]+|\["[^"]+"\]|\['[^']+'\])+/,Co=new RegExp(`^(${Ze.source})\\s*(==|!=)\\s*(${Ze.source})$`),xo=new RegExp(`^(${Ze.source})\\s+in\\s+(${Ze.source})$`),Oo=/^([^\s=!]+)\s*==\s*(.+)$/,No=/^([^\s=!]+)\s*!=\s*(.+)$/,Uu=new RegExp(`^(?:${Rt.source})$`);var Fo=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function Mo(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:Re,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(Fo);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:To(s[1])};let l=n.match(xo);if(l)return{type:"field_in_set",negated:t,field:l[1].trim(),rightField:l[2].trim()};let c=n.match(Co);if(c)return{type:"field_equality",negated:c[2]==="!="?!t:t,field:c[1].trim(),rightField:c[3].trim()};let u=n.match(Eo);if(u)return{type:"array_includes",negated:t,field:u[2].trim(),value:xn(u[1])};let d=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(d){let w=jo(d[2]);if(w!==null)return{type:"in_set",negated:t,field:d[1].trim(),values:w}}let f=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(f)return{type:"comparison",negated:t,field:f[1].trim(),operator:f[2],value:parseFloat(f[3])};let p=n.match(Ro);if(p)return{type:"equality",negated:t,field:p[2].trim(),value:Ee(p[1].trim())};let m=n.match(Oo);if(m)return{type:"equality",negated:t,field:m[1].trim(),value:Ee(m[2].trim())};let g=n.match(No);if(g)return{type:"inequality",negated:t,field:g[1].trim(),value:Ee(g[2].trim())};let _=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return _?{type:"truthy",negated:t,field:_[1].trim()}:{type:"truthy",negated:!1,field:Re,value:e.trim()}}var Re="__unrecognized_condition_forces_deny__";var Do=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Cn(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==Re&&Do.test(r.field)&&t.push(r.field);return t}var Lo=["input.normalized.","input.normalized["];function $o(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions)for(let i of Po(r))typeof i!="string"||i===Re||Lo.some(o=>i.startsWith(o))&&t.add(i);return[...t].sort()}var In=/\binput\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/g;function Po(e){let{field:t,rightField:n}=e;if(t!==Re){let i=typeof t=="string"?[t]:[];return typeof n=="string"&&n.length>0&&i.push(n),i}let r=typeof e.value=="string"?e.value:"";return In.lastIndex=0,[...r.matchAll(In)].map(i=>i[0])}function xn(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 jo(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(xn(s))}return a}var Bo=Object.freeze([{seedId:"c91bd6e3-6530-438e-9a02-034faa7e89c6",legacyCode:"CF1",name:"Block secrets",formerNames:["Block credentials and secrets in outbound messages"]},{seedId:"cb2b2edc-8187-493e-8076-3d119f47ccc8",legacyCode:"CF3",name:"Mask PCI and financial data",formerNames:["Mask payment and bank identifiers","Mask financial data (PCI)"]},{seedId:"7039315d-fd88-4f23-83c2-7df68ad5899e",legacyCode:"CF4",name:"Mask PII",formerNames:["Mask government and national identifiers","Mask PII: government & national IDs","Mask PII identifiers"]},{seedId:"e670cefd-7b57-491b-9883-46010a9ac23c",legacyCode:"CF17",name:"Mask PII when PHI is present",formerNames:[]},{seedId:"7343eda7-99e1-419d-8f77-93f4a32b6bfe",legacyCode:"CF6",name:"Block sensitive subject matter",formerNames:["Ask before sending sensitive subject matter"]},{seedId:"15f1ad89-e27b-46b9-825c-0ca2417b4122",legacyCode:"CF7",name:"Block compensation data",formerNames:["Block pay and compensation data","Hold pay and compensation data","Block pay & compensation"]},{seedId:"2120140a-9720-4624-9b88-d43d62907d6b",legacyCode:"CF8",name:"Block legal and privileged material",formerNames:["Hold legal and privileged material","Block legal & privileged material"]},{seedId:"e1e19ea7-cbc9-4e4f-8931-0c02c88ef467",legacyCode:"CF9",name:"Block security incident details",formerNames:["Hold security-incident detail","Block security-incident detail"]},{seedId:"57d64032-c804-4566-811e-a013c5fd3496",legacyCode:"CF10",name:"Block PHI",formerNames:["Block health information","Hold health information","Block PHI (health information)"]},{seedId:"b5dd9f3a-3d4f-41c7-941f-6b0dacaafd2b",legacyCode:"CF11",name:"Block credential discussions",formerNames:["Block credential discussion without a secret","Hold credential discussion without a secret","Block credential discussion (no secret present)"]},{seedId:"8896cc10-2111-4001-b6a5-4d7187206182",legacyCode:"CF14",name:"Block PCI",formerNames:["Block payment cards outright"]},{seedId:"64b2ee93-31d6-404c-867f-cb5ef5e37785",legacyCode:"CF15",name:"Block PII",formerNames:["Block government identifiers outright","Block government IDs outright","Block PII identifiers outright"]},{seedId:"dbc59b09-7514-4667-a320-ba6ddab5a11c",legacyCode:"CF16",name:"Mask sensitive subject matter",formerNames:[],retired:!0},{seedId:"ca177a99-afda-43ca-a20f-e1c5a5339b2d",legacyCode:"CF18",name:"Mask PHI",formerNames:["Mask PHI (health identifiers)"]}]);var zu=new Map(Bo.map(e=>[e.seedId,e]));var On=["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"],Uo=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],zo=["production","staging","development","test"],qo=["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 Sn={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 Go(e){let t=Vo(e);return t===null?"other":Sn[t]??Sn[t.replace(/_/g,"")]??"other"}function Nn(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=Go(t.targetApp)),n.context=r}return n}var Ce=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],Ko=["read","write","delete","share","export","decide","execute"],Tn=["none","low","medium","high","critical"],St=["public","internal","confidential","restricted"],Ho=[...St,"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"],Wo={action_class:On,operation:Ko,"context/app_category":Uo,"context/environment":zo,"context/actor_function":qo,"read/classification":Ho,"read/data_categories":Ce,"read/data_sensitivity":Tn,"read/sensitivity":St,"write/data_categories":Ce,"write/data_sensitivity":Tn,"write/sensitivity":St};function Fn(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(Wo)){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 et=Object.freeze([{slug:"secret",label:"Secrets and credentials",description:"API keys, tokens, private keys, connection strings.",icon:"KeyRound",generic:"credentials",cfFamily:!0,detectors:["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string"]},{slug:"financial",label:"Payment and banking",description:"Card numbers, IBANs, routing numbers, tax IDs.",icon:"Landmark",generic:"financial",cfFamily:!0,detectors:["pan","iban","aba_routing","us_ein","swift_bic","in_pan_tax","au_tfn"]},{slug:"national_id",label:"Government and national IDs",description:"SSN, National Insurance, Aadhaar, CPF, DNI/NIE, SIN, NHS, TFN.",icon:"Contact",generic:"pii",cfFamily:!0,detectors:["ssn","uk_nino","in_aadhaar","br_cpf","es_dni_nie","ca_sin","uk_nhs_number"]},{slug:"contact",label:"Contact details",description:"Email addresses, phone numbers, dates of birth.",icon:"Mail",generic:"pii",cfFamily:!0,detectors:["email","us_phone","date_of_birth"]},{slug:"network_identifier",label:"Network identifiers",description:"IP and MAC addresses - recognised by the catalog, governed by no firewall family.",icon:"Network",generic:"pii",cfFamily:!1,detectors:["ipv4","mac_address"]}]),Yo=Object.freeze({private_key:"secret",jwt:"secret",aws_access_key:"secret",github_token:"secret",slack_token:"secret",stripe_secret:"secret",google_api_key:"secret",llm_api_key:"secret",bearer_token:"secret",connection_string:"secret",pan:"financial",iban:"financial",aba_routing:"financial",us_ein:"financial",swift_bic:"financial",in_pan_tax:"financial",au_tfn:"financial",ssn:"pii",uk_nino:"pii",in_aadhaar:"pii",br_cpf:"pii",es_dni_nie:"pii",ca_sin:"pii",uk_nhs_number:"pii",email:"pii",us_phone:"pii",date_of_birth:"pii",ipv4:"identifier",mac_address:"identifier"}),qu=new Map(et.map(e=>[e.slug,e])),Vu=new Map(et.flatMap(e=>e.detectors.map(t=>[t,e]))),Qo=et.flatMap(e=>e.detectors);function xe(e){for(let t of na(e))if(Ce.includes(t))return t;return null}function Zo(){let e={};for(let t of Qo){let n=xe(t);n!==null&&(e[t]=n)}return e}function Jo(){let e={secret:new Set,financial:new Set,pii:new Set,identifier:new Set};for(let[n,r]of Object.entries(Yo)){let i=xe(n);i!==null&&e[r].add(i)}let t=n=>Ce.filter(r=>n.has(r));return Object.freeze({secret:t(e.secret),financial:t(e.financial),pii:t(e.pii),identifier:t(e.identifier)})}var Xo=Object.freeze([{slug:"sensitive_personal",label:"Sensitive Personal",description:"Data about a person."},{slug:"sensitive_organizational",label:"Sensitive Organizational",description:"The organization's own secrets, finances and confidential matters."}]),W=["sensitive_personal"],Se=["sensitive_organizational"],ea=["sensitive_personal","sensitive_organizational"],Ct=Object.freeze([{slug:"pii",label:"PII",description:"Anything that identifies a person: names, government IDs, contact details, personal tax numbers.",topics:W},{slug:"phi",label:"PHI",description:"Health information about a person, and the identifiers that tie it to them.",topics:W},{slug:"pci",label:"PCI",description:"Payment card data: card numbers and the details that travel with them.",topics:ea},{slug:"special_category_gdpr",label:"GDPR Special Category",description:"Data GDPR protects most strictly: beliefs, ethnicity, union membership, sex life.",topics:W},{slug:"biometric",label:"Biometric",description:"Fingerprints, face and voice templates, and other body measurements used to identify someone.",topics:W},{slug:"genetic",label:"Genetic",description:"DNA and other inherited characteristics.",topics:W},{slug:"contact",label:"Contact",description:"How to reach a person: email addresses and phone numbers.",topics:W},{slug:"location",label:"Location",description:"Where a person is or has been.",topics:W},{slug:"children",label:"Children",description:"Data about people under the age of consent.",topics:W},{slug:"financial",label:"Financial",description:"The organization's banking and tax-entity identifiers: IBANs, routing numbers, EINs.",topics:Se},{slug:"secrets",label:"Secrets",description:"Live keys and tokens: anyone holding one can act as the system it unlocks.",topics:Se},{slug:"credentials",label:"Credentials",description:"Anything that grants access, and talk about it: keys, tokens, passwords, security incidents.",topics:Se},{slug:"mnpi",label:"MNPI",description:"Material non-public information, including pay and compensation.",topics:Se},{slug:"legal",label:"Legal / Privileged",description:"Attorney-client communications and material under legal hold.",topics:Se}]),ta=Object.freeze(Ct.map(e=>e.slug)),Gu=Object.freeze(Object.fromEntries(ta.map(e=>[e,Object.freeze({field:"data_categories",tokens:Object.freeze([e])})])));var Ku=Object.freeze({mnpi:["mnpi","material_nonpublic","pre_release_earnings"],legal:["attorney_client","legal_hold","privileged"]}),q=["secrets","credentials"],Tt=Object.freeze({private_key:q,aws_access_key:q,github_token:q,slack_token:q,stripe_secret:q,google_api_key:q,llm_api_key:q,connection_string:q,jwt:q,bearer_token:q,iban:["financial"],aba_routing:["financial"],us_ein:["financial"],swift_bic:["financial"],pan:["pci"],in_pan_tax:["pii"],au_tfn:["pii"],ssn:["pii"],uk_nino:["pii"],in_aadhaar:["pii"],br_cpf:["pii"],es_dni_nie:["pii"],ca_sin:["pii"],uk_nhs_number:["phi","pii"],email:["pii","contact"],us_phone:["pii","contact"],date_of_birth:["pii"],ipv4:["pii"],mac_address:["pii"],person_name:["pii"],phi:["phi"],compensation:["mnpi"],legal_privileged:["legal"],security_incident:["credentials"],credentials:["credentials"]}),Hu=Object.freeze({phone:"us_phone",card:"pan"}),Wu=new Map(Ct.map(e=>[e.slug,e]));function na(e){return Object.prototype.hasOwnProperty.call(Tt,e)?Tt[e]??[]:[]}var Yu=Object.freeze(Object.fromEntries(et.flatMap(e=>e.detectors.flatMap(t=>{let n=xe(t);return n!==null&&n!==e.generic?[[t,n]]:[]})))),Qu=Object.freeze(Object.fromEntries(["phi","compensation","legal_privileged","credentials","security_incident","person_name"].map(e=>[e,xe(e)])));var Mn=["compensation","credentials","legal_privileged","phi","security_incident"];var ra=new Set(Mn),ia=Object.freeze(Object.keys(Tt).filter(e=>!ra.has(e))),oa=Object.freeze([...new Set([...Ce,...Ct.map(e=>e.slug)])]),aa=Object.freeze(Xo.map(e=>e.slug)),Zu=Object.freeze({data_categories:oa,detectors:ia,topics:Mn,data_topics:aa}),En="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",Ju=new RegExp(`^(?=.{1,253}$)${En}(?:\\.${En})+$`,"i");var sa='"secret" in input.categories',Xu=`
5
+ decision = "deny" if {
6
+ ${sa}
7
+ }
8
+ `;var Rn=64,la=64,Oe={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}};function tt(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[],identity:Ln()}}var ca=new Set(["deny","approval_required","escalate"]);function Y(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>Rn?r.slice(0,Rn):r}function Je(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Te(e){return typeof e=="string"&&e.length>0?e:null}function Dn(e,t){let n=Je(t.data_categories),r=Te(t.classification),i=Je(t.taint),o=Te(t.action_class),a=o&&On.includes(o)?o:null,s=Te(t.target_app),l=Te(t.decision),c={...e.action_counts};if(a)if(a in c)c[a]=(c[a]??0)+1;else if(Object.keys(c).length<la)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:Y(e.retrieved_data_categories,n),retrieved_classifications:Y(e.retrieved_classifications,r?[r]:[]),taint:Y(e.taint,i),action_classes:Y(e.action_classes,a?[a]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&ca.has(l)?1:0),event_count:e.event_count+1,target_apps:Y(e.target_apps,s?[s]:[]),identity:ua(e.identity,t)}}function ua(e,t){let n=e??Ln(),r=Je(t.attested_subjects),i=Y(n.attested_subjects,r),o=Te(t.subject_id);return{attested_subjects:i,claimed_subjects:Y(n.claimed_subjects,Je(t.claimed_subjects)),acted_subjects:Y(n.acted_subjects,o?[o]:[])}}function Ln(){return{attested_subjects:[],claimed_subjects:[],acted_subjects:[]}}var da=["tier1","tier2","tier3"];function $n(e){return typeof e=="string"&&da.includes(e)}var fa=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],pa=["internal","customer_facing","experimental","third_party"],Pn=[...fa,...pa];function ma(e){return typeof e=="string"&&Pn.includes(e)}function jn(e){let t=new Set;for(let n of e)ma(n)&&t.add(n);return Pn.filter(n=>t.has(n))}var ga={trust_tier:null,categories:[],business_functions:[],business_function:null,blast_radius_tier:null};function Bn(e,t,n){if(t.length>0&&n.add(t),!(e===null||typeof e!="object"||Array.isArray(e)))for(let[r,i]of Object.entries(e))Bn(i,t.length>0?`${t}.${r}`:r,n)}function Un(e){let t=new Set;return Bn(e,"",t),t}var ed=Un(tt()),td=Un(ga),ha=["action_counts"];for(let e of ha){let t=tt()[e];if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`closed-input-paths: session.${e} is no longer a dynamic map \u2014 remove it from DYNAMIC_SESSION_MAPS or the carve-out admits every spelling under it.`)}var nd=new RegExp("^\\p{White_Space}*$","u");var zn="generic",qn=[{id:"finance_accounting",name:"Finance & Accounting",icon:"Landmark",description:"Payments, invoicing, ledgers, transactions, refunds, financial reporting, SOX/AML/KYC controls."},{id:"hr",name:"Human Resources",icon:"Users",description:"Employee records, payroll, hiring/recruiting, benefits, personnel actions and PII of staff."},{id:"engineering",name:"Engineering",icon:"Code",description:"Source code, build/deploy pipelines, infrastructure changes, production systems and developer tooling."},{id:"it_security",name:"IT & Security",icon:"ShieldCheck",description:"Credentials, secrets, access control, configuration, threat/exfiltration prevention and security operations."},{id:"legal",name:"Legal",icon:"Scale",description:"Contracts, NDAs, litigation, counsel communications and legal-hold material."},{id:"privacy_compliance",name:"Privacy & Compliance",icon:"BadgeCheck",description:"GDPR/CCPA/HIPAA, consent, data-subject rights, special-category data and regulatory data handling."},{id:"sales",name:"Sales",icon:"TrendingUp",description:"CRM, leads, deals, quotes, pipeline and customer commercial relationships."},{id:"marketing",name:"Marketing",icon:"Megaphone",description:"Campaigns, content, brand, social channels and prospect/audience data."},{id:"operations",name:"Operations",icon:"Cog",description:"Business operations, logistics, internal workflows, vendor/ops tooling and process automation."},{id:"customer_support",name:"Customer Support",icon:"LifeBuoy",description:"Support tickets, customer communications, account servicing and help-desk actions."},{id:"procurement",name:"Procurement",icon:"ShoppingCart",description:"Purchasing, supplier management, purchase orders, sourcing and spend approvals."},{id:zn,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."}],ya=qn.map(e=>e.id),rd=new Map(qn.map(e=>[e.id,e])),id=new Set(ya);function Vn(e){return Array.isArray(e)&&e.length>0?[...e]:[zn]}var _a=/^[a-z][a-z0-9_]*$/;function Gn(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&_a.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var ba=["narrow","moderate","broad","unbounded","unknown"];function Kn(e){return typeof e=="string"&&ba.includes(e)}function va(e){let t=e-(e>>>1&1431655765);return t=(t&858993459)+(t>>>2&858993459),t=t+(t>>>4)&252645135,Math.imul(t,16843009)>>>24&255}function wa(e,t){if(typeof e!="string"||typeof t!="string"||e.length!==16||t.length!==16)return 64;let n=0;for(let r=0;r<16;r+=8){let i=parseInt(e.slice(r,r+8),16),o=parseInt(t.slice(r,r+8),16);if(!Number.isFinite(i)||!Number.isFinite(o))return 64;n+=va((i^o)>>>0)}return n}var ka=["proposed","approved","revoked"];function Aa(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.skill_id=="string"&&t.skill_id.length>0&&typeof t.skill_schema_hash=="string"&&t.skill_schema_hash.length>0&&typeof t.status=="string"&&ka.includes(t.status)}function Hn(e,t){let n=typeof e.action=="string"?e.action:"",r=typeof e.actionSchemaId=="string"&&e.actionSchemaId.length>0?e.actionSchemaId:null,i=typeof e.fingerprint=="string"&&e.fingerprint.length>0?e.fingerprint:null,o=typeof e.fingerprintRadius=="number"&&Number.isFinite(e.fingerprintRadius)?e.fingerprintRadius:15;if(n.length===0&&r===null&&i===null)return{blocked:!1,skillId:null};for(let a of t)if(Aa(a)&&a.status==="approved"){if(n.length>0&&a.skill_id===n)return{blocked:!0,skillId:a.skill_id,matchedBy:"action"};if(r!==null&&a.skill_schema_hash===r)return{blocked:!0,skillId:a.skill_id,matchedBy:"schema"};if(i!==null&&typeof a.skill_fingerprint=="string"){let s=wa(i,a.skill_fingerprint);if(s<=o&&s<64)return{blocked:!0,skillId:a.skill_id,matchedBy:"fingerprint",fingerprintDistance:s}}}return{blocked:!1,skillId:null}}function Wn(e){return e==="open"||e==="closed"?e:null}var Sa=["ssn","email","phone","card","iban","jwt","aws_access_key","pan","us_phone","private_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","us_ein","swift_bic","in_pan_tax","aba_routing","ca_sin","uk_nhs_number","au_tfn","in_aadhaar","br_cpf","uk_nino","es_dni_nie","ipv4","mac_address","date_of_birth"];var Ta=["tool_name","function","name","action"];function Xe(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)Xe(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)Xe(o,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Ea(e){let t=[];return Xe(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function Ra(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function Ca(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function xa(e,t={}){if(t.discriminatorField===null)return null;let n=[];Xe(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??Ta;for(let i of r){let o=null;for(let[a,s]of n){if(Ra(a)!==i)continue;let l=Ca(s);l!==null&&(o===null||a<o.path)&&(o={path:a,value:l})}if(o)return o.value}return null}function Yn(e,t={}){let n=Ia("sha256").update(Ea(e).join(",")).digest("hex").slice(0,16),r=xa(e,t);return r!==null?`${n}:${r}`:n}var Oa={phone:"us_phone",card:"pan"},Na=(()=>{let e=Zo(),t={};for(let n of Sa){let r=Oa[n]??n,i=e[r]??xe(r);if(i===null)throw new Error(`DETECTOR_DATA_CATEGORY: no data-taxonomy generic for detector "${n}" (canonical "${r}") \u2014 add it to DATA_TAXONOMY.`);t[n]=i}return Object.freeze(t)})(),ad=Jo();function Qn(e){return Na[e]}var Fa=["action","retrieval","delegation"];function Ma(e){return typeof e=="string"&&Fa.includes(e)}var Da=new Set(["rules"]);function Zn(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Da.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Ma):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}function Jn(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=Et(r)}catch{continue}let o=$o(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()}}import{z as at}from"zod";var Dt="[REDACTED]";function nt(e){return!/[\p{P}\p{Z}]/u.test(e)}function hr(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:"\u2022",c=a+s>=o;return i.map((u,d)=>!c&&(d<a||d>=o-s)?u:nt(u)?l:u).join("")}function La(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return hr(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:"\u2022",a=Array.from(r);return(a.length<=1?o:a[0]+a.slice(1).map(s=>nt(s)?o:s).join(""))+i}function yr(e){let t=[],n=0,r=!1,i=0;for(let o=0;o<e.length;o++){let a=e[o];if(a==="\\"){o++;continue}if(r){a==="]"&&(r=!1);continue}if(a==="["){r=!0;continue}if(a==="("){n++;continue}if(a===")"){n--;continue}a==="|"&&n===0&&(t.push(e.slice(i,o)),i=o+1)}return t.push(e.slice(i)),t}function Xn(e,t){let n=e[t];if(n==="*")return{min:0,max:null,next:t+1};if(n==="+")return{min:1,max:null,next:t+1};if(n==="?")return{min:0,max:1,next:t+1};if(n==="{"){let r=e.indexOf("}",t);if(r===-1)return null;let i=e.slice(t+1,r),o=/^(\d+)(?:,(\d*))?$/.exec(i);if(!o)return null;let a=Number(o[1]),s=a;return o[2]!==void 0&&(s=o[2]===""?null:Number(o[2])),{min:a,max:s,next:r+1}}return null}function $a(e){let t;try{t=new RegExp(`^(?:${e})$`,"u")}catch{return null}let n=new Set;for(let r=0;r<128;r++){let i=String.fromCharCode(r);try{t.test(i)&&n.add(i)}catch{return null}}return n}function _r(e){if(e.length===0)return null;let t=e[0];if(t==="\\")return e.length>1?e.slice(0,2):null;if(t==="["){let n=1;for(;n<e.length&&e[n]!=="]";)n+=e[n]==="\\"?2:1;return n<e.length?e.slice(0,n+1):null}if(t==="("){let n=0,r=!1;for(let i=0;i<e.length;i++){let o=e[i];if(o==="\\"){i++;continue}if(r){o==="]"&&(r=!1);continue}if(o==="["){r=!0;continue}if(o==="("){n++;continue}if(o===")"){if(n--,n===0){let a=e.slice(1,i),s=/^\?(?::|<[=!]|[=!])/.exec(a);return s&&(a=a.slice(s[0].length)),_r(yr(a)[0]??"")}continue}}return null}return t==="^"||t==="$"?null:t}function Pa(e){let t=e.map(n=>{let r=_r(n);return r===null?null:$a(r)});for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let i=t[n],o=t[r];if(i===null||o===null)return!0;for(let a of i)if(o.has(a))return!0}return!1}function Ot(e,t,n=!1,r=!1){let i=yr(e);if(i.length>1){n&&r&&Pa(i)&&(t.safe=!1);let c=i.map(u=>Ot(u,t,n,r));return c.some(u=>u===null)?null:c.every(u=>u===c[0])?c[0]:null}let o=0,a=0,s=0,l=0;for(;a<e.length;){let c=1,u=e[a];if(u==="\\")a+=2;else if(u==="["){let f=a+1;for(;f<e.length&&e[f]!=="]";)e[f]==="\\"&&f++,f++;a=f+1}else if(u==="("){let f=1,p=a+1,m=!1;for(;p<e.length&&f>0;){let F=e[p];if(F==="\\"){p+=2;continue}if(m){F==="]"&&(m=!1),p++;continue}if(F==="["){m=!0,p++;continue}F==="("?f++:F===")"&&f--,p++}let g=e.slice(a+1,p-1),_=/^\?(?::|<?[=!]|<[A-Za-z_$][\w$]*>)/.exec(g),w=/^\?(?:<?[=!])/.test(g);_&&(g=g.slice(_[0].length));let S=Xn(e,p),v=S!==null&&(S.max===null||S.max>1);c=w?0:Ot(g,t,n||v,v),a=p}else(u==="^"||u==="$")&&(c=0),a++;let d=Xn(e,a);d!==null&&(a=d.next,(e[a]==="?"||e[a]==="+")&&a++,d.max===null&&c===null&&(t.safe=!1),(d.max===null||d.max>1)&&(l+=1,c===null&&(s+=1,(n||s>1)&&(t.safe=!1)),n&&l>1&&(t.safe=!1)),c=d.min===d.max&&c!==null?c*d.min:null),c===null||o===null?o=null:o+=c}return o}function br(e){let t={safe:!0};try{Ot(e,t)}catch{return!1}return t.safe}function ja(e,t,n){let r=n.length>0?n:"\u2022",i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{if(!br(t))throw new Error("keepPattern is not safe for a backtracking engine");let d=new RegExp(t,"g"),f;for(;(f=d.exec(e))!==null;){if(f[0].length===0){d.lastIndex++;continue}for(let p=f.index;p<f.index+f[0].length;p++)i[p]=!0}}catch{}let o=[],a=0;for(let d of e)o.push({ch:d,at:a}),a+=d.length;let s=!1,l=!0;for(let{ch:d,at:f}of o)if(nt(d)&&(s=!0,i[f]!==!0)){l=!1;break}let c=s&&l,u="";for(let{ch:d,at:f}of o)u+=!c&&i[f]===!0||!nt(d)?d:r;return u}function Ba(e,t){let n=t.maskChar??"\u2022";switch(t.mode){case"partial":return hr(e,t.keepFirst??0,t.keepLast??0,n);case"email":return La(e,n);case"custom":return ja(e,t.keepPattern,n);default:return t.replacement??Dt}}var Ua=/[^\u0000-\u007F]/,vr=new RegExp("^\\p{Nd}$","u"),za=new RegExp("^\\p{Pd}$","u"),qa=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,Va=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,Ga=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),wr="<invisible>",er=new Map;function Ka(e){let t=String.fromCodePoint(e).normalize("NFKC");if(t.length===1&&t>="0"&&t<="9")return t;let n=e;for(let i=0;i<256&&n>0&&vr.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function Ha(e){if(e<128)return null;let t=er.get(e);if(t!==void 0)return t;let n=(()=>{if(e>=65281&&e<=65374)return String.fromCharCode(e-65248);let r=String.fromCodePoint(e);return vr.test(r)?Ka(e):za.test(r)||Ga.has(e)?"-":qa.test(r)?" ":Va.test(r)?wr:null})();return er.set(e,n),n}function Lt(e){if(typeof e!="string"||e.length===0||!Ua.test(e))return[];let t=tr(e,"as-separator");if(t===null)return[];let n=tr(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function tr(e,t){let n=[],r=[],i=!1;for(let o=0;o<e.length;){let a=e.codePointAt(o),s=a>65535?2:1,l=Ha(a);if(l===null){for(let c=0;c<s;c++)n.push(e[o+c]),r.push(o+c);o+=s;continue}if(i=!0,l===wr){t==="as-separator"&&(n.push(" "),r.push(o)),o+=s;continue}n.push(l),r.push(o),o+=s}return i?(r.push(e.length),{label:t,text:n.join(""),offsets:Int32Array.from(r)}):null}function Wa(e,t){return{start:e.offsets[t.start],end:e.offsets[t.end]}}function Ya(e){if(e.length<=1)return[...e];let t=[...e].sort((i,o)=>i.start-o.start||i.end-o.end),n=[],r={start:t[0].start,end:t[0].end};for(let i=1;i<t.length;i++){let o=t[i];o.start<=r.end?o.end>r.end&&(r={start:r.start,end:o.end}):(n.push(r),r={start:o.start,end:o.end})}return n.push(r),n}function nr(e,t){let n=[];e.lastIndex=0;let r;for(;(r=e.exec(t))!==null;){if(r[0].length===0){e.lastIndex++;continue}n.push({start:r.index,end:r.index+r[0].length})}return n}var rt="[REDACTED]",$t=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"in_pan_tax",re:/\b[A-Z]{3}[ABCFGHJLPTE][A-Z]\d{4}[A-Z]\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"date_of_birth",re:/\b(?:\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])|(?:0[1-9]|[12]\d|3[01])[/.](?:0[1-9]|1[0-2])[/.]\d{4}|(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12]\d|3[01])\/\d{4})\b/g},{name:"us_phone",re:/(?:\(\d{3}\)|\b(?:\+?1[ .-]?)?\d{3}\)?)[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}],ld=$t.map(({name:e,re:t})=>({name:e,source:t.source})),Qa="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function Za(e){return kr(e,Qa)}function kr(e,t){let n="",r=!1;for(let i=0;i<e.length;i++){let o=e[i];if(o==="\\"){if(!r&&e[i+1]==="b"){n+=t,i++;continue}n+=o+(e[i+1]??""),i++;continue}o==="["?r=!0:o==="]"&&(r=!1),n+=o}return n}function Ar(e){return new RegExp(Za(e.source),e.flags)}var Ja="(?:\\b|_)";function Nt(e){return kr(e,Ja)}var Xa=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function es(e){let t=Xa.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function Pt(e){if(!/^\d+$/.test(e))return!1;let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let i=e.charCodeAt(r)-48;n&&(i*=2,i>9&&(i-=9)),t+=i,n=!n}return t%10===0}var ts=[{network:"visa",ranges:[["4","4"]],lengths:[13,16,19]},{network:"mastercard",ranges:[["51","55"],["2221","2720"]],lengths:[16]},{network:"amex",ranges:[["34","34"],["37","37"]],lengths:[15]},{network:"discover",ranges:[["6011","6011"],["644","649"],["65","65"],["622126","622925"]],lengths:[16,17,18,19]},{network:"jcb",ranges:[["3528","3589"]],lengths:[16,17,18,19]},{network:"unionpay",ranges:[["62","62"],["81","81"]],lengths:[16,17,18,19]},{network:"china_t_union",ranges:[["31","31"]],lengths:[19]},{network:"diners",ranges:[["36","36"],["38","39"],["300","305"]],lengths:[14,15,16,17,18,19]},{network:"maestro",ranges:[["5018","5018"],["5020","5020"],["5038","5038"],["5893","5893"],["6304","6304"],["6759","6759"],["6761","6763"]],lengths:[13,14,15,16,17,18,19]},{network:"mir",ranges:[["2200","2204"]],lengths:[16,17,18,19]},{network:"borica",ranges:[["2205","2205"]],lengths:[16]},{network:"dankort",ranges:[["5019","5019"]],lengths:[16]},{network:"rupay",ranges:[["60","60"],["65","65"],["81","82"],["508","508"],["353","353"],["356","356"]],lengths:[16]},{network:"interpayment",ranges:[["636","636"]],lengths:[16,17,18,19]},{network:"instapayment",ranges:[["637","639"]],lengths:[16]},{network:"troy",ranges:[["9792","9792"]],lengths:[16]},{network:"verve",ranges:[["506099","506198"],["650002","650027"],["507865","507964"]],lengths:[16,18,19]},{network:"lankapay",ranges:[["357111","357111"]],lengths:[16]},{network:"uzcard",ranges:[["8600","8600"]],lengths:[16]},{network:"humo",ranges:[["9860","9860"]],lengths:[16]},{network:"napas",ranges:[["9704","9704"]],lengths:[16,19]}];function ns(e){if(!/^\d+$/.test(e))return null;for(let t of ts)if(t.lengths.includes(e.length))for(let[n,r]of t.ranges){let i=e.slice(0,n.length);if(i.length===n.length&&i>=n&&i<=r)return t.network}return null}function rs(e){return e.length>=13&&e.length<=19&&ns(e)!==null&&Pt(e)}function is(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 os(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 as=[[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]],ss=[[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 ls(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=as[t][ss[r%8][n[r].charCodeAt(0)-48]];return t===0}function cs(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 us(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 ds=[1,4,3,7,5,8,6,9,10];function fs(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)*ds[n];return t%11===0}var ps="TRWAGMYFPDXBNJZSQVHLCKE";function ms(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 ps[Number(a)%23]===o}var gs=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function hs(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!gs.has(t.slice(0,2)):!1}var jt=[{name:"pan",re:/\b\d(?:[ -]?\d){12,18}\b/g,normalize:e=>e.replace(/[ -]/g,""),validate:rs},{name:"iban",re:/\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]){10,30}\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:is},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:os},{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:hs(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&&ls(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:cs},{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:ms},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&Pt(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:us},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:fs}],Ir=[{name:"person_name",detect:(e,t)=>t.person_name?.(e)??[]}],ys="[^\\s\\S]",_s=Ir.map(e=>e.name),cd=new Set(_s),bs=Object.fromEntries([...$t,...jt].map(e=>[e.name,e.re.source])),E=bs,ud=jt.map(e=>e.name),Sr=$t.map(({name:e,re:t})=>({name:e,re:Ar(t)})),Tr=jt.map(e=>({...e,re:Ar(e.re)})),dd=[...Sr,...Tr].map(({name:e,re:t})=>({name:String(e),source:t.source})),Bt=["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","pan","iban","aba_routing","us_ein","swift_bic","ssn","uk_nino","in_aadhaar","in_pan_tax","br_cpf","es_dni_nie","ca_sin","uk_nhs_number","au_tfn","email","us_phone","date_of_birth","person_name","ipv4","mac_address"],vs={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
9
  MIIEv\u2026
6
- -----END PRIVATE KEY-----`,template:{pattern:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.mac_address,mode:"full"},defaultEnabled:!1}},Ze=Object.freeze(Object.fromEntries(Et.map(e=>{let t=xa[e];return[e,{...t,template:{...t.template,pattern:ga(wt(t.template.pattern))}}]})));var cu=new Set(Et.filter(e=>!Ze[e].defaultEnabled));function Oa(e,t){let n=new Set;for(let r of Et)(Ze[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function Qe(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=Rt(t),o=e;for(let{name:a,re:s}of lr){let l=a;n.has(l)||(o=o.replace(s,c=>(r?.(l),i(c))))}for(let{name:a,re:s,normalize:l,validate:c}of cr)n.has(a)||(o=qa(o,s,l,c,t,a,r));return o}function Rt(e){return typeof e=="function"?e:()=>e}var zn=e=>"\0".repeat(e.length);function Na(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=It(e);if(i.length===0)return Qe(e,t,n,r);let o=new Set,a=f=>{o.add(f)},s=Qe(e,zn,n,a),l=!0,c=new Array(e.length).fill(!1);for(let f=0;f<e.length;f++)c[f]=s[f]==="\0"&&e[f]!=="\0";for(let f of i){let m=Qe(f.text,zn,n,a);for(let g=0;g<f.text.length;g++)if(!(m[g]!=="\0"||f.text[g]==="\0"))for(let p=f.offsets[g];p<f.offsets[g+1];p++)c[p]||(c[p]=!0,l=!1)}if(l)return Qe(e,t,n,r);for(let f of o)r?.(f);let u="",d=0;for(;d<e.length;){if(!c[d]){u+=e[d],d++;continue}let f=d;for(;d<e.length&&c[d];)d++;u+=Rt(t)(e.slice(f,d))}return u}function Ce(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var Vn=new Map;function Ma(e){let t=Vn.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),Vn.set(e.source,t)),t}var Da=4096,Fa=64,Kn=null;function La(e){return Kn!==null?Kn:Da+e.length*Fa}var ur=!1,j={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},dr={spanBudget:0,depthCap:0};function $a(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:La(e),exhausted:!1}}function pr(e,t,n,r,i,o,a){j.spanCalls++;let s=t*a.stride+n.length,l=ur?void 0:a.chosen.get(s);if(l!==void 0)return l;if(a.budget<=0)return a.exhausted=!0,null;a.budget--,j.spanMisses++;let c=Pa(e,t,n,r,i,o,a);return a.chosen.set(s,c),c}function Pa(e,t,n,r,i,o,a){let s=Ma(r),l=[];for(let u=n.length-1;u>=1;u--)if(Ce(n[u])){let d=n.slice(0,u);s.test(d)&&l.push(d)}let c=Ce(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(o(i(u),u)&&!Ba(e,t,u,r,i,o,a))return u;return null}var Gn=new Map;function ja(e){let t=Gn.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),Gn.set(e.source,t)),t}function Ba(e,t,n,r,i,o,a){j.cutCalls++;let s=t*a.stride+n.length,l=ur?void 0:a.cuts.get(s);if(l!==void 0)return l;if(a.budget<=0)return a.exhausted=!0,!0;a.budget--,j.cutMisses++;let c=Ua(e,t,n,r,i,o,a);return a.cuts.set(s,c),c}function Ua(e,t,n,r,i,o,a){let s=t+n.length,l=ja(r);for(let c=1;c<n.length;c++){if(Ce(n[c])||!Ce(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 f=pr(e,u,d[0],r,i,o,a);if(f!==null&&u+f.length>s&&Ce(e[u+f.length]))return!0}return!1}function qa(e,t,n,r,i,o,a){let s=Rt(i);t.lastIndex=0;let l="",c=0,u=$a(e),d=j.spanMisses+j.cutMisses,f;for(;(f=t.exec(e))!==null;){let m=f[0],g=f.index;if(m.length===0){t.lastIndex=g+1;continue}let p;try{p=pr(e,g,m,t,n,r,u)}catch(_){if(_ instanceof RangeError&&/call stack/i.test(_.message))u.exhausted=!0,p=null;else throw _}if(u.exhausted)return j.budgetExhausted++,dr.spanBudget++,Hn(d),l+e.slice(c,g)+s(e.slice(g));if(p!==null)a?.(o),l+=e.slice(c,g)+s(p),c=g+p.length,t.lastIndex=c;else{let _=m.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=_===-1?g+m.length:g+1+_+1}if(t.lastIndex>e.length)break}return Hn(d),l+e.slice(c)}function Hn(e){let t=j.spanMisses+j.cutMisses-e;t>j.maxMissesInAPass&&(j.maxMissesInAPass=t)}function Ct(e,t=or,n,r){return Va(e,t,Oa(n,r))}var za=256;function Va(e,t,n){let r=new Set,i=!n.has("pan"),o=s=>{r.add(s)},a=(s,l)=>{if(l>za)return dr.depthCap++,t;if(typeof s=="string")return Na(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&&kt(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 fr(e,t=or){return Ct(e,t).value}function Ka(e){let{value:t,detectors:n}=Ct(e),r=n.some(i=>Ze[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function Ga(e,t){let{blocked:n,redacted:r,detectors:i}=Ka(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 Ha(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var Wa=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function Qa(e){return Wa.has(Ha(e))}function pe(e,t,n){return n.enforced&&Qa(e)?Ga(t,{failMode:n.failMode}):{verdict:"allow",redacted:t,detectors:[]}}var Ya=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,mr=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"}),Za=new RegExp(`[${Object.keys(mr).join("")}]`,"gu"),Ja=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),gr="\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",Xa=Object.freeze(Object.fromEntries([...gr].map((e,t)=>[e,String.fromCharCode(97+t)]))),es=new RegExp(`[${gr}\u2800]`,"g"),hr=/[⠀-⣿]/;function ts(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 ns(e){return e.replace(Ya,"")}function yr(e){return e.replace(Za,t=>mr[t]??t)}function rs(e){return e.replace(/[4@31!05$79(8]/g,t=>Ja[t]??t)}function is(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 os(e){return hr.test(e)?e.replace(es,t=>t==="\u2800"?" ":Xa[t]??t):e}function Wn(e){let t;try{t=ts(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=ns(t),t=yr(t),t}var as=/^[A-Za-z0-9+/]{16,}={0,2}$/,ss=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,Qn=/[A-Za-z0-9+/]{20,}={0,2}/g;function At(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 _r=new TextDecoder("utf-8",{fatal:!1});function br(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=_r.decode(n);return t===r?[t]:[r,t]}function ls(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=_r.decode(n);return r===i?[r]:[i,r]}function Yn(e){let t=e.trim(),n=[];if(ss.test(t))for(let r of ls(t))n.push({decoded:r,textiness:At(r)});if(as.test(t)&&t.length%4===0)for(let r of br(t))n.push({decoded:r,textiness:At(r)});return n}function Zn(e,t){let n=[],r;for(Qn.lastIndex=0;(r=Qn.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let o of br(i))n.push({decoded:o,textiness:At(o)})}return n}var cs=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function vr(e,t=cs){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=m=>{m.length>0&&m.length<=r&&a.add(m)},l=!1,c=!1,u=0,d=0,f=[{s:e,depth:0}];for(;f.length>0;){if(u>=i){c=!0;break}let m=f.pop();if(m===void 0)break;let{s:g,depth:p}=m;if(g.length>r){c=!0;continue}u++,p>d&&(d=p);let _=Wn(g);s(_);let I=rs(_);if(I!==_&&s(I),s(is(_)),hr.test(g)&&s(os(_)),p>=n){let S=Wn(g);(Yn(S).length>0||Zn(S,o).length>0)&&(c=!0);continue}let A=[...Yn(_),...Zn(_,o)];for(let S of A){if(l=!0,S.decoded.length>r){c=!0;continue}S.textiness>=.85&&S.decoded!==_?f.push({s:S.decoded,depth:p+1}):s(S.decoded)}}return{views:[...a],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:d}}var wr=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],us=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),ds=8,ps=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Jn=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function fs(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||ps.has(i)&&Jn(t[r-1])&&Jn(t[r+1])&&(n++,n>=ds))return!0}return!1}var ms=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function gs(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(ms.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var hs=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function ys(e){for(let t of hs)if(e>=t.lo&&e<=t.hi)return t.name;return null}function _s(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=ys(o.codePointAt(0));if(a===null){i=!1;break}a==="latin"?n++:yr(o)!==o&&r++}if(i&&n>0&&r>0)return!0}return!1}var Xn=Object.freeze({signals:[],contributes:!1});function bs(e){if(typeof e!="string"||e.length===0)return{...Xn,signals:[]};let t=new Set;try{fs(e)&&t.add("hidden_text_carrier"),gs(e)&&t.add("injected_turn_boundary"),_s(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=vr(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Xn,signals:[]}}return{signals:[...wr.filter(n=>t.has(n))],contributes:us.some(n=>t.has(n))}}var Je=[{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 er(e){return typeof e!="string"||e.length===0?[]:Je.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function vs(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(er(e)),{views:n}=vr(e);for(let r of n)for(let i of er(r))t.add(i);return Je.filter(r=>t.has(r.name)).map(r=>r.name)}function ws(e){let t=new Set,n=new Set,r=!1,i=o=>{if(o!=null){if(typeof o=="string"){for(let s of vs(o))t.add(s);let a=bs(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:Je.filter(o=>t.has(o.name)).map(o=>o.name),structural:wr.filter(o=>n.has(o))}}function ks(e){return ws(e).matched}var uu=Je.map(e=>e.name);var As=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Is="i:injection";function kr(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=Ct(e.content);for(let o of i){let a=Ze[o]?.category;a&&t.add(`c:${a}`)}ks(e.content)&&t.add(Is)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&As.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var vt="(?: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))",du=[{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${vt}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${vt}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${vt}\\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}],tr="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Ss=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${tr}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${tr}|programming|training))`,Ts="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",nr="(?:\\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)",Es="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",pu=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${Ts}${Ss}\\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}?${nr}`,"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+(?:${Es}\\b|[\\s\\S]{0,40}?${nr})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var fu=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var W=e=>`[^.!?;\\n]{0,${e}}?`,Rs=["\\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("|"),Ar="(?: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)",mu=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Rs})\\s${W(40)}\\b${Ar}\\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${W(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${W(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${W(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${W(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${W(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")}]),gu=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${W(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${W(30)}\\b${Ar}\\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 Re=e=>`[^.!?;\\n]{0,${e}}?`,hu=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${Re(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${Re(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${Re(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${Re(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${Re(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 xt="[REDACTED]",de="\u2022",Ye=e=>/[\p{L}\p{N}]/u.test(e);function Ir(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:de,c=a+s>=o;return i.map((u,d)=>!c&&(d<a||d>=o-s)?u:Ye(u)?l:u).join("")}function Cs(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Ir(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:de;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>Ye(a)?o:a).join(""))+i}function xs(e,t,n){let r=n.length>0?n:de,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(Ye(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]||!Ye(u)?l+=u:l+=r}return l}function Sr(e,t){let n=t.mode??"full";return n==="partial"?Ir(e,t.keepFirst??0,t.keepLast??0,t.maskChar??de):n==="email"?Cs(e,t.maskChar??de):n==="custom"?xs(e,t.keepPattern,t.maskChar??de):t.replacement??xt}function Os(e,t){return typeof e=="string"?Sr(e,t):t.replacement??xt}function Tr(e){let t=[],n=e.replacement??xt;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:wt(r),replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:wt(i),replacer:o=>Sr(o,r)})}return t}function Er(e){try{return new RegExp(e,"g")}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`[visiq-redact] Invalid redaction pattern "${e}": ${n}`)}}function Rr(e,t){if(It(e).length===0){let n=e;for(let{source:r,replacer:i}of t)n=n.replace(Er(r),o=>i(o));return n}return Ns(e,t)}function Ns(e,t){let n=e;for(let{source:r,replacer:i}of t){let o=Er(r),a=[...qn(o,n)];for(let u of It(n))for(let d of qn(o,u.text))a.push(ca(u,d));let s=ua(a);if(s.length===0)continue;let l="",c=0;for(let{start:u,end:d}of s)l+=n.slice(c,u)+i(n.slice(u,d)),c=d;n=l+n.slice(c)}return n}function L(e,t){return e==null?e:typeof e=="string"?Ms(e,t):typeof e=="object"?Ds(e,t):e}function Ms(e,t){if(typeof e!="string")return e;let n=Tr(t);return n.length===0?e:Rr(e,n)}function Ds(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=Tr(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]=Os(l[u],d);continue}c[u]=a(l[u])}return c}return typeof s=="string"&&o?Rr(s,r):s};return a(e)}import{createHash as Iu}from"node:crypto";var Cr=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Fs(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:Cr(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:Cr(t.spawn.prompt)}),t}function Ls(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 $s=1440*60*1e3,Ps="VISIQ_BUNDLE_GRACE_TTL_MS",js="VISIQ_BUNDLE_CACHE_DISABLED",Bs="VISIQ_CACHE_DIR",Us=Xe.object({graceTtlMs:Xe.number().int().nonnegative().optional(),disabled:Xe.boolean().optional(),cacheDir:Xe.string().min(1).optional()}).strict();function qs(e){return e==null?{}:Us.parse(e)}function zs(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Ps];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return $s}function Vs(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[js]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var xr;function Ks(){if(xr!==void 0)return xr;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Gs(e){return JSON.stringify(Nt(e))}function Nt(e){if(Array.isArray(e))return e.map(Nt);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Nt(t[r]);return n}return e}function Hs(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Ws(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 $r(){if(!Ks())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 Pr(e,t){return e.createHash("sha256").update(Gs(t)).digest("hex")}function Qs(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Bs]?.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 Ys(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function jr(e,t,n){return e.path.join(Qs(e,n),"bundles",`${Ys(e,t)}.json`)}async function Zs(e,t,n,r={}){let i=await $r();if(i)try{let o=jr(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:Pr(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 Js(e,t={}){let n=await $r();if(!n)return null;try{let r=await n.fs.readFile(jr(n,e,t),"utf-8"),i=Ws(JSON.parse(r));return!i||Pr(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var xe;async function Xs(){if(xe!==void 0)return xe;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;xe=typeof t=="function"?t:null}catch{xe=null}return xe}function el(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=_t(i)}catch{continue}let a=typeof r.id=="string"?r.id:"<rule>";for(let s of _n(o))t.push(`${a}: ${s}`)}return t}function tl(e){return jn(e)}function nl(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var rl=5e3,il=600*1e3,ol=1e4,al=25,Or=1e3,sl=5e3,ll=100,Nr=2e3,cl=10,ul=512,dl=1800*1e3,pl=.7,fl="monitor",ml="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",Mr="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.",et="open";function Oe(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function gl(e,t){return kr({content:e,resourceMetadata:t})}var hl=h.object({operations:h.array(h.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:h.string().min(1,"agentId is required"),sessionId:h.string().min(1).max(255).optional(),toolName:h.string().optional(),toolArgs:h.record(h.unknown()).optional(),targetResource:h.string().optional(),resourceType:h.string().optional(),resourceMetadata:h.record(h.unknown()).optional(),normalized:h.record(h.unknown()).optional(),query:h.string().optional(),contentPreview:h.string().optional(),telemetry:h.record(h.unknown()).optional(),context:h.record(h.unknown()).optional(),mcpServer:h.string().min(1).max(255).optional(),identity:h.object({attested:h.array(h.string().min(1).max(255)).max(32).optional(),claimed:h.array(h.string().min(1).max(255)).max(32).optional(),subjectId:h.string().min(1).max(255).optional()}).optional()}),yl=h.object({version:h.string().min(1),dialect_version:h.number().int().optional(),min_dialect:h.number().int().optional(),shutdown:h.boolean().optional(),agent_mode:h.enum(["enforce","monitor","off"]).optional(),cognition_capture:h.boolean().optional(),agent_mode_by_operation:h.object({action:h.string().optional(),retrieval:h.string().optional(),delegation:h.string().optional()}).partial().optional(),agent_attributes:h.object({trust_tier:h.string().nullable().optional(),categories:h.array(h.string()).optional(),business_function:h.string().nullable().optional(),business_functions:h.array(h.string()).nullable().optional(),blast_radius_tier:h.string().nullable().optional(),no_coverage:h.string().nullable().optional(),fail_mode:h.string().nullable().optional()}).optional(),rules:h.array(h.record(h.unknown())),action_schemas:h.array(h.object({id:h.string(),plane:h.string().optional(),field_mappings:h.array(h.record(h.unknown())).optional(),derived_fields:h.array(h.record(h.unknown())).optional(),action_class:h.string().nullable().optional(),action_class_confidence:h.number().optional()})).optional(),no_coverage:h.object({no_coverage_defaults:h.record(h.string()),autopilot_enabled:h.boolean(),enduser_hitl_enabled:h.boolean(),hitl_timeout_seconds:h.number().optional()}).optional(),skill_blacklist:h.array(h.record(h.unknown())).optional()});function _l(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=Nn(Mn(n));return{trust_tier:Sn(t)?t:null,categories:En(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&Dn(e.blast_radius_tier)?e.blast_radius_tier:null}}function bl(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 vl(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Mt=new Set,Dr=!1;async function Fr(e){let t=[];for(let n of Mt){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 wl(){if(!Dr&&!(typeof process>"u"||typeof process.once!="function")){Dr=!0,process.once("beforeExit",()=>{Fr(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await Fr(!0)}finally{process.kill(process.pid,e)}})()})}}var Br=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];skillBlacklist=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;cacheIdentity;bundleCacheDisabled;bundleGraceTtlMs;bundleCacheDirOverride;diskFallbackServed=!1;agentMode=fl;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=Oe(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??et;governedFailMode=null;telemetryBuffer=[];droppedTelemetry=0;inFlightTelemetry=new Set;telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastSkillInventorySig=null;skillInventoryPromise=null;lastCloneCaptureSig=null;toolDescriptions=new Map;constructor(e,t,n,r,i,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=qs(s);if(this.bundleCacheDisabled=Vs(d.disabled),this.bundleGraceTtlMs=zs(d.graceTtlMs),this.bundleCacheDirOverride=d.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let f={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:Ls(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...o!==void 0?{sdkVersion:o}:{},...a!==void 0?{sdkDialect:a}:{}};this.client=new gt(f,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},rl),Ot(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},ol),Ot(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},sl),Ot(this.cognitionTimer),Mt.add(this),wl()}else this.client=null}async evaluate(e){let t=hl.parse(e),n=Date.now();if(this.operatorShutdown){let m=this.denyAll(t,ml);return this.applyAgentMode(m,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,Mr,n);let m=this.denyAll(t,Mr);return this.applyAgentMode(m,"enforce",t,n)}if(t.operations.every(m=>this.modeFor(m)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let m;if(this.agentModeConfirmed?m=this.agentMode:this.bundleApplyFailed?m="enforce":m="monitor",m==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let g=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(g,m,t,n)}if(this.modeFor("action")!=="off"){let m=this.matchSkillQuarantine(t);if(m){let g=this.denyAll(t,m);return this.applyAgentMode(g,this.modeFor("action"),t,n)}}let r=this.readSession(t.sessionId),i=await Xs();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")?wn(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(m){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${m instanceof Error?m.message:String(m)}`,n);throw m}let d=[...new Set(t.operations.flatMap(m=>this.normalizedRefs[m]??[]))].sort();d.length>0&&nl(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 f=kn(t.normalized);return f.length>0&&(u.normalizedDrift=f,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${f.length} value(s) outside the canonical vocabulary \u2014 a builder-authored rule can only select in-vocab values, so these cannot match one, so a rule keyed on the canonical value does not fire here. Check the harness classifier's casing/spelling. Affected: ${f.slice(0,5).join("; ")}${f.length>5?`; +${f.length-5} more`:""}`))),this.foldSession(t,u.enforced?u.decision:"permit"),u.enforced&&u.action.decision==="approval_required"&&await this.registerHitl(t,u),this.bufferTelemetry(t,u,Date.now()-n,u.enforced),u}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}matchSkillQuarantine(e){if(this.skillBlacklist.length===0)return null;let t=e.context?.skill;if(!t||t.activated!==!0)return null;let n=typeof t.name=="string"?t.name:"",r=typeof t.fingerprint=="string"?t.fingerprint:null;if(n.length===0&&r===null)return null;let i=Fn({action:n,fingerprint:r},this.skillBlacklist);return i.blocked?i.matchedBy==="fingerprint"?"skill quarantined for the agent \u2014 its content signature matches a blacklisted skill (a renamed or edited re-skin); blocked ([D-27])":"skill quarantined for the agent \u2014 it is on the approved blacklist; blocked ([D-27])":null}readSession(e){if(!e)return Ee;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>dl?(this.sessions.delete(e),Ee):t.state:Ee}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>=pl)return o}foldSubjectId(e){let t=e.identity?.subjectId;if(typeof t=="string"&&t.length>0)return t;let n=e.normalized?.write;if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let r=n.subject_id;if(typeof r=="string"&&r.length>0)return r}}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=An(r===Ee?We():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,taint:o?gl(e.contentPreview,i):void 0,action_class:a?this.foldActionClass(e):void 0,target_app:a?e.targetResource??e.toolName:void 0,attested_subjects:e.identity?.attested,claimed_subjects:e.identity?.claimed,subject_id:a?this.foldSubjectId(e):void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>ul){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=yl.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=el(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=>Pn(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?_l(t.agent_attributes):null,this.agentNoCoverage=Ln(t.agent_attributes?.no_coverage),this.governedFailMode=Oe(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=bl(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=tl(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",...ee(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>=il&&(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 Js(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Hs(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 Zs(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({...ze(),...e?{agent_type:e}:{},...t?.model?{model:t.model}:{},...t?.systemPrompt?{systemPrompt:t.systemPrompt}:{},...t?.toolSchemas&&t.toolSchemas.length>0?{toolSchemas:t.toolSchemas}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));for(let n of e)n.description&&this.toolDescriptions.set(n.name,n.description);t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}reportSkillInventory(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,h:n.content_hash})).sort((n,r)=>n.n===r.n?n.h.localeCompare(r.h):n.n.localeCompare(r.n)));t!==this.lastSkillInventorySig&&(this.lastSkillInventorySig=t,this.skillInventoryPromise=this.client.reportSkillInventory(e).catch(()=>{}))}captureCloneMetadata(e){if(!this.client||!this.resolvedAgentId||!(e.model||e.systemPrompt||(e.toolSchemas?.length??0)>0))return;let t=JSON.stringify({m:e.model??"",s:e.systemPrompt??"",t:e.toolSchemas??[]});t!==this.lastCloneCaptureSig&&(this.lastCloneCaptureSig=t,this.client.registerEnvironment({...ze(),...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=$n(n),i={...n};return e.toolArgs&&(i.tool_args=fr(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?vl(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?{[sn]: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,cl)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=al&&this.flushTelemetry()}pendingTelemetryCount(){return this.telemetryBuffer.length}hasBackend(){return this.client!==null}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0),{client:t}=this,n=(async()=>{try{await t.sendTelemetry(e)}catch(r){this.droppedTelemetry+=e.length,console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",r)}})();this.inFlightTelemetry.add(n);try{await n}finally{this.inFlightTelemetry.delete(n)}}async drainInFlightTelemetry(){for(let e=0;e<8&&this.inFlightTelemetry.size>0;e+=1)await Promise.allSettled([...this.inFlightTelemetry])}droppedTelemetryCount(){return this.droppedTelemetry}enforceTelemetryCap(){let e=this.telemetryBuffer.length-Or;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Or})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Fs(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=ll&&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-Nr;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Nr})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}if(this.skillInventoryPromise)try{await this.skillInventoryPromise}catch{}await this.flushTelemetry(),await this.drainInFlightTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),Mt.delete(this)}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.cognitionTimer&&(clearInterval(this.cognitionTimer),this.cognitionTimer=null),this.flushTelemetry(),this.flushCognition()}};function Ot(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function kl(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function B(e,...t){for(let n of t){let r=kl(e[n]);if(r)return r}}var Al=[{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:B(t,"task","input","reason","message"),source:"structural"}}},{framework:"voltagent",matches:e=>e==="delegate_task",extract:(e,t)=>{let n=B(t,"targetAgent","agent","subAgent","agentName","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:B(t,"task","message","input"),description:B(t,"purpose"),source:"structural"}:null}},{framework:"crewai",matches:e=>/delegate work to (co-?worker|.+)/i.test(e),extract:(e,t)=>{let n=B(t,"coworker","agent","role");return n?{childAgentId:n,childName:n,kind:"teammate",agentType:n,task:B(t,"task","question"),description:B(t,"context"),source:"structural"}:null}},{framework:"llamaindex",matches:e=>e==="handoff"||/handoff/i.test(e),extract:(e,t)=>{let n=B(t,"to_agent","toAgent","agent_name","agentName","agent","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:B(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=B(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:B(t,"task","message","input","reason","prompt"),source:"heuristic"}:null}}];function tt(e,t){if(!e)return null;let n=t??{};for(let r of Al)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function nt(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}var Il={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"},Sl=new Set(["workspace_deactivate_skill"]),Tl=new Set(["read","read_file","readfile","view","cat"]);function El(e){return Sl.has((e??"").trim())}function Rl(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function Lr(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function Cl(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=Il[n];if(i){let o=Lr(r,["name","skill_name","identifier","skill","path"]);return o?{skill:o,via:n,framework:i}:null}if(Tl.has(n.toLowerCase())){let o=Lr(r,["path","file_path","filePath","target","file"]),a=o?Rl(o):null;return a?{skill:a,via:n,framework:"unknown"}:null}return null}function Ur(e,t){let{activation:n,attributedSkill:r}=e;if(r)return{skill:{name:r,activated:!!n,...n?{via:n.via,framework:n.framework}:{},...t?{fingerprint:t}:{}}}}var qr=class{#e=null;activate(e){return this.#e=e,e}deactivate(e){(!e||this.#e?.skill===e)&&(this.#e=null)}current(){return this.#e}observe(e,t){let n=Cl(e,t);if(n)return this.activate(n),{activation:n,attributedSkill:n.skill};if(El(e)){let r=this.#e?.skill??null,i=t&&typeof t.name=="string"?t.name:void 0;return this.deactivate(i),{activation:null,attributedSkill:r}}return{activation:null,attributedSkill:this.#e?.skill??null}}};var Su=512*1024;function Dt(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 zr(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 $(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 Q="0.2.22";import{AsyncLocalStorage as xl}from"node:async_hooks";var O=new xl,Ol=5120,Vr=50;function Nl(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 Y(e){if(!e)return;let t=r=>r.length<=Vr?r.slice():r.slice(r.length-Vr),n=r=>Nl(r,Ol);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 Ft=12e4,Kr=2e3,Gr=3,Ml=5e3;function Ne(e,t){return e==="mask"&&(t?.length??0)>0}var Dl=new Set(["approved","resolved"]),Fl=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function Ll(e){return new Promise(t=>setTimeout(t,e))}function $l(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 Me(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=Ft,maskFallback:o=!1,sdkVersion:a,fetchImpl:s=globalThis.fetch,sleep:l=Ll,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)}`,f={Accept:"application/json",...ee(a)};n&&(f.Authorization=`Bearer ${n}`);let m=Date.now()+Math.max(0,i),g=0;for(c(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=m)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 _=new AbortController,I=setTimeout(()=>_.abort(),Ml),A;try{A=await s(d,{method:"GET",headers:f,signal:_.signal})}finally{clearTimeout(I)}if(!A.ok)throw new Error(`HTTP ${A.status} ${A.statusText}`);let S=await A.json();p=$l(S),g=0}catch(_){g+=1;let I=_ instanceof Error?_.message:String(_);if(c(`[VisIQ HITL] Poll failed for decision ${r} (${g}/${Gr}): ${I}`),g>=Gr)return u(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${I}`);await l(Kr);continue}if(p!==null){let _=p.toLowerCase();return Dl.has(_)?(c(`[VisIQ HITL] Decision ${r} approved (${p}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${p})`}):Fl.has(_)?(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(Kr)}}function Z(e){return e??Oe(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??et}function w(e,t){try{console.error(`[VisIQ] FAIL-OPEN (${e}): ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`)}catch{}}function V(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 fe(e){let t=e.getFailMode;return(typeof t=="function"?t.call(e):void 0)??Z()}function re(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 Wr(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&Ne(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}var Hr=new Set;function jt(e){Hr.has(e)||(Hr.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 it(e,t,n){let r=O.getStore(),i=Y(r),o=n.sessionId??r?.session_id,a=await e.evaluate({operations:["retrieval"],agentId:t,...o?{sessionId:o}:{},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 Wr(a)}async function ot(e,t,n){return await e.awaitBundleReady(),it(e,t,n)}function Qr(e,t,n=Z()){switch(t.action){case"allow":case"escalate":return e;case"deny":return null;case"redact":{if(t.redactionRules.length===0)return e;try{return L(e,$(t.redactionRules))}catch{return n==="closed"?null:(w("redact-error","document redaction failed \u2014 document passed UNREDACTED"),e)}}default:return jt(String(t.action)),n==="closed"?null:(w("unknown-retrieval-verb",`unrecognized outcome "${String(t.action)}" \u2014 document passed through`),e)}}var Pl=["pageContent","text","content"];function at(e){let t=e.metadata;if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Object.keys(r).length>0)return r}let n={};for(let[r,i]of Object.entries(e))!Pl.includes(r)&&r!=="metadata"&&(n[r]=i);return n}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=at(a),c=await it(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s.slice(0,500)}),u=Qr(o,c,fe(r));u!==null&&i.push(u)}return i}async function Zr(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await it(n,t,{resourceType:"document",resourceMetadata:{content_preview:e.slice(0,500)},contentPreview:e.slice(0,500)})}catch(i){return fe(n)==="closed"?"[RECALL] Retrieved context blocked \u2014 policy evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":(w("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 L(e,$(r.redactionRules))}catch{return fe(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(w("redact-error","text redaction failed \u2014 text passed UNREDACTED"),e)}}default:return jt(String(r.action)),fe(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(w("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 text passed through`),e)}}var Jr=4,Xr=1e3;function rt(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 ei(e,t,n){let r=[];for(let i of e){let o=i,a=String(o.pageContent??o.text??o.content??""),s={...at(o),content_preview:a.slice(0,500)},l;try{l=await it(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:a.slice(0,500)})}catch(u){if(fe(n)==="closed")continue;w("eval-error",`document retrieval evaluation failed \u2014 document passed through: ${u instanceof Error?u.message:String(u)}`),r.push(i);continue}let c=Qr(i,l,fe(n));c!==null&&r.push(c)}return r}async function $t(e,t,n,r,i){if(r>Jr||i.nodes++>Xr)return e;if(Array.isArray(e)){if(rt(e))return i.matched=!0,ei(e,t,n);let o=[];for(let a of e)o.push(await $t(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 $t(o[s],t,n,r+1,i);return a}return e}async function st(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&rt(e))return ei(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await $t(e,t,n,0,r);if(r.matched)return i}return e}var jl={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function Pt(e,t,n){if(t>Jr||n.n++>Xr)return e;if(Array.isArray(e))return rt(e)?[]:e.map(r=>Pt(r,t+1,n));if(e!==null&&typeof e=="object"){if(rt([e]))return{...jl};let r=e,i={};for(let o of Object.keys(r))i[o]=Pt(r[o],t+1,n);return i}return e}function Lt(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?Pt(e,0,{n:0}):e}function ti(e,t,n=Z()){let r=Wr(t);switch(r.action){case"allow":case"escalate":return e;case"deny":return Lt(e);case"redact":{if(r.redactionRules.length===0)return e;try{return L(e,$(r.redactionRules))}catch{return n==="closed"?Lt(e):(w("redact-error","result redaction failed \u2014 result passed UNREDACTED"),e)}}default:return jt(String(r.action)),n==="closed"?Lt(e):(w("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 result passed through`),e)}}function x(e){return typeof e=="object"&&e!==null?e:null}function ni(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}function Bl(e,t){let n=x(e.metadata),r=n&&typeof n.name=="string"?n.name:void 0;return ni(e.name,e.id,r,t)}function Ul(e){let t=x(e.metadata),n=t&&typeof t.description=="string"?t.description:void 0,r=ni(e.description,n);return r===void 0?void 0:r.slice(0,4e3)}function ql(e){let t=x(e);return t!==null&&("type"in t||"properties"in t||"$schema"in t)}function zl(e){let t=x(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=x(n);if(r===null)return{type:"object"};let i={};for(let o of Object.keys(r))i[o]={};return{type:"object",properties:i}}var Vl=new Set(["default","const","enum","examples","example"]);function Bt(e){if(Array.isArray(e))return e.map(Bt);let t=x(e);if(t===null)return e;let n={};for(let[r,i]of Object.entries(t))Vl.has(r)||(n[r]=Bt(i));return n}function Kl(e){let t;if(ql(e))t=e;else{let n=zl(e);if(n===void 0)return;t=n}try{let n=JSON.stringify(t);if(n.length>2e4){let r=x(t),i=r&&x(r.properties);if(i){let o={};for(let a of Object.keys(i))o[a]={};return{type:"object",properties:o}}return{type:"object"}}return Bt(JSON.parse(n))}catch{return}}function Gl(e){let t=x(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:Kl(n)}function Hl(e,t){let n=x(e);if(n===null)return null;let r=Bl(n,t);if(r===void 0)return null;let i={name:r.slice(0,255)},o=Ul(n);o!==void 0&&(i.description=o);let a=Gl(n);return a!==void 0&&(i.input_schema=a),i}function ie(e){let t=[],n=new Set,r=(i,o)=>{try{let a=Hl(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=x(e);if(i!==null){for(let o of Object.keys(i))if(r(i[o],o),t.length>=200)break}}return t}function Ut(e){try{let t=x(e);if(t===null)return[];let n=[],r=new Set,i=c=>{for(let u of c)!r.has(u.name)&&n.length<200&&(r.add(u.name),n.push(u))};t.tools!==void 0&&i(ie(t.tools));let o=x(t.settings);o&&o.tools!==void 0&&i(ie(o.tools));for(let c of["getTools","listTools"]){let u=t[c];if(typeof u=="function")try{let d=u.call(t);if(d&&typeof d.then=="function")continue;i(ie(d))}catch{}}let a=x(t.nodes)?t:x(t.graph)??x(t.builder)??t,s=x(a.nodes);if(s)for(let c of Object.keys(s)){let u=x(s[c]);if(!u)continue;u.tools!==void 0&&i(ie(u.tools));let d=x(u.bound);d&&d.tools!==void 0&&i(ie(d.tools))}let{agents:l}=t;if(l instanceof Map)for(let c of l.values()){let u=x(c);u&&u.tools!==void 0&&i(ie(u.tools))}return n}catch{return[]}}async function ri(e){let t=x(e);if(!t)return[];let n=[],r=new Set;for(let i of["getTools","listTools"]){let o=t[i];if(typeof o=="function")try{let a=o.call(t);if(!a||typeof a.then!="function")continue;for(let s of ie(await a))r.has(s.name)||(r.add(s.name),n.push(s))}catch{}}return n}import{z as lt}from"zod";var Wl=lt.object({decision:lt.enum(["permit","deny"]),reason:lt.string(),handoff_event_id:lt.string().nullable()}),z=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},oe=class extends z{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},Ql="https://api.visiqlabs.com",Yl=1e4,me=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??Ql,timeoutMs:e.timeoutMs??Yl},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 z(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=Wl.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 ii=new Map;async function oi(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=ii.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 me({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 ii.set(e,o),o}var De=Symbol.for("visiq.orchestrate.wrapped");function Zl(e){return e instanceof z&&typeof e.status=="number"&&e.status>=400&&e.status<500}function ai(e,t){if(!t.agentId||t.agentId.trim()==="")throw new z("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new z("grantToken is required","CONFIG_ERROR");if(e[De]===!0)return e;let n=new me(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(Zl(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 z(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new oe(s.reason,s.handoffEventId)};return new Proxy(e,{get(o,a,s){let l=Reflect.get(o,a,s);return a===De?!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}})}function ci(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t.slice(0,255):null}function si(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){let i=ci(r);if(!(i===null||n.has(i))&&(n.add(i),t.push(i),t.length===32))break}return t.length>0?t:void 0}function li(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=si(t.attested),r=si(t.claimed),i=ci(t.subjectId);if(!(!n&&!r&&i===null))return{...n?{attested:n}:{},...r?{claimed:r}:{},...i!==null?{subjectId:i}:{}}}function ui(e){if(e==null)return;if(typeof e=="function")return()=>{let n;try{n=e()}catch(r){Jl(r);return}return li(n)};let t=li(e);return t===void 0?void 0:()=>t}function Jl(e){let t=e instanceof Error?e.message:String(e);try{console.error(`[VisIQ] IDENTITY-DROPPED: the identity resolver threw (${t}) \u2014 this call carries NO attested principal, so any identity-binding rule will DENY it. Fix the resolver; it must never throw.`)}catch{}}function ae(e){return e?.subjectId?{write:{subject_id:e.subjectId}}:void 0}import{randomUUID as bi}from"node:crypto";var di=Symbol.for("visiq.semantickernel.instrumented");function mi(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 pi(e){let t=e.arguments;return t&&typeof t=="object"&&"arguments"in t&&t.arguments&&typeof t.arguments=="object"?t.arguments:t??{}}function fi(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 K(e,t){e.result&&typeof e.result=="object"?e.result.value=t:e.result={value:t}}function Xl(e){return e.result?.value}function ec(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=pi(o),u=l;try{let p=e.resolveIdentity?.(),_=ae(p),I=await n.evaluate({operations:["action"],agentId:t,...e.hostSessionId?{sessionId:e.hostSessionId}:{},...p?{identity:p}:{},..._?{normalized:_}:{},toolName:s,toolArgs:c,...u!==void 0?{targetResource:u}:{}}),A=re(I);if(!A.allowed){K(o,N({outcome:"deny",code:A.ruleCode??"DENY",reason:A.reason}));return}A.decision==="mask"&&A.argRedactionRules.length>0&&fi(o,L(c,$(A.argRedactionRules)));let S=pi(o),M=pe(s,S,{failMode:r==="closed"?"closed":"open",enforced:I.enforced});if(M.verdict==="block"){K(o,N({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${M.detectors.join(",")})`}));return}M.verdict==="redact"&&(fi(o,M.redacted),w("outbound-secret-redacted",`outbound secret screen redacted ${M.detectors.length} detector(s): ${M.detectors.join(",")}`))}catch(p){if(r==="closed"){K(o,N({outcome:"error",code:"EVAL-ERROR",mechanism:`evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${p instanceof Error?p.message:String(p)}`}));return}w("eval-error",`SK action pre-gate failed for "${s}": ${p instanceof Error?p.message:String(p)}`)}try{let p=await ot(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l},...e.hostSessionId?{sessionId:e.hostSessionId}:{}});if(p.action==="deny"||p.action==="escalate"){K(o,`[RECALL: access denied \u2014 ${p.reason}]`);return}}catch(p){if(r==="closed"){K(o,`[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${p instanceof Error?p.message:String(p)}.`);return}w("eval-error",`SK retrieval pre-gate failed for "${s}": ${p instanceof Error?p.message:String(p)}`)}await a(o);let d=Xl(o),m=(typeof d=="string"?d:(()=>{try{return JSON.stringify(d)??String(d)}catch{return String(d)}})()).slice(0,500),g;try{g=await ot(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l,content_preview:m},contentPreview:m,...e.hostSessionId?{sessionId:e.hostSessionId}:{}})}catch(p){r==="closed"?K(o,"[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):w("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"){K(o,`[RECALL: access denied \u2014 ${g.reason}]`);return}if(g.action==="redact"&&g.redactionRules&&g.redactionRules.length>0&&d!==null&&d!==void 0)try{K(o,L(d,$(g.redactionRules)))}catch(p){r==="closed"?K(o,"[RECALL] Result withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):w("redact-error",`SK result redaction failed for "${s}" \u2014 result passed UNREDACTED: ${p instanceof Error?p.message:String(p)}`)}}}function tc(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 ot(e.unified,e.agentId,{resourceType:"prompt",resourceMetadata:{},contentPreview:i.slice(0,500),...e.hostSessionId?{sessionId:e.hostSessionId}:{}})}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":w("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=L(i,$(o.redactionRules))}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed).":w("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 gi(e,t){let n=e;if(n[di]===!0)return t.onWrap?.(),e;let r=ec(t),i=tc(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[di]=!0,t.onWrap?.()),e}function N(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 ct(e){return e instanceof Error?e.message:String(e)}var nc=/https?:\/\/[^\s"'`,)}\]]+/;function zt(e){let t=e.match(nc);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var ge=Symbol.for("visiq.toolexec.instrumented"),hi=Symbol.for("visiq.agentclone.instrumented"),Vt=Symbol.for("visiq.instrument.deferred");function rc(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}var Kt={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 vi(e){if(e===null||typeof e!="object")return null;let t=e;if(rc(t))return null;if(mi(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}var yi=new WeakMap;function ic(e){let t=yi.get(e);return t||(t=new qr,yi.set(e,t)),t}async function oc(e,t,n,r,i,o,a){let{agentId:s,unified:l}=e,c=Y(i),u=e.resolveIdentity?.(),d=ae(u),f;try{let T=ic(e).observe(t,n);f=Ur(T)}catch{f=void 0}let m=a?nt(a,s):void 0,g=m||f?{...m??{},...f??{}}:void 0,p,_=!1;try{await l.awaitBundleReady();let T=await l.evaluate({operations:a?["action","delegation"]:["action"],agentId:s,toolName:t,toolArgs:n,...g?{context:g}:{},...o?{sessionId:o}:{},...u?{identity:u}:{},...d?{normalized:d}:{},...r!==void 0?{targetResource:r}:{},...c?{telemetry:c}:{}});({enforced:_}=T),p=re(T)}catch(T){let P=T instanceof Error?T.message:String(T);return e.failMode==="closed"?{block:N({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${P} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})}:(w("eval-error",`policy evaluation failed for tool "${t}": ${P}`),{block:null})}if(p.decision==="approval_required"&&p.decisionId){let T=l.getApiKey()??e.apiKey,P=await Me({endpoint:l.getEndpoint()??e.endpoint??"",...T?{apiKey:T}:{},decisionId:p.decisionId,timeoutMs:e.hitlTimeoutMs,sdkVersion:Q});return P.resolution!=="proceed"?{block:N({outcome:"approval_required",code:p.ruleCode??"HITL-BLOCK",reason:p.reason,mechanism:P.reason}),decision:p}:{block:null}}if(!p.allowed)return{block:N({outcome:"deny",code:p.ruleCode??"DENY",reason:p.reason}),decision:p};let I=n,A=!1,S;if(p.decision==="mask"&&p.argRedactionRules&&p.argRedactionRules.length>0)try{let T=$(p.argRedactionRules);I=L(n,T),A=!0,S=p}catch(T){let P=T instanceof Error?T.message:String(T);if(e.failMode==="closed")return{block:N({outcome:"error",code:"MASK-ERROR",mechanism:`argument masking failed: ${P} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})};w("mask-error",`argument masking failed for tool "${t}" \u2014 running with UNMASKED args: ${P}`)}let M=pe(t,I,{failMode:e.failMode==="closed"?"closed":"open",enforced:_});return M.verdict==="block"?{block:N({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"&&(I=M.redacted,A=!0,w("outbound-secret-redacted",`outbound secret screen redacted ${M.detectors.length} detector(s): ${M.detectors.join(",")}`),S??={allowed:!0,decision:"mask",ruleCode:"OUTPUT-BLOCK",reason:"outbound secret redacted before egress",argRedactionRules:[]}),A?{block:null,maskedArgs:I,decision:S}:{block:null})}async function Gt(e,t,n,r,i){let o=O.getStore(),a=o??e.telemetry,s=o?o.session_id:e.runSessionId??e.hostSessionId,l=tt(t,n);l&&we(e.unified,{agentId:e.agentId,sessionId:a?.session_id,...e.framework?{framework:e.framework}:{}},l);let c={agentId:e.agentId,sessionId:a?.session_id,...e.framework?{framework:e.framework}:{}},u=_e(t,n);try{ke(e.unified,c,{toolName:t,...u?{memory:u}:{},argSummary:r.slice(0,512)})}catch(_){V("step-beat",`emit failed for tool "${t}": ${ct(_)}`)}let d=Date.now(),f=await oc(e,t,n,zt(r),a,s,l);if(f.block!==null){try{f.decision&&ue(e.unified,c,{toolName:t,decision:f.decision.decision??"deny",...f.decision.ruleCode?{ruleCode:f.decision.ruleCode}:{},...f.decision.reason?{ruleLabel:f.decision.reason}:{},enforced:!0,harnessMessage:f.block})}catch(_){V("intervention-beat",`emit failed for tool "${t}": ${ct(_)}`)}return f.block}if(f.maskedArgs!==void 0&&f.decision)try{ue(e.unified,c,{toolName:t,decision:f.decision.decision??"mask",...f.decision.ruleCode?{ruleCode:f.decision.ruleCode}:{},...f.decision.reason?{ruleLabel:f.decision.reason}:{},enforced:!0})}catch(_){V("intervention-beat",`emit failed for tool "${t}": ${ct(_)}`)}let m=f.maskedArgs??n,g=await i(m),p=await st(g,e.agentId,e.unified);try{Ae(e.unified,c,{toolName:t,ok:!0,durationMs:Date.now()-d,...te(p)!==void 0?{bytes:te(p)}:{},...ne(p)!==void 0?{itemCount:ne(p)}:{},...u?{memory:u}:{}})}catch(_){V("observation-beat",`emit failed for tool "${t}": ${ct(_)}`)}return p}function Le(e,t,n){let r=e;if(r[ge]){n.onWrap?.();return}if(typeof r.execute!="function")return;let i=r.execute;$e(r,"execute",async function(...a){let s=Dt(a[0]);return Gt(n,t,s,Pe(s),l=>Promise.resolve(i.apply(this,[l,...a.slice(1)])))}),r[ge]=!0,n.onWrap?.()}function ac(e,t,n){let r=e;if(r[ge]){n.onWrap?.();return}if(typeof r.invoke!="function")return;let i=r.invoke;$e(r,"invoke",async function(...a){let s=a[1],l=zr(s),c=typeof s=="string"?s:Pe(l);return Gt(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[ge]=!0,n.onWrap?.()}function sc(e,t){let n=e;if(n[ge]){t.onWrap?.();return}if(typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",o=n.call;$e(n,"call",async function(...s){let l=Dt(s[0]);return Gt(t,i,l,Pe(l),c=>Promise.resolve(o.apply(this,[c,...s.slice(1)])))}),n[ge]=!0,t.onWrap?.()}function Ht(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&Le(r,n,t);return e}function wi(e,t,n){let r={...t,framework:n};switch(n){case"vercel":return lc(e,r);case"mastra":return cc(e,r);case"openai":return ki(e,r);case"llamaindex":return dc(e,r);case"voltagent":return uc(e,r);case"semantic-kernel":return gi(e,r);default:return e}}function lc(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"&&Ht(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=Wt(r.onStepFinish)),ut(e,["generate","stream"],async(o,a)=>(Fe(a,o[0]),o),t.hostSessionId),e}function cc(e,t){let n=e;return yc(n,t)==="deferred"&&(n[Vt]=!0),bc(n,t),ut(e,["generate","stream","generateVNext","streamVNext"],async(r,i)=>{Fe(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=Wt(o.onStepFinish);let a=[...r];return a[1]=o,a},t.hostSessionId),e}function uc(e,t){let n=mc(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;Le(r,typeof i=="string"?i:"unknown",t)}}return ut(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{Fe(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=Wt(o.onStepFinish);let a=[...r];return a[1]=o,a},t.hostSessionId),e}function dc(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"&&sc(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 ut(e,["run"],async(o,a)=>(Fe(a,o[0]),o),t.hostSessionId),gc(e,"runStream",(o,a,s)=>{s||Fe(a,o[0])},t.hostSessionId),e}function ki(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;ac(i,typeof o=="string"?o:"unknown",t)}}return fc(e,t),pc(e,t),e}function pc(e,t){let n=e;if(n[hi])return;let r=n.clone,i=Object.getPrototypeOf(e),o=typeof r=="function"?r:i?.clone;if(typeof o!="function")return;Object.defineProperty(e,"clone",{value:function(...s){let l=o.apply(this,s);return l!==null&&typeof l=="object"&&ki(l,t),l},writable:!0,configurable:!0,enumerable:!1}),n[hi]=!0}function fc(e,t){let n=e;if(n.__visiq_openai_hooks||typeof n.on!="function")return;let r=n.on,{telemetry:i,unified:o}=t;r.call(e,"agent_start",(...a)=>{let s=t.hostSessionId??bi();i.session_id=s,t.runSessionId=s,i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let l=a[2];l!=null&&i.llm_prompts.push(Pe(l).slice(0,5120));try{let c=a[0],{getSystemPrompt:u}=n;typeof u=="function"&&Promise.resolve(u.call(e,c)).then(d=>{typeof d=="string"&&d.trim().length>0&&o.captureCloneMetadata({systemPrompt:d,agentType:"openai_agents"})}).catch(()=>{})}catch{}}),r.call(e,"agent_end",(...a)=>{let s=a[1];typeof s=="string"&&s&&i.llm_responses.push(s.slice(0,5120))}),n.__visiq_openai_hooks=!0}function mc(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 ut(e,t,n,r){let i=e;for(let o of t){if(typeof i[o]!="function")continue;let a=`__visiq_wrapped_${o}`;if(i[a])continue;let s=i[o];i[o]=function(...l){let c=Ii(r);return O.run(c,async()=>{let u=await n(l,c);return s.apply(e,u)})},i[a]=!0}}function gc(e,t,n,r){let i=e;if(typeof i[t]!="function")return;let o=`__visiq_wrapped_${t}`;if(i[o])return;let a=i[t];i[t]=function(...s){let l=O.getStore(),c=l??Ii(r);return n(s,c,l!==void 0),O.run(c,()=>a.apply(e,s))},i[o]=!0}function Wt(e){return t=>{let n=O.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 Fe(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(Pe(n).slice(0,5120))}var hc=["listTools","getTools"];function yc(e,t){for(let n of hc){let r=e[n];if(typeof r!="function")continue;let i;try{i=r.call(e)}catch{continue}if(i&&typeof i=="object")return typeof i.then!="function"?(Ht(i,t),Ai(e,i),"sync"):(i.then(()=>{},()=>{}),_c(e,n,r,t),"deferred")}return"none"}function _c(e,t,n,r){let i=o=>(o&&typeof o=="object"&&(Ht(o,r),Ai(e,o)),o);$e(e,t,function(...o){let a=n.apply(this??e,o);return a&&typeof a.then=="function"?a.then(i):i(a)})}var qt=Symbol.for("visiq.mastra.governedNames"),_i=Symbol.for("visiq.mastra.assembly.instrumented");function Ai(e,t){let n=e[qt];n instanceof Set||(n=new Set,e[qt]=n);for(let r of Object.keys(t))n.add(r)}function bc(e,t){let n=e;if(n[_i])return;let r=Object.getPrototypeOf(e),i=typeof e.convertTools=="function"?e.convertTools:r?.convertTools;if(typeof i!="function")return;let o=a=>{if(!a||typeof a!="object")return a;let s=n[qt],l=s instanceof Set?s:new Set;for(let[c,u]of Object.entries(a))l.has(c)||u!==null&&typeof u=="object"&&Le(u,c,t);return a};$e(n,"convertTools",function(...a){let s=i.apply(this??e,a);return s&&typeof s.then=="function"?s.then(o):o(s)}),n[_i]=!0}function Ii(e){return{session_id:e??bi(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function $e(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function Pe(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Fi(e,t){let n=Cc(t);if(e[De]===!0)return e;let r=Mc(e);if(r==="langchain-executor"||r==="langchain-graph")return le(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,Qt(r,null),n.failMode,{model:Ti(e)}),Ri(e,n),Dc(e,n);let i=vi(e);if(i){le(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,Qt("unknown",i),n.failMode,{model:Ti(e)}),Ri(e,n),Ec(e,n,Qt("unknown",i));let o=0,a=Ui(n);a.onWrap=()=>{o+=1};let s=wi(e,a,i),l=s[Vt]===!0;if(o===0&&!l){let c=0;try{c=Ut(e).length}catch{c=0}if(c>0){let u=`[VisIQ] Detected a ${Kt[i]} that ADVERTISES ${String(c)} 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(u);w("zero-instrument",`advertised ${String(c)} tool(s), instrumented none`),console.warn(u)}else{let u=`[VisIQ] Detected a ${Kt[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(u);console.warn(u)}}return s}if(Uc(e)){let o=process.env.VISIQ_GRANT_ID;return o?zc(e,n,o):Vc(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 wc="https://api.visiqlabs.com",kc="\0",Si=new Map;function Qt(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 Ti(e){try{if(typeof e!="object"||e===null)return;let t=e,n=he(t.model);if(n)return n;let{settings:r}=t;if(typeof r=="object"&&r!==null){let a=he(r.model);if(a)return a}let{llm:i}=t;if(typeof i=="object"&&i!==null){let a=Ei(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=he(s.model)??(typeof l=="object"&&l!==null?Ei(l):void 0);if(c)return c}}return}catch{return}}function Ei(e){return he(e.model)??he(e.modelId)??he(e.model_name)}function he(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 J(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Li(e){try{if(typeof e!="object"||e===null)return;let t=e,{settings:n}=t;if(typeof n=="object"&&n!==null){let s=J(n.instructions);if(s)return s}let r=J(t.instructions);if(r)return r;let i=J(t.systemPrompt);if(i)return i;let o=J(t.system);if(o)return o;let{agents:a}=t;if(a instanceof Map){for(let s of a.values())if(typeof s=="object"&&s!==null){let l=s,c=J(l.systemPrompt)??J(l.instructions)??J(l.system);if(c)return c}}return}catch{return}}async function Ac(e){let t=Li(e);if(t)return t;try{if(typeof e=="object"&&e!==null){let n=e.getInstructions;if(typeof n=="function"){let r=await n.call(e),i=J(r);if(i)return i}}}catch{}}function Ic(e){try{if(!Array.isArray(e))return;for(let t of e){let n=Array.isArray(t)?t:[t];for(let r of n)if(Sc(r)){let i=Tc(r);if(i)return i}}return}catch{return}}function Sc(e){if(typeof e!="object"||e===null)return!1;let t=e,n=t._getType;if(typeof n=="function")try{if(n.call(e)==="system")return!0}catch{}return t.role==="system"||t.type==="system"?!0:e.constructor?.name==="SystemMessage"}function Tc(e){let t=e.content;if(typeof t=="string")return t.trim()||void 0;if(Array.isArray(t))return t.map(r=>r&&typeof r=="object"&&typeof r.text=="string"?r.text:"").join("").trim()||void 0}function le(e,t,n,r,i,o,a){let s=[e??"",t??"",n??"",r??"",o??""].join(kc),l=Si.get(s);return l||(l=new Br(e,t,n,void 0,r,Q,mt),l.registerHostEnvironment(i,a),Si.set(s,l)),o!==void 0&&l.setFailMode(o),l}function Ri(e,t){try{let n=le(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),r=Ut(e);r.length>0&&n.reportToolSurface(r),ri(e).then(i=>{let o=i.filter(a=>!r.some(s=>s.name===a.name));o.length>0&&n.reportToolSurface(o)}).catch(()=>{})}catch{}}function Ec(e,t,n){try{let r=le(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),i=Li(e);if(i){r.captureCloneMetadata({systemPrompt:i,...n?{agentType:n}:{}});return}Ac(e).then(o=>{o&&r.captureCloneMetadata({systemPrompt:o,...n?{agentType:n}:{}})}).catch(()=>{})}catch{}}function Rc(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 Cc(e){let t=e?.agentId??process.env.VISIQ_AGENT_ID??Oc(),n=e?.apiKey??process.env.VISIQ_API_KEY,r=e?.endpoint??process.env.VISIQ_ENDPOINT??(n?wc:void 0),i=typeof e?.sessionId=="string"?e.sessionId.trim():"",o=i.length>0?i.slice(0,255):void 0;return{agentId:t,...o?{sessionId:o}:{},...(()=>{let a=ui(e?.identity);return a?{resolveIdentity:a}:{}})(),apiKey:n,endpoint:r,hitlTimeoutMs:Nc(e?.hitlTimeoutMs),timeoutMs:Rc(e?.timeoutMs),onInstrumentFailure:e?.onInstrumentFailure??xc(),failMode:Z(e?.failMode)}}function xc(){let e=process.env.VISIQ_ON_INSTRUMENT_FAILURE;if(e==="throw")return"throw";if(e==="warn")return"warn"}function Oc(){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=pt.join(t,"package.json");if(dt.existsSync(r)){let o=JSON.parse(dt.readFileSync(r,"utf8"));if(typeof o.name=="string"&&o.name.trim()){let a=e(o.name);if(a)return a}break}let i=pt.dirname(t);if(i===t)break;t=i}}catch{}try{let t=e(Di.hostname());if(t)return t}catch{}return"agent"}function Nc(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 Ft}function Mc(e){let t=e;if(typeof t.invoke=="function"&&t.agent&&Array.isArray(t.tools))return"langchain-executor";if(typeof t.invoke=="function"&&t.nodes&&(t.edges||t.lg_is_pregel===!0||typeof t.builder=="object"&&t.builder!==null&&t.builder.edges))return"langchain-graph";if(typeof t.invoke=="function"){let n=Jt(t);if(n!==t&&n.nodes&&(n.lg_is_pregel===!0||n.channels))return"langchain-graph"}return"unknown"}function Dc(e,t){let n=e,r=le(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),i=Fc(n);for(let l of i)Xt(l,t.agentId,r),Pc(l,t.agentId,r,t),ji(l,r,t);let{nodes:o}=Jt(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);w("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=Zt(Ci(c,t.sessionId)),d=Ni(t.agentId,r),f=c?.callbacks??[];return O.run(u,()=>s.call(this,l,{...c,callbacks:[...f,d]}))},typeof n.stream=="function"){let l=n.stream;n.stream=function(c,u){let d=Zt(Ci(u,t.sessionId)),f=Ni(t.agentId,r),m=u?.callbacks??[];return O.run(d,()=>l.call(this,c,{...u,callbacks:[...m,f]}))}}return e}function Jt(e){if(e.nodes&&typeof e.nodes=="object")return e;for(let t of["graph","builder"]){let n=e[t];if(n&&typeof n=="object"&&n.nodes)return n}return e}function Fc(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}=Jt(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 Ci(e,t){let n=o=>{if(typeof o!="string")return null;let a=o.trim();return a.length>0?a.slice(0,255):null},r=n(t);if(r)return r;let i=e?.configurable;if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let o=i,a=n(o.thread_id)??n(o.session_id);if(a)return a}return Mi()}function Zt(e){return{session_id:e??Mi(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Xt(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 xi(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 xi(s,t,String(a),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&Xt(r.retriever,t,n)}}var Lc=Symbol.for("visiq.operations"),$c=new Set(["action","retrieval","delegation"]);function $i(e){if(typeof e!="object"||e===null)return;let t=e[Lc]??e.visiqOperations;if(!Array.isArray(t))return;let n=t.filter(r=>typeof r=="string"&&$c.has(r));return n.length>0?Array.from(new Set(n)):void 0}function Pc(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(R=>R.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),d=l.some(R=>c.has(R)),f=u.has(l[0]??""),m=d||f,g=["update","delete","create","archive","insert","remove"],p=l.some(R=>g.some(b=>R.length>b.length&&R.endsWith(b))),I=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!m&&!p,A=$i(i),S=A?.includes("retrieval")??!1;if(A!==void 0&&!S||!(s||I||S))return;let P=A?S&&A.includes("action"):d||p;if(!P)if(s)Xt(i.retriever,t,n);else{let R=globalThis,b=Symbol.for("visiq.recall.closureRetrieverWarned"),U=R[b]??=new Set;U.has(a)||(U.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 X=i.func;P?(i[Pi]=!0,i.func=async function(...R){await n.awaitBundleReady();let b=R[0],U=typeof b=="object"&&b!==null?b:{input:b},ye=typeof U.query=="string"?U.query:void 0,v=O.getStore(),k=Y(v),D;try{let F=r?.resolveIdentity?.(),G=ae(F);D=await n.evaluate({operations:["retrieval","action"],agentId:t,...v?.session_id?{sessionId:v.session_id}:{},...F?{identity:F}:{},...G?{normalized:G}:{},toolName:a||"unknown",toolArgs:U,resourceType:"document",resourceMetadata:{},...ye!==void 0?{query:ye}:{},...k?{telemetry:k}:{}})}catch(F){let G=F instanceof Error?F.message:String(F);return Z(r?.failMode)==="closed"?N({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${G} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(w("eval-error",`policy evaluation failed for hybrid tool "${a||"unknown"}": ${G}`),X.apply(this,R))}let C=re(D),ft=Ne(C.hitlFallback,C.argRedactionRules),en=R,tn=()=>{try{return en=[L(U,$(C.argRedactionRules)),...R.slice(1)],null}catch{return Z(r?.failMode)==="closed"?N({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(w("mask-error",`argument masking failed for tool "${a||"unknown"}" \u2014 running with UNMASKED args`),null)}};if(C.decision==="approval_required"&&C.decisionId&&r){let F=await Me({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:C.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:ft,sdkVersion:Q});if(F.resolution==="mask"){let G=tn();if(G)return G}else if(F.resolution!=="proceed")return N({outcome:"approval_required",code:C.ruleCode??"HITL-BLOCK",reason:C.reason,mechanism:F.reason})}else if(!C.allowed)return N({outcome:"deny",code:C.ruleCode??"DENY",reason:C.reason});if(C.decision==="mask"&&C.argRedactionRules.length>0){let F=tn();if(F)return F}let Vi=await X.apply(this,en);return ti(Vi,D,r?.failMode)}):i.func=async function(...R){let b=await X.apply(this,R);return typeof b=="string"?Zr(b,t,n):st(b,t,n)},i[o]=!0}var Pi=Symbol.for("visiq.hybrid.instrumented");async function xi(e,t,n,r){return Yr(e,t,n,r)}var Oi=["invoke","call","_call"],se=new vc;function ji(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[Pi]||$i(r)?.every(c=>c==="retrieval")||!Oi.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,f,m)=>{let g=se.getStore();if(g!==void 0&&g.gateKey===s&&!g.entered.has(m))return g.entered.add(m),c.call(u,d,...f);let p;if(typeof d=="string")p=d;else{let v=d?.input;p=v!=null?String(v):JSON.stringify(d)??""}let _=O.getStore(),I=Y(_),A=typeof d=="object"&&d!==null?d:{input:p},S=tt(a,A);S&&we(t,{agentId:o,sessionId:_?.session_id,framework:"langchain"},S);let M={agentId:o,sessionId:_?.session_id,framework:"langchain"},T=_e(a,A);try{ke(t,M,{toolName:a,...T?{memory:T}:{},argSummary:p.slice(0,512)})}catch(v){V("step-beat",`emit failed for tool "${a}": ${Yt(v)}`)}let P=Date.now(),X=async v=>{let k=await v();try{Ae(t,M,{toolName:a,ok:!0,durationMs:Date.now()-P,...te(k)!==void 0?{bytes:te(k)}:{},...ne(k)!==void 0?{itemCount:ne(k)}:{},...T?{memory:T}:{}})}catch(D){V("observation-beat",`emit failed for tool "${a}": ${Yt(D)}`)}return k},R=(v,k,D,C)=>{try{ue(t,M,{toolName:a,decision:v,...k?{ruleCode:k}:{},...D?{ruleLabel:D}:{},enforced:!0,...C?{harnessMessage:C}:{}})}catch(ft){V("intervention-beat",`emit failed for tool "${a}": ${Yt(ft)}`)}};await t.awaitBundleReady();let b,U=!1;try{let v=n.resolveIdentity?.(),k=ae(v),D=await t.evaluate({operations:S?["action","delegation"]:["action"],agentId:o,..._?.session_id?{sessionId:_.session_id}:{},...v?{identity:v}:{},...k?{normalized:k}:{},toolName:a,toolArgs:A,targetResource:zt(p),...I?{telemetry:I}:{},...S?{context:nt(S,o)}:{}});({enforced:U}=D),b=re(D)}catch(v){let k=v instanceof Error?v.message:String(v);return n.failMode==="closed"?N({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${k} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(w("eval-error",`policy evaluation failed for tool "${a}": ${k}`),se.run({gateKey:s,entered:new Set([m])},()=>c.call(u,d,...f)))}let ye=v=>{let k=pe(a,v,{failMode:n.failMode==="closed"?"closed":"open",enforced:U});if(k.verdict==="block"){let C=N({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${k.detectors.join(",")})`});return R("deny","OUTPUT-BLOCK","outbound content carried a live secret",C),C}let D=v;return k.verdict==="redact"&&(D=k.redacted,w("outbound-secret-redacted",`outbound secret screen redacted ${k.detectors.length} detector(s): ${k.detectors.join(",")}`),R("mask","OUTPUT-BLOCK","outbound secret redacted before egress")),X(()=>se.run({gateKey:s,entered:new Set([m])},()=>c.call(u,D,...f)))};if(b.decision==="approval_required"&&b.decisionId){let v=Ne(b.hitlFallback,b.argRedactionRules),k=await Me({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:b.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:v,sdkVersion:Q});if(k.resolution==="proceed")return X(()=>se.run({gateKey:s,entered:new Set([m])},()=>c.call(u,d,...f)));if(k.resolution==="mask")try{let C=L(d,$(b.argRedactionRules));return R("mask",b.ruleCode,b.reason),X(()=>se.run({gateKey:s,entered:new Set([m])},()=>c.call(u,C,...f)))}catch{return n.failMode==="closed"?N({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(w("mask-error",`HITL mask fallback failed for tool "${a}" \u2014 running with UNMASKED args`),se.run({gateKey:s,entered:new Set([m])},()=>c.call(u,d,...f)))}let D=N({outcome:"approval_required",code:b.ruleCode??"HITL-BLOCK",reason:b.reason,mechanism:k.reason});return R("approval_required",b.ruleCode,b.reason,D),D}if(!b.allowed){let v=N({outcome:"deny",code:b.ruleCode??"DENY",reason:b.reason});return R("deny",b.ruleCode,b.reason,v),v}if(b.decision==="mask"&&b.argRedactionRules.length>0)try{let v=L(d,$(b.argRedactionRules));return R("mask",b.ruleCode,b.reason),ye(v)}catch{return n.failMode==="closed"?N({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(w("mask-error",`argument masking failed for tool "${a}" \u2014 running with UNMASKED args`),se.run({gateKey:s,entered:new Set([m])},()=>c.call(u,d,...f)))}return ye(d)};for(let c of Oi){if(typeof r[c]!="function")continue;let u=r[c];r[c]=function(d,...f){return l(u,this,d,f,c)}}r[i]=!0}function Yt(e){return e instanceof Error?e.message:String(e)}function jc(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 Bc(e,t){let n=(m,g)=>{if(!m||typeof m!="object")return;let p=m[g];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"),f=s!==void 0?Math.max(0,s-(u??0)-(d??0)):void 0;return{...f!==void 0?{tokensIn:f}:{},...l!==void 0?{tokensOut:l}:{},...u!==void 0?{cacheRead:u}:{},...d!==void 0?{cacheWrite:d}:{}}}function Ni(e,t){let n=(r,i,o,a)=>{let s=jc(r,i,o);s&&(a.llm_model=s,t.captureCloneMetadata({model:s,agentType:"langchain"}))};return{name:"VisiqHandler",handleChatModelStart:async(r,i,o,a,s,l,c)=>{let u=O.getStore();if(u){try{if(Array.isArray(i))for(let d of i){let f=Array.isArray(d)?d:[d];for(let m of f){let g=m?.content;u.llm_prompts.push(typeof g=="string"?g:JSON.stringify(g??m))}}}catch{}n(r,s,c,u);try{let d=Ic(i);d&&t.captureCloneMetadata({systemPrompt:d,agentType:"langchain"})}catch{}}},handleLLMStart:async(r,i,o,a,s,l,c)=>{let u=O.getStore();u&&(u.llm_prompts.push(...i),n(r,s,c,u))},handleLLMEnd:async r=>{let i=O.getStore();if(!i)return;let a=r?.generations?.[0]?.[0],s=typeof a?.text=="string"?a.text:"";s&&i.llm_responses.push(s);try{let l=r?.llmOutput,c=a?.message&&typeof a.message=="object"?a.message:void 0,u=Bc(l,c);if(!u&&!s)return;let d=c?.tool_calls,f=typeof l?.model=="string"?l.model:void 0,m=i.llm_model??f;await t.awaitBundleReady(),yt(t,{agentId:e,sessionId:i.session_id,framework:"langchain"},{...s?{texts:[s]}:{},...u?{usage:u}:{},...m?{model:m}:{},final:!(Array.isArray(d)&&d.length>0)})}catch{}},handleAgentAction:async r=>{let i=O.getStore();if(!i)return;let o=typeof r.log=="string"?r.log:"";o&&i.agent_reasoning.push(o)},handleRetrieverStart:async(r,i,o)=>{let a=O.getStore();a&&a.retrieverQueries.set(o,i??"")},handleRetrieverEnd:async(r,i)=>{let o=O.getStore();if(!o)return;let a=o.retrieverQueries.get(i)??"";if(o.retrieverQueries.delete(i),!Array.isArray(r))return;let s=Y(o);for(let l of r){let c=l,u=String(c.pageContent??c.text??c.content??""),d=at(c);await t.evaluate({operations:["retrieval"],agentId:e,resourceType:"document",resourceMetadata:d,query:a,contentPreview:u.slice(0,500),...s?{telemetry:s}:{}})}},handleRetrieverError:async(r,i)=>{let o=O.getStore();o&&o.retrieverQueries.delete(i)}}}var Bi=["_call","execute","call","run","invoke"];function Uc(e){let t=e;for(let n of Bi)if(typeof t[n]=="function")return!0;return!1}function qc(e){return e instanceof oe?!0:e instanceof z?typeof e.status=="number"&&e.status>=400&&e.status<500:!1}function zc(e,t,n){let r=null,i=null,o=!1,a=async()=>{if(r)return r;if(i)throw new oe(`Failed to bootstrap grant ${n}: ${i.message}`,null);let s;try{s=await oi(t.agentId,n)}catch(l){throw o=qc(l),o&&(i=l instanceof Error?l:new Error(String(l))),new oe(`Failed to bootstrap grant ${n}: ${l instanceof Error?l.message:String(l)}`,null)}return r=ai(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===De)return!0;let u=Reflect.get(s,l,c);return typeof u!="function"||typeof l!="string"||!Bi.includes(l)?u:async function(...d){let f;try{f=await a()}catch(g){if(o||t.failMode==="closed")throw g;return w("grant-bootstrap",`grant ${n} bootstrap failed: ${g instanceof Error?g.message:String(g)}`),u.call(this,...d)}return f[l].call(f,...d)}}})}function Vc(e,t){let n=le(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode);ji(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";Le(e,i,Ui(t))}return e}function Ui(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}:{},...e.sessionId?{hostSessionId:e.sessionId}:{},...e.resolveIdentity?{resolveIdentity:e.resolveIdentity}:{},telemetry:Zt(e.sessionId)}}async function qi(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 me({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 je=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),ce(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return ce(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return ce(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return ce(this.transport,"POST","/api/discovery/fleet/stop")}};var Be=class{constructor(t){this.transport=t}transport;connectAws(t){return ce(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function Kc(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 je(r),integrations:new Be(r)}}async function ce(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,o={...ee(Q)};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 zi=Fi;zi.delegate=qi;var Qd=zi;export{et as DEFAULT_FAIL_MODE,je as FleetClient,Be as IntegrationsClient,Kc as createVisiqClient,qi as delegate,Oe as normalizeFailMode,Qd as visiq};
10
+ -----END PRIVATE KEY-----`,template:{pattern:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"13\u201319 digit primary account numbers (PCI-DSS), token-fenced, issued by a card network at that length (Visa, Mastercard, Amex, Discover, JCB, UnionPay, Diners, Maestro and the regional networks), and Luhn-valid. Collision rate: MEASURED 3.0% of benign 16-digit runs: the network table admits ~30% of 16-digit prefixes and Luhn leaves ~1 in 10 of those. A 13-digit run is only ever a Visa card, so epoch-millisecond timestamps never match. Default-ON because PCI-DSS makes masking mandatory.",category:"financial",example:"4242 4242 4242 4242",template:{pattern:E.pan,mode:"partial",keepLast:4,templateOnly:{reason:"A rego rule cannot run Luhn or the card-network table, so the rule masks EVERY token-fenced 13-19 digit run (grouped or not): the floor's regex without the two validators that make it precise. More than 9 in 10 of those are not card numbers.",examples:["4242 4242 4242 4243","4242424242424241"],measuredOverMaskRate:.924}},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible. Collision rate: MEASURED 1.0% \u2014 mod-97 leaves ~1 in 97, the most precise detector on this floor alongside br_cpf.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:E.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:E.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:E.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:E.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:E.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},uk_nino:{id:"uk_nino",label:"UK National Insurance numbers",description:"UK NINOs (e.g. AB 12 34 56 C). DEFAULT-OFF \u2014 NO CHECKSUM. Precision comes only from the issued alphabet and the never-issued administrative prefixes (BG, GB, NK, KN, TN, NT, ZZ), so roughly half of tokens already shaped 2-letters/6-digits/[A-D] validate. All-lowercase candidates are rejected (git short SHAs), but that does NOT exclude uppercase business identifiers \u2014 serial, part, batch, PO, coupon and asset tags share the shape exactly and were measured being masked. Opt in when UK NINOs are expected in your traffic.",category:"pii",example:"AB 12 34 56 C",template:{pattern:"\\b(?:[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Za-ceghj-npr-tw-z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-Da-d]|[A-CEGHJ-PR-TW-Za-ceghj-pr-tw-z][A-CEGHJ-NPR-TW-Z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-Da-d]|[A-CEGHJ-PR-TW-Za-ceghj-pr-tw-z][A-CEGHJ-NPR-TW-Za-ceghj-npr-tw-z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-D])\\b",mode:"full",templateOnly:{reason:"uk_nino has no checksum, but the floor still rejects the seven NEVER-ISSUED administrative prefixes (BG GB NK KN TN NT ZZ). A rego rule cannot express that exclusion without enumerating hundreds of letter pairs (RE2 has no lookahead), so the rule masks those too.",examples:["NK 12 34 56 A","ZZ 12 34 56 C"],measuredOverMaskRate:.019}},defaultEnabled:!1},in_aadhaar:{id:"in_aadhaar",label:"Aadhaar numbers (India)",description:"12-digit UIDAI Aadhaar numbers, Verhoeff-checksum validated and constrained to the issued 2-9 leading digit. Keeps the last 4 visible. Collision rate: MEASURED 10.0% of benign 12-digit ids starting 2-9 (order/transaction numbers): Verhoeff leaves ~1 in 10. Looser than pan (3.0%, card-network table plus Luhn) and well behind iban (1.0%); it stays default-ON because the two US identifiers this floor has always shipped, ssn and us_ein, collide at 100%.",category:"pii",example:"2345 6789 0124",template:{pattern:"\\b[2-9]\\d{3}(?:[ -]\\d{4}[ -]?\\d{4}|\\d{4}[ -]\\d{4})\\b",mode:"partial",keepLast:4,floorOnly:{reason:"The floor accepts the entirely UNPUNCTUATED 12-digit form because Verhoeff gates it (~1 in 10 survive). A rego rule cannot run Verhoeff, so a bare \\d{12} in a rule would mask every 12-digit order id and E.164 Indian mobile number in the tenant. The rule requires at least one printed separator \u2014 every half-punctuated form is covered; only the bare digit run stays floor-only.",examples:["234567890124","id=234567890124"]},templateOnly:{reason:"A rego rule cannot run the Verhoeff checksum, so the rule masks EVERY 4-4-4 grouping that starts 2-9 \u2014 including the ~9 in 10 that are not Aadhaar numbers at all.",examples:["2345 6789 0125","2345-6789-0123"],measuredOverMaskRate:.903}},defaultEnabled:!0},in_pan_tax:{id:"in_pan_tax",label:"India PAN (tax ID)",description:"India Permanent Account Number \u2014 the income-tax id (ABCPE1234F), NOT a payment-card PAN. NO CHECKSUM: the only discriminator is the holder-type letter in position 4, which removes just 15 of 26 possibilities in one position, so roughly 4 in 10 uniform 5-letter/4-digit/1-letter tokens validate. DEFAULT-OFF for that reason \u2014 an uppercase SKU or part number of the same shape is masked, and nothing in the value distinguishes it.",category:"financial",example:"ABCPE1234F",template:{pattern:E.in_pan_tax,mode:"full"},defaultEnabled:!1},br_cpf:{id:"br_cpf",label:"CPF numbers (Brazil)",description:"Brazilian CPF, closed by TWO independent mod-11 check digits. Collision rate: MEASURED 1.0% of benign 11-digit runs (~1-in-100) \u2014 the most precise detector on this floor, alongside iban. Repdigits are rejected. Keeps the last 2 visible.",category:"pii",example:"123.456.789-09",template:{pattern:"\\b\\d{3}(?:\\.\\d{3}\\.?\\d{3}-?\\d{2}|\\d{3}(?:\\.\\d{3}-?\\d{2}|\\d{3}-\\d{2}))\\b",mode:"partial",keepLast:2,floorOnly:{reason:"The floor accepts the entirely bare 11-digit form because TWO mod-11 check digits gate it (~1 in 100 survive). A rego rule cannot run mod-11, so a bare \\d{11} in a rule would mask every 11-digit identifier in the tenant. The rule requires at least one printed separator; the bare form stays floor-only.",examples:["11144477735","ref 11144477735","12345678909"]},templateOnly:{reason:"A rego rule cannot run the two mod-11 check digits, so the rule masks EVERY punctuated 3-3-3-2 digit grouping \u2014 including the ~99 in 100 that are not CPFs.",examples:["123.456.789-10","111.444.777-34"],measuredOverMaskRate:.995}},defaultEnabled:!0},es_dni_nie:{id:"es_dni_nie",label:"DNI / NIE numbers (Spain)",description:"Spanish national ID (8 digits + letter) and foreigner ID (X/Y/Z + 7 digits + letter), validated by the mod-23 check letter. Collision rate: MEASURED 4.0% of benign 8-digit-plus-letter tokens (invoice/order numbers with a suffix letter): mod-23 leaves ~1 in 23. More precise than in_aadhaar (10.0%); behind pan (3.0%), br_cpf (1.0%) and iban (1.0%).",category:"pii",example:"12345678Z",template:{pattern:E.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:E.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:E.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:E.us_phone,mode:"partial",keepLast:4},defaultEnabled:!1},person_name:{id:"person_name",label:"Person names",description:"Personal names, located by an on-device n-gram model rather than a pattern - a name has no written shape to anchor on. MEASURED on the committed corpora (experiments/browser-context-firewall/eval): clinical chat partial precision/recall 0.817/0.817; ordinary prose 0.177/0.750, i.e. on general text most flagged spans are places, works and organisations rather than people. Runs only where a model is supplied.",category:"pii",example:"Jane Doe",template:{pattern:ys,mode:"full"},defaultEnabled:!0},ipv4:{id:"ipv4",label:"IPv4 addresses",description:"Dotted-quad IPv4 addresses. DEFAULT-OFF (common + usually benign).",category:"identifier",example:"203.0.113.42",template:{pattern:E.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:E.mac_address,mode:"full"},defaultEnabled:!1}},it=Object.freeze(Object.fromEntries(Bt.map(e=>{let t=vs[e];return[e,{...t,template:{...t.template,pattern:es(Nt(t.template.pattern))}}]})));var fd=new Set(Bt.filter(e=>!it[e].defaultEnabled));function ws(e,t){let n=new Set;for(let r of Bt)(it[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function ks(e,t,n,r,i){let o=Ir.filter(f=>!n.has(f.name));if(o.length===0)return e;let a=Fe(e,Ft,n),s=(f,p)=>{for(let m=f;m<p;m++)if(a[m]==="\0"&&e[m]!=="\0")return!0;return!1},l=[];for(let f of o){let p=f.detect(e,i).filter(m=>m.start>=0&&m.end<=e.length&&m.start<m.end&&!s(m.start,m.end));if(p.length!==0){r?.(f.name);for(let m of p)l.push({start:m.start,end:m.end,value:m.value,id:f.name})}}if(l.length===0)return e;l.sort((f,p)=>f.start-p.start||f.end-p.end);let c=De(t),u="",d=0;for(let f of l)f.start<d||(u+=e.slice(d,f.start),u+=c(e.slice(f.start,f.end),f.id),d=f.end);return u+e.slice(d)}function Fe(e,t,n,r,i){if(typeof e!="string"||e.length===0)return e;let o=De(t),a=i===void 0?e:ks(e,t,n,r,i);for(let{name:s,re:l}of Sr){let c=s;n.has(c)||(a=a.replace(l,u=>(r?.(c),o(u,c))))}for(let{name:s,re:l,normalize:c,validate:u}of Tr)n.has(s)||(a=Fs(a,l,c,u,t,s,r));return a}function De(e){return typeof e=="function"?e:()=>e}var Ft=e=>"\0".repeat(e.length);function As(e,t,n,r,i){if(typeof e!="string"||e.length===0)return e;let o=Lt(e);if(o.length===0)return Fe(e,t,n,r,i);let a=new Set,s=p=>{a.add(p)},l=Fe(e,Ft,n,s,i),c=!0,u=new Array(e.length).fill(!1);for(let p=0;p<e.length;p++)u[p]=l[p]==="\0"&&e[p]!=="\0";for(let p of o){let m=Fe(p.text,Ft,n,s);for(let g=0;g<p.text.length;g++)if(!(m[g]!=="\0"||p.text[g]==="\0"))for(let _=p.offsets[g];_<p.offsets[g+1];_++)u[_]||(u[_]=!0,c=!1)}if(c)return Fe(e,t,n,r,i);for(let p of a)r?.(p);let d="",f=0;for(;f<e.length;){if(!u[f]){d+=e[f],f++;continue}let p=f;for(;f<e.length&&u[f];)f++;d+=De(t)(e.slice(p,f))}return d}function Me(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var rr=new Map;function Is(e){let t=rr.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),rr.set(e.source,t)),t}var Ss=4096,Ts=64,ir=null;function Es(e){return ir!==null?ir:Ss+e.length*Ts}var Er=!1,j={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},Rr={spanBudget:0,depthCap:0};function Rs(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:Es(e),exhausted:!1}}function Cr(e,t,n,r,i,o,a){j.spanCalls++;let s=t*a.stride+n.length,l=Er?void 0:a.chosen.get(s);if(l!==void 0)return l;if(a.budget<=0)return a.exhausted=!0,null;a.budget--,j.spanMisses++;let c=Cs(e,t,n,r,i,o,a);return a.chosen.set(s,c),c}function Cs(e,t,n,r,i,o,a){let s=Is(r),l=[];for(let u=n.length-1;u>=1;u--)if(Me(n[u])){let d=n.slice(0,u);s.test(d)&&l.push(d)}let c=Me(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(o(i(u),u)&&!Os(e,t,u,r,i,o,a))return u;return null}var or=new Map;function xs(e){let t=or.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),or.set(e.source,t)),t}function Os(e,t,n,r,i,o,a){j.cutCalls++;let s=t*a.stride+n.length,l=Er?void 0:a.cuts.get(s);if(l!==void 0)return l;if(a.budget<=0)return a.exhausted=!0,!0;a.budget--,j.cutMisses++;let c=Ns(e,t,n,r,i,o,a);return a.cuts.set(s,c),c}function Ns(e,t,n,r,i,o,a){let s=t+n.length,l=xs(r);for(let c=1;c<n.length;c++){if(Me(n[c])||!Me(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 f=Cr(e,u,d[0],r,i,o,a);if(f!==null&&u+f.length>s&&Me(e[u+f.length]))return!0}return!1}function Fs(e,t,n,r,i,o,a){let s=De(i);t.lastIndex=0;let l="",c=0,u=Rs(e),d=j.spanMisses+j.cutMisses,f;for(;(f=t.exec(e))!==null;){let p=f[0],m=f.index;if(p.length===0){t.lastIndex=m+1;continue}let g;try{g=Cr(e,m,p,t,n,r,u)}catch(_){if(_ instanceof RangeError&&/call stack/i.test(_.message))u.exhausted=!0,g=null;else throw _}if(u.exhausted)return j.budgetExhausted++,Rr.spanBudget++,ar(d),l+e.slice(c,m)+s(e.slice(m),o);if(g!==null)a?.(o),l+=e.slice(c,m)+s(g,o),c=m+g.length,t.lastIndex=c;else{let _=p.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=_===-1?m+p.length:m+1+_+1}if(t.lastIndex>e.length)break}return ar(d),l+e.slice(c)}function ar(e){let t=j.spanMisses+j.cutMisses-e;t>j.maxMissesInAPass&&(j.maxMissesInAPass=t)}function Ut(e,t=rt,n,r){return Ds(e,t,ws(n,r))}var Ms=256;function Ds(e,t,n,r){let i=De(t),o=new Set,a=!n.has("pan"),s=c=>{o.add(c)},l=(c,u)=>{if(u>Ms)return Rr.depthCap++,typeof t=="string"?t:rt;if(typeof c=="string")return As(c,t,n,s,r);if(typeof c=="number"&&Number.isInteger(c)&&c>0){if(!a)return c;let d=String(c);if(d.length>=13&&d.length<=19&&Pt(d)){o.add("pan");let f=i(d,"pan");return f===d?rt:f}return c}if(Array.isArray(c))return c.map(d=>l(d,u+1));if(c!==null&&typeof c=="object"){let d=c,f={};for(let p of Object.keys(d))f[p]=l(d[p],u+1);return f}return c};return{value:l(e,0),detectors:[...o].sort()}}function xr(e,t=rt){return Ut(e,t).value}function Ls(e){let{value:t,detectors:n}=Ut(e),r=n.some(i=>it[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function $s(e,t){let{blocked:n,redacted:r,detectors:i}=Ls(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 Ps(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var js=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function Bs(e){return js.has(Ps(e))}function pe(e,t,n){return n.enforced&&Bs(e)?$s(t,{failMode:n.failMode}):{verdict:"allow",redacted:t,detectors:[]}}var Us=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Or=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"}),zs=new RegExp(`[${Object.keys(Or).join("")}]`,"gu"),qs=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),Nr="\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",Vs=Object.freeze(Object.fromEntries([...Nr].map((e,t)=>[e,String.fromCharCode(97+t)]))),Gs=new RegExp(`[${Nr}\u2800]`,"g"),Fr=/[⠀-⣿]/;function Ks(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 Hs(e){return e.replace(Us,"")}function Mr(e){return e.replace(zs,t=>Or[t]??t)}function Ws(e){return e.replace(/[4@31!05$79(8]/g,t=>qs[t]??t)}function Ys(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 Qs(e){return Fr.test(e)?e.replace(Gs,t=>t==="\u2800"?" ":Vs[t]??t):e}function sr(e){let t;try{t=Ks(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=Hs(t),t=Mr(t),t}var Zs=/^[A-Za-z0-9+/]{16,}={0,2}$/,Js=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,lr=/[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 Dr=new TextDecoder("utf-8",{fatal:!1});function Lr(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=Dr.decode(n);return t===r?[t]:[r,t]}function Xs(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=Dr.decode(n);return r===i?[r]:[i,r]}function cr(e){let t=e.trim(),n=[];if(Js.test(t))for(let r of Xs(t))n.push({decoded:r,textiness:Mt(r)});if(Zs.test(t)&&t.length%4===0)for(let r of Lr(t))n.push({decoded:r,textiness:Mt(r)});return n}function ur(e,t){let n=[],r;for(lr.lastIndex=0;(r=lr.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let o of Lr(i))n.push({decoded:o,textiness:Mt(o)})}return n}var el=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function $r(e,t=el){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=p=>{p.length>0&&p.length<=r&&a.add(p)},l=!1,c=!1,u=0,d=0,f=[{s:e,depth:0}];for(;f.length>0;){if(u>=i){c=!0;break}let p=f.pop();if(p===void 0)break;let{s:m,depth:g}=p;if(m.length>r){c=!0;continue}u++,g>d&&(d=g);let _=sr(m);s(_);let w=Ws(_);if(w!==_&&s(w),s(Ys(_)),Fr.test(m)&&s(Qs(_)),g>=n){let v=sr(m);(cr(v).length>0||ur(v,o).length>0)&&(c=!0);continue}let S=[...cr(_),...ur(_,o)];for(let v of S){if(l=!0,v.decoded.length>r){c=!0;continue}v.textiness>=.85&&v.decoded!==_?f.push({s:v.decoded,depth:g+1}):s(v.decoded)}}return{views:[...a],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:d}}var Pr=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],tl=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),nl=8,rl=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),dr=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function il(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||rl.has(i)&&dr(t[r-1])&&dr(t[r+1])&&(n++,n>=nl))return!0}return!1}var ol=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function al(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(ol.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var sl=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function ll(e){for(let t of sl)if(e>=t.lo&&e<=t.hi)return t.name;return null}function cl(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=ll(o.codePointAt(0));if(a===null){i=!1;break}a==="latin"?n++:Mr(o)!==o&&r++}if(i&&n>0&&r>0)return!0}return!1}var fr=Object.freeze({signals:[],contributes:!1});function ul(e){if(typeof e!="string"||e.length===0)return{...fr,signals:[]};let t=new Set;try{il(e)&&t.add("hidden_text_carrier"),al(e)&&t.add("injected_turn_boundary"),cl(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=$r(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...fr,signals:[]}}return{signals:[...Pr.filter(n=>t.has(n))],contributes:tl.some(n=>t.has(n))}}var ot=[{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 pr(e){return typeof e!="string"||e.length===0?[]:ot.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function dl(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(pr(e)),{views:n}=$r(e);for(let r of n)for(let i of pr(r))t.add(i);return ot.filter(r=>t.has(r.name)).map(r=>r.name)}function fl(e){let t=new Set,n=new Set,r=!1,i=o=>{if(o!=null){if(typeof o=="string"){for(let s of dl(o))t.add(s);let a=ul(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:ot.filter(o=>t.has(o.name)).map(o=>o.name),structural:Pr.filter(o=>n.has(o))}}function pl(e){return fl(e).matched}var pd=ot.map(e=>e.name);var ml=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var gl="i:injection";function jr(e){let t=new Set,n=[];if(e.content!==void 0&&e.content!==null){let{detectors:o}=Ut(e.content);for(let a of o){n.push(a);let s=it[a]?.category;s&&t.add(`c:${s}`)}pl(e.content)&&t.add(gl)}let r=e.resourceMetadata??{},i=r.source_trust;return(r.untrusted_source===!0||typeof i=="string"&&ml.has(i.toLowerCase()))&&t.add("i:untrusted"),{labels:[...t].sort(),detectors:n}}var xt="(?: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))",md=[{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${xt}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${xt}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${xt}\\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}],mr="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",hl=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${mr}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${mr}|programming|training))`,yl="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",gr="(?:\\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)",_l="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",gd=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${yl}${hl}\\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}?${gr}`,"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+(?:${_l}\\b|[\\s\\S]{0,40}?${gr})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var hd=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var Q=e=>`[^.!?;\\n]{0,${e}}?`,bl=["\\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("|"),Br="(?: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)",yd=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${bl})\\s${Q(40)}\\b${Br}\\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")}]),_d=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${Br}\\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 Ne=e=>`[^.!?;\\n]{0,${e}}?`,bd=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${Ne(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${Ne(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${Ne(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${Ne(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${Ne(30)}\\b(?:external|customer|customers|public|press|social\\s+media|third[\\s-]party|prospect|prospects)\\b`,"i"),/\b(?:cold\s+outreach|marketing\s+blast|phishing\s+email|press\s+release)\b/i],purposeFunctions:["marketing","sales","customer_support"],purposePatterns:[/\b(?:marketing|campaign|outreach|email\s+assistant|support|customer|sales|lead|leads|communication|communications)\b/i]}]);function Ur(e,t){return Ba(e,{mode:t.mode??"full",...t.keepFirst===void 0?{}:{keepFirst:t.keepFirst},...t.keepLast===void 0?{}:{keepLast:t.keepLast},...t.maskChar===void 0?{}:{maskChar:t.maskChar},...t.replacement===void 0?{}:{replacement:t.replacement},...t.keepPattern===void 0?{}:{keepPattern:t.keepPattern}})}function vl(e,t){return typeof e=="string"?Ur(e,t):t.replacement??Dt}function zr(e){let t=[],n=e.replacement??Dt;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:Nt(r),replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:Nt(i),replacer:o=>Ur(o,r)})}return t}function qr(e){if(!br(e))throw new Error(`[visiq-redact] Redaction pattern "${e}" can backtrack exponentially and was refused. A group repeated with * or + must have a fixed-length body: (\\d{4})+ is fine, (\\d+)+ is not.`);try{return new RegExp(e,"g")}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`[visiq-redact] Invalid redaction pattern "${e}": ${n}`)}}function Vr(e,t){if(Lt(e).length===0){let n=e;for(let{source:r,replacer:i}of t)n=n.replace(qr(r),o=>i(o));return n}return wl(e,t)}function wl(e,t){let n=e;for(let{source:r,replacer:i}of t){let o=qr(r),a=[...nr(o,n)];for(let u of Lt(n))for(let d of nr(o,u.text))a.push(Wa(u,d));let s=Ya(a);if(s.length===0)continue;let l="",c=0;for(let{start:u,end:d}of s)l+=n.slice(c,u)+i(n.slice(u,d)),c=d;n=l+n.slice(c)}return n}function L(e,t){return e==null?e:typeof e=="string"?kl(e,t):typeof e=="object"?Al(e,t):e}function kl(e,t){if(typeof e!="string")return e;let n=zr(t);return n.length===0?e:Vr(e,n)}function Al(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=zr(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]=vl(l[u],d);continue}c[u]=a(l[u])}return c}return typeof s=="string"&&o?Vr(s,r):s};return a(e)}import{createHash as Rd}from"node:crypto";var Gr=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Il(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:Gr(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:Gr(t.spawn.prompt)}),t}function Sl(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 Tl=1440*60*1e3,El="VISIQ_BUNDLE_GRACE_TTL_MS",Rl="VISIQ_BUNDLE_CACHE_DISABLED",Cl="VISIQ_CACHE_DIR",xl=at.object({graceTtlMs:at.number().int().nonnegative().optional(),disabled:at.boolean().optional(),cacheDir:at.string().min(1).optional()}).strict();function Ol(e){return e==null?{}:xl.parse(e)}function Nl(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[El];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Tl}function Fl(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Rl]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var Kr;function Ml(){if(Kr!==void 0)return Kr;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Dl(e){return JSON.stringify(qt(e))}function qt(e){if(Array.isArray(e))return e.map(qt);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=qt(t[r]);return n}return e}function Ll(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function $l(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 Xr(){if(!Ml())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 ei(e,t){return e.createHash("sha256").update(Dl(t)).digest("hex")}function Pl(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Cl]?.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 jl(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function ti(e,t,n){return e.path.join(Pl(e,n),"bundles",`${jl(e,t)}.json`)}async function Bl(e,t,n,r={}){let i=await Xr();if(i)try{let o=ti(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:ei(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 Ul(e,t={}){let n=await Xr();if(!n)return null;try{let r=await n.fs.readFile(ti(n,e,t),"utf-8"),i=$l(JSON.parse(r));return!i||ei(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var Le;async function zl(){if(Le!==void 0)return Le;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;Le=typeof t=="function"?t:null}catch{Le=null}return Le}function ql(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=Et(i)}catch{continue}let a=typeof r.id=="string"?r.id:"<rule>";for(let s of Cn(o))t.push(`${a}: ${s}`)}return t}function Vl(e){return Jn(e)}function Gl(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var Kl=5e3,Hl=600*1e3,Wl=1e4,Yl=25,Hr=1e3,Ql=5e3,Zl=100,Wr=2e3,Jl=10,Xl=512,ec=1800*1e3,tc=.7,nc="monitor",rc="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",Yr="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.",st="open";function $e(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}var ic=h.object({operations:h.array(h.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:h.string().min(1,"agentId is required"),sessionId:h.string().min(1).max(255).optional(),toolName:h.string().optional(),toolArgs:h.record(h.unknown()).optional(),targetResource:h.string().optional(),resourceType:h.string().optional(),resourceMetadata:h.record(h.unknown()).optional(),normalized:h.record(h.unknown()).optional(),query:h.string().optional(),contentPreview:h.string().optional(),telemetry:h.record(h.unknown()).optional(),context:h.record(h.unknown()).optional(),mcpServer:h.string().min(1).max(255).optional(),identity:h.object({attested:h.array(h.string().min(1).max(255)).max(32).optional(),claimed:h.array(h.string().min(1).max(255)).max(32).optional(),subjectId:h.string().min(1).max(255).optional()}).optional()}),oc=h.object({version:h.string().min(1),dialect_version:h.number().int().optional(),min_dialect:h.number().int().optional(),shutdown:h.boolean().optional(),agent_mode:h.enum(["enforce","monitor","off"]).optional(),cognition_capture:h.boolean().optional(),agent_mode_by_operation:h.object({action:h.string().optional(),retrieval:h.string().optional(),delegation:h.string().optional()}).partial().optional(),agent_attributes:h.object({trust_tier:h.string().nullable().optional(),categories:h.array(h.string()).optional(),business_function:h.string().nullable().optional(),business_functions:h.array(h.string()).nullable().optional(),blast_radius_tier:h.string().nullable().optional(),no_coverage:h.string().nullable().optional(),fail_mode:h.string().nullable().optional()}).optional(),rules:h.array(h.record(h.unknown())),action_schemas:h.array(h.object({id:h.string(),plane:h.string().optional(),field_mappings:h.array(h.record(h.unknown())).optional(),derived_fields:h.array(h.record(h.unknown())).optional(),action_class:h.string().nullable().optional(),action_class_confidence:h.number().optional()})).optional(),no_coverage:h.object({no_coverage_defaults:h.record(h.string()),autopilot_enabled:h.boolean(),enduser_hitl_enabled:h.boolean(),hitl_timeout_seconds:h.number().optional()}).optional(),skill_blacklist:h.array(h.record(h.unknown())).optional()});function ac(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=Vn(Gn(n));return{trust_tier:$n(t)?t:null,categories:jn(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&Kn(e.blast_radius_tier)?e.blast_radius_tier:null}}function sc(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 lc(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Vt=new Set,Qr=!1;async function Zr(e){let t=[];for(let n of Vt){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 cc(){if(!Qr&&!(typeof process>"u"||typeof process.once!="function")){Qr=!0,process.once("beforeExit",()=>{Zr(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await Zr(!0)}finally{process.kill(process.pid,e)}})()})}}var ni=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];skillBlacklist=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;cacheIdentity;bundleCacheDisabled;bundleGraceTtlMs;bundleCacheDirOverride;diskFallbackServed=!1;agentMode=nc;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=$e(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??st;governedFailMode=null;telemetryBuffer=[];droppedTelemetry=0;inFlightTelemetry=new Set;telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastSkillInventorySig=null;skillInventoryPromise=null;lastCloneCaptureSig=null;toolDescriptions=new Map;constructor(e,t,n,r,i,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=Ol(s);if(this.bundleCacheDisabled=Fl(d.disabled),this.bundleGraceTtlMs=Nl(d.graceTtlMs),this.bundleCacheDirOverride=d.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let f={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:Sl(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...o!==void 0?{sdkVersion:o}:{},...a!==void 0?{sdkDialect:a}:{}};this.client=new kt(f,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Kl),zt(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Wl),zt(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Ql),zt(this.cognitionTimer),Vt.add(this),cc()}else this.client=null}async evaluate(e){let t=ic.parse(e),n=Date.now();if(this.operatorShutdown){let p=this.denyAll(t,rc);return this.applyAgentMode(p,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,Yr,n);let p=this.denyAll(t,Yr);return this.applyAgentMode(p,"enforce",t,n)}if(t.operations.every(p=>this.modeFor(p)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let p;if(this.agentModeConfirmed?p=this.agentMode:this.bundleApplyFailed?p="enforce":p="monitor",p==="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,p,t,n)}if(this.modeFor("action")!=="off"){let p=this.matchSkillQuarantine(t);if(p){let m=this.denyAll(t,p);return this.applyAgentMode(m,this.modeFor("action"),t,n)}}let r=this.readSession(t.sessionId),i=await zl();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")?Nn(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(p){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${p instanceof Error?p.message:String(p)}`,n);throw p}let d=[...new Set(t.operations.flatMap(p=>this.normalizedRefs[p]??[]))].sort();d.length>0&&Gl(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 f=Fn(t.normalized);return f.length>0&&(u.normalizedDrift=f,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${f.length} value(s) outside the canonical vocabulary \u2014 a builder-authored rule can only select in-vocab values, so these cannot match one, so a rule keyed on the canonical value does not fire here. Check the harness classifier's casing/spelling. Affected: ${f.slice(0,5).join("; ")}${f.length>5?`; +${f.length-5} more`:""}`))),this.foldSession(t,u.enforced?u.decision:"permit"),u.enforced&&u.action.decision==="approval_required"&&await this.registerHitl(t,u),this.bufferTelemetry(t,u,Date.now()-n,u.enforced),u}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}matchSkillQuarantine(e){if(this.skillBlacklist.length===0)return null;let t=e.context?.skill;if(!t||t.activated!==!0)return null;let n=typeof t.name=="string"?t.name:"",r=typeof t.fingerprint=="string"?t.fingerprint:null;if(n.length===0&&r===null)return null;let i=Hn({action:n,fingerprint:r},this.skillBlacklist);return i.blocked?i.matchedBy==="fingerprint"?"skill quarantined for the agent \u2014 its content signature matches a blacklisted skill (a renamed or edited re-skin); blocked ([D-27])":"skill quarantined for the agent \u2014 it is on the approved blacklist; blocked ([D-27])":null}readSession(e){if(!e)return Oe;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>ec?(this.sessions.delete(e),Oe):t.state:Oe}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>=tc)return o}foldSubjectId(e){let t=e.identity?.subjectId;if(typeof t=="string"&&t.length>0)return t;let n=e.normalized?.write;if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let r=n.subject_id;if(typeof r=="string"&&r.length>0)return r}}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=o?jr({content:e.contentPreview,resourceMetadata:i}):void 0,l=s?.labels,c=Array.isArray(i.data_categories)?i.data_categories:[],u=(s?.detectors??[]).map(p=>Qn(p)).filter(p=>p!==void 0),d=o?[...new Set([...c,...u])]:void 0,f=Dn(r===Oe?tt():r,{data_categories:d,classification:o?i.classification:void 0,taint:l,action_class:a?this.foldActionClass(e):void 0,target_app:a?e.targetResource??e.toolName:void 0,attested_subjects:e.identity?.attested,claimed_subjects:e.identity?.claimed,subject_id:a?this.foldSubjectId(e):void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:f,touchedAt:Date.now()}),this.sessions.size>Xl){let p=this.sessions.keys().next().value;p!==void 0&&this.sessions.delete(p)}}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=oc.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=ql(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=>Zn(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?ac(t.agent_attributes):null,this.agentNoCoverage=Wn(t.agent_attributes?.no_coverage),this.governedFailMode=$e(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=sc(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=Vl(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",...ne(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>=Hl&&(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 Ul(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Ll(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 Bl(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({...Ye(),...e?{agent_type:e}:{},...t?.model?{model:t.model}:{},...t?.systemPrompt?{systemPrompt:t.systemPrompt}:{},...t?.toolSchemas&&t.toolSchemas.length>0?{toolSchemas:t.toolSchemas}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));for(let n of e)n.description&&this.toolDescriptions.set(n.name,n.description);t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}reportSkillInventory(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,h:n.content_hash})).sort((n,r)=>n.n===r.n?n.h.localeCompare(r.h):n.n.localeCompare(r.n)));t!==this.lastSkillInventorySig&&(this.lastSkillInventorySig=t,this.skillInventoryPromise=this.client.reportSkillInventory(e).catch(()=>{}))}captureCloneMetadata(e){if(!this.client||!this.resolvedAgentId||!(e.model||e.systemPrompt||(e.toolSchemas?.length??0)>0))return;let t=JSON.stringify({m:e.model??"",s:e.systemPrompt??"",t:e.toolSchemas??[]});t!==this.lastCloneCaptureSig&&(this.lastCloneCaptureSig=t,this.client.registerEnvironment({...Ye(),...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=Yn(n),i={...n};return e.toolArgs&&(i.tool_args=xr(e.toolArgs)),{canonical:n,id:r,rawEventForWire:i}}bufferTelemetry(e,t,n,r,i=!1){let o=this.buildActionSchemaEvent(e),a=crypto.randomUUID();t.decisionId=a,this.telemetryBuffer.push({decision_id:a,agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:r?lc(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?{[_n]:this.harnessKind}:{},...e.context??{},...i?{fail_open:!0}:{},...t.normalizedColdStart?{normalized_cold_start:!0,normalized_inert_conditions:t.normalizedColdStart.length}:{},...t.normalizedDrift?{normalized_drift:!0,normalized_drift_values:t.normalizedDrift.length,normalized_drift_fields:t.normalizedDrift.slice(0,Jl)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Yl&&this.flushTelemetry()}pendingTelemetryCount(){return this.telemetryBuffer.length}hasBackend(){return this.client!==null}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0),{client:t}=this,n=(async()=>{try{await t.sendTelemetry(e)}catch(r){this.droppedTelemetry+=e.length,console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",r)}})();this.inFlightTelemetry.add(n);try{await n}finally{this.inFlightTelemetry.delete(n)}}async drainInFlightTelemetry(){for(let e=0;e<8&&this.inFlightTelemetry.size>0;e+=1)await Promise.allSettled([...this.inFlightTelemetry])}droppedTelemetryCount(){return this.droppedTelemetry}enforceTelemetryCap(){let e=this.telemetryBuffer.length-Hr;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Hr})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Il(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Zl&&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-Wr;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Wr})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}if(this.skillInventoryPromise)try{await this.skillInventoryPromise}catch{}await this.flushTelemetry(),await this.drainInFlightTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),Vt.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 zt(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function uc(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function B(e,...t){for(let n of t){let r=uc(e[n]);if(r)return r}}var dc=[{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:B(t,"task","input","reason","message"),source:"structural"}}},{framework:"voltagent",matches:e=>e==="delegate_task",extract:(e,t)=>{let n=B(t,"targetAgent","agent","subAgent","agentName","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:B(t,"task","message","input"),description:B(t,"purpose"),source:"structural"}:null}},{framework:"crewai",matches:e=>/delegate work to (co-?worker|.+)/i.test(e),extract:(e,t)=>{let n=B(t,"coworker","agent","role");return n?{childAgentId:n,childName:n,kind:"teammate",agentType:n,task:B(t,"task","question"),description:B(t,"context"),source:"structural"}:null}},{framework:"llamaindex",matches:e=>e==="handoff"||/handoff/i.test(e),extract:(e,t)=>{let n=B(t,"to_agent","toAgent","agent_name","agentName","agent","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:B(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=B(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:B(t,"task","message","input","reason","prompt"),source:"heuristic"}:null}}];function lt(e,t){if(!e)return null;let n=t??{};for(let r of dc)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function ct(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}var fc={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"},pc=new Set(["workspace_deactivate_skill"]),mc=new Set(["read","read_file","readfile","view","cat"]);function gc(e){return pc.has((e??"").trim())}function hc(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function Jr(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function yc(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=fc[n];if(i){let o=Jr(r,["name","skill_name","identifier","skill","path"]);return o?{skill:o,via:n,framework:i}:null}if(mc.has(n.toLowerCase())){let o=Jr(r,["path","file_path","filePath","target","file"]),a=o?hc(o):null;return a?{skill:a,via:n,framework:"unknown"}:null}return null}function ri(e,t){let{activation:n,attributedSkill:r}=e;if(r)return{skill:{name:r,activated:!!n,...n?{via:n.via,framework:n.framework}:{},...t?{fingerprint:t}:{}}}}var ii=class{#e=null;activate(e){return this.#e=e,e}deactivate(e){(!e||this.#e?.skill===e)&&(this.#e=null)}current(){return this.#e}observe(e,t){let n=yc(e,t);if(n)return this.activate(n),{activation:n,attributedSkill:n.skill};if(gc(e)){let r=this.#e?.skill??null,i=t&&typeof t.name=="string"?t.name:void 0;return this.deactivate(i),{activation:null,attributedSkill:r}}return{activation:null,attributedSkill:this.#e?.skill??null}}};var Cd=512*1024;function Gt(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 oi(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 $(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.25";import{AsyncLocalStorage as _c}from"node:async_hooks";var O=new _c,bc=5120,ai=50;function vc(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 J(e){if(!e)return;let t=r=>r.length<=ai?r.slice():r.slice(r.length-ai),n=r=>vc(r,bc);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 Kt=12e4,si=2e3,li=3,wc=5e3;function Pe(e,t){return e==="mask"&&(t?.length??0)>0}var kc=new Set(["approved","resolved"]),Ac=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function Ic(e){return new Promise(t=>setTimeout(t,e))}function Sc(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 je(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=Kt,maskFallback:o=!1,sdkVersion:a,fetchImpl:s=globalThis.fetch,sleep:l=Ic,log:c=g=>console.warn(g)}=e,u=g=>o?{resolution:"mask",reason:g}:{resolution:"block",reason:g};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)}`,f={Accept:"application/json",...ne(a)};n&&(f.Authorization=`Bearer ${n}`);let p=Date.now()+Math.max(0,i),m=0;for(c(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=p)return c(`[VisIQ HITL] Decision ${r} timed out after ${i}ms \u2014 ${o?"masking":"blocking"} (G001)`),u("HITL approval timed out");let g=null;try{let _=new AbortController,w=setTimeout(()=>_.abort(),wc),S;try{S=await s(d,{method:"GET",headers:f,signal:_.signal})}finally{clearTimeout(w)}if(!S.ok)throw new Error(`HTTP ${S.status} ${S.statusText}`);let v=await S.json();g=Sc(v),m=0}catch(_){m+=1;let w=_ instanceof Error?_.message:String(_);if(c(`[VisIQ HITL] Poll failed for decision ${r} (${m}/${li}): ${w}`),m>=li)return u(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${w}`);await l(si);continue}if(g!==null){let _=g.toLowerCase();return kc.has(_)?(c(`[VisIQ HITL] Decision ${r} approved (${g}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${g})`}):Ac.has(_)?(c(`[VisIQ HITL] Decision ${r} resolved as ${g} \u2014 ${o?"masking":"blocking"}`),u(`Not approved by human reviewer (${g})`)):(c(`[VisIQ HITL] Decision ${r} returned unknown status '${g}' \u2014 ${o?"masking":"blocking"} (G001)`),u(`HITL returned unknown status '${g}' \u2014 fail-closed (G001)`))}await l(si)}}function X(e){return e??$e(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??st}function A(e,t){try{console.error(`[VisIQ] FAIL-OPEN (${e}): ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`)}catch{}}function G(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 me(e){let t=e.getFailMode;return(typeof t=="function"?t.call(e):void 0)??X()}function oe(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 ui(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&Pe(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}var ci=new Set;function Qt(e){ci.has(e)||(ci.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 dt(e,t,n){let r=O.getStore(),i=J(r),o=n.sessionId??r?.session_id,a=await e.evaluate({operations:["retrieval"],agentId:t,...o?{sessionId:o}:{},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 ui(a)}async function ft(e,t,n){return await e.awaitBundleReady(),dt(e,t,n)}function di(e,t,n=X()){switch(t.action){case"allow":case"escalate":return e;case"deny":return null;case"redact":{if(t.redactionRules.length===0)return e;try{return L(e,$(t.redactionRules))}catch{return n==="closed"?null:(A("redact-error","document redaction failed \u2014 document passed UNREDACTED"),e)}}default:return Qt(String(t.action)),n==="closed"?null:(A("unknown-retrieval-verb",`unrecognized outcome "${String(t.action)}" \u2014 document passed through`),e)}}var Tc=["pageContent","text","content"];function pt(e){let t=e.metadata;if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Object.keys(r).length>0)return r}let n={};for(let[r,i]of Object.entries(e))!Tc.includes(r)&&r!=="metadata"&&(n[r]=i);return n}async function fi(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=pt(a),c=await dt(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s}),u=di(o,c,me(r));u!==null&&i.push(u)}return i}async function pi(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await dt(n,t,{resourceType:"document",resourceMetadata:{content_preview:e},contentPreview:e})}catch(i){return me(n)==="closed"?"[RECALL] Retrieved context blocked \u2014 policy evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":(A("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 L(e,$(r.redactionRules))}catch{return me(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(A("redact-error","text redaction failed \u2014 text passed UNREDACTED"),e)}}default:return Qt(String(r.action)),me(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(A("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 text passed through`),e)}}var mi=4,gi=1e3;function ut(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 hi(e,t,n){let r=[];for(let i of e){let o=i,a=String(o.pageContent??o.text??o.content??""),s={...pt(o),content_preview:a},l;try{l=await dt(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:a})}catch(u){if(me(n)==="closed")continue;A("eval-error",`document retrieval evaluation failed \u2014 document passed through: ${u instanceof Error?u.message:String(u)}`),r.push(i);continue}let c=di(i,l,me(n));c!==null&&r.push(c)}return r}async function Wt(e,t,n,r,i){if(r>mi||i.nodes++>gi)return e;if(Array.isArray(e)){if(ut(e))return i.matched=!0,hi(e,t,n);let o=[];for(let a of e)o.push(await Wt(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 Wt(o[s],t,n,r+1,i);return a}return e}async function mt(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&ut(e))return hi(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await Wt(e,t,n,0,r);if(r.matched)return i}return e}var Ec={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function Yt(e,t,n){if(t>mi||n.n++>gi)return e;if(Array.isArray(e))return ut(e)?[]:e.map(r=>Yt(r,t+1,n));if(e!==null&&typeof e=="object"){if(ut([e]))return{...Ec};let r=e,i={};for(let o of Object.keys(r))i[o]=Yt(r[o],t+1,n);return i}return e}function Ht(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?Yt(e,0,{n:0}):e}function yi(e,t,n=X()){let r=ui(t);switch(r.action){case"allow":case"escalate":return e;case"deny":return Ht(e);case"redact":{if(r.redactionRules.length===0)return e;try{return L(e,$(r.redactionRules))}catch{return n==="closed"?Ht(e):(A("redact-error","result redaction failed \u2014 result passed UNREDACTED"),e)}}default:return Qt(String(r.action)),n==="closed"?Ht(e):(A("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 result passed through`),e)}}function x(e){return typeof e=="object"&&e!==null?e:null}function _i(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}function Rc(e,t){let n=x(e.metadata),r=n&&typeof n.name=="string"?n.name:void 0;return _i(e.name,e.id,r,t)}function Cc(e){let t=x(e.metadata),n=t&&typeof t.description=="string"?t.description:void 0,r=_i(e.description,n);return r===void 0?void 0:r.slice(0,4e3)}function xc(e){let t=x(e);return t!==null&&("type"in t||"properties"in t||"$schema"in t)}function Oc(e){let t=x(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=x(n);if(r===null)return{type:"object"};let i={};for(let o of Object.keys(r))i[o]={};return{type:"object",properties:i}}var Nc=new Set(["default","const","enum","examples","example"]);function Zt(e){if(Array.isArray(e))return e.map(Zt);let t=x(e);if(t===null)return e;let n={};for(let[r,i]of Object.entries(t))Nc.has(r)||(n[r]=Zt(i));return n}function Fc(e){let t;if(xc(e))t=e;else{let n=Oc(e);if(n===void 0)return;t=n}try{let n=JSON.stringify(t);if(n.length>2e4){let r=x(t),i=r&&x(r.properties);if(i){let o={};for(let a of Object.keys(i))o[a]={};return{type:"object",properties:o}}return{type:"object"}}return Zt(JSON.parse(n))}catch{return}}function Mc(e){let t=x(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:Fc(n)}function Dc(e,t){let n=x(e);if(n===null)return null;let r=Rc(n,t);if(r===void 0)return null;let i={name:r.slice(0,255)},o=Cc(n);o!==void 0&&(i.description=o);let a=Mc(n);return a!==void 0&&(i.input_schema=a),i}function ae(e){let t=[],n=new Set,r=(i,o)=>{try{let a=Dc(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=x(e);if(i!==null){for(let o of Object.keys(i))if(r(i[o],o),t.length>=200)break}}return t}function Jt(e){try{let t=x(e);if(t===null)return[];let n=[],r=new Set,i=c=>{for(let u of c)!r.has(u.name)&&n.length<200&&(r.add(u.name),n.push(u))};t.tools!==void 0&&i(ae(t.tools));let o=x(t.settings);o&&o.tools!==void 0&&i(ae(o.tools));for(let c of["getTools","listTools"]){let u=t[c];if(typeof u=="function")try{let d=u.call(t);if(d&&typeof d.then=="function")continue;i(ae(d))}catch{}}let a=x(t.nodes)?t:x(t.graph)??x(t.builder)??t,s=x(a.nodes);if(s)for(let c of Object.keys(s)){let u=x(s[c]);if(!u)continue;u.tools!==void 0&&i(ae(u.tools));let d=x(u.bound);d&&d.tools!==void 0&&i(ae(d.tools))}let{agents:l}=t;if(l instanceof Map)for(let c of l.values()){let u=x(c);u&&u.tools!==void 0&&i(ae(u.tools))}return n}catch{return[]}}async function bi(e){let t=x(e);if(!t)return[];let n=[],r=new Set;for(let i of["getTools","listTools"]){let o=t[i];if(typeof o=="function")try{let a=o.call(t);if(!a||typeof a.then!="function")continue;for(let s of ae(await a))r.has(s.name)||(r.add(s.name),n.push(s))}catch{}}return n}import{z as gt}from"zod";var Lc=gt.object({decision:gt.enum(["permit","deny"]),reason:gt.string(),handoff_event_id:gt.string().nullable()}),V=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},se=class extends V{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},$c="https://api.visiqlabs.com",Pc=1e4,ge=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??$c,timeoutMs:e.timeoutMs??Pc},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 V(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=Lc.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 vi=new Map;async function wi(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=vi.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 ge({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 vi.set(e,o),o}var Be=Symbol.for("visiq.orchestrate.wrapped");function jc(e){return e instanceof V&&typeof e.status=="number"&&e.status>=400&&e.status<500}function ki(e,t){if(!t.agentId||t.agentId.trim()==="")throw new V("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new V("grantToken is required","CONFIG_ERROR");if(e[Be]===!0)return e;let n=new ge(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(jc(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 V(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new se(s.reason,s.handoffEventId)};return new Proxy(e,{get(o,a,s){let l=Reflect.get(o,a,s);return a===Be?!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}})}function Si(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t.slice(0,255):null}function Ai(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){let i=Si(r);if(!(i===null||n.has(i))&&(n.add(i),t.push(i),t.length===32))break}return t.length>0?t:void 0}function Ii(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=Ai(t.attested),r=Ai(t.claimed),i=Si(t.subjectId);if(!(!n&&!r&&i===null))return{...n?{attested:n}:{},...r?{claimed:r}:{},...i!==null?{subjectId:i}:{}}}function Ti(e){if(e==null)return;if(typeof e=="function")return()=>{let n;try{n=e()}catch(r){Bc(r);return}return Ii(n)};let t=Ii(e);return t===void 0?void 0:()=>t}function Bc(e){let t=e instanceof Error?e.message:String(e);try{console.error(`[VisIQ] IDENTITY-DROPPED: the identity resolver threw (${t}) \u2014 this call carries NO attested principal, so any identity-binding rule will DENY it. Fix the resolver; it must never throw.`)}catch{}}function le(e){return e?.subjectId?{write:{subject_id:e.subjectId}}:void 0}import{randomUUID as Di}from"node:crypto";var Ei=Symbol.for("visiq.semantickernel.instrumented");function xi(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 Ri(e){let t=e.arguments;return t&&typeof t=="object"&&"arguments"in t&&t.arguments&&typeof t.arguments=="object"?t.arguments:t??{}}function Ci(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 K(e,t){e.result&&typeof e.result=="object"?e.result.value=t:e.result={value:t}}function Uc(e){return e.result?.value}function zc(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=Ri(o),u=l;try{let m=e.resolveIdentity?.(),g=le(m),_=await n.evaluate({operations:["action"],agentId:t,...e.hostSessionId?{sessionId:e.hostSessionId}:{},...m?{identity:m}:{},...g?{normalized:g}:{},toolName:s,toolArgs:c,...u!==void 0?{targetResource:u}:{}}),w=oe(_);if(!w.allowed){K(o,N({outcome:"deny",code:w.ruleCode??"DENY",reason:w.reason}));return}w.decision==="mask"&&w.argRedactionRules.length>0&&Ci(o,L(c,$(w.argRedactionRules)));let S=Ri(o),v=pe(s,S,{failMode:r==="closed"?"closed":"open",enforced:_.enforced});if(v.verdict==="block"){K(o,N({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${v.detectors.join(",")})`}));return}v.verdict==="redact"&&(Ci(o,v.redacted),A("outbound-secret-redacted",`outbound secret screen redacted ${v.detectors.length} detector(s): ${v.detectors.join(",")}`))}catch(m){if(r==="closed"){K(o,N({outcome:"error",code:"EVAL-ERROR",mechanism:`evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${m instanceof Error?m.message:String(m)}`}));return}A("eval-error",`SK action pre-gate failed for "${s}": ${m instanceof Error?m.message:String(m)}`)}try{let m=await ft(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l},...e.hostSessionId?{sessionId:e.hostSessionId}:{}});if(m.action==="deny"||m.action==="escalate"){K(o,`[RECALL: access denied \u2014 ${m.reason}]`);return}}catch(m){if(r==="closed"){K(o,`[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${m instanceof Error?m.message:String(m)}.`);return}A("eval-error",`SK retrieval pre-gate failed for "${s}": ${m instanceof Error?m.message:String(m)}`)}await a(o);let d=Uc(o),f=typeof d=="string"?d:(()=>{try{return JSON.stringify(d)??String(d)}catch{return String(d)}})(),p;try{p=await ft(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l,content_preview:f},contentPreview:f,...e.hostSessionId?{sessionId:e.hostSessionId}:{}})}catch(m){r==="closed"?K(o,"[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):A("eval-error",`SK post-result retrieval eval failed for "${s}": ${m instanceof Error?m.message:String(m)}`);return}if(p.action==="deny"||p.action==="escalate"){K(o,`[RECALL: access denied \u2014 ${p.reason}]`);return}if(p.action==="redact"&&p.redactionRules&&p.redactionRules.length>0&&d!==null&&d!==void 0)try{K(o,L(d,$(p.redactionRules)))}catch(m){r==="closed"?K(o,"[RECALL] Result withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):A("redact-error",`SK result redaction failed for "${s}" \u2014 result passed UNREDACTED: ${m instanceof Error?m.message:String(m)}`)}}}function qc(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 ft(e.unified,e.agentId,{resourceType:"prompt",resourceMetadata:{},contentPreview:i,...e.hostSessionId?{sessionId:e.hostSessionId}:{}})}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":A("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=L(i,$(o.redactionRules))}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed).":A("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 Oi(e,t){let n=e;if(n[Ei]===!0)return t.onWrap?.(),e;let r=zc(t),i=qc(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[Ei]=!0,t.onWrap?.()),e}function N(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 ht(e){return e instanceof Error?e.message:String(e)}var Vc=/https?:\/\/[^\s"'`,)}\]]+/;function en(e){let t=e.match(Vc);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var he=Symbol.for("visiq.toolexec.instrumented"),Ni=Symbol.for("visiq.agentclone.instrumented"),tn=Symbol.for("visiq.instrument.deferred");function Gc(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}var nn={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 Li(e){if(e===null||typeof e!="object")return null;let t=e;if(Gc(t))return null;if(xi(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}var Fi=new WeakMap;function Kc(e){let t=Fi.get(e);return t||(t=new ii,Fi.set(e,t)),t}async function Hc(e,t,n,r,i,o,a){let{agentId:s,unified:l}=e,c=J(i),u=e.resolveIdentity?.(),d=le(u),f;try{let T=Kc(e).observe(t,n);f=ri(T)}catch{f=void 0}let p=a?ct(a,s):void 0,m=p||f?{...p??{},...f??{}}:void 0,g,_=!1;try{await l.awaitBundleReady();let T=await l.evaluate({operations:a?["action","delegation"]:["action"],agentId:s,toolName:t,toolArgs:n,...m?{context:m}:{},...o?{sessionId:o}:{},...u?{identity:u}:{},...d?{normalized:d}:{},...r!==void 0?{targetResource:r}:{},...c?{telemetry:c}:{}});({enforced:_}=T),g=oe(T)}catch(T){let P=T instanceof Error?T.message:String(T);return e.failMode==="closed"?{block:N({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${P} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})}:(A("eval-error",`policy evaluation failed for tool "${t}": ${P}`),{block:null})}if(g.decision==="approval_required"&&g.decisionId){let T=l.getApiKey()??e.apiKey,P=await je({endpoint:l.getEndpoint()??e.endpoint??"",...T?{apiKey:T}:{},decisionId:g.decisionId,timeoutMs:e.hitlTimeoutMs,sdkVersion:Z});return P.resolution!=="proceed"?{block:N({outcome:"approval_required",code:g.ruleCode??"HITL-BLOCK",reason:g.reason,mechanism:P.reason}),decision:g}:{block:null}}if(!g.allowed)return{block:N({outcome:"deny",code:g.ruleCode??"DENY",reason:g.reason}),decision:g};let w=n,S=!1,v;if(g.decision==="mask"&&g.argRedactionRules&&g.argRedactionRules.length>0)try{let T=$(g.argRedactionRules);w=L(n,T),S=!0,v=g}catch(T){let P=T instanceof Error?T.message:String(T);if(e.failMode==="closed")return{block:N({outcome:"error",code:"MASK-ERROR",mechanism:`argument masking failed: ${P} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})};A("mask-error",`argument masking failed for tool "${t}" \u2014 running with UNMASKED args: ${P}`)}let F=pe(t,w,{failMode:e.failMode==="closed"?"closed":"open",enforced:_});return F.verdict==="block"?{block:N({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${F.detectors.join(",")})`}),decision:{allowed:!1,decision:"deny",ruleCode:"OUTPUT-BLOCK",reason:"outbound content carried a live secret",argRedactionRules:[]}}:(F.verdict==="redact"&&(w=F.redacted,S=!0,A("outbound-secret-redacted",`outbound secret screen redacted ${F.detectors.length} detector(s): ${F.detectors.join(",")}`),v??={allowed:!0,decision:"mask",ruleCode:"OUTPUT-BLOCK",reason:"outbound secret redacted before egress",argRedactionRules:[]}),S?{block:null,maskedArgs:w,decision:v}:{block:null})}async function rn(e,t,n,r,i){let o=O.getStore(),a=o??e.telemetry,s=o?o.session_id:e.runSessionId??e.hostSessionId,l=lt(t,n);l&&ke(e.unified,{agentId:e.agentId,sessionId:a?.session_id,...e.framework?{framework:e.framework}:{}},l);let c={agentId:e.agentId,sessionId:a?.session_id,...e.framework?{framework:e.framework}:{}},u=be(t,n);try{Ae(e.unified,c,{toolName:t,...u?{memory:u}:{},argSummary:r.slice(0,512)})}catch(_){G("step-beat",`emit failed for tool "${t}": ${ht(_)}`)}let d=Date.now(),f=await Hc(e,t,n,en(r),a,s,l);if(f.block!==null){try{f.decision&&fe(e.unified,c,{toolName:t,decision:f.decision.decision??"deny",...f.decision.ruleCode?{ruleCode:f.decision.ruleCode}:{},...f.decision.reason?{ruleLabel:f.decision.reason}:{},enforced:!0,harnessMessage:f.block})}catch(_){G("intervention-beat",`emit failed for tool "${t}": ${ht(_)}`)}return f.block}if(f.maskedArgs!==void 0&&f.decision)try{fe(e.unified,c,{toolName:t,decision:f.decision.decision??"mask",...f.decision.ruleCode?{ruleCode:f.decision.ruleCode}:{},...f.decision.reason?{ruleLabel:f.decision.reason}:{},enforced:!0})}catch(_){G("intervention-beat",`emit failed for tool "${t}": ${ht(_)}`)}let p=f.maskedArgs??n,m=await i(p),g=await mt(m,e.agentId,e.unified);try{Ie(e.unified,c,{toolName:t,ok:!0,durationMs:Date.now()-d,...re(g)!==void 0?{bytes:re(g)}:{},...ie(g)!==void 0?{itemCount:ie(g)}:{},...u?{memory:u}:{}})}catch(_){G("observation-beat",`emit failed for tool "${t}": ${ht(_)}`)}return g}function ze(e,t,n){let r=e;if(r[he]){n.onWrap?.();return}if(typeof r.execute!="function")return;let i=r.execute;qe(r,"execute",async function(...a){let s=Gt(a[0]);return rn(n,t,s,Ve(s),l=>Promise.resolve(i.apply(this,[l,...a.slice(1)])))}),r[he]=!0,n.onWrap?.()}function Wc(e,t,n){let r=e;if(r[he]){n.onWrap?.();return}if(typeof r.invoke!="function")return;let i=r.invoke;qe(r,"invoke",async function(...a){let s=a[1],l=oi(s),c=typeof s=="string"?s:Ve(l);return rn(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[he]=!0,n.onWrap?.()}function Yc(e,t){let n=e;if(n[he]){t.onWrap?.();return}if(typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",o=n.call;qe(n,"call",async function(...s){let l=Gt(s[0]);return rn(t,i,l,Ve(l),c=>Promise.resolve(o.apply(this,[c,...s.slice(1)])))}),n[he]=!0,t.onWrap?.()}function on(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&ze(r,n,t);return e}function $i(e,t,n){let r={...t,framework:n};switch(n){case"vercel":return Qc(e,r);case"mastra":return Zc(e,r);case"openai":return Pi(e,r);case"llamaindex":return Xc(e,r);case"voltagent":return Jc(e,r);case"semantic-kernel":return Oi(e,r);default:return e}}function Qc(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"&&on(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=an(r.onStepFinish)),yt(e,["generate","stream"],async(o,a)=>(Ue(a,o[0]),o),t.hostSessionId),e}function Zc(e,t){let n=e;return ou(n,t)==="deferred"&&(n[tn]=!0),su(n,t),yt(e,["generate","stream","generateVNext","streamVNext"],async(r,i)=>{Ue(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=an(o.onStepFinish);let a=[...r];return a[1]=o,a},t.hostSessionId),e}function Jc(e,t){let n=nu(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;ze(r,typeof i=="string"?i:"unknown",t)}}return yt(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{Ue(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=an(o.onStepFinish);let a=[...r];return a[1]=o,a},t.hostSessionId),e}function Xc(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"&&Yc(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 yt(e,["run"],async(o,a)=>(Ue(a,o[0]),o),t.hostSessionId),ru(e,"runStream",(o,a,s)=>{s||Ue(a,o[0])},t.hostSessionId),e}function Pi(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;Wc(i,typeof o=="string"?o:"unknown",t)}}return tu(e,t),eu(e,t),e}function eu(e,t){let n=e;if(n[Ni])return;let r=n.clone,i=Object.getPrototypeOf(e),o=typeof r=="function"?r:i?.clone;if(typeof o!="function")return;Object.defineProperty(e,"clone",{value:function(...s){let l=o.apply(this,s);return l!==null&&typeof l=="object"&&Pi(l,t),l},writable:!0,configurable:!0,enumerable:!1}),n[Ni]=!0}function tu(e,t){let n=e;if(n.__visiq_openai_hooks||typeof n.on!="function")return;let r=n.on,{telemetry:i,unified:o}=t;r.call(e,"agent_start",(...a)=>{let s=t.hostSessionId??Di();i.session_id=s,t.runSessionId=s,i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let l=a[2];l!=null&&i.llm_prompts.push(Ve(l).slice(0,5120));try{let c=a[0],{getSystemPrompt:u}=n;typeof u=="function"&&Promise.resolve(u.call(e,c)).then(d=>{typeof d=="string"&&d.trim().length>0&&o.captureCloneMetadata({systemPrompt:d,agentType:"openai_agents"})}).catch(()=>{})}catch{}}),r.call(e,"agent_end",(...a)=>{let s=a[1];typeof s=="string"&&s&&i.llm_responses.push(s.slice(0,5120))}),n.__visiq_openai_hooks=!0}function nu(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 yt(e,t,n,r){let i=e;for(let o of t){if(typeof i[o]!="function")continue;let a=`__visiq_wrapped_${o}`;if(i[a])continue;let s=i[o];i[o]=function(...l){let c=Bi(r);return O.run(c,async()=>{let u=await n(l,c);return s.apply(e,u)})},i[a]=!0}}function ru(e,t,n,r){let i=e;if(typeof i[t]!="function")return;let o=`__visiq_wrapped_${t}`;if(i[o])return;let a=i[t];i[t]=function(...s){let l=O.getStore(),c=l??Bi(r);return n(s,c,l!==void 0),O.run(c,()=>a.apply(e,s))},i[o]=!0}function an(e){return t=>{let n=O.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 Ue(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(Ve(n).slice(0,5120))}var iu=["listTools","getTools"];function ou(e,t){for(let n of iu){let r=e[n];if(typeof r!="function")continue;let i;try{i=r.call(e)}catch{continue}if(i&&typeof i=="object")return typeof i.then!="function"?(on(i,t),ji(e,i),"sync"):(i.then(()=>{},()=>{}),au(e,n,r,t),"deferred")}return"none"}function au(e,t,n,r){let i=o=>(o&&typeof o=="object"&&(on(o,r),ji(e,o)),o);qe(e,t,function(...o){let a=n.apply(this??e,o);return a&&typeof a.then=="function"?a.then(i):i(a)})}var Xt=Symbol.for("visiq.mastra.governedNames"),Mi=Symbol.for("visiq.mastra.assembly.instrumented");function ji(e,t){let n=e[Xt];n instanceof Set||(n=new Set,e[Xt]=n);for(let r of Object.keys(t))n.add(r)}function su(e,t){let n=e;if(n[Mi])return;let r=Object.getPrototypeOf(e),i=typeof e.convertTools=="function"?e.convertTools:r?.convertTools;if(typeof i!="function")return;let o=a=>{if(!a||typeof a!="object")return a;let s=n[Xt],l=s instanceof Set?s:new Set;for(let[c,u]of Object.entries(a))l.has(c)||u!==null&&typeof u=="object"&&ze(u,c,t);return a};qe(n,"convertTools",function(...a){let s=i.apply(this??e,a);return s&&typeof s.then=="function"?s.then(o):o(s)}),n[Mi]=!0}function Bi(e){return{session_id:e??Di(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function qe(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function Ve(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Ji(e,t){let n=_u(t);if(e[Be]===!0)return e;let r=ku(e);if(r==="langchain-executor"||r==="langchain-graph")return ue(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,sn(r,null),n.failMode,{model:zi(e)}),Vi(e,n),Au(e,n);let i=Li(e);if(i){ue(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,sn("unknown",i),n.failMode,{model:zi(e)}),Vi(e,n),gu(e,n,sn("unknown",i));let o=0,a=io(n);a.onWrap=()=>{o+=1};let s=$i(e,a,i),l=s[tn]===!0;if(o===0&&!l){let c=0;try{c=Jt(e).length}catch{c=0}if(c>0){let u=`[VisIQ] Detected a ${nn[i]} that ADVERTISES ${String(c)} 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(u);A("zero-instrument",`advertised ${String(c)} tool(s), instrumented none`),console.warn(u)}else{let u=`[VisIQ] Detected a ${nn[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(u);console.warn(u)}}return s}if(xu(e)){let o=process.env.VISIQ_GRANT_ID;return o?Nu(e,n,o):Fu(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 cu="https://api.visiqlabs.com",uu="\0",Ui=new Map;function sn(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 zi(e){try{if(typeof e!="object"||e===null)return;let t=e,n=ye(t.model);if(n)return n;let{settings:r}=t;if(typeof r=="object"&&r!==null){let a=ye(r.model);if(a)return a}let{llm:i}=t;if(typeof i=="object"&&i!==null){let a=qi(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=ye(s.model)??(typeof l=="object"&&l!==null?qi(l):void 0);if(c)return c}}return}catch{return}}function qi(e){return ye(e.model)??ye(e.modelId)??ye(e.model_name)}function ye(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 ee(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Xi(e){try{if(typeof e!="object"||e===null)return;let t=e,{settings:n}=t;if(typeof n=="object"&&n!==null){let s=ee(n.instructions);if(s)return s}let r=ee(t.instructions);if(r)return r;let i=ee(t.systemPrompt);if(i)return i;let o=ee(t.system);if(o)return o;let{agents:a}=t;if(a instanceof Map){for(let s of a.values())if(typeof s=="object"&&s!==null){let l=s,c=ee(l.systemPrompt)??ee(l.instructions)??ee(l.system);if(c)return c}}return}catch{return}}async function du(e){let t=Xi(e);if(t)return t;try{if(typeof e=="object"&&e!==null){let n=e.getInstructions;if(typeof n=="function"){let r=await n.call(e),i=ee(r);if(i)return i}}}catch{}}function fu(e){try{if(!Array.isArray(e))return;for(let t of e){let n=Array.isArray(t)?t:[t];for(let r of n)if(pu(r)){let i=mu(r);if(i)return i}}return}catch{return}}function pu(e){if(typeof e!="object"||e===null)return!1;let t=e,n=t._getType;if(typeof n=="function")try{if(n.call(e)==="system")return!0}catch{}return t.role==="system"||t.type==="system"?!0:e.constructor?.name==="SystemMessage"}function mu(e){let t=e.content;if(typeof t=="string")return t.trim()||void 0;if(Array.isArray(t))return t.map(r=>r&&typeof r=="object"&&typeof r.text=="string"?r.text:"").join("").trim()||void 0}function ue(e,t,n,r,i,o,a){let s=[e??"",t??"",n??"",r??"",o??""].join(uu),l=Ui.get(s);return l||(l=new ni(e,t,n,void 0,r,Z,wt),l.registerHostEnvironment(i,a),Ui.set(s,l)),o!==void 0&&l.setFailMode(o),l}function Vi(e,t){try{let n=ue(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),r=Jt(e);r.length>0&&n.reportToolSurface(r),bi(e).then(i=>{let o=i.filter(a=>!r.some(s=>s.name===a.name));o.length>0&&n.reportToolSurface(o)}).catch(()=>{})}catch{}}function gu(e,t,n){try{let r=ue(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),i=Xi(e);if(i){r.captureCloneMetadata({systemPrompt:i,...n?{agentType:n}:{}});return}du(e).then(o=>{o&&r.captureCloneMetadata({systemPrompt:o,...n?{agentType:n}:{}})}).catch(()=>{})}catch{}}function hu(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}}var Gi=!1;function yu(e){if(!(e||Gi)){Gi=!0;try{console.error("[VisIQ] NOT CONFIGURED: no VISIQ_API_KEY resolved \u2014 this agent is running UNGOVERNED. No policy is evaluated, no decision is enforced and nothing is recorded. NOTE: the SDK reads the PROCESS environment and does NOT load a .env file \u2014 if your keys are in .env, start the agent with `node --env-file=.env` (Node 20+) or export them in your shell.")}catch{}}}function _u(e){let t=e?.agentId??process.env.VISIQ_AGENT_ID??vu(),n=e?.apiKey??process.env.VISIQ_API_KEY;yu(n);let r=e?.endpoint??process.env.VISIQ_ENDPOINT??(n?cu:void 0),i=typeof e?.sessionId=="string"?e.sessionId.trim():"",o=i.length>0?i.slice(0,255):void 0;return{agentId:t,...o?{sessionId:o}:{},...(()=>{let a=Ti(e?.identity);return a?{resolveIdentity:a}:{}})(),apiKey:n,endpoint:r,hitlTimeoutMs:wu(e?.hitlTimeoutMs),timeoutMs:hu(e?.timeoutMs),onInstrumentFailure:e?.onInstrumentFailure??bu(),failMode:X(e?.failMode)}}function bu(){let e=process.env.VISIQ_ON_INSTRUMENT_FAILURE;if(e==="throw")return"throw";if(e==="warn")return"warn"}function vu(){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=bt.join(t,"package.json");if(_t.existsSync(r)){let o=JSON.parse(_t.readFileSync(r,"utf8"));if(typeof o.name=="string"&&o.name.trim()){let a=e(o.name);if(a)return a}break}let i=bt.dirname(t);if(i===t)break;t=i}}catch{}try{let t=e(Zi.hostname());if(t)return t}catch{}return"agent"}function wu(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 Kt}function ku(e){let t=e;if(typeof t.invoke=="function"&&t.agent&&Array.isArray(t.tools))return"langchain-executor";if(typeof t.invoke=="function"&&t.nodes&&(t.edges||t.lg_is_pregel===!0||typeof t.builder=="object"&&t.builder!==null&&t.builder.edges))return"langchain-graph";if(typeof t.invoke=="function"){let n=un(t);if(n!==t&&n.nodes&&(n.lg_is_pregel===!0||n.channels))return"langchain-graph"}return"unknown"}function Au(e,t){let n=e,r=ue(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),i=Iu(n);for(let l of i)dn(l,t.agentId,r),Eu(l,t.agentId,r,t),no(l,r,t);let{nodes:o}=un(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);A("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=cn(Ki(c,t.sessionId)),d=Yi(t.agentId,r),f=c?.callbacks??[];return O.run(u,()=>s.call(this,l,{...c,callbacks:[...f,d]}))},typeof n.stream=="function"){let l=n.stream;n.stream=function(c,u){let d=cn(Ki(u,t.sessionId)),f=Yi(t.agentId,r),p=u?.callbacks??[];return O.run(d,()=>l.call(this,c,{...u,callbacks:[...p,f]}))}}return e}function un(e){if(e.nodes&&typeof e.nodes=="object")return e;for(let t of["graph","builder"]){let n=e[t];if(n&&typeof n=="object"&&n.nodes)return n}return e}function Iu(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}=un(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 Ki(e,t){let n=o=>{if(typeof o!="string")return null;let a=o.trim();return a.length>0?a.slice(0,255):null},r=n(t);if(r)return r;let i=e?.configurable;if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let o=i,a=n(o.thread_id)??n(o.session_id);if(a)return a}return Qi()}function cn(e){return{session_id:e??Qi(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function dn(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 Hi(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 Hi(s,t,String(a),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&dn(r.retriever,t,n)}}var Su=Symbol.for("visiq.operations"),Tu=new Set(["action","retrieval","delegation"]);function eo(e){if(typeof e!="object"||e===null)return;let t=e[Su]??e.visiqOperations;if(!Array.isArray(t))return;let n=t.filter(r=>typeof r=="string"&&Tu.has(r));return n.length>0?Array.from(new Set(n)):void 0}function Eu(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(R=>R.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),d=l.some(R=>c.has(R)),f=u.has(l[0]??""),p=d||f,m=["update","delete","create","archive","insert","remove"],g=l.some(R=>m.some(b=>R.length>b.length&&R.endsWith(b))),w=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!p&&!g,S=eo(i),v=S?.includes("retrieval")??!1;if(S!==void 0&&!v||!(s||w||v))return;let P=S?v&&S.includes("action"):d||g;if(!P)if(s)dn(i.retriever,t,n);else{let R=globalThis,b=Symbol.for("visiq.recall.closureRetrieverWarned"),U=R[b]??=new Set;U.has(a)||(U.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 te=i.func;P?(i[to]=!0,i.func=async function(...R){await n.awaitBundleReady();let b=R[0],U=typeof b=="object"&&b!==null?b:{input:b},_e=typeof U.query=="string"?U.query:void 0,k=O.getStore(),I=J(k),M;try{let D=r?.resolveIdentity?.(),H=le(D);M=await n.evaluate({operations:["retrieval","action"],agentId:t,...k?.session_id?{sessionId:k.session_id}:{},...D?{identity:D}:{},...H?{normalized:H}:{},toolName:a||"unknown",toolArgs:U,resourceType:"document",resourceMetadata:{},..._e!==void 0?{query:_e}:{},...I?{telemetry:I}:{}})}catch(D){let H=D instanceof Error?D.message:String(D);return X(r?.failMode)==="closed"?N({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${H} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(A("eval-error",`policy evaluation failed for hybrid tool "${a||"unknown"}": ${H}`),te.apply(this,R))}let C=oe(M),vt=Pe(C.hitlFallback,C.argRedactionRules),fn=R,pn=()=>{try{return fn=[L(U,$(C.argRedactionRules)),...R.slice(1)],null}catch{return X(r?.failMode)==="closed"?N({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(A("mask-error",`argument masking failed for tool "${a||"unknown"}" \u2014 running with UNMASKED args`),null)}};if(C.decision==="approval_required"&&C.decisionId&&r){let D=await je({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:C.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:vt,sdkVersion:Z});if(D.resolution==="mask"){let H=pn();if(H)return H}else if(D.resolution!=="proceed")return N({outcome:"approval_required",code:C.ruleCode??"HITL-BLOCK",reason:C.reason,mechanism:D.reason})}else if(!C.allowed)return N({outcome:"deny",code:C.ruleCode??"DENY",reason:C.reason});if(C.decision==="mask"&&C.argRedactionRules.length>0){let D=pn();if(D)return D}let so=await te.apply(this,fn);return yi(so,M,r?.failMode)}):i.func=async function(...R){let b=await te.apply(this,R);return typeof b=="string"?pi(b,t,n):mt(b,t,n)},i[o]=!0}var to=Symbol.for("visiq.hybrid.instrumented");async function Hi(e,t,n,r){return fi(e,t,n,r)}var Wi=["invoke","call","_call"],ce=new lu;function no(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[to]||eo(r)?.every(c=>c==="retrieval")||!Wi.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,f,p)=>{let m=ce.getStore();if(m!==void 0&&m.gateKey===s&&!m.entered.has(p))return m.entered.add(p),c.call(u,d,...f);let g;if(typeof d=="string")g=d;else{let k=d?.input;g=k!=null?String(k):JSON.stringify(d)??""}let _=O.getStore(),w=J(_),S=typeof d=="object"&&d!==null?d:{input:g},v=lt(a,S);v&&ke(t,{agentId:o,sessionId:_?.session_id,framework:"langchain"},v);let F={agentId:o,sessionId:_?.session_id,framework:"langchain"},T=be(a,S);try{Ae(t,F,{toolName:a,...T?{memory:T}:{},argSummary:g.slice(0,512)})}catch(k){G("step-beat",`emit failed for tool "${a}": ${ln(k)}`)}let P=Date.now(),te=async k=>{let I=await k();try{Ie(t,F,{toolName:a,ok:!0,durationMs:Date.now()-P,...re(I)!==void 0?{bytes:re(I)}:{},...ie(I)!==void 0?{itemCount:ie(I)}:{},...T?{memory:T}:{}})}catch(M){G("observation-beat",`emit failed for tool "${a}": ${ln(M)}`)}return I},R=(k,I,M,C)=>{try{fe(t,F,{toolName:a,decision:k,...I?{ruleCode:I}:{},...M?{ruleLabel:M}:{},enforced:!0,...C?{harnessMessage:C}:{}})}catch(vt){G("intervention-beat",`emit failed for tool "${a}": ${ln(vt)}`)}};await t.awaitBundleReady();let b,U=!1;try{let k=n.resolveIdentity?.(),I=le(k),M=await t.evaluate({operations:v?["action","delegation"]:["action"],agentId:o,..._?.session_id?{sessionId:_.session_id}:{},...k?{identity:k}:{},...I?{normalized:I}:{},toolName:a,toolArgs:S,targetResource:en(g),...w?{telemetry:w}:{},...v?{context:ct(v,o)}:{}});({enforced:U}=M),b=oe(M)}catch(k){let I=k instanceof Error?k.message:String(k);return n.failMode==="closed"?N({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${I} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(A("eval-error",`policy evaluation failed for tool "${a}": ${I}`),ce.run({gateKey:s,entered:new Set([p])},()=>c.call(u,d,...f)))}let _e=k=>{let I=pe(a,k,{failMode:n.failMode==="closed"?"closed":"open",enforced:U});if(I.verdict==="block"){let C=N({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${I.detectors.join(",")})`});return R("deny","OUTPUT-BLOCK","outbound content carried a live secret",C),C}let M=k;return I.verdict==="redact"&&(M=I.redacted,A("outbound-secret-redacted",`outbound secret screen redacted ${I.detectors.length} detector(s): ${I.detectors.join(",")}`),R("mask","OUTPUT-BLOCK","outbound secret redacted before egress")),te(()=>ce.run({gateKey:s,entered:new Set([p])},()=>c.call(u,M,...f)))};if(b.decision==="approval_required"&&b.decisionId){let k=Pe(b.hitlFallback,b.argRedactionRules),I=await je({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:b.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:k,sdkVersion:Z});if(I.resolution==="proceed")return te(()=>ce.run({gateKey:s,entered:new Set([p])},()=>c.call(u,d,...f)));if(I.resolution==="mask")try{let C=L(d,$(b.argRedactionRules));return R("mask",b.ruleCode,b.reason),te(()=>ce.run({gateKey:s,entered:new Set([p])},()=>c.call(u,C,...f)))}catch{return n.failMode==="closed"?N({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(A("mask-error",`HITL mask fallback failed for tool "${a}" \u2014 running with UNMASKED args`),ce.run({gateKey:s,entered:new Set([p])},()=>c.call(u,d,...f)))}let M=N({outcome:"approval_required",code:b.ruleCode??"HITL-BLOCK",reason:b.reason,mechanism:I.reason});return R("approval_required",b.ruleCode,b.reason,M),M}if(!b.allowed){let k=N({outcome:"deny",code:b.ruleCode??"DENY",reason:b.reason});return R("deny",b.ruleCode,b.reason,k),k}if(b.decision==="mask"&&b.argRedactionRules.length>0)try{let k=L(d,$(b.argRedactionRules));return R("mask",b.ruleCode,b.reason),_e(k)}catch{return n.failMode==="closed"?N({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(A("mask-error",`argument masking failed for tool "${a}" \u2014 running with UNMASKED args`),ce.run({gateKey:s,entered:new Set([p])},()=>c.call(u,d,...f)))}return _e(d)};for(let c of Wi){if(typeof r[c]!="function")continue;let u=r[c];r[c]=function(d,...f){return l(u,this,d,f,c)}}r[i]=!0}function ln(e){return e instanceof Error?e.message:String(e)}function Ru(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 Cu(e,t){let n=(p,m)=>{if(!p||typeof p!="object")return;let g=p[m];return typeof g=="number"&&Number.isFinite(g)?g: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"),f=s!==void 0?Math.max(0,s-(u??0)-(d??0)):void 0;return{...f!==void 0?{tokensIn:f}:{},...l!==void 0?{tokensOut:l}:{},...u!==void 0?{cacheRead:u}:{},...d!==void 0?{cacheWrite:d}:{}}}function Yi(e,t){let n=(r,i,o,a)=>{let s=Ru(r,i,o);s&&(a.llm_model=s,t.captureCloneMetadata({model:s,agentType:"langchain"}))};return{name:"VisiqHandler",handleChatModelStart:async(r,i,o,a,s,l,c)=>{let u=O.getStore();if(u){try{if(Array.isArray(i))for(let d of i){let f=Array.isArray(d)?d:[d];for(let p of f){let m=p?.content;u.llm_prompts.push(typeof m=="string"?m:JSON.stringify(m??p))}}}catch{}n(r,s,c,u);try{let d=fu(i);d&&t.captureCloneMetadata({systemPrompt:d,agentType:"langchain"})}catch{}}},handleLLMStart:async(r,i,o,a,s,l,c)=>{let u=O.getStore();u&&(u.llm_prompts.push(...i),n(r,s,c,u))},handleLLMEnd:async r=>{let i=O.getStore();if(!i)return;let a=r?.generations?.[0]?.[0],s=typeof a?.text=="string"?a.text:"";s&&i.llm_responses.push(s);try{let l=r?.llmOutput,c=a?.message&&typeof a.message=="object"?a.message:void 0,u=Cu(l,c);if(!u&&!s)return;let d=c?.tool_calls,f=typeof l?.model=="string"?l.model:void 0,p=i.llm_model??f;await t.awaitBundleReady(),It(t,{agentId:e,sessionId:i.session_id,framework:"langchain"},{...s?{texts:[s]}:{},...u?{usage:u}:{},...p?{model:p}:{},final:!(Array.isArray(d)&&d.length>0)})}catch{}},handleAgentAction:async r=>{let i=O.getStore();if(!i)return;let o=typeof r.log=="string"?r.log:"";o&&i.agent_reasoning.push(o)},handleRetrieverStart:async(r,i,o)=>{let a=O.getStore();a&&a.retrieverQueries.set(o,i??"")},handleRetrieverEnd:async(r,i)=>{let o=O.getStore();if(!o)return;let a=o.retrieverQueries.get(i)??"";if(o.retrieverQueries.delete(i),!Array.isArray(r))return;let s=J(o);for(let l of r){let c=l,u=String(c.pageContent??c.text??c.content??""),d=pt(c);await t.evaluate({operations:["retrieval"],agentId:e,resourceType:"document",resourceMetadata:d,query:a,contentPreview:u,...s?{telemetry:s}:{}})}},handleRetrieverError:async(r,i)=>{let o=O.getStore();o&&o.retrieverQueries.delete(i)}}}var ro=["_call","execute","call","run","invoke"];function xu(e){let t=e;for(let n of ro)if(typeof t[n]=="function")return!0;return!1}function Ou(e){return e instanceof se?!0:e instanceof V?typeof e.status=="number"&&e.status>=400&&e.status<500:!1}function Nu(e,t,n){let r=null,i=null,o=!1,a=async()=>{if(r)return r;if(i)throw new se(`Failed to bootstrap grant ${n}: ${i.message}`,null);let s;try{s=await wi(t.agentId,n)}catch(l){throw o=Ou(l),o&&(i=l instanceof Error?l:new Error(String(l))),new se(`Failed to bootstrap grant ${n}: ${l instanceof Error?l.message:String(l)}`,null)}return r=ki(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===Be)return!0;let u=Reflect.get(s,l,c);return typeof u!="function"||typeof l!="string"||!ro.includes(l)?u:async function(...d){let f;try{f=await a()}catch(m){if(o||t.failMode==="closed")throw m;return A("grant-bootstrap",`grant ${n} bootstrap failed: ${m instanceof Error?m.message:String(m)}`),u.call(this,...d)}return f[l].call(f,...d)}}})}function Fu(e,t){let n=ue(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode);no(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";ze(e,i,io(t))}return e}function io(e){return{agentId:e.agentId,unified:ue(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}:{},...e.sessionId?{hostSessionId:e.sessionId}:{},...e.resolveIdentity?{resolveIdentity:e.resolveIdentity}:{},telemetry:cn(e.sessionId)}}async function oo(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 ge({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 Ge=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),de(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return de(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return de(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return de(this.transport,"POST","/api/discovery/fleet/stop")}};var Ke=class{constructor(t){this.transport=t}transport;connectAws(t){return de(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function Mu(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 Ge(r),integrations:new Ke(r)}}async function de(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,o={...ne(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 ao=Ji;ao.delegate=oo;var ep=ao;export{st as DEFAULT_FAIL_MODE,Ge as FleetClient,Ke as IntegrationsClient,Mu as createVisiqClient,oo as delegate,$e as normalizeFailMode,ep as visiq};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visiq/harness",
3
- "version": "0.2.22",
3
+ "version": "0.2.25",
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",