@visiq/harness 0.2.17 → 0.2.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{randomUUID as Ll}from"node:crypto";import*as ot from"node:fs";import*as at from"node:path";import*as gi from"node:os";import{AsyncLocalStorage as Fl}from"node:async_hooks";import{z as h}from"zod";import*as j from"node:os";import{randomUUID as me}from"node:crypto";var lt=1,Yt="X-VisIQ-SDK",Zt="X-VisIQ-Dialect",Jt="unknown";function W(e,t=1){return{[Yt]:e&&e.length>0?e:Jt,[Zt]:String(t)}}var Xt="interceptor_source",Ii=h.enum(["enforce","audit","off"]),Ti=h.enum(["closed","open"]),en=h.enum(["enforce","monitor","off"]),Ei=h.object({apiKey:h.string().min(1,"apiKey is required"),agentId:h.string().min(1,"agentId is required"),endpoint:h.string().url().optional(),mode:Ii.optional(),timeoutMs:h.number().int().positive().optional(),hitlTimeoutMs:h.number().int().positive().optional(),failBehavior:Ti.optional()}),ic=h.object({agent_id:h.string().min(1),target_app:h.string().min(1),action:h.string().min(1),context:h.record(h.unknown()).optional(),session_id:h.string().min(1).max(255).optional(),action_schema_id:h.string().min(1).max(128).optional(),telemetry:h.record(h.unknown()).optional()}),Ri=h.object({field:h.string().optional(),pattern:h.string().optional(),replacement:h.string().optional(),mode:h.enum(["full","partial","email"]).optional(),keepFirst:h.number().optional(),keepLast:h.number().optional(),maskChar:h.string().optional()}),Ci=h.object({decision_id:h.string().min(1),decision:h.enum(["permit","deny","approval_required","mask"]),reason:h.string().optional(),rule_code:h.string().nullable().optional(),enforced:h.boolean().optional(),agent_mode:en.optional(),arg_redaction_rules:h.array(Ri).optional(),plane:h.string().nullable().optional(),operation:h.string().nullable().optional(),is_retrieval:h.boolean().optional(),metadata:h.record(h.unknown()).optional()}),xi=h.object({field:h.string().min(1),operator:h.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:h.union([h.string(),h.number(),h.array(h.string())])}),Oi=h.object({id:h.string().min(1),rule_code:h.string().default(""),name:h.string().min(1),description:h.string().nullable().default(null),effect:h.enum(["allow","deny","hitl","mask"]),resource_type:h.string().min(1),rego_source:h.string().default(""),target_app:h.string().nullable().default(null),action_pattern:h.string().nullable().default(null),conditions:h.array(xi).default([]),priority:h.number().int().default(0)}),Ni=h.object({version:h.string().min(1),agent_mode:en.optional(),rules:h.array(Oi),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()}),Mi=2e3,Di=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function Li(e){let t=e.rules.filter(n=>Di(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 ct=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return W(this.config.sdkVersion,this.config.sdkDialect)}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return Ci.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=Ni.parse(o);return Li(a),a}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async reportSkillInventory(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/skills`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,skills:e})});n.ok||console.warn(`[ALLOW] Skill-inventory report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Skill-inventory report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let 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 Fi(Mi)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Fi(e){return new Promise(t=>setTimeout(t,e))}function je(){let e={};try{let t=`${j.platform()} ${j.release()}`.trim();t&&(e.os=t)}catch{}try{let t=j.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=j.userInfo();t&&(e.username=t)}catch{}try{let t=$i();t&&(e.ip=t)}catch{}return e}function $i(){let e=j.networkInterfaces();for(let t of Object.keys(e))for(let n of e[t]??[])if((n.family==="IPv4"||n.family===4)&&!n.internal&&n.address)return n.address}function Pi(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function $e(e,...t){for(let n of t){let r=Pi(e[n]);if(r)return r}}function Pe(e){if($e(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if($e(e,"user_id","userId"))return"user";if($e(e,"agent_id","agentId"))return"agent";if($e(e,"org_id","orgId","namespace"))return"org"}var ji=[{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=Pe(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=Pe(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=Pe(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=Pe(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function fe(e,t){if(!e)return null;let n=t??{};for(let r of ji)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function ut(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 Qt=new Map;function ge(e){let t=(Qt.get(e)??0)+1;return Qt.set(e,t),t}function tn(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 dt(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 tc}from"node:crypto";import*as st from"node:fs";import*as lt from"node:path";import*as ki from"node:os";import{AsyncLocalStorage as nc}from"node:async_hooks";import{z as h}from"zod";import*as j from"node:os";import{randomUUID as ge}from"node:crypto";var ut=1,Xt="X-VisIQ-SDK",en="X-VisIQ-Dialect",tn="unknown";function Q(e,t=1){return{[Xt]:e&&e.length>0?e:tn,[en]:String(t)}}var nn="interceptor_source",Mi=h.enum(["enforce","audit","off"]),Di=h.enum(["closed","open"]),rn=h.enum(["enforce","monitor","off"]),Fi=h.object({apiKey:h.string().min(1,"apiKey is required"),agentId:h.string().min(1,"agentId is required"),endpoint:h.string().url().optional(),mode:Mi.optional(),timeoutMs:h.number().int().positive().optional(),hitlTimeoutMs:h.number().int().positive().optional(),failBehavior:Di.optional()}),Cc=h.object({agent_id:h.string().min(1),target_app:h.string().min(1),action:h.string().min(1),context:h.record(h.unknown()).optional(),session_id:h.string().min(1).max(255).optional(),action_schema_id:h.string().min(1).max(128).optional(),telemetry:h.record(h.unknown()).optional()}),Li=h.object({field:h.string().optional(),pattern:h.string().optional(),replacement:h.string().optional(),mode:h.enum(["full","partial","email"]).optional(),keepFirst:h.number().optional(),keepLast:h.number().optional(),maskChar:h.string().optional()}),$i=h.object({decision_id:h.string().min(1),decision:h.enum(["permit","deny","approval_required","mask"]),reason:h.string().optional(),rule_code:h.string().nullable().optional(),enforced:h.boolean().optional(),agent_mode:rn.optional(),arg_redaction_rules:h.array(Li).optional(),plane:h.string().nullable().optional(),operation:h.string().nullable().optional(),is_retrieval:h.boolean().optional(),metadata:h.record(h.unknown()).optional()}),Pi=h.object({field:h.string().min(1),operator:h.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:h.union([h.string(),h.number(),h.array(h.string())])}),ji=h.object({id:h.string().min(1),rule_code:h.string().default(""),name:h.string().min(1),description:h.string().nullable().default(null),effect:h.enum(["allow","deny","hitl","mask"]),resource_type:h.string().min(1),rego_source:h.string().default(""),target_app:h.string().nullable().default(null),action_pattern:h.string().nullable().default(null),conditions:h.array(Pi).default([]),priority:h.number().int().default(0)}),Bi=h.object({version:h.string().min(1),agent_mode:rn.optional(),rules:h.array(ji),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()}),Ui=2e3,qi=e=>new RegExp("^\\p{White_Space}*$","u").test(e)||e.trim().length===0;function zi(e){let t=e.rules.filter(n=>qi(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 dt=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return Q(this.config.sdkVersion,this.config.sdkDialect)}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return $i.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=Bi.parse(o);return zi(a),a}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async reportSkillInventory(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/skills`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,skills:e})});n.ok||console.warn(`[ALLOW] Skill-inventory report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Skill-inventory report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let 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 Vi(Ui)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Vi(e){return new Promise(t=>setTimeout(t,e))}function Be(){let e={};try{let t=`${j.platform()} ${j.release()}`.trim();t&&(e.os=t)}catch{}try{let t=j.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=j.userInfo();t&&(e.username=t)}catch{}try{let t=Ki();t&&(e.ip=t)}catch{}return e}function Ki(){let e=j.networkInterfaces();for(let t of Object.keys(e))for(let n of e[t]??[])if((n.family==="IPv4"||n.family===4)&&!n.internal&&n.address)return n.address}function Gi(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Pe(e,...t){for(let n of t){let r=Gi(e[n]);if(r)return r}}function je(e){if(Pe(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(Pe(e,"user_id","userId"))return"user";if(Pe(e,"agent_id","agentId"))return"agent";if(Pe(e,"org_id","orgId","namespace"))return"org"}var Hi=[{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=je(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=je(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=je(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=je(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function me(e,t){if(!e)return null;let n=t??{};for(let r of Hi)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function pt(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 Jt=new Map;function he(e){let t=(Jt.get(e)??0)+1;return Jt.set(e,t),t}function on(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 ft(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=
|
|
4
|
-
`).map(l=>Ui(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],g=c[2].trim();r.set(f,ve(g)),a++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let f=u[1],g=u[2].trim(),m=u[3].trim(),p=[];if(m&&m!=="}"){let O=m.endsWith("}")?m.slice(0,-1).trim():m;O&&p.push(O),m.endsWith("}")||(a++,a=Be(o,a,p))}else m==="}"||(a++,a=Be(o,a,p));let _=on(p);i.push({variable:f,value:ve(g),conditions:_,rawConditions:rn(p)}),a++;continue}let d=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(d){let f=d[1],g=d[2].trim(),m=[];if(g&&g!=="}"){let _=g.endsWith("}")?g.slice(0,-1).trim():g;_&&m.push(_),g.endsWith("}")||(a++,a=Be(o,a,m))}else g==="}"||(a++,a=Be(o,a,m));let p=on(m);i.push({variable:f,value:"true",conditions:p,rawConditions:rn(m)}),a++;continue}a++}let s={defaults:r,rules:i};return nn.set(t,s),s}function Ui(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 Be(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 ve(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function qi(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function on(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=Wi(i);o&&t.push(o)}}return t}var ft=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,zi=new RegExp(`^(${ft.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),Vi=new RegExp(`^(${ft.source})\\s*==\\s*((?:input|data)\\S*)$`),Ki=/^([^\s=!]+)\s*==\s*(.+)$/,Gi=/^([^\s=!]+)\s*!=\s*(.+)$/,cc=new RegExp(`^(?:${ft.source})$`);var Hi=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function Wi(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:qe,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(Hi);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:qi(s[1])};let l=n.match(zi);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:pn(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let p=Ji(c[2]);if(p!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:p}}let u=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(u)return{type:"comparison",negated:t,field:u[1].trim(),operator:u[2],value:parseFloat(u[3])};let d=n.match(Vi);if(d)return{type:"equality",negated:t,field:d[2].trim(),value:ve(d[1].trim())};let f=n.match(Ki);if(f)return{type:"equality",negated:t,field:f[1].trim(),value:ve(f[2].trim())};let g=n.match(Gi);if(g)return{type:"inequality",negated:t,field:g[1].trim(),value:ve(g[2].trim())};let m=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return m?{type:"truthy",negated:t,field:m[1].trim()}:{type:"truthy",negated:!1,field:qe,value:e.trim()}}var qe="__unrecognized_condition_forces_deny__";var Qi=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function dn(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==qe&&Qi.test(r.field)&&t.push(r.field);return t}var Yi=["input.normalized.","input.normalized["];function Zi(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions){let{field:i}=r;typeof i!="string"||i===qe||Yi.some(o=>i.startsWith(o))&&t.add(i)}return[...t].sort()}function pn(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 Ji(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(pn(s))}return a}var uc=new RegExp("^\\p{White_Space}*$","u");var Xi=["tier1","tier2","tier3"];function fn(e){return typeof e=="string"&&Xi.includes(e)}var eo=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],to=["internal","customer_facing","experimental","third_party"],mn=[...eo,...to];function no(e){return typeof e=="string"&&mn.includes(e)}function gn(e){let t=new Set;for(let n of e)no(n)&&t.add(n);return mn.filter(n=>t.has(n))}var hn=["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"],ro=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],io=["production","staging","development","test"],oo=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function ao(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 an={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 so(e){let t=ao(e);return t===null?"other":an[t]??an[t.replace(/_/g,"")]??"other"}function yn(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=so(t.targetApp)),n.context=r}return n}var sn=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],lo=["read","write","delete","share","export","decide","execute"],ln=["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"],uo={action_class:hn,operation:lo,"context/app_category":ro,"context/environment":io,"context/actor_function":oo,"read/classification":co,"read/data_categories":sn,"read/data_sensitivity":ln,"write/data_categories":sn,"write/data_sensitivity":ln};function _n(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(uo)){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 cn=64,po=64,we={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function bn(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var fo=new Set(["deny","approval_required","escalate"]);function be(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>cn?r.slice(0,cn):r}function un(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Ue(e){return typeof e=="string"&&e.length>0?e:null}function vn(e,t){let n=un(t.data_categories),r=Ue(t.classification),i=un(t.taint),o=Ue(t.action_class),a=o&&hn.includes(o)?o:null,s=Ue(t.target_app),l=Ue(t.decision),c={...e.action_counts};if(a)if(a in c)c[a]=(c[a]??0)+1;else if(Object.keys(c).length<po)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:be(e.retrieved_data_categories,n),retrieved_classifications:be(e.retrieved_classifications,r?[r]:[]),taint:be(e.taint,i),action_classes:be(e.action_classes,a?[a]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&fo.has(l)?1:0),event_count:e.event_count+1,target_apps:be(e.target_apps,s?[s]:[])}}var wn="generic",kn=[{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:wn,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."}],mo=kn.map(e=>e.id),dc=new Map(kn.map(e=>[e.id,e])),pc=new Set(mo);function An(e){return Array.isArray(e)&&e.length>0?[...e]:[wn]}var go=/^[a-z][a-z0-9_]*$/;function Sn(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&go.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var ho=["narrow","moderate","broad","unbounded","unknown"];function In(e){return typeof e=="string"&&ho.includes(e)}function Tn(e){return e==="open"||e==="closed"?e:null}var _o=["tool_name","function","name","action"];function ze(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)ze(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)ze(o,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function bo(e){let t=[];return ze(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function vo(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function wo(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function ko(e,t={}){if(t.discriminatorField===null)return null;let n=[];ze(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??_o;for(let i of r){let o=null;for(let[a,s]of n){if(vo(a)!==i)continue;let l=wo(s);l!==null&&(o===null||a<o.path)&&(o={path:a,value:l})}if(o)return o.value}return null}function En(e,t={}){let n=yo("sha256").update(bo(e).join(",")).digest("hex").slice(0,16),r=ko(e,t);return r!==null?`${n}:${r}`:n}var Ao=["action","retrieval","delegation"];function So(e){return typeof e=="string"&&Ao.includes(e)}var Io=new Set(["rules"]);function Rn(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Io.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(So):[];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 Cn(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=pt(r)}catch{continue}let o=Zi(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 We}from"zod";var To=/[^\u0000-\u007F]/,Hn=new RegExp("^\\p{Nd}$","u"),Eo=new RegExp("^\\p{Pd}$","u"),Ro=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,Co=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,xo=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),Wn="<invisible>",xn=new Map;function Oo(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&&Hn.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function No(e){if(e<128)return null;let t=xn.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 Hn.test(r)?Oo(e):Eo.test(r)||xo.has(e)?"-":Ro.test(r)?" ":Co.test(r)?Wn:null})();return xn.set(e,n),n}function _t(e){if(typeof e!="string"||e.length===0||!To.test(e))return[];let t=On(e,"as-separator");if(t===null)return[];let n=On(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function On(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=No(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===Wn){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 Mo(e,t){return{start:e.offsets[t.start],end:e.offsets[t.end]}}function Do(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 Nn(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 Qn="[REDACTED]",bt=[{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}],gc=bt.map(({name:e,re:t})=>({name:e,source:t.source})),Lo="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function Fo(e){return Yn(e,Lo)}function Yn(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 Zn(e){return new RegExp(Fo(e.source),e.flags)}var $o="(?:\\b|_)";function gt(e){return Yn(e,$o)}var Po=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function jo(e){let t=Po.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function ht(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 Bo(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 Uo(e){if(!/^\d{9}$/.test(e))return!1;let t=[3,7,1,3,7,1,3,7,1],n=0;for(let r=0;r<9;r++)n+=(e.charCodeAt(r)-48)*t[r];return n%10===0}var qo=[[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]],zo=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]];function Vo(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=qo[t][zo[r%8][n[r].charCodeAt(0)-48]];return t===0}function Ko(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 Go(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 Ho=[1,4,3,7,5,8,6,9,10];function Wo(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)*Ho[n];return t%11===0}var Qo="TRWAGMYFPDXBNJZSQVHLCKE";function Yo(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 Qo[Number(a)%23]===o}var Zo=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Jo(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Zo.has(t.slice(0,2)):!1}var vt=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&ht(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:Bo},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Uo},{name:"uk_nino",re:/\b[A-Za-z]{2} ?\d{2} ?\d{2} ?\d{2} ?[A-Da-d]\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:(e,t)=>t!==void 0&&t===t.toLowerCase()?!1:Jo(e)},{name:"in_aadhaar",re:/\b[2-9]\d{3}[ -]?\d{4}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===12&&Vo(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:Ko},{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:Yo},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&ht(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Go},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Wo}],Xo=Object.fromEntries([...bt,...vt].map(e=>[e.name,e.re.source])),S=Xo,hc=vt.map(e=>e.name),Jn=bt.map(({name:e,re:t})=>({name:e,re:Zn(t)})),Xn=vt.map(e=>({...e,re:Zn(e.re)})),yc=[...Jn,...Xn].map(({name:e,re:t})=>({name:String(e),source:t.source})),wt=["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"],ea={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=on(n.usage);e.emitCognition({clientEventId:ge(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:he(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 ye(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:ge(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:he(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 _e(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=n.memory?pt(n.memory):void 0;e.emitCognition({clientEventId:ge(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:he(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 be(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=pt(n.memory,{itemCount:a,bytes:o})),e.emitCognition({clientEventId:ge(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:he(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 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;e.emitCognition({clientEventId:ge(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:he(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 Y(e){try{let t=JSON.stringify(e);return typeof t=="string"?t.length:void 0}catch{return}}function Z(e){try{return Array.isArray(e)?e.length:void 0}catch{return}}import{z as y}from"zod";import{createHash as Wi}from"crypto";import{createHash as Co}from"crypto";var an=new Map;function sn(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function mt(e){let t=Wi("sha256").update(e).digest("hex"),n=an.get(t);if(n)return n;let r=new Map,i=[],o=e.split(`
|
|
4
|
+
`).map(l=>Qi(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 p=c[1],f=c[2].trim();r.set(p,we(f)),a++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let p=u[1],f=u[2].trim(),m=u[3].trim(),g=[];if(m&&m!=="}"){let I=m.endsWith("}")?m.slice(0,-1).trim():m;I&&g.push(I),m.endsWith("}")||(a++,a=Ue(o,a,g))}else m==="}"||(a++,a=Ue(o,a,g));let _=ln(g);i.push({variable:p,value:we(f),conditions:_,rawConditions:sn(g)}),a++;continue}let d=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(d){let p=d[1],f=d[2].trim(),m=[];if(f&&f!=="}"){let _=f.endsWith("}")?f.slice(0,-1).trim():f;_&&m.push(_),f.endsWith("}")||(a++,a=Ue(o,a,m))}else f==="}"||(a++,a=Ue(o,a,m));let g=ln(m);i.push({variable:p,value:"true",conditions:g,rawConditions:sn(m)}),a++;continue}a++}let s={defaults:r,rules:i};return an.set(t,s),s}function Qi(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 Ue(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 we(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Yi(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function ln(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=no(i);o&&t.push(o)}}return t}var gt=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,Zi=new RegExp(`^(${gt.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),Ji=new RegExp(`^(${gt.source})\\s*==\\s*((?:input|data)\\S*)$`),Xi=/^([^\s=!]+)\s*==\s*(.+)$/,eo=/^([^\s=!]+)\s*!=\s*(.+)$/,Dc=new RegExp(`^(?:${gt.source})$`);var to=/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/;function no(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:ze,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(to);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:Yi(s[1])};let l=n.match(Zi);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:gn(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let g=ao(c[2]);if(g!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:g}}let u=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(u)return{type:"comparison",negated:t,field:u[1].trim(),operator:u[2],value:parseFloat(u[3])};let d=n.match(Ji);if(d)return{type:"equality",negated:t,field:d[2].trim(),value:we(d[1].trim())};let p=n.match(Xi);if(p)return{type:"equality",negated:t,field:p[1].trim(),value:we(p[2].trim())};let f=n.match(eo);if(f)return{type:"inequality",negated:t,field:f[1].trim(),value:we(f[2].trim())};let m=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return m?{type:"truthy",negated:t,field:m[1].trim()}:{type:"truthy",negated:!1,field:ze,value:e.trim()}}var ze="__unrecognized_condition_forces_deny__";var ro=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function mn(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==ze&&ro.test(r.field)&&t.push(r.field);return t}var io=["input.normalized.","input.normalized["];function oo(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions){let{field:i}=r;typeof i!="string"||i===ze||io.some(o=>i.startsWith(o))&&t.add(i)}return[...t].sort()}function gn(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 ao(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(gn(s))}return a}var Fc=new RegExp("^\\p{White_Space}*$","u");var so=["tier1","tier2","tier3"];function hn(e){return typeof e=="string"&&so.includes(e)}var lo=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],co=["internal","customer_facing","experimental","third_party"],yn=[...lo,...co];function uo(e){return typeof e=="string"&&yn.includes(e)}function _n(e){let t=new Set;for(let n of e)uo(n)&&t.add(n);return yn.filter(n=>t.has(n))}var bn=["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"],po=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],fo=["production","staging","development","test"],mo=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function go(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 cn={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 ho(e){let t=go(e);return t===null?"other":cn[t]??cn[t.replace(/_/g,"")]??"other"}function vn(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=ho(t.targetApp)),n.context=r}return n}var un=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],yo=["read","write","delete","share","export","decide","execute"],dn=["none","low","medium","high","critical"],_o=["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"],bo={action_class:bn,operation:yo,"context/app_category":po,"context/environment":fo,"context/actor_function":mo,"read/classification":_o,"read/data_categories":un,"read/data_sensitivity":dn,"write/data_categories":un,"write/data_sensitivity":dn};function wn(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(bo)){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 pn=64,vo=64,ke={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function kn(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var wo=new Set(["deny","approval_required","escalate"]);function ve(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>pn?r.slice(0,pn):r}function fn(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function qe(e){return typeof e=="string"&&e.length>0?e:null}function An(e,t){let n=fn(t.data_categories),r=qe(t.classification),i=fn(t.taint),o=qe(t.action_class),a=o&&bn.includes(o)?o:null,s=qe(t.target_app),l=qe(t.decision),c={...e.action_counts};if(a)if(a in c)c[a]=(c[a]??0)+1;else if(Object.keys(c).length<vo)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:ve(e.retrieved_data_categories,n),retrieved_classifications:ve(e.retrieved_classifications,r?[r]:[]),taint:ve(e.taint,i),action_classes:ve(e.action_classes,a?[a]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&wo.has(l)?1:0),event_count:e.event_count+1,target_apps:ve(e.target_apps,s?[s]:[])}}var Sn="generic",In=[{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:Sn,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."}],ko=In.map(e=>e.id),Lc=new Map(In.map(e=>[e.id,e])),$c=new Set(ko);function Tn(e){return Array.isArray(e)&&e.length>0?[...e]:[Sn]}var Ao=/^[a-z][a-z0-9_]*$/;function En(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Ao.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var So=["narrow","moderate","broad","unbounded","unknown"];function Rn(e){return typeof e=="string"&&So.includes(e)}function Io(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 To(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+=Io((i^o)>>>0)}return n}var Eo=["proposed","approved","revoked"];function Ro(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"&&Eo.includes(t.status)}function Cn(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(Ro(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=To(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 xn(e){return e==="open"||e==="closed"?e:null}var xo=["tool_name","function","name","action"];function Ve(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)Ve(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)Ve(o,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Oo(e){let t=[];return Ve(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function No(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function Mo(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function Do(e,t={}){if(t.discriminatorField===null)return null;let n=[];Ve(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??xo;for(let i of r){let o=null;for(let[a,s]of n){if(No(a)!==i)continue;let l=Mo(s);l!==null&&(o===null||a<o.path)&&(o={path:a,value:l})}if(o)return o.value}return null}function On(e,t={}){let n=Co("sha256").update(Oo(e).join(",")).digest("hex").slice(0,16),r=Do(e,t);return r!==null?`${n}:${r}`:n}var Fo=["action","retrieval","delegation"];function Lo(e){return typeof e=="string"&&Fo.includes(e)}var $o=new Set(["rules"]);function Nn(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!$o.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Lo):[];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 Mn(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=mt(r)}catch{continue}let o=oo(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 Qe}from"zod";var Po=/[^\u0000-\u007F]/,Zn=new RegExp("^\\p{Nd}$","u"),jo=new RegExp("^\\p{Pd}$","u"),Bo=/^[\p{Zs}\p{Zl}\p{Zp}]$/u,Uo=/^[\p{Default_Ignorable_Code_Point}\p{Cf}]$/u,qo=new Map([[8722,"-"],[8259,"-"],[8231,"-"]]),Jn="<invisible>",Dn=new Map;function zo(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&&Zn.test(String.fromCodePoint(n-1));i++)n--;let r=(e-n)%10;return String.fromCharCode(48+r)}function Vo(e){if(e<128)return null;let t=Dn.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 Zn.test(r)?zo(e):jo.test(r)||qo.has(e)?"-":Bo.test(r)?" ":Uo.test(r)?Jn:null})();return Dn.set(e,n),n}function vt(e){if(typeof e!="string"||e.length===0||!Po.test(e))return[];let t=Fn(e,"as-separator");if(t===null)return[];let n=Fn(e,"as-nothing");return n===null||n.text===t.text?[t]:[t,n]}function Fn(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=Vo(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===Jn){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 Ko(e,t){return{start:e.offsets[t.start],end:e.offsets[t.end]}}function Go(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 Ln(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 Xn="[REDACTED]",wt=[{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}],Bc=wt.map(({name:e,re:t})=>({name:e,source:t.source})),Ho="(?:(?<![A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?![A-Za-z0-9]))";function Wo(e){return er(e,Ho)}function er(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 tr(e){return new RegExp(Wo(e.source),e.flags)}var Qo="(?:\\b|_)";function yt(e){return er(e,Qo)}var Yo=/^\(\?<!\[((?:[^\]\\]|\\.)*)\]\)/;function Zo(e){let t=Yo.exec(e);return t?`(?:^|[^${t[1]}])${e.slice(t[0].length)}`:e}function _t(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 Jo(e){let t=e.replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let 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 Xo(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 ea=[[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]],ta=[[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 na(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=ea[t][ta[r%8][n[r].charCodeAt(0)-48]];return t===0}function ra(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 ia(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 oa=[1,4,3,7,5,8,6,9,10];function aa(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)*oa[n];return t%11===0}var sa="TRWAGMYFPDXBNJZSQVHLCKE";function la(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 ca=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function ua(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!ca.has(t.slice(0,2)):!1}var kt=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&_t(e)},{name:"iban",re:/\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]){10,30}\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:Jo},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Xo},{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:ua(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&&na(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:ra},{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:la},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&_t(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:ia},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:aa}],da=Object.fromEntries([...wt,...kt].map(e=>[e.name,e.re.source])),T=da,Uc=kt.map(e=>e.name),nr=wt.map(({name:e,re:t})=>({name:e,re:tr(t)})),rr=kt.map(e=>({...e,re:tr(e.re)})),qc=[...nr,...rr].map(({name:e,re:t})=>({name:String(e),source:t.source})),At=["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"],pa={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
5
5
|
MIIEv\u2026
|
|
6
|
-
-----END PRIVATE KEY-----`,template:{pattern:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.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:S.mac_address,mode:"full"},defaultEnabled:!1}},Ge=Object.freeze(Object.fromEntries(wt.map(e=>{let t=ea[e];return[e,{...t,template:{...t.template,pattern:jo(gt(t.template.pattern))}}]})));var _c=new Set(wt.filter(e=>!Ge[e].defaultEnabled));function ta(e,t){let n=new Set;for(let r of wt)(Ge[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function Ve(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=kt(t),o=e;for(let{name:a,re:s}of Jn){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 Xn)n.has(a)||(o=pa(o,s,l,c,t,a,r));return o}function kt(e){return typeof e=="function"?e:()=>e}var Mn=e=>"\0".repeat(e.length);function na(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=_t(e);if(i.length===0)return Ve(e,t,n,r);let o=new Set,a=f=>{o.add(f)},s=Ve(e,Mn,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 g=Ve(f.text,Mn,n,a);for(let m=0;m<f.text.length;m++)if(!(g[m]!=="\0"||f.text[m]==="\0"))for(let p=f.offsets[m];p<f.offsets[m+1];p++)c[p]||(c[p]=!0,l=!1)}if(l)return Ve(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+=kt(t)(e.slice(f,d))}return u}function Ae(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var Dn=new Map;function ra(e){let t=Dn.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),Dn.set(e.source,t)),t}var ia=4096,oa=64,Ln=null;function aa(e){return Ln!==null?Ln:ia+e.length*oa}var er=!1,F={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},tr={spanBudget:0,depthCap:0};function sa(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:aa(e),exhausted:!1}}function nr(e,t,n,r,i,o,a){F.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--,F.spanMisses++;let c=la(e,t,n,r,i,o,a);return a.chosen.set(s,c),c}function la(e,t,n,r,i,o,a){let s=ra(r),l=[];for(let u=n.length-1;u>=1;u--)if(Ae(n[u])){let d=n.slice(0,u);s.test(d)&&l.push(d)}let c=Ae(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(o(i(u),u)&&!ua(e,t,u,r,i,o,a))return u;return null}var Fn=new Map;function ca(e){let t=Fn.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),Fn.set(e.source,t)),t}function ua(e,t,n,r,i,o,a){F.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--,F.cutMisses++;let c=da(e,t,n,r,i,o,a);return a.cuts.set(s,c),c}function da(e,t,n,r,i,o,a){let s=t+n.length,l=ca(r);for(let c=1;c<n.length;c++){if(Ae(n[c])||!Ae(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=nr(e,u,d[0],r,i,o,a);if(f!==null&&u+f.length>s&&Ae(e[u+f.length]))return!0}return!1}function pa(e,t,n,r,i,o,a){let s=kt(i);t.lastIndex=0;let l="",c=0,u=sa(e),d=F.spanMisses+F.cutMisses,f;for(;(f=t.exec(e))!==null;){let g=f[0],m=f.index;if(g.length===0){t.lastIndex=m+1;continue}let p;try{p=nr(e,m,g,t,n,r,u)}catch(_){if(_ instanceof RangeError&&/call stack/i.test(_.message))u.exhausted=!0,p=null;else throw _}if(u.exhausted)return F.budgetExhausted++,tr.spanBudget++,$n(d),l+e.slice(c,m)+s(e.slice(m));if(p!==null)a?.(o),l+=e.slice(c,m)+s(p),c=m+p.length,t.lastIndex=c;else{let _=g.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=_===-1?m+g.length:m+1+_+1}if(t.lastIndex>e.length)break}return $n(d),l+e.slice(c)}function $n(e){let t=F.spanMisses+F.cutMisses-e;t>F.maxMissesInAPass&&(F.maxMissesInAPass=t)}function At(e,t=Qn,n,r){return ma(e,t,ta(n,r))}var fa=256;function ma(e,t,n){let r=new Set,i=!n.has("pan"),o=s=>{r.add(s)},a=(s,l)=>{if(l>fa)return tr.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&&ht(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 rr(e,t=Qn){return At(e,t).value}function ga(e){let{value:t,detectors:n}=At(e),r=n.some(i=>Ge[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function ha(e,t){let{blocked:n,redacted:r,detectors:i}=ga(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 ya(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var _a=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function ba(e){return _a.has(ya(e))}function ie(e,t,n){return n.enforced&&ba(e)?ha(t,{failMode:n.failMode}):{verdict:"allow",redacted:t,detectors:[]}}var va=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,ir=Object.freeze({\u0430:"a",\u0435:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0456:"i",\u0455:"s",\u043A:"k",\u043C:"m",\u0442:"t",\u043D:"h",\u0432:"b",\u0433:"r",\u03BF:"o",\u03B1:"a",\u03C1:"p",\u03B9:"i",\u03C4:"t",\u03B5:"e",\u03BA:"k",\u03BD:"v",\u03C5:"u",\u03B7:"n",\u0131:"i","\u04CF":"l",\u0578:"n"}),wa=new RegExp(`[${Object.keys(ir).join("")}]`,"gu"),ka=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),or="\u2801\u2803\u2809\u2819\u2811\u280B\u281B\u2813\u280A\u281A\u2805\u2807\u280D\u281D\u2815\u280F\u281F\u2817\u280E\u281E\u2825\u2827\u283A\u282D\u283D\u2835",Aa=Object.freeze(Object.fromEntries([...or].map((e,t)=>[e,String.fromCharCode(97+t)]))),Sa=new RegExp(`[${or}\u2800]`,"g"),ar=/[⠀-⣿]/;function Ia(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 Ta(e){return e.replace(va,"")}function sr(e){return e.replace(wa,t=>ir[t]??t)}function Ea(e){return e.replace(/[4@31!05$79(8]/g,t=>ka[t]??t)}function Ra(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 Ca(e){return ar.test(e)?e.replace(Sa,t=>t==="\u2800"?" ":Aa[t]??t):e}function Pn(e){let t;try{t=Ia(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=Ta(t),t=sr(t),t}var xa=/^[A-Za-z0-9+/]{16,}={0,2}$/,Oa=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,jn=/[A-Za-z0-9+/]{20,}={0,2}/g;function yt(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 lr=new TextDecoder("utf-8",{fatal:!1});function cr(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=lr.decode(n);return t===r?[t]:[r,t]}function Na(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=lr.decode(n);return r===i?[r]:[i,r]}function Bn(e){let t=e.trim(),n=[];if(Oa.test(t))for(let r of Na(t))n.push({decoded:r,textiness:yt(r)});if(xa.test(t)&&t.length%4===0)for(let r of cr(t))n.push({decoded:r,textiness:yt(r)});return n}function Un(e,t){let n=[],r;for(jn.lastIndex=0;(r=jn.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let o of cr(i))n.push({decoded:o,textiness:yt(o)})}return n}var Ma=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function ur(e,t=Ma){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=g=>{g.length>0&&g.length<=r&&a.add(g)},l=!1,c=!1,u=0,d=0,f=[{s:e,depth:0}];for(;f.length>0;){if(u>=i){c=!0;break}let g=f.pop();if(g===void 0)break;let{s:m,depth:p}=g;if(m.length>r){c=!0;continue}u++,p>d&&(d=p);let _=Pn(m);s(_);let O=Ea(_);if(O!==_&&s(O),s(Ra(_)),ar.test(m)&&s(Ca(_)),p>=n){let R=Pn(m);(Bn(R).length>0||Un(R,o).length>0)&&(c=!0);continue}let A=[...Bn(_),...Un(_,o)];for(let R of A){if(l=!0,R.decoded.length>r){c=!0;continue}R.textiness>=.85&&R.decoded!==_?f.push({s:R.decoded,depth:p+1}):s(R.decoded)}}return{views:[...a],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:d}}var dr=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],Da=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),La=8,Fa=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),qn=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function $a(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||Fa.has(i)&&qn(t[r-1])&&qn(t[r+1])&&(n++,n>=La))return!0}return!1}var Pa=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function ja(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(Pa.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Ba=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Ua(e){for(let t of Ba)if(e>=t.lo&&e<=t.hi)return t.name;return null}function qa(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=Ua(o.codePointAt(0));if(a===null){i=!1;break}a==="latin"?n++:sr(o)!==o&&r++}if(i&&n>0&&r>0)return!0}return!1}var zn=Object.freeze({signals:[],contributes:!1});function za(e){if(typeof e!="string"||e.length===0)return{...zn,signals:[]};let t=new Set;try{$a(e)&&t.add("hidden_text_carrier"),ja(e)&&t.add("injected_turn_boundary"),qa(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=ur(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...zn,signals:[]}}return{signals:[...dr.filter(n=>t.has(n))],contributes:Da.some(n=>t.has(n))}}var He=[{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 Vn(e){return typeof e!="string"||e.length===0?[]:He.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function Va(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(Vn(e)),{views:n}=ur(e);for(let r of n)for(let i of Vn(r))t.add(i);return He.filter(r=>t.has(r.name)).map(r=>r.name)}function Ka(e){let t=new Set,n=new Set,r=!1,i=o=>{if(o!=null){if(typeof o=="string"){for(let s of Va(o))t.add(s);let a=za(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:He.filter(o=>t.has(o.name)).map(o=>o.name),structural:dr.filter(o=>n.has(o))}}function Ga(e){return Ka(e).matched}var bc=He.map(e=>e.name);var Ha=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Wa="i:injection";function pr(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=At(e.content);for(let o of i){let a=Ge[o]?.category;a&&t.add(`c:${a}`)}Ga(e.content)&&t.add(Wa)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Ha.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var mt="(?: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))",vc=[{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${mt}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${mt}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${mt}\\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}],Kn="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Qa=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${Kn}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${Kn}|programming|training))`,Ya="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Gn="(?:\\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)",Za="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",wc=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${Ya}${Qa}\\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}?${Gn}`,"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+(?:${Za}\\b|[\\s\\S]{0,40}?${Gn})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var kc=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var z=e=>`[^.!?;\\n]{0,${e}}?`,Ja=["\\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("|"),fr="(?: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)",Ac=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Ja})\\s${z(40)}\\b${fr}\\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${z(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${z(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${z(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${z(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${z(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")}]),Sc=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${z(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${z(30)}\\b${fr}\\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 ke=e=>`[^.!?;\\n]{0,${e}}?`,Ic=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${ke(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${ke(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${ke(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${ke(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${ke(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 St="[REDACTED]",re="\u2022",Ke=e=>/[\p{L}\p{N}]/u.test(e);function mr(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:re,c=a+s>=o;return i.map((u,d)=>!c&&(d<a||d>=o-s)?u:Ke(u)?l:u).join("")}function Xa(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return mr(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:re;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>Ke(a)?o:a).join(""))+i}function es(e,t,n){let r=n.length>0?n:re,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(Ke(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]||!Ke(u)?l+=u:l+=r}return l}function gr(e,t){let n=t.mode??"full";return n==="partial"?mr(e,t.keepFirst??0,t.keepLast??0,t.maskChar??re):n==="email"?Xa(e,t.maskChar??re):n==="custom"?es(e,t.keepPattern,t.maskChar??re):t.replacement??St}function ts(e,t){return typeof e=="string"?gr(e,t):t.replacement??St}function hr(e){let t=[],n=e.replacement??St;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:gt(r),replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:gt(i),replacer:o=>gr(o,r)})}return t}function yr(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 _r(e,t){if(_t(e).length===0){let n=e;for(let{source:r,replacer:i}of t)n=n.replace(yr(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=yr(r),a=[...Nn(o,n)];for(let u of _t(n))for(let d of Nn(o,u.text))a.push(Mo(u,d));let s=Do(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 M(e,t){return e==null?e:typeof e=="string"?rs(e,t):typeof e=="object"?is(e,t):e}function rs(e,t){if(typeof e!="string")return e;let n=hr(t);return n.length===0?e:_r(e,n)}function is(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=hr(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]=ts(l[u],d);continue}c[u]=a(l[u])}return c}return typeof s=="string"&&o?_r(s,r):s};return a(e)}import{createHash as Mc}from"node:crypto";var br=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function os(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:br(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:br(t.spawn.prompt)}),t}function as(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 ss=1440*60*1e3,ls="VISIQ_BUNDLE_GRACE_TTL_MS",cs="VISIQ_BUNDLE_CACHE_DISABLED",us="VISIQ_CACHE_DIR",ds=We.object({graceTtlMs:We.number().int().nonnegative().optional(),disabled:We.boolean().optional(),cacheDir:We.string().min(1).optional()}).strict();function ps(e){return e==null?{}:ds.parse(e)}function fs(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[ls];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return ss}function ms(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[cs]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var vr;function gs(){if(vr!==void 0)return vr;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function hs(e){return JSON.stringify(Tt(e))}function Tt(e){if(Array.isArray(e))return e.map(Tt);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Tt(t[r]);return n}return e}function ys(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function _s(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 Tr(){if(!gs())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 Er(e,t){return e.createHash("sha256").update(hs(t)).digest("hex")}function bs(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[us]?.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 vs(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function Rr(e,t,n){return e.path.join(bs(e,n),"bundles",`${vs(e,t)}.json`)}async function ws(e,t,n,r={}){let i=await Tr();if(i)try{let o=Rr(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:Er(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 ks(e,t={}){let n=await Tr();if(!n)return null;try{let r=await n.fs.readFile(Rr(n,e,t),"utf-8"),i=_s(JSON.parse(r));return!i||Er(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var Se;async function As(){if(Se!==void 0)return Se;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;Se=typeof t=="function"?t:null}catch{Se=null}return Se}function Ss(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=pt(i)}catch{continue}let a=typeof r.id=="string"?r.id:"<rule>";for(let s of dn(o))t.push(`${a}: ${s}`)}return t}function Is(e){return Cn(e)}function Ts(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var Es=5e3,Rs=600*1e3,Cs=1e4,xs=25,wr=1e3,Os=5e3,Ns=100,kr=2e3,Ms=10,Ds=512,Ls=1800*1e3,Fs=.7,$s="monitor",Ps="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",Ar="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.",Qe="open";function Ie(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function js(e,t){return pr({content:e,resourceMetadata:t})}var Bs=y.object({operations:y.array(y.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:y.string().min(1,"agentId is required"),sessionId:y.string().min(1).max(255).optional(),toolName:y.string().optional(),toolArgs:y.record(y.unknown()).optional(),targetResource:y.string().optional(),resourceType:y.string().optional(),resourceMetadata:y.record(y.unknown()).optional(),normalized:y.record(y.unknown()).optional(),query:y.string().optional(),contentPreview:y.string().optional(),telemetry:y.record(y.unknown()).optional(),context:y.record(y.unknown()).optional(),mcpServer:y.string().min(1).max(255).optional()}),Us=y.object({version:y.string().min(1),dialect_version:y.number().int().optional(),min_dialect:y.number().int().optional(),shutdown:y.boolean().optional(),agent_mode:y.enum(["enforce","monitor","off"]).optional(),cognition_capture:y.boolean().optional(),agent_mode_by_operation:y.object({action:y.string().optional(),retrieval:y.string().optional(),delegation:y.string().optional()}).partial().optional(),agent_attributes:y.object({trust_tier:y.string().nullable().optional(),categories:y.array(y.string()).optional(),business_function:y.string().nullable().optional(),business_functions:y.array(y.string()).nullable().optional(),blast_radius_tier:y.string().nullable().optional(),no_coverage:y.string().nullable().optional(),fail_mode:y.string().nullable().optional()}).optional(),rules:y.array(y.record(y.unknown())),action_schemas:y.array(y.object({id:y.string(),plane:y.string().optional(),field_mappings:y.array(y.record(y.unknown())).optional(),derived_fields:y.array(y.record(y.unknown())).optional(),action_class:y.string().nullable().optional(),action_class_confidence:y.number().optional()})).optional(),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()}).optional()});function qs(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=An(Sn(n));return{trust_tier:fn(t)?t:null,categories:gn(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&In(e.blast_radius_tier)?e.blast_radius_tier:null}}function zs(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 Vs(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Et=new Set,Sr=!1;async function Ir(e){let t=[];for(let n of Et){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 Ks(){if(!Sr&&!(typeof process>"u"||typeof process.once!="function")){Sr=!0,process.once("beforeExit",()=>{Ir(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await Ir(!0)}finally{process.kill(process.pid,e)}})()})}}var Cr=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;cacheIdentity;bundleCacheDisabled;bundleGraceTtlMs;bundleCacheDirOverride;diskFallbackServed=!1;agentMode=$s;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=Ie(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Qe;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=ps(s);if(this.bundleCacheDisabled=ms(d.disabled),this.bundleGraceTtlMs=fs(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:as(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...o!==void 0?{sdkVersion:o}:{},...a!==void 0?{sdkDialect:a}:{}};this.client=new ct(f,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Es),It(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Cs),It(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Os),It(this.cognitionTimer),Et.add(this),Ks()}else this.client=null}async evaluate(e){let t=Bs.parse(e),n=Date.now();if(this.operatorShutdown){let g=this.denyAll(t,Ps);return this.applyAgentMode(g,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,Ar,n);let g=this.denyAll(t,Ar);return this.applyAgentMode(g,"enforce",t,n)}if(t.operations.every(g=>this.modeFor(g)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let g;if(this.agentModeConfirmed?g=this.agentMode:this.bundleApplyFailed?g="enforce":g="monitor",g==="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,g,t,n)}let r=this.readSession(t.sessionId),i=await As();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")?yn(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(g){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${g instanceof Error?g.message:String(g)}`,n);throw g}let d=[...new Set(t.operations.flatMap(g=>this.normalizedRefs[g]??[]))].sort();d.length>0&&Ts(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=_n(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}readSession(e){if(!e)return we;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Ls?(this.sessions.delete(e),we):t.state:we}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>=Fs)return o}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=vn(r===we?bn():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,taint:o?js(e.contentPreview,i):void 0,action_class:a?this.foldActionClass(e):void 0,target_app:a?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>Ds){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=Us.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=Ss(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=>Rn(i)).filter(i=>i!==null),this.agentAttributes=t.agent_attributes?qs(t.agent_attributes):null,this.agentNoCoverage=Tn(t.agent_attributes?.no_coverage),this.governedFailMode=Ie(t.agent_attributes?.fail_mode)??null,this.bundleVersion=t.version,this.bundleLoaded=!0,this.noCoverage=t.no_coverage?{no_coverage_defaults:t.no_coverage.no_coverage_defaults,autopilot_enabled:t.no_coverage.autopilot_enabled,enduser_hitl_enabled:t.no_coverage.enduser_hitl_enabled}:null,t.agent_mode!==void 0&&(this.agentMode=t.agent_mode,this.agentModeConfirmed=!0),this.agentModeByOperation=zs(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=Is(this.rules),this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1,this.lastNormalizedWarnRearmMs=Date.now(),this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json",...W(this.sdkVersion,this.sdkDialect)};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304){let a=Date.now();a-this.lastNormalizedWarnRearmMs>=Rs&&(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 ks(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(ys(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 ws(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({...je(),...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({...je(),...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=En(n),i={...n};return e.toolArgs&&(i.tool_args=rr(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?Vs(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?{[Xt]: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,Ms)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=xs&&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-wr;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${wr})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(os(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Ns&&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-kr;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${kr})`))}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(),Et.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 It(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function Gs(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function $(e,...t){for(let n of t){let r=Gs(e[n]);if(r)return r}}var Hs=[{framework:"openai-agents",matches:e=>/^transfer_to_.+/.test(e),extract:(e,t)=>{let n=e.replace(/^transfer_to_/,"");return{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"teammate",task:$(t,"task","input","reason","message"),source:"structural"}}},{framework:"voltagent",matches:e=>e==="delegate_task",extract:(e,t)=>{let n=$(t,"targetAgent","agent","subAgent","agentName","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:$(t,"task","message","input"),description:$(t,"purpose"),source:"structural"}:null}},{framework:"crewai",matches:e=>/delegate work to (co-?worker|.+)/i.test(e),extract:(e,t)=>{let n=$(t,"coworker","agent","role");return n?{childAgentId:n,childName:n,kind:"teammate",agentType:n,task:$(t,"task","question"),description:$(t,"context"),source:"structural"}:null}},{framework:"llamaindex",matches:e=>e==="handoff"||/handoff/i.test(e),extract:(e,t)=>{let n=$(t,"to_agent","toAgent","agent_name","agentName","agent","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:$(t,"reason","task","message"),source:"structural"}:null}},{framework:"generic",matches:e=>/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)([_-].+)?$/i.test(e),extract:(e,t)=>{let n=$(t,"agent","agentName","agentId","target","targetAgent","to","to_agent","coworker","name")??(/[_-]/.test(e)?e.replace(/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)[_-]/i,""):void 0);return n?{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"subagent",task:$(t,"task","message","input","reason","prompt"),source:"heuristic"}:null}}];function Ye(e,t){if(!e)return null;let n=t??{};for(let r of Hs)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function Ze(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 Dc=512*1024;function Rt(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 xr(e){if(typeof e=="string"){try{let t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{input:e}}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{input:e===void 0?"":String(e)}}function D(e){let t=[],n=[],r,i=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let l={mode:a.mode};a.field&&(l.field=a.field),a.pattern&&(l.pattern=a.pattern),typeof a.keepFirst=="number"&&(l.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(l.keepLast=a.keepLast),a.maskChar&&(l.maskChar=a.maskChar),a.keepPattern&&(l.keepPattern=a.keepPattern),a.replacement!==void 0&&(l.replacement=a.replacement),i.push(l);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:s}=a;s&&r===void 0&&(r=s)}let o={};return t.length>0&&(o.fields=t),n.length>0&&(o.patterns=n),r!==void 0&&(o.replacement=r),i.length>0&&(o.directives=i),o}var V="0.2.17";import{AsyncLocalStorage as Ws}from"node:async_hooks";var x=new Ws,Qs=5120,Or=50;function Ys(e,t){if(typeof e!="string")return"";let n=new TextEncoder,r=n.encode(e);if(r.length<=t)return e;let o=`\u2026[truncated ${Math.ceil(r.length/1024)}KB]`,a=n.encode(o).length,s=Math.max(0,t-a),l=r.subarray(0,s);return new TextDecoder("utf-8",{fatal:!1}).decode(l)+o}function K(e){if(!e)return;let t=r=>r.length<=Or?r.slice():r.slice(r.length-Or),n=r=>Ys(r,Qs);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 Ct=12e4,Nr=2e3,Mr=3,Zs=5e3;function Te(e,t){return e==="mask"&&(t?.length??0)>0}var Js=new Set(["approved","resolved"]),Xs=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function el(e){return new Promise(t=>setTimeout(t,e))}function tl(e){if(typeof e!="object"||e===null)return null;let t=e,n=t.hitl_result;if(typeof n=="string"&&n.length>0)return n;let{hitl:r}=t;if(r&&typeof r=="object"){let{status:i}=r;if(typeof i=="string"&&i.length>0)return i==="pending"?null:i}return null}async function Ee(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=Ct,maskFallback:o=!1,sdkVersion:a,fetchImpl:s=globalThis.fetch,sleep:l=el,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",...W(a)};n&&(f.Authorization=`Bearer ${n}`);let g=Date.now()+Math.max(0,i),m=0;for(c(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=g)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,O=setTimeout(()=>_.abort(),Zs),A;try{A=await s(d,{method:"GET",headers:f,signal:_.signal})}finally{clearTimeout(O)}if(!A.ok)throw new Error(`HTTP ${A.status} ${A.statusText}`);let R=await A.json();p=tl(R),m=0}catch(_){m+=1;let O=_ instanceof Error?_.message:String(_);if(c(`[VisIQ HITL] Poll failed for decision ${r} (${m}/${Mr}): ${O}`),m>=Mr)return u(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${O}`);await l(Nr);continue}if(p!==null){let _=p.toLowerCase();return Js.has(_)?(c(`[VisIQ HITL] Decision ${r} approved (${p}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${p})`}):Xs.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(Nr)}}function G(e){return e??Ie(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Qe}function v(e,t){try{console.error(`[VisIQ] FAIL-OPEN (${e}): ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`)}catch{}}function U(e,t){try{console.error(`[VisIQ] TRACE-DEGRADED (${e}): ${t} \u2014 the governance decision was still made and enforced; only the execution-trace beat was lost.`)}catch{}}function oe(e){let t=e.getFailMode;return(typeof t=="function"?t.call(e):void 0)??G()}function Z(e){return e.enforced?{allowed:e.action.allowed,decision:e.action.decision,...e.action.decisionId!==void 0?{decisionId:e.action.decisionId}:{},...e.ruleCode!==null?{ruleCode:e.ruleCode}:{},reason:e.reason,argRedactionRules:e.action.argRedactionRules??[],...e.action.hitlFallback?{hitlFallback:e.action.hitlFallback}:{}}:{allowed:!0,decision:"permit",reason:e.reason,argRedactionRules:[]}}function Lr(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&Te(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}var Dr=new Set;function Mt(e){Dr.has(e)||(Dr.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 Xe(e,t,n){let r=x.getStore(),i=K(r),o=await e.evaluate({operations:["retrieval"],agentId:t,...r?.session_id?{sessionId:r.session_id}:{},resourceType:n.resourceType??"document",resourceMetadata:n.resourceMetadata??{},...n.query!==void 0?{query:n.query}:{},...n.contentPreview!==void 0?{contentPreview:n.contentPreview}:{},...i?{telemetry:i}:{}});return Lr(o)}async function et(e,t,n){return await e.awaitBundleReady(),Xe(e,t,n)}function Fr(e,t,n=G()){switch(t.action){case"allow":case"escalate":return e;case"deny":return null;case"redact":{if(t.redactionRules.length===0)return e;try{return M(e,D(t.redactionRules))}catch{return n==="closed"?null:(v("redact-error","document redaction failed \u2014 document passed UNREDACTED"),e)}}default:return Mt(String(t.action)),n==="closed"?null:(v("unknown-retrieval-verb",`unrecognized outcome "${String(t.action)}" \u2014 document passed through`),e)}}async function $r(e,t,n,r){if(!Array.isArray(e)||e.length===0)return e;await r.awaitBundleReady();let i=[];for(let o of e){let a=o,s=String(a.pageContent??a.text??a.content??""),l=a.metadata??{},c=await Xe(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s.slice(0,500)}),u=Fr(o,c,oe(r));u!==null&&i.push(u)}return i}async function Pr(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await Xe(n,t,{resourceType:"document",resourceMetadata:{content_preview:e.slice(0,500)},contentPreview:e.slice(0,500)})}catch(i){return oe(n)==="closed"?"[RECALL] Retrieved context blocked \u2014 policy evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":(v("eval-error",`retrieval evaluation failed \u2014 text passed through: ${i instanceof Error?i.message:String(i)}`),e)}switch(r.action){case"allow":case"escalate":return e;case"deny":return"[RECALL] Retrieved context was blocked by policy.";case"redact":{if(r.redactionRules.length===0)return e;try{return M(e,D(r.redactionRules))}catch{return oe(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(v("redact-error","text redaction failed \u2014 text passed UNREDACTED"),e)}}default:return Mt(String(r.action)),oe(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(v("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 text passed through`),e)}}var jr=4,Br=1e3;function Je(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 Ur(e,t,n){let r=[];for(let i of e){let o=i,a=String(o.pageContent??o.text??o.content??""),s={...o.metadata??{},content_preview:a.slice(0,500)},l;try{l=await Xe(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:a.slice(0,500)})}catch(u){if(oe(n)==="closed")continue;v("eval-error",`document retrieval evaluation failed \u2014 document passed through: ${u instanceof Error?u.message:String(u)}`),r.push(i);continue}let c=Fr(i,l,oe(n));c!==null&&r.push(c)}return r}async function Ot(e,t,n,r,i){if(r>jr||i.nodes++>Br)return e;if(Array.isArray(e)){if(Je(e))return i.matched=!0,Ur(e,t,n);let o=[];for(let a of e)o.push(await Ot(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 Ot(o[s],t,n,r+1,i);return a}return e}async function tt(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&Je(e))return Ur(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await Ot(e,t,n,0,r);if(r.matched)return i}return e}var nl={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function Nt(e,t,n){if(t>jr||n.n++>Br)return e;if(Array.isArray(e))return Je(e)?[]:e.map(r=>Nt(r,t+1,n));if(e!==null&&typeof e=="object"){if(Je([e]))return{...nl};let r=e,i={};for(let o of Object.keys(r))i[o]=Nt(r[o],t+1,n);return i}return e}function xt(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?Nt(e,0,{n:0}):e}function qr(e,t,n=G()){let r=Lr(t);switch(r.action){case"allow":case"escalate":return e;case"deny":return xt(e);case"redact":{if(r.redactionRules.length===0)return e;try{return M(e,D(r.redactionRules))}catch{return n==="closed"?xt(e):(v("redact-error","result redaction failed \u2014 result passed UNREDACTED"),e)}}default:return Mt(String(r.action)),n==="closed"?xt(e):(v("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 result passed through`),e)}}function E(e){return typeof e=="object"&&e!==null?e:null}function zr(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}function rl(e,t){let n=E(e.metadata),r=n&&typeof n.name=="string"?n.name:void 0;return zr(e.name,e.id,r,t)}function il(e){let t=E(e.metadata),n=t&&typeof t.description=="string"?t.description:void 0,r=zr(e.description,n);return r===void 0?void 0:r.slice(0,4e3)}function ol(e){let t=E(e);return t!==null&&("type"in t||"properties"in t||"$schema"in t)}function al(e){let t=E(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=E(n);if(r===null)return{type:"object"};let i={};for(let o of Object.keys(r))i[o]={};return{type:"object",properties:i}}var sl=new Set(["default","const","enum","examples","example"]);function Dt(e){if(Array.isArray(e))return e.map(Dt);let t=E(e);if(t===null)return e;let n={};for(let[r,i]of Object.entries(t))sl.has(r)||(n[r]=Dt(i));return n}function ll(e){let t;if(ol(e))t=e;else{let n=al(e);if(n===void 0)return;t=n}try{let n=JSON.stringify(t);if(n.length>2e4){let r=E(t),i=r&&E(r.properties);if(i){let o={};for(let a of Object.keys(i))o[a]={};return{type:"object",properties:o}}return{type:"object"}}return Dt(JSON.parse(n))}catch{return}}function cl(e){let t=E(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:ll(n)}function ul(e,t){let n=E(e);if(n===null)return null;let r=rl(n,t);if(r===void 0)return null;let i={name:r.slice(0,255)},o=il(n);o!==void 0&&(i.description=o);let a=cl(n);return a!==void 0&&(i.input_schema=a),i}function J(e){let t=[],n=new Set,r=(i,o)=>{try{let a=ul(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=E(e);if(i!==null){for(let o of Object.keys(i))if(r(i[o],o),t.length>=200)break}}return t}function Lt(e){try{let t=E(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(J(t.tools));let o=E(t.settings);o&&o.tools!==void 0&&i(J(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(J(d))}catch{}}let a=E(t.nodes)?t:E(t.graph)??E(t.builder)??t,s=E(a.nodes);if(s)for(let c of Object.keys(s)){let u=E(s[c]);if(!u)continue;u.tools!==void 0&&i(J(u.tools));let d=E(u.bound);d&&d.tools!==void 0&&i(J(d.tools))}let{agents:l}=t;if(l instanceof Map)for(let c of l.values()){let u=E(c);u&&u.tools!==void 0&&i(J(u.tools))}return n}catch{return[]}}async function Vr(e){let t=E(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 J(await a))r.has(s.name)||(r.add(s.name),n.push(s))}catch{}}return n}import{z as nt}from"zod";var dl=nt.object({decision:nt.enum(["permit","deny"]),reason:nt.string(),handoff_event_id:nt.string().nullable()}),B=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},X=class extends B{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},pl="https://api.visiqlabs.com",fl=1e4,ae=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??pl,timeoutMs:e.timeoutMs??fl},this.fetch=t}get headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Agent-ID":this.config.agentId}}async post(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.fetch(`${this.config.endpoint}${e}`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:n.signal})}finally{clearTimeout(r)}let o=await i.json();if(!i.ok){let a=o?.error??`HTTP ${i.status}`;throw new B(a,"API_ERROR",i.status)}return o}async requestGrant(e){let t=await this.post("/orchestrate/grants",{parent_agent_id:e.parentAgentId,child_agent_id:e.childAgentId,tool_scope:e.toolScope??null,context_scope:e.contextScope??null,purpose:e.purpose,duration_seconds:e.durationSeconds,max_depth:e.maxDepth,parent_grant_token:e.parentGrantToken});return{grantId:t.grant_id,status:"pending",effectiveToolScope:t.effective_tool_scope,effectiveContextScope:t.effective_context_scope,acceptDeadline:t.accept_deadline}}async acceptGrant(e){let t=await this.post(`/orchestrate/grants/${e}/accept`,{});return{grantToken:t.grant_token,toolScope:t.tool_scope,contextScope:t.context_scope,expiresAt:t.expires_at}}async evaluate(e){let t=await this.post("/orchestrate/evaluate",{grant_token:e.grantToken,action:e.action,resource_type:e.resourceType,resource_metadata:e.resourceMetadata??{}}),n=dl.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 Kr=new Map;async function Gr(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=Kr.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 ae({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 Kr.set(e,o),o}var Re=Symbol.for("visiq.orchestrate.wrapped");function ml(e){return e instanceof B&&typeof e.status=="number"&&e.status>=400&&e.status<500}function Hr(e,t){if(!t.agentId||t.agentId.trim()==="")throw new B("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new B("grantToken is required","CONFIG_ERROR");if(e[Re]===!0)return e;let n=new ae(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(ml(l))throw l;if(r==="permit"){console.warn('[VisIQ] FAIL-OPEN (orchestrate-eval-error): evaluate failed \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed (or failBehavior:"deny") to block instead.',l);return}throw new B(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new X(s.reason,s.handoffEventId)};return new Proxy(e,{get(o,a,s){let l=Reflect.get(o,a,s);return a===Re?!0:a==="_call"&&typeof l=="function"?async function(c,...u){let d=o.name;return await i(d??"_call"),l.call(this??o,c,...u)}:(a==="call"||a==="execute"||a==="run")&&typeof l=="function"?async function(c,...u){let d=o.name;return await i(d??String(a)),l.call(this??o,c,...u)}:l}})}import{randomUUID as ti}from"node:crypto";var Wr=Symbol.for("visiq.semantickernel.instrumented");function Zr(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 Qr(e){let t=e.arguments;return t&&typeof t=="object"&&"arguments"in t&&t.arguments&&typeof t.arguments=="object"?t.arguments:t??{}}function Yr(e,t){let n=e.arguments;if(n&&typeof n=="object"&&"arguments"in n&&n.arguments&&typeof n.arguments=="object"){let r=n.arguments;for(let i of Object.keys(r))delete r[i];Object.assign(r,t);return}e.arguments=t}function q(e,t){e.result&&typeof e.result=="object"?e.result.value=t:e.result={value:t}}function gl(e){return e.result?.value}function hl(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=Qr(o),u=l;try{let p=await n.evaluate({operations:["action"],agentId:t,toolName:s,toolArgs:c,...u!==void 0?{targetResource:u}:{}}),_=Z(p);if(!_.allowed){q(o,C({outcome:"deny",code:_.ruleCode??"DENY",reason:_.reason}));return}_.decision==="mask"&&_.argRedactionRules.length>0&&Yr(o,M(c,D(_.argRedactionRules)));let O=Qr(o),A=ie(s,O,{failMode:r==="closed"?"closed":"open",enforced:p.enforced});if(A.verdict==="block"){q(o,C({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${A.detectors.join(",")})`}));return}A.verdict==="redact"&&(Yr(o,A.redacted),v("outbound-secret-redacted",`outbound secret screen redacted ${A.detectors.length} detector(s): ${A.detectors.join(",")}`))}catch(p){if(r==="closed"){q(o,C({outcome:"error",code:"EVAL-ERROR",mechanism:`evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${p instanceof Error?p.message:String(p)}`}));return}v("eval-error",`SK action pre-gate failed for "${s}": ${p instanceof Error?p.message:String(p)}`)}try{let p=await et(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l}});if(p.action==="deny"||p.action==="escalate"){q(o,`[RECALL: access denied \u2014 ${p.reason}]`);return}}catch(p){if(r==="closed"){q(o,`[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${p instanceof Error?p.message:String(p)}.`);return}v("eval-error",`SK retrieval pre-gate failed for "${s}": ${p instanceof Error?p.message:String(p)}`)}await a(o);let d=gl(o),g=(typeof d=="string"?d:(()=>{try{return JSON.stringify(d)??String(d)}catch{return String(d)}})()).slice(0,500),m;try{m=await et(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l,content_preview:g},contentPreview:g})}catch(p){r==="closed"?q(o,"[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):v("eval-error",`SK post-result retrieval eval failed for "${s}": ${p instanceof Error?p.message:String(p)}`);return}if(m.action==="deny"||m.action==="escalate"){q(o,`[RECALL: access denied \u2014 ${m.reason}]`);return}if(m.action==="redact"&&m.redactionRules&&m.redactionRules.length>0&&d!==null&&d!==void 0)try{q(o,M(d,D(m.redactionRules)))}catch(p){r==="closed"?q(o,"[RECALL] Result withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):v("redact-error",`SK result redaction failed for "${s}" \u2014 result passed UNREDACTED: ${p instanceof Error?p.message:String(p)}`)}}}function yl(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 et(e.unified,e.agentId,{resourceType:"prompt",resourceMetadata:{},contentPreview:i.slice(0,500)})}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":v("eval-error",`SK prompt-render eval failed: ${a instanceof Error?a.message:String(a)}`);return}if(o.action==="redact"&&o.redactionRules&&o.redactionRules.length>0){try{n.renderedPrompt=M(i,D(o.redactionRules))}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed).":v("redact-error",`SK prompt redaction failed \u2014 prompt passed UNREDACTED: ${a instanceof Error?a.message:String(a)}`)}return}(o.action==="deny"||o.action==="escalate")&&(n.renderedPrompt=`[RECALL: prompt suppressed \u2014 ${o.reason}]`)}}function Jr(e,t){let n=e;if(n[Wr]===!0)return t.onWrap?.(),e;let r=hl(t),i=yl(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[Wr]=!0,t.onWrap?.()),e}function C(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 rt(e){return e instanceof Error?e.message:String(e)}var _l=/https?:\/\/[^\s"'`,)}\]]+/;function $t(e){let t=e.match(_l);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var se=Symbol.for("visiq.toolexec.instrumented"),Xr=Symbol.for("visiq.agentclone.instrumented"),Pt=Symbol.for("visiq.instrument.deferred");function bl(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}var jt={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 ni(e){if(e===null||typeof e!="object")return null;let t=e;if(bl(t))return null;if(Zr(e))return"semantic-kernel";if(typeof t.generateText=="function"&&(typeof t.getTools=="function"||t.toolManager!==void 0))return"voltagent";if(typeof t.run=="function"&&typeof t.runStream=="function"&&t.agents!==void 0)return"llamaindex";if(Array.isArray(t.tools)&&t.handoffs!==void 0&&(typeof t.on=="function"||t.eventEmitter!==void 0))return"openai";if(typeof t.generate=="function"&&typeof t.getLLM=="function"&&(typeof t.listTools=="function"||typeof t.getTools=="function"))return"mastra";if(typeof t.generate=="function"){let n=t.settings;if(n&&typeof n=="object"&&n.tools!==void 0||t.tools!==void 0)return"vercel"}return null}async function vl(e,t,n,r,i,o){let{agentId:a,unified:s}=e,l=K(i),c,u=!1;try{await s.awaitBundleReady();let p=await s.evaluate({operations:o?["action","delegation"]:["action"],agentId:a,toolName:t,toolArgs:n,...o?{context:Ze(o,a)}:{},...i?.session_id?{sessionId:i.session_id}:{},...r!==void 0?{targetResource:r}:{},...l?{telemetry:l}:{}});({enforced:u}=p),c=Z(p)}catch(p){let _=p instanceof Error?p.message:String(p);return e.failMode==="closed"?{block:C({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${_} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})}:(v("eval-error",`policy evaluation failed for tool "${t}": ${_}`),{block:null})}if(c.decision==="approval_required"&&c.decisionId){let p=s.getApiKey()??e.apiKey,_=await Ee({endpoint:s.getEndpoint()??e.endpoint??"",...p?{apiKey:p}:{},decisionId:c.decisionId,timeoutMs:e.hitlTimeoutMs,sdkVersion:V});return _.resolution!=="proceed"?{block:C({outcome:"approval_required",code:c.ruleCode??"HITL-BLOCK",reason:c.reason,mechanism:_.reason}),decision:c}:{block:null}}if(!c.allowed)return{block:C({outcome:"deny",code:c.ruleCode??"DENY",reason:c.reason}),decision:c};let d=n,f=!1,g;if(c.decision==="mask"&&c.argRedactionRules&&c.argRedactionRules.length>0)try{let p=D(c.argRedactionRules);d=M(n,p),f=!0,g=c}catch(p){let _=p instanceof Error?p.message:String(p);if(e.failMode==="closed")return{block:C({outcome:"error",code:"MASK-ERROR",mechanism:`argument masking failed: ${_} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})};v("mask-error",`argument masking failed for tool "${t}" \u2014 running with UNMASKED args: ${_}`)}let m=ie(t,d,{failMode:e.failMode==="closed"?"closed":"open",enforced:u});return m.verdict==="block"?{block:C({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${m.detectors.join(",")})`}),decision:{allowed:!1,decision:"deny",ruleCode:"OUTPUT-BLOCK",reason:"outbound content carried a live secret",argRedactionRules:[]}}:(m.verdict==="redact"&&(d=m.redacted,f=!0,v("outbound-secret-redacted",`outbound secret screen redacted ${m.detectors.length} detector(s): ${m.detectors.join(",")}`),g??={allowed:!0,decision:"mask",ruleCode:"OUTPUT-BLOCK",reason:"outbound secret redacted before egress",argRedactionRules:[]}),f?{block:null,maskedArgs:d,decision:g}:{block:null})}async function Bt(e,t,n,r,i){let o=x.getStore()??e.telemetry,a=Ye(t,n);a&&he(e.unified,{agentId:e.agentId,sessionId:o?.session_id,...e.framework?{framework:e.framework}:{}},a);let s={agentId:e.agentId,sessionId:o?.session_id,...e.framework?{framework:e.framework}:{}},l=fe(t,n);try{ye(e.unified,s,{toolName:t,...l?{memory:l}:{},argSummary:r.slice(0,512)})}catch(m){U("step-beat",`emit failed for tool "${t}": ${rt(m)}`)}let c=Date.now(),u=await vl(e,t,n,$t(r),o,a);if(u.block!==null){try{u.decision&&ne(e.unified,s,{toolName:t,decision:u.decision.decision??"deny",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0,harnessMessage:u.block})}catch(m){U("intervention-beat",`emit failed for tool "${t}": ${rt(m)}`)}return u.block}if(u.maskedArgs!==void 0&&u.decision)try{ne(e.unified,s,{toolName:t,decision:u.decision.decision??"mask",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0})}catch(m){U("intervention-beat",`emit failed for tool "${t}": ${rt(m)}`)}let d=u.maskedArgs??n,f=await i(d),g=await tt(f,e.agentId,e.unified);try{_e(e.unified,s,{toolName:t,ok:!0,durationMs:Date.now()-c,...Q(g)!==void 0?{bytes:Q(g)}:{},...Y(g)!==void 0?{itemCount:Y(g)}:{},...l?{memory:l}:{}})}catch(m){U("observation-beat",`emit failed for tool "${t}": ${rt(m)}`)}return g}function xe(e,t,n){let r=e;if(r[se]){n.onWrap?.();return}if(typeof r.execute!="function")return;let i=r.execute;Oe(r,"execute",async function(...a){let s=Rt(a[0]);return Bt(n,t,s,Ne(s),l=>Promise.resolve(i.apply(this,[l,...a.slice(1)])))}),r[se]=!0,n.onWrap?.()}function wl(e,t,n){let r=e;if(r[se]){n.onWrap?.();return}if(typeof r.invoke!="function")return;let i=r.invoke;Oe(r,"invoke",async function(...a){let s=a[1],l=xr(s),c=typeof s=="string"?s:Ne(l);return Bt(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[se]=!0,n.onWrap?.()}function kl(e,t){let n=e;if(n[se]){t.onWrap?.();return}if(typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",o=n.call;Oe(n,"call",async function(...s){let l=Rt(s[0]);return Bt(t,i,l,Ne(l),c=>Promise.resolve(o.apply(this,[c,...s.slice(1)])))}),n[se]=!0,t.onWrap?.()}function Ut(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&xe(r,n,t);return e}function ri(e,t,n){let r={...t,framework:n};switch(n){case"vercel":return Al(e,r);case"mastra":return Sl(e,r);case"openai":return ii(e,r);case"llamaindex":return Tl(e,r);case"voltagent":return Il(e,r);case"semantic-kernel":return Jr(e,r);default:return e}}function Al(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"&&Ut(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=qt(r.onStepFinish)),it(e,["generate","stream"],async(o,a)=>(Ce(a,o[0]),o)),e}function Sl(e,t){let n=e;return Nl(n,t)==="deferred"&&(n[Pt]=!0),Dl(n,t),it(e,["generate","stream","generateVNext","streamVNext"],async(r,i)=>{Ce(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=qt(o.onStepFinish);let a=[...r];return a[1]=o,a}),e}function Il(e,t){let n=Cl(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;xe(r,typeof i=="string"?i:"unknown",t)}}return it(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{Ce(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=qt(o.onStepFinish);let a=[...r];return a[1]=o,a}),e}function Tl(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"&&kl(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 it(e,["run"],async(o,a)=>(Ce(a,o[0]),o)),xl(e,"runStream",(o,a,s)=>{s||Ce(a,o[0])}),e}function ii(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;wl(i,typeof o=="string"?o:"unknown",t)}}return Rl(e,t),El(e,t),e}function El(e,t){let n=e;if(n[Xr])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"&&ii(l,t),l},writable:!0,configurable:!0,enumerable:!1}),n[Xr]=!0}function Rl(e,t){let n=e;if(n.__visiq_openai_hooks||typeof n.on!="function")return;let r=n.on,{telemetry:i}=t;r.call(e,"agent_start",(...o)=>{i.session_id=ti(),i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let a=o[2];a!=null&&i.llm_prompts.push(Ne(a).slice(0,5120))}),r.call(e,"agent_end",(...o)=>{let a=o[1];typeof a=="string"&&a&&i.llm_responses.push(a.slice(0,5120))}),n.__visiq_openai_hooks=!0}function Cl(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 it(e,t,n){let r=e;for(let i of t){if(typeof r[i]!="function")continue;let o=`__visiq_wrapped_${i}`;if(r[o])continue;let a=r[i];r[i]=function(...s){let l=ai();return x.run(l,async()=>{let c=await n(s,l);return a.apply(e,c)})},r[o]=!0}}function xl(e,t,n){let r=e;if(typeof r[t]!="function")return;let i=`__visiq_wrapped_${t}`;if(r[i])return;let o=r[t];r[t]=function(...a){let s=x.getStore(),l=s??ai();return n(a,l,s!==void 0),x.run(l,()=>o.apply(e,a))},r[i]=!0}function qt(e){return t=>{let n=x.getStore(),r=t;if(n&&typeof r?.text=="string"&&r.text&&n.llm_responses.push(r.text.slice(0,5120)),typeof e=="function")return e(t)}}function Ce(e,t){if(t==null)return;let n=t;if(typeof t=="object"){let r=t;n=r.prompt??r.messages??t}e.llm_prompts.push(Ne(n).slice(0,5120))}var Ol=["listTools","getTools"];function Nl(e,t){for(let n of Ol){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"?(Ut(i,t),oi(e,i),"sync"):(i.then(()=>{},()=>{}),Ml(e,n,r,t),"deferred")}return"none"}function Ml(e,t,n,r){let i=o=>(o&&typeof o=="object"&&(Ut(o,r),oi(e,o)),o);Oe(e,t,function(...o){let a=n.apply(this??e,o);return a&&typeof a.then=="function"?a.then(i):i(a)})}var Ft=Symbol.for("visiq.mastra.governedNames"),ei=Symbol.for("visiq.mastra.assembly.instrumented");function oi(e,t){let n=e[Ft];n instanceof Set||(n=new Set,e[Ft]=n);for(let r of Object.keys(t))n.add(r)}function Dl(e,t){let n=e;if(n[ei])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[Ft],l=s instanceof Set?s:new Set;for(let[c,u]of Object.entries(a))l.has(c)||u!==null&&typeof u=="object"&&xe(u,c,t);return a};Oe(n,"convertTools",function(...a){let s=i.apply(this??e,a);return s&&typeof s.then=="function"?s.then(o):o(s)}),n[ei]=!0}function ai(){return{session_id:ti(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Oe(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function Ne(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function hi(e,t){let n=Bl(t);if(e[Re]===!0)return e;let r=Vl(e);if(r==="langchain-executor"||r==="langchain-graph")return ce(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,li(r,null),n.failMode,{model:ci(e)}),di(e,n),Kl(e,n);let i=ni(e);if(i){ce(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,li("unknown",i),n.failMode,{model:ci(e)}),di(e,n);let o=0,a=wi(n);a.onWrap=()=>{o+=1};let s=ri(e,a,i),l=s[Pt]===!0;if(o===0&&!l){let c=0;try{c=Lt(e).length}catch{c=0}if(c>0){let u=`[VisIQ] Detected a ${jt[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);v("zero-instrument",`advertised ${String(c)} tool(s), instrumented none`),console.warn(u)}else{let u=`[VisIQ] Detected a ${jt[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(Jl(e)){let o=process.env.VISIQ_GRANT_ID;return o?ec(e,n,o):tc(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 $l="https://api.visiqlabs.com",Pl="\0",si=new Map;function li(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 ci(e){try{if(typeof e!="object"||e===null)return;let t=e,n=le(t.model);if(n)return n;let{settings:r}=t;if(typeof r=="object"&&r!==null){let a=le(r.model);if(a)return a}let{llm:i}=t;if(typeof i=="object"&&i!==null){let a=ui(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=le(s.model)??(typeof l=="object"&&l!==null?ui(l):void 0);if(c)return c}}return}catch{return}}function ui(e){return le(e.model)??le(e.modelId)??le(e.model_name)}function le(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 ce(e,t,n,r,i,o,a){let s=[e??"",t??"",n??"",r??"",o??""].join(Pl),l=si.get(s);return l||(l=new Cr(e,t,n,void 0,r,V,lt),l.registerHostEnvironment(i,a),si.set(s,l)),o!==void 0&&l.setFailMode(o),l}function di(e,t){try{let n=ce(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),r=Lt(e);r.length>0&&n.reportToolSurface(r),Vr(e).then(i=>{let o=i.filter(a=>!r.some(s=>s.name===a.name));o.length>0&&n.reportToolSurface(o)}).catch(()=>{})}catch{}}function jl(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 Bl(e){let t=e?.agentId??process.env.VISIQ_AGENT_ID??ql(),n=e?.apiKey??process.env.VISIQ_API_KEY,r=e?.endpoint??process.env.VISIQ_ENDPOINT??(n?$l:void 0);return{agentId:t,apiKey:n,endpoint:r,hitlTimeoutMs:zl(e?.hitlTimeoutMs),timeoutMs:jl(e?.timeoutMs),onInstrumentFailure:e?.onInstrumentFailure??Ul(),failMode:G(e?.failMode)}}function Ul(){let e=process.env.VISIQ_ON_INSTRUMENT_FAILURE;if(e==="throw")return"throw";if(e==="warn")return"warn"}function ql(){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=at.join(t,"package.json");if(ot.existsSync(r)){let o=JSON.parse(ot.readFileSync(r,"utf8"));if(typeof o.name=="string"&&o.name.trim()){let a=e(o.name);if(a)return a}break}let i=at.dirname(t);if(i===t)break;t=i}}catch{}try{let t=e(gi.hostname());if(t)return t}catch{}return"agent"}function zl(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 Ct}function Vl(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=Kt(t);if(n!==t&&n.nodes&&(n.lg_is_pregel===!0||n.channels))return"langchain-graph"}return"unknown"}function Kl(e,t){let n=e,r=ce(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),i=Gl(n);for(let l of i)Gt(l,t.agentId,r),Ql(l,t.agentId,r,t),bi(l,r,t);let{nodes:o}=Kt(n);if(!!o&&typeof o=="object"&&"tools"in o&&i.length===0){let l="[VisIQ] Detected a LangGraph agent whose compiled graph carries a ToolNode, but resolved ZERO tools from it \u2014 its tool calls run UN-GOVERNED while this SDK appears correctly wired. This is almost always a compiled-graph tool bag that moved on a @langchain/langgraph version bump. Upgrade @visiq/harness, or pass the tools through visiq() directly (visiq(tools, \u2026)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw / VISIQ_FAIL_MODE=closed) to refuse to run ungoverned.";if(t.onInstrumentFailure!==void 0?t.onInstrumentFailure==="throw":t.failMode==="closed")throw new Error(l);v("zero-instrument","langgraph compiled-graph ToolNode present, resolved no tools"),console.warn(l)}let s=n.invoke;if(n.invoke=function(l,c){let u=Vt(),d=mi(t.agentId,r),f=c?.callbacks??[];return x.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=Vt(),f=mi(t.agentId,r),g=u?.callbacks??[];return x.run(d,()=>l.call(this,c,{...u,callbacks:[...g,f]}))}}return e}function Kt(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 Gl(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}=Kt(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 Vt(){return{session_id:Ll(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Gt(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 pi(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 pi(s,t,String(a),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&Gt(r.retriever,t,n)}}var Hl=Symbol.for("visiq.operations"),Wl=new Set(["action","retrieval","delegation"]);function yi(e){if(typeof e!="object"||e===null)return;let t=e[Hl]??e.visiqOperations;if(!Array.isArray(t))return;let n=t.filter(r=>typeof r=="string"&&Wl.has(r));return n.length>0?Array.from(new Set(n)):void 0}function Ql(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(I=>I.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),d=l.some(I=>c.has(I)),f=u.has(l[0]??""),g=d||f,m=["update","delete","create","archive","insert","remove"],p=l.some(I=>m.some(b=>I.length>b.length&&I.endsWith(b))),O=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!g&&!p,A=yi(i),R=A?.includes("retrieval")??!1;if(A!==void 0&&!R||!(s||O||R))return;let Fe=A?R&&A.includes("action"):d||p;if(!Fe)if(s)Gt(i.retriever,t,n);else{let I=globalThis,b=Symbol.for("visiq.recall.closureRetrieverWarned"),P=I[b]??=new Set;P.has(a)||(P.add(a),console.warn(`[VisIQ] Retriever tool "${a||"(unnamed)"}" exposes no reachable retriever (e.g. LangChain createRetrieverTool returns a joined string). RECALL masks its output via value-shape + whole-result rules, but PER-DOCUMENT metadata/classification rules cannot apply to a metadata-less joined string. For full per-doc governance, pass the retriever to visiq() directly, or use a tool that returns a Document[].`))}let H=i.func;Fe?(i[_i]=!0,i.func=async function(...I){await n.awaitBundleReady();let b=I[0],P=typeof b=="object"&&b!==null?b:{input:b},de=typeof P.query=="string"?P.query:void 0,w=x.getStore(),k=K(w),N;try{N=await n.evaluate({operations:["retrieval","action"],agentId:t,...w?.session_id?{sessionId:w.session_id}:{},toolName:a||"unknown",toolArgs:P,resourceType:"document",resourceMetadata:{},...de!==void 0?{query:de}:{},...k?{telemetry:k}:{}})}catch(L){let pe=L instanceof Error?L.message:String(L);return G(r?.failMode)==="closed"?C({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${pe} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(v("eval-error",`policy evaluation failed for hybrid tool "${a||"unknown"}": ${pe}`),H.apply(this,I))}let T=Z(N),st=Te(T.hitlFallback,T.argRedactionRules),Ht=I,Wt=()=>{try{return Ht=[M(P,D(T.argRedactionRules)),...I.slice(1)],null}catch{return G(r?.failMode)==="closed"?C({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(v("mask-error",`argument masking failed for tool "${a||"unknown"}" \u2014 running with UNMASKED args`),null)}};if(T.decision==="approval_required"&&T.decisionId&&r){let L=await Ee({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:T.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:st,sdkVersion:V});if(L.resolution==="mask"){let pe=Wt();if(pe)return pe}else if(L.resolution!=="proceed")return C({outcome:"approval_required",code:T.ruleCode??"HITL-BLOCK",reason:T.reason,mechanism:L.reason})}else if(!T.allowed)return C({outcome:"deny",code:T.ruleCode??"DENY",reason:T.reason});if(T.decision==="mask"&&T.argRedactionRules.length>0){let L=Wt();if(L)return L}let Si=await H.apply(this,Ht);return qr(Si,N,r?.failMode)}):i.func=async function(...I){let b=await H.apply(this,I);return typeof b=="string"?Pr(b,t,n):tt(b,t,n)},i[o]=!0}var _i=Symbol.for("visiq.hybrid.instrumented");async function pi(e,t,n,r){return $r(e,t,n,r)}var fi=["invoke","call","_call"],ee=new Fl;function bi(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[_i]||yi(r)?.every(c=>c==="retrieval")||!fi.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,g)=>{let m=ee.getStore();if(m!==void 0&&m.gateKey===s&&!m.entered.has(g))return m.entered.add(g),c.call(u,d,...f);let p;if(typeof d=="string")p=d;else{let w=d?.input;p=w!=null?String(w):JSON.stringify(d)??""}let _=x.getStore(),O=K(_),A=typeof d=="object"&&d!==null?d:{input:p},R=Ye(a,A);R&&he(t,{agentId:o,sessionId:_?.session_id,framework:"langchain"},R);let Le={agentId:o,sessionId:_?.session_id,framework:"langchain"},ue=fe(a,A);try{ye(t,Le,{toolName:a,...ue?{memory:ue}:{},argSummary:p.slice(0,512)})}catch(w){U("step-beat",`emit failed for tool "${a}": ${zt(w)}`)}let Fe=Date.now(),H=async w=>{let k=await w();try{_e(t,Le,{toolName:a,ok:!0,durationMs:Date.now()-Fe,...Q(k)!==void 0?{bytes:Q(k)}:{},...Y(k)!==void 0?{itemCount:Y(k)}:{},...ue?{memory:ue}:{}})}catch(N){U("observation-beat",`emit failed for tool "${a}": ${zt(N)}`)}return k},I=(w,k,N,T)=>{try{ne(t,Le,{toolName:a,decision:w,...k?{ruleCode:k}:{},...N?{ruleLabel:N}:{},enforced:!0,...T?{harnessMessage:T}:{}})}catch(st){U("intervention-beat",`emit failed for tool "${a}": ${zt(st)}`)}};await t.awaitBundleReady();let b,P=!1;try{let w=await t.evaluate({operations:R?["action","delegation"]:["action"],agentId:o,..._?.session_id?{sessionId:_.session_id}:{},toolName:a,toolArgs:A,targetResource:$t(p),...O?{telemetry:O}:{},...R?{context:Ze(R,o)}:{}});({enforced:P}=w),b=Z(w)}catch(w){let k=w instanceof Error?w.message:String(w);return n.failMode==="closed"?C({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${k} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(v("eval-error",`policy evaluation failed for tool "${a}": ${k}`),ee.run({gateKey:s,entered:new Set([g])},()=>c.call(u,d,...f)))}let de=w=>{let k=ie(a,w,{failMode:n.failMode==="closed"?"closed":"open",enforced:P});if(k.verdict==="block"){let T=C({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${k.detectors.join(",")})`});return I("deny","OUTPUT-BLOCK","outbound content carried a live secret",T),T}let N=w;return k.verdict==="redact"&&(N=k.redacted,v("outbound-secret-redacted",`outbound secret screen redacted ${k.detectors.length} detector(s): ${k.detectors.join(",")}`),I("mask","OUTPUT-BLOCK","outbound secret redacted before egress")),H(()=>ee.run({gateKey:s,entered:new Set([g])},()=>c.call(u,N,...f)))};if(b.decision==="approval_required"&&b.decisionId){let w=Te(b.hitlFallback,b.argRedactionRules),k=await Ee({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:b.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:w,sdkVersion:V});if(k.resolution==="proceed")return H(()=>ee.run({gateKey:s,entered:new Set([g])},()=>c.call(u,d,...f)));if(k.resolution==="mask")try{let T=M(d,D(b.argRedactionRules));return I("mask",b.ruleCode,b.reason),H(()=>ee.run({gateKey:s,entered:new Set([g])},()=>c.call(u,T,...f)))}catch{return n.failMode==="closed"?C({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(v("mask-error",`HITL mask fallback failed for tool "${a}" \u2014 running with UNMASKED args`),ee.run({gateKey:s,entered:new Set([g])},()=>c.call(u,d,...f)))}let N=C({outcome:"approval_required",code:b.ruleCode??"HITL-BLOCK",reason:b.reason,mechanism:k.reason});return I("approval_required",b.ruleCode,b.reason,N),N}if(!b.allowed){let w=C({outcome:"deny",code:b.ruleCode??"DENY",reason:b.reason});return I("deny",b.ruleCode,b.reason,w),w}if(b.decision==="mask"&&b.argRedactionRules.length>0)try{let w=M(d,D(b.argRedactionRules));return I("mask",b.ruleCode,b.reason),de(w)}catch{return n.failMode==="closed"?C({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(v("mask-error",`argument masking failed for tool "${a}" \u2014 running with UNMASKED args`),ee.run({gateKey:s,entered:new Set([g])},()=>c.call(u,d,...f)))}return de(d)};for(let c of fi){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 zt(e){return e instanceof Error?e.message:String(e)}function Yl(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 Zl(e,t){let n=(g,m)=>{if(!g||typeof g!="object")return;let p=g[m];return typeof p=="number"&&Number.isFinite(p)?p:void 0},r=e?.tokenUsage,i=n(r,"promptTokens"),o=n(r,"completionTokens");if(i!==void 0||o!==void 0)return{...i!==void 0?{tokensIn:i}:{},...o!==void 0?{tokensOut:o}:{}};let a=t?.usage_metadata,s=n(a,"input_tokens"),l=n(a,"output_tokens");if(s===void 0&&l===void 0)return;let c=a&&typeof a=="object"?a.input_token_details:void 0,u=n(c,"cache_read"),d=n(c,"cache_creation"),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 mi(e,t){return{name:"VisiqHandler",handleLLMStart:async(n,r,i,o,a,s,l)=>{let c=x.getStore();if(!c)return;c.llm_prompts.push(...r);let u=Yl(n,a,l);u&&(c.llm_model=u,t.captureCloneMetadata({model:u,agentType:"langchain"}))},handleLLMEnd:async n=>{let r=x.getStore();if(!r)return;let o=n?.generations?.[0]?.[0],a=typeof o?.text=="string"?o.text:"";a&&r.llm_responses.push(a);try{let s=n?.llmOutput,l=o?.message&&typeof o.message=="object"?o.message:void 0,c=Zl(s,l);if(!c&&!a)return;let u=l?.tool_calls,d=typeof s?.model=="string"?s.model:void 0,f=r.llm_model??d;await t.awaitBundleReady(),dt(t,{agentId:e,sessionId:r.session_id,framework:"langchain"},{...a?{texts:[a]}:{},...c?{usage:c}:{},...f?{model:f}:{},final:!(Array.isArray(u)&&u.length>0)})}catch{}},handleAgentAction:async n=>{let r=x.getStore();if(!r)return;let i=typeof n.log=="string"?n.log:"";i&&r.agent_reasoning.push(i)},handleRetrieverStart:async(n,r,i)=>{let o=x.getStore();o&&o.retrieverQueries.set(i,r??"")},handleRetrieverEnd:async(n,r)=>{let i=x.getStore();if(!i)return;let o=i.retrieverQueries.get(r)??"";if(i.retrieverQueries.delete(r),!Array.isArray(n))return;let a=K(i);for(let s of n){let l=s,c=String(l.pageContent??l.text??l.content??""),u=l.metadata??{};await t.evaluate({operations:["retrieval"],agentId:e,resourceType:"document",resourceMetadata:u,query:o,contentPreview:c.slice(0,500),...a?{telemetry:a}:{}})}},handleRetrieverError:async(n,r)=>{let i=x.getStore();i&&i.retrieverQueries.delete(r)}}}var vi=["_call","execute","call","run","invoke"];function Jl(e){let t=e;for(let n of vi)if(typeof t[n]=="function")return!0;return!1}function Xl(e){return e instanceof X?!0:e instanceof B?typeof e.status=="number"&&e.status>=400&&e.status<500:!1}function ec(e,t,n){let r=null,i=null,o=!1,a=async()=>{if(r)return r;if(i)throw new X(`Failed to bootstrap grant ${n}: ${i.message}`,null);let s;try{s=await Gr(t.agentId,n)}catch(l){throw o=Xl(l),o&&(i=l instanceof Error?l:new Error(String(l))),new X(`Failed to bootstrap grant ${n}: ${l instanceof Error?l.message:String(l)}`,null)}return r=Hr(e,{agentId:t.agentId,grantToken:s,failBehavior:t.failMode==="closed"?"deny":"permit",...t.apiKey?{apiKey:t.apiKey}:{},...t.endpoint?{endpoint:t.endpoint}:{}}),r};return new Proxy(e,{get(s,l,c){if(l===Re)return!0;let u=Reflect.get(s,l,c);return typeof u!="function"||typeof l!="string"||!vi.includes(l)?u:async function(...d){let f;try{f=await a()}catch(m){if(o||t.failMode==="closed")throw m;return v("grant-bootstrap",`grant ${n} bootstrap failed: ${m instanceof Error?m.message:String(m)}`),u.call(this,...d)}return f[l].call(f,...d)}}})}function tc(e,t){let n=ce(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode);bi(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";xe(e,i,wi(t))}return e}function wi(e){return{agentId:e.agentId,unified:ce(e.apiKey,e.endpoint,e.agentId,e.timeoutMs,void 0,e.failMode),hitlTimeoutMs:e.hitlTimeoutMs,failMode:e.failMode,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:Vt()}}async function ki(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 ae({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 Me=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),te(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return te(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return te(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return te(this.transport,"POST","/api/discovery/fleet/stop")}};var De=class{constructor(t){this.transport=t}transport;connectAws(t){return te(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function nc(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 Me(r),integrations:new De(r)}}async function te(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,o={...W(V)};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 Ai=hi;Ai.delegate=ki;var Xu=Ai;export{Qe as DEFAULT_FAIL_MODE,Me as FleetClient,De as IntegrationsClient,nc as createVisiqClient,ki as delegate,Ie as normalizeFailMode,Xu as visiq};
|
|
6
|
+
-----END PRIVATE KEY-----`,template:{pattern:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.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:T.mac_address,mode:"full"},defaultEnabled:!1}},He=Object.freeze(Object.fromEntries(At.map(e=>{let t=pa[e];return[e,{...t,template:{...t.template,pattern:Zo(yt(t.template.pattern))}}]})));var zc=new Set(At.filter(e=>!He[e].defaultEnabled));function fa(e,t){let n=new Set;for(let r of At)(He[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function Ke(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=St(t),o=e;for(let{name:a,re:s}of nr){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 rr)n.has(a)||(o=Sa(o,s,l,c,t,a,r));return o}function St(e){return typeof e=="function"?e:()=>e}var $n=e=>"\0".repeat(e.length);function ma(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=vt(e);if(i.length===0)return Ke(e,t,n,r);let o=new Set,a=p=>{o.add(p)},s=Ke(e,$n,n,a),l=!0,c=new Array(e.length).fill(!1);for(let p=0;p<e.length;p++)c[p]=s[p]==="\0"&&e[p]!=="\0";for(let p of i){let f=Ke(p.text,$n,n,a);for(let m=0;m<p.text.length;m++)if(!(f[m]!=="\0"||p.text[m]==="\0"))for(let g=p.offsets[m];g<p.offsets[m+1];g++)c[g]||(c[g]=!0,l=!1)}if(l)return Ke(e,t,n,r);for(let p of o)r?.(p);let u="",d=0;for(;d<e.length;){if(!c[d]){u+=e[d],d++;continue}let p=d;for(;d<e.length&&c[d];)d++;u+=St(t)(e.slice(p,d))}return u}function Se(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var Pn=new Map;function ga(e){let t=Pn.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),Pn.set(e.source,t)),t}var ha=4096,ya=64,jn=null;function _a(e){return jn!==null?jn:ha+e.length*ya}var ir=!1,L={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},or={spanBudget:0,depthCap:0};function ba(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:_a(e),exhausted:!1}}function ar(e,t,n,r,i,o,a){L.spanCalls++;let s=t*a.stride+n.length,l=ir?void 0:a.chosen.get(s);if(l!==void 0)return l;if(a.budget<=0)return a.exhausted=!0,null;a.budget--,L.spanMisses++;let c=va(e,t,n,r,i,o,a);return a.chosen.set(s,c),c}function va(e,t,n,r,i,o,a){let s=ga(r),l=[];for(let u=n.length-1;u>=1;u--)if(Se(n[u])){let d=n.slice(0,u);s.test(d)&&l.push(d)}let c=Se(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(o(i(u),u)&&!ka(e,t,u,r,i,o,a))return u;return null}var Bn=new Map;function wa(e){let t=Bn.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),Bn.set(e.source,t)),t}function ka(e,t,n,r,i,o,a){L.cutCalls++;let s=t*a.stride+n.length,l=ir?void 0:a.cuts.get(s);if(l!==void 0)return l;if(a.budget<=0)return a.exhausted=!0,!0;a.budget--,L.cutMisses++;let c=Aa(e,t,n,r,i,o,a);return a.cuts.set(s,c),c}function Aa(e,t,n,r,i,o,a){let s=t+n.length,l=wa(r);for(let c=1;c<n.length;c++){if(Se(n[c])||!Se(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 p=ar(e,u,d[0],r,i,o,a);if(p!==null&&u+p.length>s&&Se(e[u+p.length]))return!0}return!1}function Sa(e,t,n,r,i,o,a){let s=St(i);t.lastIndex=0;let l="",c=0,u=ba(e),d=L.spanMisses+L.cutMisses,p;for(;(p=t.exec(e))!==null;){let f=p[0],m=p.index;if(f.length===0){t.lastIndex=m+1;continue}let g;try{g=ar(e,m,f,t,n,r,u)}catch(_){if(_ instanceof RangeError&&/call stack/i.test(_.message))u.exhausted=!0,g=null;else throw _}if(u.exhausted)return L.budgetExhausted++,or.spanBudget++,Un(d),l+e.slice(c,m)+s(e.slice(m));if(g!==null)a?.(o),l+=e.slice(c,m)+s(g),c=m+g.length,t.lastIndex=c;else{let _=f.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=_===-1?m+f.length:m+1+_+1}if(t.lastIndex>e.length)break}return Un(d),l+e.slice(c)}function Un(e){let t=L.spanMisses+L.cutMisses-e;t>L.maxMissesInAPass&&(L.maxMissesInAPass=t)}function It(e,t=Xn,n,r){return Ta(e,t,fa(n,r))}var Ia=256;function Ta(e,t,n){let r=new Set,i=!n.has("pan"),o=s=>{r.add(s)},a=(s,l)=>{if(l>Ia)return or.depthCap++,t;if(typeof s=="string")return ma(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&&_t(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 sr(e,t=Xn){return It(e,t).value}function Ea(e){let{value:t,detectors:n}=It(e),r=n.some(i=>He[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function Ra(e,t){let{blocked:n,redacted:r,detectors:i}=Ea(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 Ca(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}var xa=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function Oa(e){return xa.has(Ca(e))}function ae(e,t,n){return n.enforced&&Oa(e)?Ra(t,{failMode:n.failMode}):{verdict:"allow",redacted:t,detectors:[]}}var Na=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,lr=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"}),Ma=new RegExp(`[${Object.keys(lr).join("")}]`,"gu"),Da=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),cr="\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",Fa=Object.freeze(Object.fromEntries([...cr].map((e,t)=>[e,String.fromCharCode(97+t)]))),La=new RegExp(`[${cr}\u2800]`,"g"),ur=/[⠀-⣿]/;function $a(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 Pa(e){return e.replace(Na,"")}function dr(e){return e.replace(Ma,t=>lr[t]??t)}function ja(e){return e.replace(/[4@31!05$79(8]/g,t=>Da[t]??t)}function Ba(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 Ua(e){return ur.test(e)?e.replace(La,t=>t==="\u2800"?" ":Fa[t]??t):e}function qn(e){let t;try{t=$a(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=Pa(t),t=dr(t),t}var qa=/^[A-Za-z0-9+/]{16,}={0,2}$/,za=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,zn=/[A-Za-z0-9+/]{20,}={0,2}/g;function bt(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 pr=new TextDecoder("utf-8",{fatal:!1});function fr(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=pr.decode(n);return t===r?[t]:[r,t]}function Va(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=pr.decode(n);return r===i?[r]:[i,r]}function Vn(e){let t=e.trim(),n=[];if(za.test(t))for(let r of Va(t))n.push({decoded:r,textiness:bt(r)});if(qa.test(t)&&t.length%4===0)for(let r of fr(t))n.push({decoded:r,textiness:bt(r)});return n}function Kn(e,t){let n=[],r;for(zn.lastIndex=0;(r=zn.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let o of fr(i))n.push({decoded:o,textiness:bt(o)})}return n}var Ka=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function mr(e,t=Ka){if(typeof e!="string"||e.length===0)return{views:[],anyDecoded:!1,truncated:!1,nodes:0,maxDepthSeen:0};let{maxDepth:n,byteCap:r,maxNodes:i,maxBlobsPerNode:o}=t,a=new Set,s=f=>{f.length>0&&f.length<=r&&a.add(f)},l=!1,c=!1,u=0,d=0,p=[{s:e,depth:0}];for(;p.length>0;){if(u>=i){c=!0;break}let f=p.pop();if(f===void 0)break;let{s:m,depth:g}=f;if(m.length>r){c=!0;continue}u++,g>d&&(d=g);let _=qn(m);s(_);let I=ja(_);if(I!==_&&s(I),s(Ba(_)),ur.test(m)&&s(Ua(_)),g>=n){let A=qn(m);(Vn(A).length>0||Kn(A,o).length>0)&&(c=!0);continue}let b=[...Vn(_),...Kn(_,o)];for(let A of b){if(l=!0,A.decoded.length>r){c=!0;continue}A.textiness>=.85&&A.decoded!==_?p.push({s:A.decoded,depth:g+1}):s(A.decoded)}}return{views:[...a],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:d}}var gr=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],Ga=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),Ha=8,Wa=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Gn=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function Qa(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||Wa.has(i)&&Gn(t[r-1])&&Gn(t[r+1])&&(n++,n>=Ha))return!0}return!1}var Ya=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function Za(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(Ya.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Ja=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Xa(e){for(let t of Ja)if(e>=t.lo&&e<=t.hi)return t.name;return null}function es(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=Xa(o.codePointAt(0));if(a===null){i=!1;break}a==="latin"?n++:dr(o)!==o&&r++}if(i&&n>0&&r>0)return!0}return!1}var Hn=Object.freeze({signals:[],contributes:!1});function ts(e){if(typeof e!="string"||e.length===0)return{...Hn,signals:[]};let t=new Set;try{Qa(e)&&t.add("hidden_text_carrier"),Za(e)&&t.add("injected_turn_boundary"),es(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=mr(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Hn,signals:[]}}return{signals:[...gr.filter(n=>t.has(n))],contributes:Ga.some(n=>t.has(n))}}var We=[{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 Wn(e){return typeof e!="string"||e.length===0?[]:We.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function ns(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(Wn(e)),{views:n}=mr(e);for(let r of n)for(let i of Wn(r))t.add(i);return We.filter(r=>t.has(r.name)).map(r=>r.name)}function rs(e){let t=new Set,n=new Set,r=!1,i=o=>{if(o!=null){if(typeof o=="string"){for(let s of ns(o))t.add(s);let a=ts(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:We.filter(o=>t.has(o.name)).map(o=>o.name),structural:gr.filter(o=>n.has(o))}}function is(e){return rs(e).matched}var Vc=We.map(e=>e.name);var os=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var as="i:injection";function hr(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=It(e.content);for(let o of i){let a=He[o]?.category;a&&t.add(`c:${a}`)}is(e.content)&&t.add(as)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&os.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var ht="(?: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))",Kc=[{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${ht}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${ht}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${ht}\\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}],Qn="(?: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+${Qn}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${Qn}|programming|training))`,ls="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Yn="(?:\\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)",cs="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Gc=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${ls}${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}?${Yn}`,"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+(?:${cs}\\b|[\\s\\S]{0,40}?${Yn})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Hc=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var z=e=>`[^.!?;\\n]{0,${e}}?`,us=["\\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("|"),yr="(?: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)",Wc=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${us})\\s${z(40)}\\b${yr}\\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${z(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${z(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${z(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${z(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${z(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")}]),Qc=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${z(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${z(30)}\\b${yr}\\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 Ae=e=>`[^.!?;\\n]{0,${e}}?`,Yc=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${Ae(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${Ae(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${Ae(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${Ae(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${Ae(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 Tt="[REDACTED]",oe="\u2022",Ge=e=>/[\p{L}\p{N}]/u.test(e);function _r(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:oe,c=a+s>=o;return i.map((u,d)=>!c&&(d<a||d>=o-s)?u:Ge(u)?l:u).join("")}function ds(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return _r(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:oe;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>Ge(a)?o:a).join(""))+i}function ps(e,t,n){let r=n.length>0?n:oe,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(Ge(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]||!Ge(u)?l+=u:l+=r}return l}function br(e,t){let n=t.mode??"full";return n==="partial"?_r(e,t.keepFirst??0,t.keepLast??0,t.maskChar??oe):n==="email"?ds(e,t.maskChar??oe):n==="custom"?ps(e,t.keepPattern,t.maskChar??oe):t.replacement??Tt}function fs(e,t){return typeof e=="string"?br(e,t):t.replacement??Tt}function vr(e){let t=[],n=e.replacement??Tt;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:yt(r),replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:yt(i),replacer:o=>br(o,r)})}return t}function wr(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 kr(e,t){if(vt(e).length===0){let n=e;for(let{source:r,replacer:i}of t)n=n.replace(wr(r),o=>i(o));return n}return ms(e,t)}function ms(e,t){let n=e;for(let{source:r,replacer:i}of t){let o=wr(r),a=[...Ln(o,n)];for(let u of vt(n))for(let d of Ln(o,u.text))a.push(Ko(u,d));let s=Go(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 M(e,t){return e==null?e:typeof e=="string"?gs(e,t):typeof e=="object"?hs(e,t):e}function gs(e,t){if(typeof e!="string")return e;let n=vr(t);return n.length===0?e:kr(e,n)}function hs(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=vr(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]=fs(l[u],d);continue}c[u]=a(l[u])}return c}return typeof s=="string"&&o?kr(s,r):s};return a(e)}import{createHash as iu}from"node:crypto";var Ar=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function ys(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:Ar(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:Ar(t.spawn.prompt)}),t}function _s(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 bs=1440*60*1e3,vs="VISIQ_BUNDLE_GRACE_TTL_MS",ws="VISIQ_BUNDLE_CACHE_DISABLED",ks="VISIQ_CACHE_DIR",As=Qe.object({graceTtlMs:Qe.number().int().nonnegative().optional(),disabled:Qe.boolean().optional(),cacheDir:Qe.string().min(1).optional()}).strict();function Ss(e){return e==null?{}:As.parse(e)}function Is(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[vs];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return bs}function Ts(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[ws]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var Sr;function Es(){if(Sr!==void 0)return Sr;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Rs(e){return JSON.stringify(Rt(e))}function Rt(e){if(Array.isArray(e))return e.map(Rt);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Rt(t[r]);return n}return e}function Cs(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function xs(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 Or(){if(!Es())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 Nr(e,t){return e.createHash("sha256").update(Rs(t)).digest("hex")}function Os(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[ks]?.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 Ns(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function Mr(e,t,n){return e.path.join(Os(e,n),"bundles",`${Ns(e,t)}.json`)}async function Ms(e,t,n,r={}){let i=await Or();if(i)try{let o=Mr(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:Nr(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 Ds(e,t={}){let n=await Or();if(!n)return null;try{let r=await n.fs.readFile(Mr(n,e,t),"utf-8"),i=xs(JSON.parse(r));return!i||Nr(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var Ie;async function Fs(){if(Ie!==void 0)return Ie;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;Ie=typeof t=="function"?t:null}catch{Ie=null}return Ie}function Ls(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=mt(i)}catch{continue}let a=typeof r.id=="string"?r.id:"<rule>";for(let s of mn(o))t.push(`${a}: ${s}`)}return t}function $s(e){return Mn(e)}function Ps(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var js=5e3,Bs=600*1e3,Us=1e4,qs=25,Ir=1e3,zs=5e3,Vs=100,Tr=2e3,Ks=10,Gs=512,Hs=1800*1e3,Ws=.7,Qs="monitor",Ys="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",Er="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.",Ye="open";function Te(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Zs(e,t){return hr({content:e,resourceMetadata:t})}var Js=y.object({operations:y.array(y.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:y.string().min(1,"agentId is required"),sessionId:y.string().min(1).max(255).optional(),toolName:y.string().optional(),toolArgs:y.record(y.unknown()).optional(),targetResource:y.string().optional(),resourceType:y.string().optional(),resourceMetadata:y.record(y.unknown()).optional(),normalized:y.record(y.unknown()).optional(),query:y.string().optional(),contentPreview:y.string().optional(),telemetry:y.record(y.unknown()).optional(),context:y.record(y.unknown()).optional(),mcpServer:y.string().min(1).max(255).optional()}),Xs=y.object({version:y.string().min(1),dialect_version:y.number().int().optional(),min_dialect:y.number().int().optional(),shutdown:y.boolean().optional(),agent_mode:y.enum(["enforce","monitor","off"]).optional(),cognition_capture:y.boolean().optional(),agent_mode_by_operation:y.object({action:y.string().optional(),retrieval:y.string().optional(),delegation:y.string().optional()}).partial().optional(),agent_attributes:y.object({trust_tier:y.string().nullable().optional(),categories:y.array(y.string()).optional(),business_function:y.string().nullable().optional(),business_functions:y.array(y.string()).nullable().optional(),blast_radius_tier:y.string().nullable().optional(),no_coverage:y.string().nullable().optional(),fail_mode:y.string().nullable().optional()}).optional(),rules:y.array(y.record(y.unknown())),action_schemas:y.array(y.object({id:y.string(),plane:y.string().optional(),field_mappings:y.array(y.record(y.unknown())).optional(),derived_fields:y.array(y.record(y.unknown())).optional(),action_class:y.string().nullable().optional(),action_class_confidence:y.number().optional()})).optional(),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()}).optional(),skill_blacklist:y.array(y.record(y.unknown())).optional()});function el(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=Tn(En(n));return{trust_tier:hn(t)?t:null,categories:_n(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&Rn(e.blast_radius_tier)?e.blast_radius_tier:null}}function tl(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 nl(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Ct=new Set,Rr=!1;async function Cr(e){let t=[];for(let n of Ct){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 rl(){if(!Rr&&!(typeof process>"u"||typeof process.once!="function")){Rr=!0,process.once("beforeExit",()=>{Cr(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await Cr(!0)}finally{process.kill(process.pid,e)}})()})}}var Dr=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=Qs;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=Te(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Ye;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=Ss(s);if(this.bundleCacheDisabled=Ts(d.disabled),this.bundleGraceTtlMs=Is(d.graceTtlMs),this.bundleCacheDirOverride=d.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let p={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:_s(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...o!==void 0?{sdkVersion:o}:{},...a!==void 0?{sdkDialect:a}:{}};this.client=new dt(p,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},js),Et(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Us),Et(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},zs),Et(this.cognitionTimer),Ct.add(this),rl()}else this.client=null}async evaluate(e){let t=Js.parse(e),n=Date.now();if(this.operatorShutdown){let f=this.denyAll(t,Ys);return this.applyAgentMode(f,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,Er,n);let f=this.denyAll(t,Er);return this.applyAgentMode(f,"enforce",t,n)}if(t.operations.every(f=>this.modeFor(f)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let f;if(this.agentModeConfirmed?f=this.agentMode:this.bundleApplyFailed?f="enforce":f="monitor",f==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let m=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(m,f,t,n)}if(this.modeFor("action")!=="off"){let f=this.matchSkillQuarantine(t);if(f){let m=this.denyAll(t,f);return this.applyAgentMode(m,this.modeFor("action"),t,n)}}let r=this.readSession(t.sessionId),i=await Fs();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")?vn(t.normalized??{},{targetApp:t.targetResource??t.toolName??""}):t.normalized,a=this.buildActionSchemaEvent(t),s=t.mcpServer?{...o??{},mcp_server:t.mcpServer}:o,l={...t,normalized:s,session:r,at:Date.now(),action_schema_id:a.id,action_schema_raw:a.canonical},c={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},u;try{u=i(l,c)}catch(f){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${f instanceof Error?f.message:String(f)}`,n);throw f}let d=[...new Set(t.operations.flatMap(f=>this.normalizedRefs[f]??[]))].sort();d.length>0&&Ps(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 p=wn(t.normalized);return p.length>0&&(u.normalizedDrift=p,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${p.length} value(s) outside the canonical vocabulary \u2014 a builder-authored rule can only select in-vocab values, so these cannot match one, so a rule keyed on the canonical value does not fire here. Check the harness classifier's casing/spelling. Affected: ${p.slice(0,5).join("; ")}${p.length>5?`; +${p.length-5} more`:""}`))),this.foldSession(t,u.enforced?u.decision:"permit"),u.enforced&&u.action.decision==="approval_required"&&await this.registerHitl(t,u),this.bufferTelemetry(t,u,Date.now()-n,u.enforced),u}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}matchSkillQuarantine(e){if(this.skillBlacklist.length===0)return null;let t=e.context?.skill;if(!t||t.activated!==!0)return null;let n=typeof t.name=="string"?t.name:"",r=typeof t.fingerprint=="string"?t.fingerprint:null;if(n.length===0&&r===null)return null;let i=Cn({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 ke;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Hs?(this.sessions.delete(e),ke):t.state:ke}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>=Ws)return o}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=An(r===ke?kn():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,taint:o?Zs(e.contentPreview,i):void 0,action_class:a?this.foldActionClass(e):void 0,target_app:a?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>Gs){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=Xs.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=Ls(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=>Nn(i)).filter(i=>i!==null),this.skillBlacklist=Array.isArray(t.skill_blacklist)?t.skill_blacklist:[],this.agentAttributes=t.agent_attributes?el(t.agent_attributes):null,this.agentNoCoverage=xn(t.agent_attributes?.no_coverage),this.governedFailMode=Te(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=tl(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=$s(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",...Q(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>=Bs&&(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 Ds(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Cs(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 Ms(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({...Be(),...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({...Be(),...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=On(n),i={...n};return e.toolArgs&&(i.tool_args=sr(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?nl(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?{[nn]: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,Ks)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=qs&&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-Ir;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Ir})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(ys(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Vs&&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-Tr;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Tr})`))}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(),Ct.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 Et(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function il(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function $(e,...t){for(let n of t){let r=il(e[n]);if(r)return r}}var ol=[{framework:"openai-agents",matches:e=>/^transfer_to_.+/.test(e),extract:(e,t)=>{let n=e.replace(/^transfer_to_/,"");return{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"teammate",task:$(t,"task","input","reason","message"),source:"structural"}}},{framework:"voltagent",matches:e=>e==="delegate_task",extract:(e,t)=>{let n=$(t,"targetAgent","agent","subAgent","agentName","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:$(t,"task","message","input"),description:$(t,"purpose"),source:"structural"}:null}},{framework:"crewai",matches:e=>/delegate work to (co-?worker|.+)/i.test(e),extract:(e,t)=>{let n=$(t,"coworker","agent","role");return n?{childAgentId:n,childName:n,kind:"teammate",agentType:n,task:$(t,"task","question"),description:$(t,"context"),source:"structural"}:null}},{framework:"llamaindex",matches:e=>e==="handoff"||/handoff/i.test(e),extract:(e,t)=>{let n=$(t,"to_agent","toAgent","agent_name","agentName","agent","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:$(t,"reason","task","message"),source:"structural"}:null}},{framework:"generic",matches:e=>/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)([_-].+)?$/i.test(e),extract:(e,t)=>{let n=$(t,"agent","agentName","agentId","target","targetAgent","to","to_agent","coworker","name")??(/[_-]/.test(e)?e.replace(/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)[_-]/i,""):void 0);return n?{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"subagent",task:$(t,"task","message","input","reason","prompt"),source:"heuristic"}:null}}];function Ze(e,t){if(!e)return null;let n=t??{};for(let r of ol)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function Je(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 al={skill:"mastra",workspace_activate_skill:"voltagent",load_skill:"openai-agents",Skill:"claude-code"},sl=new Set(["workspace_deactivate_skill"]),ll=new Set(["read","read_file","readfile","view","cat"]);function cl(e){return sl.has((e??"").trim())}function ul(e){let t=/(?:^|[/\\])([^/\\]+)[/\\]SKILL\.md$/i.exec(e.trim());return t?t[1]??null:null}function xr(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function dl(e,t){let n=(e??"").trim();if(!n)return null;let r=t??{},i=al[n];if(i){let o=xr(r,["name","skill_name","identifier","skill","path"]);return o?{skill:o,via:n,framework:i}:null}if(ll.has(n.toLowerCase())){let o=xr(r,["path","file_path","filePath","target","file"]),a=o?ul(o):null;return a?{skill:a,via:n,framework:"unknown"}:null}return null}function Fr(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 Lr=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=dl(e,t);if(n)return this.activate(n),{activation:n,attributedSkill:n.skill};if(cl(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 ou=512*1024;function xt(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 $r(e){if(typeof e=="string"){try{let t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{input:e}}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{input:e===void 0?"":String(e)}}function D(e){let t=[],n=[],r,i=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let l={mode:a.mode};a.field&&(l.field=a.field),a.pattern&&(l.pattern=a.pattern),typeof a.keepFirst=="number"&&(l.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(l.keepLast=a.keepLast),a.maskChar&&(l.maskChar=a.maskChar),a.keepPattern&&(l.keepPattern=a.keepPattern),a.replacement!==void 0&&(l.replacement=a.replacement),i.push(l);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:s}=a;s&&r===void 0&&(r=s)}let o={};return t.length>0&&(o.fields=t),n.length>0&&(o.patterns=n),r!==void 0&&(o.replacement=r),i.length>0&&(o.directives=i),o}var V="0.2.19";import{AsyncLocalStorage as pl}from"node:async_hooks";var x=new pl,fl=5120,Pr=50;function ml(e,t){if(typeof e!="string")return"";let n=new TextEncoder,r=n.encode(e);if(r.length<=t)return e;let o=`\u2026[truncated ${Math.ceil(r.length/1024)}KB]`,a=n.encode(o).length,s=Math.max(0,t-a),l=r.subarray(0,s);return new TextDecoder("utf-8",{fatal:!1}).decode(l)+o}function K(e){if(!e)return;let t=r=>r.length<=Pr?r.slice():r.slice(r.length-Pr),n=r=>ml(r,fl);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 Ot=12e4,jr=2e3,Br=3,gl=5e3;function Ee(e,t){return e==="mask"&&(t?.length??0)>0}var hl=new Set(["approved","resolved"]),yl=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function _l(e){return new Promise(t=>setTimeout(t,e))}function bl(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 Re(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=Ot,maskFallback:o=!1,sdkVersion:a,fetchImpl:s=globalThis.fetch,sleep:l=_l,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)}`,p={Accept:"application/json",...Q(a)};n&&(p.Authorization=`Bearer ${n}`);let f=Date.now()+Math.max(0,i),m=0;for(c(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=f)return c(`[VisIQ HITL] Decision ${r} timed out after ${i}ms \u2014 ${o?"masking":"blocking"} (G001)`),u("HITL approval timed out");let g=null;try{let _=new AbortController,I=setTimeout(()=>_.abort(),gl),b;try{b=await s(d,{method:"GET",headers:p,signal:_.signal})}finally{clearTimeout(I)}if(!b.ok)throw new Error(`HTTP ${b.status} ${b.statusText}`);let A=await b.json();g=bl(A),m=0}catch(_){m+=1;let I=_ instanceof Error?_.message:String(_);if(c(`[VisIQ HITL] Poll failed for decision ${r} (${m}/${Br}): ${I}`),m>=Br)return u(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${I}`);await l(jr);continue}if(g!==null){let _=g.toLowerCase();return hl.has(_)?(c(`[VisIQ HITL] Decision ${r} approved (${g}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${g})`}):yl.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(jr)}}function G(e){return e??Te(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Ye}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 U(e,t){try{console.error(`[VisIQ] TRACE-DEGRADED (${e}): ${t} \u2014 the governance decision was still made and enforced; only the execution-trace beat was lost.`)}catch{}}function se(e){let t=e.getFailMode;return(typeof t=="function"?t.call(e):void 0)??G()}function J(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 qr(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&Ee(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}var Ur=new Set;function Ft(e){Ur.has(e)||(Ur.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 et(e,t,n){let r=x.getStore(),i=K(r),o=await e.evaluate({operations:["retrieval"],agentId:t,...r?.session_id?{sessionId:r.session_id}:{},resourceType:n.resourceType??"document",resourceMetadata:n.resourceMetadata??{},...n.query!==void 0?{query:n.query}:{},...n.contentPreview!==void 0?{contentPreview:n.contentPreview}:{},...i?{telemetry:i}:{}});return qr(o)}async function tt(e,t,n){return await e.awaitBundleReady(),et(e,t,n)}function zr(e,t,n=G()){switch(t.action){case"allow":case"escalate":return e;case"deny":return null;case"redact":{if(t.redactionRules.length===0)return e;try{return M(e,D(t.redactionRules))}catch{return n==="closed"?null:(w("redact-error","document redaction failed \u2014 document passed UNREDACTED"),e)}}default:return Ft(String(t.action)),n==="closed"?null:(w("unknown-retrieval-verb",`unrecognized outcome "${String(t.action)}" \u2014 document passed through`),e)}}var vl=["pageContent","text","content"];function nt(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))!vl.includes(r)&&r!=="metadata"&&(n[r]=i);return n}async function Vr(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=nt(a),c=await et(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s.slice(0,500)}),u=zr(o,c,se(r));u!==null&&i.push(u)}return i}async function Kr(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await et(n,t,{resourceType:"document",resourceMetadata:{content_preview:e.slice(0,500)},contentPreview:e.slice(0,500)})}catch(i){return se(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 M(e,D(r.redactionRules))}catch{return se(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(w("redact-error","text redaction failed \u2014 text passed UNREDACTED"),e)}}default:return Ft(String(r.action)),se(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(w("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 text passed through`),e)}}var Gr=4,Hr=1e3;function Xe(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 Wr(e,t,n){let r=[];for(let i of e){let o=i,a=String(o.pageContent??o.text??o.content??""),s={...nt(o),content_preview:a.slice(0,500)},l;try{l=await et(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:a.slice(0,500)})}catch(u){if(se(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=zr(i,l,se(n));c!==null&&r.push(c)}return r}async function Mt(e,t,n,r,i){if(r>Gr||i.nodes++>Hr)return e;if(Array.isArray(e)){if(Xe(e))return i.matched=!0,Wr(e,t,n);let o=[];for(let a of e)o.push(await Mt(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 Mt(o[s],t,n,r+1,i);return a}return e}async function rt(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&Xe(e))return Wr(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await Mt(e,t,n,0,r);if(r.matched)return i}return e}var wl={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function Dt(e,t,n){if(t>Gr||n.n++>Hr)return e;if(Array.isArray(e))return Xe(e)?[]:e.map(r=>Dt(r,t+1,n));if(e!==null&&typeof e=="object"){if(Xe([e]))return{...wl};let r=e,i={};for(let o of Object.keys(r))i[o]=Dt(r[o],t+1,n);return i}return e}function Nt(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?Dt(e,0,{n:0}):e}function Qr(e,t,n=G()){let r=qr(t);switch(r.action){case"allow":case"escalate":return e;case"deny":return Nt(e);case"redact":{if(r.redactionRules.length===0)return e;try{return M(e,D(r.redactionRules))}catch{return n==="closed"?Nt(e):(w("redact-error","result redaction failed \u2014 result passed UNREDACTED"),e)}}default:return Ft(String(r.action)),n==="closed"?Nt(e):(w("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 result passed through`),e)}}function C(e){return typeof e=="object"&&e!==null?e:null}function Yr(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}function kl(e,t){let n=C(e.metadata),r=n&&typeof n.name=="string"?n.name:void 0;return Yr(e.name,e.id,r,t)}function Al(e){let t=C(e.metadata),n=t&&typeof t.description=="string"?t.description:void 0,r=Yr(e.description,n);return r===void 0?void 0:r.slice(0,4e3)}function Sl(e){let t=C(e);return t!==null&&("type"in t||"properties"in t||"$schema"in t)}function Il(e){let t=C(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=C(n);if(r===null)return{type:"object"};let i={};for(let o of Object.keys(r))i[o]={};return{type:"object",properties:i}}var Tl=new Set(["default","const","enum","examples","example"]);function Lt(e){if(Array.isArray(e))return e.map(Lt);let t=C(e);if(t===null)return e;let n={};for(let[r,i]of Object.entries(t))Tl.has(r)||(n[r]=Lt(i));return n}function El(e){let t;if(Sl(e))t=e;else{let n=Il(e);if(n===void 0)return;t=n}try{let n=JSON.stringify(t);if(n.length>2e4){let r=C(t),i=r&&C(r.properties);if(i){let o={};for(let a of Object.keys(i))o[a]={};return{type:"object",properties:o}}return{type:"object"}}return Lt(JSON.parse(n))}catch{return}}function Rl(e){let t=C(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:El(n)}function Cl(e,t){let n=C(e);if(n===null)return null;let r=kl(n,t);if(r===void 0)return null;let i={name:r.slice(0,255)},o=Al(n);o!==void 0&&(i.description=o);let a=Rl(n);return a!==void 0&&(i.input_schema=a),i}function X(e){let t=[],n=new Set,r=(i,o)=>{try{let a=Cl(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=C(e);if(i!==null){for(let o of Object.keys(i))if(r(i[o],o),t.length>=200)break}}return t}function $t(e){try{let t=C(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(X(t.tools));let o=C(t.settings);o&&o.tools!==void 0&&i(X(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(X(d))}catch{}}let a=C(t.nodes)?t:C(t.graph)??C(t.builder)??t,s=C(a.nodes);if(s)for(let c of Object.keys(s)){let u=C(s[c]);if(!u)continue;u.tools!==void 0&&i(X(u.tools));let d=C(u.bound);d&&d.tools!==void 0&&i(X(d.tools))}let{agents:l}=t;if(l instanceof Map)for(let c of l.values()){let u=C(c);u&&u.tools!==void 0&&i(X(u.tools))}return n}catch{return[]}}async function Zr(e){let t=C(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 X(await a))r.has(s.name)||(r.add(s.name),n.push(s))}catch{}}return n}import{z as it}from"zod";var xl=it.object({decision:it.enum(["permit","deny"]),reason:it.string(),handoff_event_id:it.string().nullable()}),B=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},ee=class extends B{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},Ol="https://api.visiqlabs.com",Nl=1e4,le=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??Ol,timeoutMs:e.timeoutMs??Nl},this.fetch=t}get headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Agent-ID":this.config.agentId}}async post(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.fetch(`${this.config.endpoint}${e}`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:n.signal})}finally{clearTimeout(r)}let o=await i.json();if(!i.ok){let a=o?.error??`HTTP ${i.status}`;throw new B(a,"API_ERROR",i.status)}return o}async requestGrant(e){let t=await this.post("/orchestrate/grants",{parent_agent_id:e.parentAgentId,child_agent_id:e.childAgentId,tool_scope:e.toolScope??null,context_scope:e.contextScope??null,purpose:e.purpose,duration_seconds:e.durationSeconds,max_depth:e.maxDepth,parent_grant_token:e.parentGrantToken});return{grantId:t.grant_id,status:"pending",effectiveToolScope:t.effective_tool_scope,effectiveContextScope:t.effective_context_scope,acceptDeadline:t.accept_deadline}}async acceptGrant(e){let t=await this.post(`/orchestrate/grants/${e}/accept`,{});return{grantToken:t.grant_token,toolScope:t.tool_scope,contextScope:t.context_scope,expiresAt:t.expires_at}}async evaluate(e){let t=await this.post("/orchestrate/evaluate",{grant_token:e.grantToken,action:e.action,resource_type:e.resourceType,resource_metadata:e.resourceMetadata??{}}),n=xl.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 Jr=new Map;async function Xr(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=Jr.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 le({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 Jr.set(e,o),o}var Ce=Symbol.for("visiq.orchestrate.wrapped");function Ml(e){return e instanceof B&&typeof e.status=="number"&&e.status>=400&&e.status<500}function ei(e,t){if(!t.agentId||t.agentId.trim()==="")throw new B("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new B("grantToken is required","CONFIG_ERROR");if(e[Ce]===!0)return e;let n=new le(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(Ml(l))throw l;if(r==="permit"){console.warn('[VisIQ] FAIL-OPEN (orchestrate-eval-error): evaluate failed \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed (or failBehavior:"deny") to block instead.',l);return}throw new B(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new ee(s.reason,s.handoffEventId)};return new Proxy(e,{get(o,a,s){let l=Reflect.get(o,a,s);return a===Ce?!0:a==="_call"&&typeof l=="function"?async function(c,...u){let d=o.name;return await i(d??"_call"),l.call(this??o,c,...u)}:(a==="call"||a==="execute"||a==="run")&&typeof l=="function"?async function(c,...u){let d=o.name;return await i(d??String(a)),l.call(this??o,c,...u)}:l}})}import{randomUUID as ci}from"node:crypto";var ti=Symbol.for("visiq.semantickernel.instrumented");function ii(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 ni(e){let t=e.arguments;return t&&typeof t=="object"&&"arguments"in t&&t.arguments&&typeof t.arguments=="object"?t.arguments:t??{}}function ri(e,t){let n=e.arguments;if(n&&typeof n=="object"&&"arguments"in n&&n.arguments&&typeof n.arguments=="object"){let r=n.arguments;for(let i of Object.keys(r))delete r[i];Object.assign(r,t);return}e.arguments=t}function q(e,t){e.result&&typeof e.result=="object"?e.result.value=t:e.result={value:t}}function Dl(e){return e.result?.value}function Fl(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=ni(o),u=l;try{let g=await n.evaluate({operations:["action"],agentId:t,toolName:s,toolArgs:c,...u!==void 0?{targetResource:u}:{}}),_=J(g);if(!_.allowed){q(o,O({outcome:"deny",code:_.ruleCode??"DENY",reason:_.reason}));return}_.decision==="mask"&&_.argRedactionRules.length>0&&ri(o,M(c,D(_.argRedactionRules)));let I=ni(o),b=ae(s,I,{failMode:r==="closed"?"closed":"open",enforced:g.enforced});if(b.verdict==="block"){q(o,O({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${b.detectors.join(",")})`}));return}b.verdict==="redact"&&(ri(o,b.redacted),w("outbound-secret-redacted",`outbound secret screen redacted ${b.detectors.length} detector(s): ${b.detectors.join(",")}`))}catch(g){if(r==="closed"){q(o,O({outcome:"error",code:"EVAL-ERROR",mechanism:`evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${g instanceof Error?g.message:String(g)}`}));return}w("eval-error",`SK action pre-gate failed for "${s}": ${g instanceof Error?g.message:String(g)}`)}try{let g=await tt(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l}});if(g.action==="deny"||g.action==="escalate"){q(o,`[RECALL: access denied \u2014 ${g.reason}]`);return}}catch(g){if(r==="closed"){q(o,`[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${g instanceof Error?g.message:String(g)}.`);return}w("eval-error",`SK retrieval pre-gate failed for "${s}": ${g instanceof Error?g.message:String(g)}`)}await a(o);let d=Dl(o),f=(typeof d=="string"?d:(()=>{try{return JSON.stringify(d)??String(d)}catch{return String(d)}})()).slice(0,500),m;try{m=await tt(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:s,plugin_name:l,content_preview:f},contentPreview:f})}catch(g){r==="closed"?q(o,"[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):w("eval-error",`SK post-result retrieval eval failed for "${s}": ${g instanceof Error?g.message:String(g)}`);return}if(m.action==="deny"||m.action==="escalate"){q(o,`[RECALL: access denied \u2014 ${m.reason}]`);return}if(m.action==="redact"&&m.redactionRules&&m.redactionRules.length>0&&d!==null&&d!==void 0)try{q(o,M(d,D(m.redactionRules)))}catch(g){r==="closed"?q(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: ${g instanceof Error?g.message:String(g)}`)}}}function Ll(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 tt(e.unified,e.agentId,{resourceType:"prompt",resourceMetadata:{},contentPreview:i.slice(0,500)})}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":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=M(i,D(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 oi(e,t){let n=e;if(n[ti]===!0)return t.onWrap?.(),e;let r=Fl(t),i=Ll(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[ti]=!0,t.onWrap?.()),e}function O(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 ot(e){return e instanceof Error?e.message:String(e)}var $l=/https?:\/\/[^\s"'`,)}\]]+/;function jt(e){let t=e.match($l);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var ce=Symbol.for("visiq.toolexec.instrumented"),ai=Symbol.for("visiq.agentclone.instrumented"),Bt=Symbol.for("visiq.instrument.deferred");function Pl(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}var Ut={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 ui(e){if(e===null||typeof e!="object")return null;let t=e;if(Pl(t))return null;if(ii(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 si=new WeakMap;function jl(e){let t=si.get(e);return t||(t=new Lr,si.set(e,t)),t}async function Bl(e,t,n,r,i,o){let{agentId:a,unified:s}=e,l=K(i),c;try{let b=jl(e).observe(t,n);c=Fr(b)}catch{c=void 0}let u=o?Je(o,a):void 0,d=u||c?{...u??{},...c??{}}:void 0,p,f=!1;try{await s.awaitBundleReady();let b=await s.evaluate({operations:o?["action","delegation"]:["action"],agentId:a,toolName:t,toolArgs:n,...d?{context:d}:{},...i?.session_id?{sessionId:i.session_id}:{},...r!==void 0?{targetResource:r}:{},...l?{telemetry:l}:{}});({enforced:f}=b),p=J(b)}catch(b){let A=b instanceof Error?b.message:String(b);return e.failMode==="closed"?{block:O({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${A} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})}:(w("eval-error",`policy evaluation failed for tool "${t}": ${A}`),{block:null})}if(p.decision==="approval_required"&&p.decisionId){let b=s.getApiKey()??e.apiKey,A=await Re({endpoint:s.getEndpoint()??e.endpoint??"",...b?{apiKey:b}:{},decisionId:p.decisionId,timeoutMs:e.hitlTimeoutMs,sdkVersion:V});return A.resolution!=="proceed"?{block:O({outcome:"approval_required",code:p.ruleCode??"HITL-BLOCK",reason:p.reason,mechanism:A.reason}),decision:p}:{block:null}}if(!p.allowed)return{block:O({outcome:"deny",code:p.ruleCode??"DENY",reason:p.reason}),decision:p};let m=n,g=!1,_;if(p.decision==="mask"&&p.argRedactionRules&&p.argRedactionRules.length>0)try{let b=D(p.argRedactionRules);m=M(n,b),g=!0,_=p}catch(b){let A=b instanceof Error?b.message:String(b);if(e.failMode==="closed")return{block:O({outcome:"error",code:"MASK-ERROR",mechanism:`argument masking failed: ${A} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})};w("mask-error",`argument masking failed for tool "${t}" \u2014 running with UNMASKED args: ${A}`)}let I=ae(t,m,{failMode:e.failMode==="closed"?"closed":"open",enforced:f});return I.verdict==="block"?{block:O({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${I.detectors.join(",")})`}),decision:{allowed:!1,decision:"deny",ruleCode:"OUTPUT-BLOCK",reason:"outbound content carried a live secret",argRedactionRules:[]}}:(I.verdict==="redact"&&(m=I.redacted,g=!0,w("outbound-secret-redacted",`outbound secret screen redacted ${I.detectors.length} detector(s): ${I.detectors.join(",")}`),_??={allowed:!0,decision:"mask",ruleCode:"OUTPUT-BLOCK",reason:"outbound secret redacted before egress",argRedactionRules:[]}),g?{block:null,maskedArgs:m,decision:_}:{block:null})}async function qt(e,t,n,r,i){let o=x.getStore()??e.telemetry,a=Ze(t,n);a&&ye(e.unified,{agentId:e.agentId,sessionId:o?.session_id,...e.framework?{framework:e.framework}:{}},a);let s={agentId:e.agentId,sessionId:o?.session_id,...e.framework?{framework:e.framework}:{}},l=me(t,n);try{_e(e.unified,s,{toolName:t,...l?{memory:l}:{},argSummary:r.slice(0,512)})}catch(m){U("step-beat",`emit failed for tool "${t}": ${ot(m)}`)}let c=Date.now(),u=await Bl(e,t,n,jt(r),o,a);if(u.block!==null){try{u.decision&&ie(e.unified,s,{toolName:t,decision:u.decision.decision??"deny",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0,harnessMessage:u.block})}catch(m){U("intervention-beat",`emit failed for tool "${t}": ${ot(m)}`)}return u.block}if(u.maskedArgs!==void 0&&u.decision)try{ie(e.unified,s,{toolName:t,decision:u.decision.decision??"mask",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0})}catch(m){U("intervention-beat",`emit failed for tool "${t}": ${ot(m)}`)}let d=u.maskedArgs??n,p=await i(d),f=await rt(p,e.agentId,e.unified);try{be(e.unified,s,{toolName:t,ok:!0,durationMs:Date.now()-c,...Y(f)!==void 0?{bytes:Y(f)}:{},...Z(f)!==void 0?{itemCount:Z(f)}:{},...l?{memory:l}:{}})}catch(m){U("observation-beat",`emit failed for tool "${t}": ${ot(m)}`)}return f}function Oe(e,t,n){let r=e;if(r[ce]){n.onWrap?.();return}if(typeof r.execute!="function")return;let i=r.execute;Ne(r,"execute",async function(...a){let s=xt(a[0]);return qt(n,t,s,Me(s),l=>Promise.resolve(i.apply(this,[l,...a.slice(1)])))}),r[ce]=!0,n.onWrap?.()}function Ul(e,t,n){let r=e;if(r[ce]){n.onWrap?.();return}if(typeof r.invoke!="function")return;let i=r.invoke;Ne(r,"invoke",async function(...a){let s=a[1],l=$r(s),c=typeof s=="string"?s:Me(l);return qt(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[ce]=!0,n.onWrap?.()}function ql(e,t){let n=e;if(n[ce]){t.onWrap?.();return}if(typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",o=n.call;Ne(n,"call",async function(...s){let l=xt(s[0]);return qt(t,i,l,Me(l),c=>Promise.resolve(o.apply(this,[c,...s.slice(1)])))}),n[ce]=!0,t.onWrap?.()}function zt(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&Oe(r,n,t);return e}function di(e,t,n){let r={...t,framework:n};switch(n){case"vercel":return zl(e,r);case"mastra":return Vl(e,r);case"openai":return pi(e,r);case"llamaindex":return Gl(e,r);case"voltagent":return Kl(e,r);case"semantic-kernel":return oi(e,r);default:return e}}function zl(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"&&zt(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=Vt(r.onStepFinish)),at(e,["generate","stream"],async(o,a)=>(xe(a,o[0]),o)),e}function Vl(e,t){let n=e;return Jl(n,t)==="deferred"&&(n[Bt]=!0),ec(n,t),at(e,["generate","stream","generateVNext","streamVNext"],async(r,i)=>{xe(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=Vt(o.onStepFinish);let a=[...r];return a[1]=o,a}),e}function Kl(e,t){let n=Ql(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;Oe(r,typeof i=="string"?i:"unknown",t)}}return at(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{xe(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=Vt(o.onStepFinish);let a=[...r];return a[1]=o,a}),e}function Gl(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"&&ql(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 at(e,["run"],async(o,a)=>(xe(a,o[0]),o)),Yl(e,"runStream",(o,a,s)=>{s||xe(a,o[0])}),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;Ul(i,typeof o=="string"?o:"unknown",t)}}return Wl(e,t),Hl(e,t),e}function Hl(e,t){let n=e;if(n[ai])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[ai]=!0}function Wl(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)=>{i.session_id=ci(),i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let s=a[2];s!=null&&i.llm_prompts.push(Me(s).slice(0,5120));try{let l=a[0],{getSystemPrompt:c}=n;typeof c=="function"&&Promise.resolve(c.call(e,l)).then(u=>{typeof u=="string"&&u.trim().length>0&&o.captureCloneMetadata({systemPrompt:u,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 Ql(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 at(e,t,n){let r=e;for(let i of t){if(typeof r[i]!="function")continue;let o=`__visiq_wrapped_${i}`;if(r[o])continue;let a=r[i];r[i]=function(...s){let l=mi();return x.run(l,async()=>{let c=await n(s,l);return a.apply(e,c)})},r[o]=!0}}function Yl(e,t,n){let r=e;if(typeof r[t]!="function")return;let i=`__visiq_wrapped_${t}`;if(r[i])return;let o=r[t];r[t]=function(...a){let s=x.getStore(),l=s??mi();return n(a,l,s!==void 0),x.run(l,()=>o.apply(e,a))},r[i]=!0}function Vt(e){return t=>{let n=x.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 xe(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(Me(n).slice(0,5120))}var Zl=["listTools","getTools"];function Jl(e,t){for(let n of Zl){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"?(zt(i,t),fi(e,i),"sync"):(i.then(()=>{},()=>{}),Xl(e,n,r,t),"deferred")}return"none"}function Xl(e,t,n,r){let i=o=>(o&&typeof o=="object"&&(zt(o,r),fi(e,o)),o);Ne(e,t,function(...o){let a=n.apply(this??e,o);return a&&typeof a.then=="function"?a.then(i):i(a)})}var Pt=Symbol.for("visiq.mastra.governedNames"),li=Symbol.for("visiq.mastra.assembly.instrumented");function fi(e,t){let n=e[Pt];n instanceof Set||(n=new Set,e[Pt]=n);for(let r of Object.keys(t))n.add(r)}function ec(e,t){let n=e;if(n[li])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[Pt],l=s instanceof Set?s:new Set;for(let[c,u]of Object.entries(a))l.has(c)||u!==null&&typeof u=="object"&&Oe(u,c,t);return a};Ne(n,"convertTools",function(...a){let s=i.apply(this??e,a);return s&&typeof s.then=="function"?s.then(o):o(s)}),n[li]=!0}function mi(){return{session_id:ci(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Ne(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function Me(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Ai(e,t){let n=dc(t);if(e[Ce]===!0)return e;let r=gc(e);if(r==="langchain-executor"||r==="langchain-graph")return ne(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,Kt(r,null),n.failMode,{model:hi(e)}),_i(e,n),hc(e,n);let i=ui(e);if(i){ne(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,Kt("unknown",i),n.failMode,{model:hi(e)}),_i(e,n),cc(e,n,Kt("unknown",i));let o=0,a=Ci(n);a.onWrap=()=>{o+=1};let s=di(e,a,i),l=s[Bt]===!0;if(o===0&&!l){let c=0;try{c=$t(e).length}catch{c=0}if(c>0){let u=`[VisIQ] Detected a ${Ut[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 ${Ut[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(Ac(e)){let o=process.env.VISIQ_GRANT_ID;return o?Ic(e,n,o):Tc(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 rc="https://api.visiqlabs.com",ic="\0",gi=new Map;function Kt(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 hi(e){try{if(typeof e!="object"||e===null)return;let t=e,n=ue(t.model);if(n)return n;let{settings:r}=t;if(typeof r=="object"&&r!==null){let a=ue(r.model);if(a)return a}let{llm:i}=t;if(typeof i=="object"&&i!==null){let a=yi(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=ue(s.model)??(typeof l=="object"&&l!==null?yi(l):void 0);if(c)return c}}return}catch{return}}function yi(e){return ue(e.model)??ue(e.modelId)??ue(e.model_name)}function ue(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 H(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Si(e){try{if(typeof e!="object"||e===null)return;let t=e,{settings:n}=t;if(typeof n=="object"&&n!==null){let s=H(n.instructions);if(s)return s}let r=H(t.instructions);if(r)return r;let i=H(t.systemPrompt);if(i)return i;let o=H(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=H(l.systemPrompt)??H(l.instructions)??H(l.system);if(c)return c}}return}catch{return}}async function oc(e){let t=Si(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=H(r);if(i)return i}}}catch{}}function ac(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=lc(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 lc(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 ne(e,t,n,r,i,o,a){let s=[e??"",t??"",n??"",r??"",o??""].join(ic),l=gi.get(s);return l||(l=new Dr(e,t,n,void 0,r,V,ut),l.registerHostEnvironment(i,a),gi.set(s,l)),o!==void 0&&l.setFailMode(o),l}function _i(e,t){try{let n=ne(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),r=$t(e);r.length>0&&n.reportToolSurface(r),Zr(e).then(i=>{let o=i.filter(a=>!r.some(s=>s.name===a.name));o.length>0&&n.reportToolSurface(o)}).catch(()=>{})}catch{}}function cc(e,t,n){try{let r=ne(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),i=Si(e);if(i){r.captureCloneMetadata({systemPrompt:i,...n?{agentType:n}:{}});return}oc(e).then(o=>{o&&r.captureCloneMetadata({systemPrompt:o,...n?{agentType:n}:{}})}).catch(()=>{})}catch{}}function uc(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 dc(e){let t=e?.agentId??process.env.VISIQ_AGENT_ID??fc(),n=e?.apiKey??process.env.VISIQ_API_KEY,r=e?.endpoint??process.env.VISIQ_ENDPOINT??(n?rc:void 0);return{agentId:t,apiKey:n,endpoint:r,hitlTimeoutMs:mc(e?.hitlTimeoutMs),timeoutMs:uc(e?.timeoutMs),onInstrumentFailure:e?.onInstrumentFailure??pc(),failMode:G(e?.failMode)}}function pc(){let e=process.env.VISIQ_ON_INSTRUMENT_FAILURE;if(e==="throw")return"throw";if(e==="warn")return"warn"}function fc(){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=lt.join(t,"package.json");if(st.existsSync(r)){let o=JSON.parse(st.readFileSync(r,"utf8"));if(typeof o.name=="string"&&o.name.trim()){let a=e(o.name);if(a)return a}break}let i=lt.dirname(t);if(i===t)break;t=i}}catch{}try{let t=e(ki.hostname());if(t)return t}catch{}return"agent"}function mc(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 Ot}function gc(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=Wt(t);if(n!==t&&n.nodes&&(n.lg_is_pregel===!0||n.channels))return"langchain-graph"}return"unknown"}function hc(e,t){let n=e,r=ne(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),i=yc(n);for(let l of i)Qt(l,t.agentId,r),vc(l,t.agentId,r,t),Ei(l,r,t);let{nodes:o}=Wt(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=Ht(),d=wi(t.agentId,r),p=c?.callbacks??[];return x.run(u,()=>s.call(this,l,{...c,callbacks:[...p,d]}))},typeof n.stream=="function"){let l=n.stream;n.stream=function(c,u){let d=Ht(),p=wi(t.agentId,r),f=u?.callbacks??[];return x.run(d,()=>l.call(this,c,{...u,callbacks:[...f,p]}))}}return e}function Wt(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 yc(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}=Wt(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 Ht(){return{session_id:tc(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Qt(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 bi(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 bi(s,t,String(a),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&Qt(r.retriever,t,n)}}var _c=Symbol.for("visiq.operations"),bc=new Set(["action","retrieval","delegation"]);function Ii(e){if(typeof e!="object"||e===null)return;let t=e[_c]??e.visiqOperations;if(!Array.isArray(t))return;let n=t.filter(r=>typeof r=="string"&&bc.has(r));return n.length>0?Array.from(new Set(n)):void 0}function vc(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(E=>E.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),d=l.some(E=>c.has(E)),p=u.has(l[0]??""),f=d||p,m=["update","delete","create","archive","insert","remove"],g=l.some(E=>m.some(v=>E.length>v.length&&E.endsWith(v))),I=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!f&&!g,b=Ii(i),A=b?.includes("retrieval")??!1;if(b!==void 0&&!A||!(s||I||A))return;let $e=b?A&&b.includes("action"):d||g;if(!$e)if(s)Qt(i.retriever,t,n);else{let E=globalThis,v=Symbol.for("visiq.recall.closureRetrieverWarned"),P=E[v]??=new Set;P.has(a)||(P.add(a),console.warn(`[VisIQ] Retriever tool "${a||"(unnamed)"}" exposes no reachable retriever (e.g. LangChain createRetrieverTool returns a joined string). RECALL masks its output via value-shape + whole-result rules, but PER-DOCUMENT metadata/classification rules cannot apply to a metadata-less joined string. For full per-doc governance, pass the retriever to visiq() directly, or use a tool that returns a Document[].`))}let W=i.func;$e?(i[Ti]=!0,i.func=async function(...E){await n.awaitBundleReady();let v=E[0],P=typeof v=="object"&&v!==null?v:{input:v},pe=typeof P.query=="string"?P.query:void 0,k=x.getStore(),S=K(k),N;try{N=await n.evaluate({operations:["retrieval","action"],agentId:t,...k?.session_id?{sessionId:k.session_id}:{},toolName:a||"unknown",toolArgs:P,resourceType:"document",resourceMetadata:{},...pe!==void 0?{query:pe}:{},...S?{telemetry:S}:{}})}catch(F){let fe=F instanceof Error?F.message:String(F);return G(r?.failMode)==="closed"?O({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${fe} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(w("eval-error",`policy evaluation failed for hybrid tool "${a||"unknown"}": ${fe}`),W.apply(this,E))}let R=J(N),ct=Ee(R.hitlFallback,R.argRedactionRules),Yt=E,Zt=()=>{try{return Yt=[M(P,D(R.argRedactionRules)),...E.slice(1)],null}catch{return G(r?.failMode)==="closed"?O({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(R.decision==="approval_required"&&R.decisionId&&r){let F=await Re({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:R.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:ct,sdkVersion:V});if(F.resolution==="mask"){let fe=Zt();if(fe)return fe}else if(F.resolution!=="proceed")return O({outcome:"approval_required",code:R.ruleCode??"HITL-BLOCK",reason:R.reason,mechanism:F.reason})}else if(!R.allowed)return O({outcome:"deny",code:R.ruleCode??"DENY",reason:R.reason});if(R.decision==="mask"&&R.argRedactionRules.length>0){let F=Zt();if(F)return F}let Ni=await W.apply(this,Yt);return Qr(Ni,N,r?.failMode)}):i.func=async function(...E){let v=await W.apply(this,E);return typeof v=="string"?Kr(v,t,n):rt(v,t,n)},i[o]=!0}var Ti=Symbol.for("visiq.hybrid.instrumented");async function bi(e,t,n,r){return Vr(e,t,n,r)}var vi=["invoke","call","_call"],te=new nc;function Ei(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[Ti]||Ii(r)?.every(c=>c==="retrieval")||!vi.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,p,f)=>{let m=te.getStore();if(m!==void 0&&m.gateKey===s&&!m.entered.has(f))return m.entered.add(f),c.call(u,d,...p);let g;if(typeof d=="string")g=d;else{let k=d?.input;g=k!=null?String(k):JSON.stringify(d)??""}let _=x.getStore(),I=K(_),b=typeof d=="object"&&d!==null?d:{input:g},A=Ze(a,b);A&&ye(t,{agentId:o,sessionId:_?.session_id,framework:"langchain"},A);let Le={agentId:o,sessionId:_?.session_id,framework:"langchain"},de=me(a,b);try{_e(t,Le,{toolName:a,...de?{memory:de}:{},argSummary:g.slice(0,512)})}catch(k){U("step-beat",`emit failed for tool "${a}": ${Gt(k)}`)}let $e=Date.now(),W=async k=>{let S=await k();try{be(t,Le,{toolName:a,ok:!0,durationMs:Date.now()-$e,...Y(S)!==void 0?{bytes:Y(S)}:{},...Z(S)!==void 0?{itemCount:Z(S)}:{},...de?{memory:de}:{}})}catch(N){U("observation-beat",`emit failed for tool "${a}": ${Gt(N)}`)}return S},E=(k,S,N,R)=>{try{ie(t,Le,{toolName:a,decision:k,...S?{ruleCode:S}:{},...N?{ruleLabel:N}:{},enforced:!0,...R?{harnessMessage:R}:{}})}catch(ct){U("intervention-beat",`emit failed for tool "${a}": ${Gt(ct)}`)}};await t.awaitBundleReady();let v,P=!1;try{let k=await t.evaluate({operations:A?["action","delegation"]:["action"],agentId:o,..._?.session_id?{sessionId:_.session_id}:{},toolName:a,toolArgs:b,targetResource:jt(g),...I?{telemetry:I}:{},...A?{context:Je(A,o)}:{}});({enforced:P}=k),v=J(k)}catch(k){let S=k instanceof Error?k.message:String(k);return n.failMode==="closed"?O({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${S} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(w("eval-error",`policy evaluation failed for tool "${a}": ${S}`),te.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,...p)))}let pe=k=>{let S=ae(a,k,{failMode:n.failMode==="closed"?"closed":"open",enforced:P});if(S.verdict==="block"){let R=O({outcome:"deny",code:"OUTPUT-BLOCK",reason:`outbound content carried a live secret (${S.detectors.join(",")})`});return E("deny","OUTPUT-BLOCK","outbound content carried a live secret",R),R}let N=k;return S.verdict==="redact"&&(N=S.redacted,w("outbound-secret-redacted",`outbound secret screen redacted ${S.detectors.length} detector(s): ${S.detectors.join(",")}`),E("mask","OUTPUT-BLOCK","outbound secret redacted before egress")),W(()=>te.run({gateKey:s,entered:new Set([f])},()=>c.call(u,N,...p)))};if(v.decision==="approval_required"&&v.decisionId){let k=Ee(v.hitlFallback,v.argRedactionRules),S=await Re({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:v.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:k,sdkVersion:V});if(S.resolution==="proceed")return W(()=>te.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,...p)));if(S.resolution==="mask")try{let R=M(d,D(v.argRedactionRules));return E("mask",v.ruleCode,v.reason),W(()=>te.run({gateKey:s,entered:new Set([f])},()=>c.call(u,R,...p)))}catch{return n.failMode==="closed"?O({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`),te.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,...p)))}let N=O({outcome:"approval_required",code:v.ruleCode??"HITL-BLOCK",reason:v.reason,mechanism:S.reason});return E("approval_required",v.ruleCode,v.reason,N),N}if(!v.allowed){let k=O({outcome:"deny",code:v.ruleCode??"DENY",reason:v.reason});return E("deny",v.ruleCode,v.reason,k),k}if(v.decision==="mask"&&v.argRedactionRules.length>0)try{let k=M(d,D(v.argRedactionRules));return E("mask",v.ruleCode,v.reason),pe(k)}catch{return n.failMode==="closed"?O({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`),te.run({gateKey:s,entered:new Set([f])},()=>c.call(u,d,...p)))}return pe(d)};for(let c of vi){if(typeof r[c]!="function")continue;let u=r[c];r[c]=function(d,...p){return l(u,this,d,p,c)}}r[i]=!0}function Gt(e){return e instanceof Error?e.message:String(e)}function wc(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 kc(e,t){let n=(f,m)=>{if(!f||typeof f!="object")return;let g=f[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"),p=s!==void 0?Math.max(0,s-(u??0)-(d??0)):void 0;return{...p!==void 0?{tokensIn:p}:{},...l!==void 0?{tokensOut:l}:{},...u!==void 0?{cacheRead:u}:{},...d!==void 0?{cacheWrite:d}:{}}}function wi(e,t){let n=(r,i,o,a)=>{let s=wc(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=x.getStore();if(u){try{if(Array.isArray(i))for(let d of i){let p=Array.isArray(d)?d:[d];for(let f of p){let m=f?.content;u.llm_prompts.push(typeof m=="string"?m:JSON.stringify(m??f))}}}catch{}n(r,s,c,u);try{let d=ac(i);d&&t.captureCloneMetadata({systemPrompt:d,agentType:"langchain"})}catch{}}},handleLLMStart:async(r,i,o,a,s,l,c)=>{let u=x.getStore();u&&(u.llm_prompts.push(...i),n(r,s,c,u))},handleLLMEnd:async r=>{let i=x.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=kc(l,c);if(!u&&!s)return;let d=c?.tool_calls,p=typeof l?.model=="string"?l.model:void 0,f=i.llm_model??p;await t.awaitBundleReady(),ft(t,{agentId:e,sessionId:i.session_id,framework:"langchain"},{...s?{texts:[s]}:{},...u?{usage:u}:{},...f?{model:f}:{},final:!(Array.isArray(d)&&d.length>0)})}catch{}},handleAgentAction:async r=>{let i=x.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=x.getStore();a&&a.retrieverQueries.set(o,i??"")},handleRetrieverEnd:async(r,i)=>{let o=x.getStore();if(!o)return;let a=o.retrieverQueries.get(i)??"";if(o.retrieverQueries.delete(i),!Array.isArray(r))return;let s=K(o);for(let l of r){let c=l,u=String(c.pageContent??c.text??c.content??""),d=nt(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=x.getStore();o&&o.retrieverQueries.delete(i)}}}var Ri=["_call","execute","call","run","invoke"];function Ac(e){let t=e;for(let n of Ri)if(typeof t[n]=="function")return!0;return!1}function Sc(e){return e instanceof ee?!0:e instanceof B?typeof e.status=="number"&&e.status>=400&&e.status<500:!1}function Ic(e,t,n){let r=null,i=null,o=!1,a=async()=>{if(r)return r;if(i)throw new ee(`Failed to bootstrap grant ${n}: ${i.message}`,null);let s;try{s=await Xr(t.agentId,n)}catch(l){throw o=Sc(l),o&&(i=l instanceof Error?l:new Error(String(l))),new ee(`Failed to bootstrap grant ${n}: ${l instanceof Error?l.message:String(l)}`,null)}return r=ei(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===Ce)return!0;let u=Reflect.get(s,l,c);return typeof u!="function"||typeof l!="string"||!Ri.includes(l)?u:async function(...d){let p;try{p=await a()}catch(m){if(o||t.failMode==="closed")throw m;return w("grant-bootstrap",`grant ${n} bootstrap failed: ${m instanceof Error?m.message:String(m)}`),u.call(this,...d)}return p[l].call(p,...d)}}})}function Tc(e,t){let n=ne(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode);Ei(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";Oe(e,i,Ci(t))}return e}function Ci(e){return{agentId:e.agentId,unified:ne(e.apiKey,e.endpoint,e.agentId,e.timeoutMs,void 0,e.failMode),hitlTimeoutMs:e.hitlTimeoutMs,failMode:e.failMode,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:Ht()}}async function xi(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 le({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 De=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),re(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return re(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return re(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return re(this.transport,"POST","/api/discovery/fleet/stop")}};var Fe=class{constructor(t){this.transport=t}transport;connectAws(t){return re(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function Ec(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 De(r),integrations:new Fe(r)}}async function re(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,o={...Q(V)};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 Oi=Ai;Oi.delegate=xi;var Id=Oi;export{Ye as DEFAULT_FAIL_MODE,De as FleetClient,Fe as IntegrationsClient,Ec as createVisiqClient,xi as delegate,Te as normalizeFailMode,Id as visiq};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@visiq/harness",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.19",
|
|
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",
|