@visiq/openclaw-plugin 0.1.7 → 0.1.8

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.
@@ -0,0 +1,9 @@
1
+ import{readFile as ln}from"node:fs/promises";import{homedir as se}from"node:os";import{join as le,isAbsolute as cn,resolve as un}from"node:path";import{createInterface as dn}from"node:readline";import{parseArgs as pn}from"node:util";var fn="https://api.visiqlabs.com",je="@visiq/openclaw-plugin",z="open";function ce(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}var gn={enabled:!0,thresholds:{}},G=[{key:"minEvents",env:"VISIQ_SEQUENCE_ANOMALY_MIN_EVENTS",cli:"sequence-anomaly-min-events",json:"min_events"},{key:"minClasses",env:"VISIQ_SEQUENCE_ANOMALY_MIN_CLASSES",cli:"sequence-anomaly-min-classes",json:"min_classes"},{key:"concentrationSigma",env:"VISIQ_SEQUENCE_ANOMALY_SIGMA",cli:"sequence-anomaly-sigma",json:"concentration_sigma"},{key:"dominanceRatio",env:"VISIQ_SEQUENCE_ANOMALY_DOMINANCE_RATIO",cli:"sequence-anomaly-dominance-ratio",json:"dominance_ratio"},{key:"dominanceShare",env:"VISIQ_SEQUENCE_ANOMALY_DOMINANCE_SHARE",cli:"sequence-anomaly-dominance-share",json:"dominance_share"},{key:"frictionRatio",env:"VISIQ_SEQUENCE_ANOMALY_FRICTION_RATIO",cli:"sequence-anomaly-friction-ratio",json:"friction_ratio"},{key:"minFrictionEvents",env:"VISIQ_SEQUENCE_ANOMALY_MIN_FRICTION_EVENTS",cli:"sequence-anomaly-min-friction-events",json:"min_friction_events"}],mn=["sequence-anomaly",...G.map(e=>e.cli)];function V(e){if(typeof e=="boolean")return e;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="0"||t==="off"||t==="false"||t==="no"||t==="disabled")return!1;if(t==="1"||t==="on"||t==="true"||t==="yes"||t==="enabled")return!0}function ue(e){if(typeof e=="number")return Number.isFinite(e)&&e>=0?e:void 0;if(typeof e!="string"||e.trim()==="")return;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function hn(...e){let t={};for(let n of e)for(let[r,i]of Object.entries(n??{}))typeof i=="number"&&(t[r]=i);return t}var _n='[VisIQ] OpenClaw plugin is installed but missing credentials. Provide them with one of (highest precedence first): (1) environment variables VISIQ_API_KEY=<key> VISIQ_AGENT_ID=<id> (set before `openclaw gateway run` / `openclaw start`) ; (2) a JSON file at the path in VISIQ_CONFIG_PATH ; (3) ~/.openclaw/openclaw.json -> plugins.entries["@visiq/openclaw-plugin"].config = { "apiKey": "<key>", "agentId": "<id>" } . Until credentials are provided the plugin is a NO-OP \u2014 tool calls run UNGOVERNED (fail-open default; set VISIQ_FAIL_MODE=closed to block instead).';function yn(e){return e==="~"||e.startsWith("~/")?le(se(),e.slice(1).replace(/^\//,"")):e}async function qe(e){try{let t=cn(e)?e:un(e),n=await ln(t,"utf-8");return JSON.parse(n)}catch{return null}}function U(e,...t){for(let n of t){let r=e[n];if(typeof r=="string")return r}}function oe(e){if(!e||typeof e!="object")return{};let t=e,n=U(t,"apiKey","api_key"),r=U(t,"agentId","agent_id"),i=U(t,"baseUrl","base_url"),a=ce(U(t,"failMode","fail_mode")),o={};n&&(o.apiKey=n),r&&(o.agentId=r),i&&(o.baseUrl=i),a&&(o.failMode=a);let l=t.sequenceAnomaly??t.sequence_anomaly;if(l!=null){let c=V(l);if(c!==void 0)o.sequenceAnomalyEnabled=c;else if(typeof l=="object"&&!Array.isArray(l)){let s=l,d=V(s.enabled);d!==void 0&&(o.sequenceAnomalyEnabled=d);let f={};for(let _ of G){let y=ue(s[_.key]??s[_.json]);y!==void 0&&(f[_.key]=y)}Object.keys(f).length>0&&(o.sequenceAnomalyThresholds=f)}}return o}async function bn(e){if(!e)return{};let t=yn(e),n=await qe(t);if(!n||typeof n!="object")return{};let r=n,i=r.plugins?.entries,a=i&&typeof i=="object"?i[je]:void 0;return a&&typeof a=="object"&&a.config?oe(a.config):oe(r)}async function Be(e){if(!e)return{};let t=await qe(e);if(!t||typeof t!="object")return{};let a=t.plugins?.entries?.[je];return!a||typeof a!="object"?{}:oe(a.config)}function vn(){return Be(le(se(),".openclaw","openclaw.json"))}function wn(){let e=process.env.OPENCLAW_CONFIG_PATH;return!e||e===le(se(),".openclaw","openclaw.json")?Promise.resolve({}):Be(e)}async function An(e){if(!process.stdout.isTTY)return{};let t=dn({input:process.stdin,output:process.stdout}),n=r=>new Promise(i=>t.question(r,a=>i(a)));try{let r={...e};if(!r.apiKey){let i=(await n("VisIQ API key: ")).trim();i&&(r.apiKey=i)}if(!r.agentId){let i=(await n("VisIQ agent ID: ")).trim();i&&(r.agentId=i)}if(!r.baseUrl){let i=(await n("VisIQ base URL (optional, press Enter for default): ")).trim();i&&(r.baseUrl=i)}return r}finally{t.close()}}function In(){try{let e={"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"},"fail-mode":{type:"string"}};for(let s of mn)e[s]={type:"string"};let{values:t}=pn({args:process.argv.slice(2),options:e,strict:!1,allowPositionals:!0}),n={},r=t["api-key"],i=t["agent-id"],a=t["base-url"],o=ce(t["fail-mode"]);typeof r=="string"&&r&&(n.apiKey=r),typeof i=="string"&&i&&(n.agentId=i),typeof a=="string"&&a&&(n.baseUrl=a),o&&(n.failMode=o);let l=V(t["sequence-anomaly"]);l!==void 0&&(n.sequenceAnomalyEnabled=l);let c={};for(let s of G){let d=ue(t[s.cli]);d!==void 0&&(c[s.key]=d)}return Object.keys(c).length>0&&(n.sequenceAnomalyThresholds=c),n}catch{return{}}}async function Pi(){return(await de()).config}async function de(){let e=In(),t={};process.env.VISIQ_API_KEY&&(t.apiKey=process.env.VISIQ_API_KEY),process.env.VISIQ_AGENT_ID&&(t.agentId=process.env.VISIQ_AGENT_ID),process.env.VISIQ_BASE_URL?t.baseUrl=process.env.VISIQ_BASE_URL:process.env.VISIQ_ENDPOINT&&(t.baseUrl=process.env.VISIQ_ENDPOINT);let n=ce(process.env.VISIQ_FAIL_MODE);n&&(t.failMode=n);let r=V(process.env.VISIQ_SEQUENCE_ANOMALY);r!==void 0&&(t.sequenceAnomalyEnabled=r);let i={};for(let f of G){let _=ue(process.env[f.env]);_!==void 0&&(i[f.key]=_)}Object.keys(i).length>0&&(t.sequenceAnomalyThresholds=i);let a=await bn(process.env.VISIQ_CONFIG_PATH),o=await vn(),l=await wn(),c={...o,...l,...a,...t,...e,sequenceAnomalyThresholds:hn(o.sequenceAnomalyThresholds,l.sequenceAnomalyThresholds,a.sequenceAnomalyThresholds,t.sequenceAnomalyThresholds,e.sequenceAnomalyThresholds)};(!c.apiKey||!c.agentId)&&process.stdout.isTTY&&process.stdin.isTTY&&(c=await An(c));let s=c.failMode??z;if(!c.apiKey||!c.agentId)return process.stderr.write(`${_n}
2
+ `),{config:null,failMode:s};let d={apiKey:c.apiKey,agentId:c.agentId,failMode:s,sequenceAnomaly:{enabled:c.sequenceAnomalyEnabled??gn.enabled,thresholds:c.sequenceAnomalyThresholds??{}}};return d.baseUrl=c.baseUrl||fn,{config:d,failMode:s}}var pe=null,Ue={ready:!1,config:null,failMode:z};function fe(){return pe||(pe=de().catch(e=>(process.stderr.write(`[VisIQ] Config resolution failed (treating as unconfigured): ${e instanceof Error?e.message:String(e)}
3
+ `),{config:null,failMode:z})).then(e=>(Ue={ready:!0,config:e.config,failMode:e.failMode},e))),pe}function K(){return fe().then(e=>e.config)}function Ve(){return fe()}function W(){return Ue}function ji(){fe()}import{z as u}from"zod";import*as E from"node:os";import{randomUUID as L}from"node:crypto";var Ge="X-VisIQ-SDK",Ke="X-VisIQ-Dialect",We="unknown";function ge(e,t=1){return{[Ge]:e&&e.length>0?e:We,[Ke]:String(t)}}var He="interceptor_source",kn=u.enum(["enforce","audit","off"]),Sn=u.enum(["closed","open"]),Qe=u.enum(["enforce","monitor","off"]),En=u.object({apiKey:u.string().min(1,"apiKey is required"),agentId:u.string().min(1,"agentId is required"),endpoint:u.string().url().optional(),mode:kn.optional(),timeoutMs:u.number().int().positive().optional(),hitlTimeoutMs:u.number().int().positive().optional(),failBehavior:Sn.optional()}),Ui=u.object({agent_id:u.string().min(1),target_app:u.string().min(1),action:u.string().min(1),context:u.record(u.unknown()).optional(),session_id:u.string().min(1).max(255).optional(),telemetry:u.record(u.unknown()).optional()}),Cn=u.object({field:u.string().optional(),pattern:u.string().optional(),replacement:u.string().optional(),mode:u.enum(["full","partial","email"]).optional(),keepFirst:u.number().optional(),keepLast:u.number().optional(),maskChar:u.string().optional()}),Tn=u.object({decision_id:u.string().min(1),decision:u.enum(["permit","deny","approval_required","mask"]),reason:u.string().optional(),rule_code:u.string().nullable().optional(),enforced:u.boolean().optional(),agent_mode:Qe.optional(),arg_redaction_rules:u.array(Cn).optional(),plane:u.string().nullable().optional(),operation:u.string().nullable().optional(),is_retrieval:u.boolean().optional(),metadata:u.record(u.unknown()).optional()}),Nn=u.object({field:u.string().min(1),operator:u.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:u.union([u.string(),u.number(),u.array(u.string())])}),Rn=u.object({id:u.string().min(1),rule_code:u.string().default(""),name:u.string().min(1),description:u.string().nullable().default(null),effect:u.enum(["allow","deny","hitl","mask"]),resource_type:u.string().min(1),rego_source:u.string().default(""),target_app:u.string().nullable().default(null),action_pattern:u.string().nullable().default(null),conditions:u.array(Nn).default([]),priority:u.number().int().default(0)}),xn=u.object({version:u.string().min(1),agent_mode:Qe.optional(),rules:u.array(Rn),no_coverage:u.object({no_coverage_defaults:u.record(u.string()),autopilot_enabled:u.boolean(),enduser_hitl_enabled:u.boolean(),hitl_timeout_seconds:u.number()}).optional()}),On=2e3,me=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return ge(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 Tn.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json",...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();return xn.parse(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}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let o=a,l=o.hitl_result;if(l==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(l==="rejected")return{decision_id:e,decision:"deny",reason:typeof o.reason=="string"?o.reason:"Rejected by human reviewer"};if(l==="timeout"||l==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await $n(On)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function $n(e){return new Promise(t=>setTimeout(t,e))}function he(){let e={};try{let t=`${E.platform()} ${E.release()}`.trim();t&&(e.os=t)}catch{}try{let t=E.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=E.userInfo();t&&(e.username=t)}catch{}try{let t=Ln();t&&(e.ip=t)}catch{}return e}function Ln(){let e=E.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 Mn(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function H(e,...t){for(let n of t){let r=Mn(e[n]);if(r)return r}}function Q(e){if(H(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(H(e,"user_id","userId"))return"user";if(H(e,"agent_id","agentId"))return"agent";if(H(e,"org_id","orgId","namespace"))return"org"}var Pn=[{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=Q(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=Q(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=Q(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=Q(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function $(e,t){if(!e)return null;let n=t??{};for(let r of Pn)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function _e(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 ze=new Map;function M(e){let t=(ze.get(e)??0)+1;return ze.set(e,t),t}function Ye(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 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,i=Array.isArray(n.texts)?n.texts.filter(o=>typeof o=="string"&&o.length>0).join(`
4
+
5
+ `):"",a=Ye(n.usage);e.emitCognition({clientEventId:L(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:M(r),ts:Date.now(),kind:n.final?"speech":"thought",visibility:"shown",provenance:"narration",...i?{content:{text:i}}:{},...a?{cost:a}:{},...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 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;e.emitCognition({clientEventId:L(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:M(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 ve(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?_e(n.memory):void 0;e.emitCognition({clientEventId:L(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:M(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 we(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=s=>typeof s=="number"&&Number.isFinite(s)&&s>=0?Math.round(s):void 0,a=i(n.bytes),o=i(n.itemCount),l=i(n.durationMs),c;n.memory&&(c=_e(n.memory,{itemCount:o,bytes:a})),e.emitCognition({clientEventId:L(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:M(r),ts:Date.now(),kind:"observation",visibility:"shown",provenance:"parsed",...l!==void 0?{durationMs:l}:{},...t.framework?{framework:t.framework}:{},tool:{name:n.toolName},result:{ok:n.ok,...a!==void 0?{bytes:a}:{},...o!==void 0?{itemCount:o}:{}},...c?{memory:c}:{}})}function Ae(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId:L(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:M(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 p}from"zod";import{createHash as Wi}from"crypto";import{createHash as Zi}from"crypto";var Dn=["tier1","tier2","tier3"];function et(e){return typeof e=="string"&&Dn.includes(e)}var Fn=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],jn=["internal","customer_facing","experimental","third_party"],tt=[...Fn,...jn];function qn(e){return typeof e=="string"&&tt.includes(e)}function nt(e){let t=new Set;for(let n of e)qn(n)&&t.add(n);return tt.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"];function rt(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 Un={wire_transfer:"funds_transfer",international_transfer:"funds_transfer",cross_border_payment:"funds_transfer",send_swift:"funds_transfer",send_wire:"funds_transfer",transfer_funds:"funds_transfer",update_wire_instructions:"funds_transfer",add_beneficiary:"funds_transfer",modify_payee:"funds_transfer",disburse_funds:"funds_disbursement",initiate_ach:"funds_disbursement",issue_refund:"funds_disbursement",execute_trade:"trade_execution",place_order:"trade_execution",post_journal_entry:"ledger_mutation",adjust_ledger:"ledger_mutation",modify_general_ledger:"ledger_mutation",raise_limit:"credit_decision",increase_credit_limit:"credit_decision",extend_credit:"credit_decision",decline_credit:"decision_adverse",deny_application:"decision_adverse",adverse_action:"decision_adverse",block_card:"card_management",cancel_card:"card_management",place_hold:"account_restriction",freeze_account:"account_restriction",restrict_account:"account_restriction",close_account:"account_closure",export_data:"data_export",export_customer_list:"data_export",download_report:"data_export",download_customer_list:"data_export",bulk_export:"data_export",share_data:"data_share",send_to_partner:"data_share",delete_records:"record_delete",delete_user:"record_delete",drop_table:"record_delete",grant_role:"access_grant",change_permissions:"permission_change",modify_access:"permission_change",rotate_keys:"credential_management",disable_mfa:"auth_policy_change",modify_security_config:"security_config_change",disable_logging:"logging_change",purge_logs:"logging_change",suppress_alert:"alert_management",dismiss_alert:"alert_management",rollback:"deployment_change",modify_billing:"record_update",close_sar:"record_update",send_email:"communication_send",send_sms:"communication_send",fulfill_dsar:"data_subject_request",process_dsar:"data_subject_request",fulfill_data_request:"data_subject_request",process_erasure_request:"data_subject_request",honor_deletion_request:"data_subject_request",export_subject_data:"data_subject_request",erase_subject_data:"data_subject_request",delete_subject_data:"data_subject_request",record_consent:"consent_change",capture_consent:"consent_change",update_consent:"consent_change",withdraw_consent:"consent_change",revoke_consent:"consent_change",opt_out:"consent_change",opt_in:"consent_change",run_payroll:"payroll_run",process_payroll:"payroll_run",submit_payroll:"payroll_run",approve_payroll:"payroll_run",create_purchase_order:"purchase_commitment",issue_purchase_order:"purchase_commitment",approve_purchase_order:"purchase_commitment",submit_purchase_order:"purchase_commitment",approve_purchase:"purchase_commitment",approve_requisition:"purchase_commitment",commit_spend:"purchase_commitment",onboard_vendor:"vendor_management",add_vendor:"vendor_management",create_supplier:"vendor_management",approve_vendor:"vendor_management",update_vendor_bank:"vendor_management",update_supplier_bank:"vendor_management",modify_supplier:"vendor_management",create_opportunity:"deal_management",update_opportunity:"deal_management",advance_deal_stage:"deal_management",update_deal_stage:"deal_management",close_deal:"deal_management",mark_closed_won:"deal_management",mark_closed_lost:"deal_management",issue_quote:"pricing_change",send_quote:"pricing_change",approve_discount:"pricing_change",apply_discount:"pricing_change",override_price:"pricing_change",update_pricing:"pricing_change",approve_special_pricing:"pricing_change",execute_contract:"contract_execution",sign_contract:"contract_execution",countersign_contract:"contract_execution",sign_agreement:"contract_execution",execute_agreement:"contract_execution",sign_nda:"contract_execution",execute_nda:"contract_execution",sign_document:"contract_execution",esign_document:"contract_execution",place_legal_hold:"legal_hold",place_litigation_hold:"legal_hold",apply_legal_hold:"legal_hold",release_legal_hold:"legal_hold",file_regulatory_report:"regulatory_filing",file_sar:"regulatory_filing",submit_regulatory_filing:"regulatory_filing",file_compliance_report:"regulatory_filing",file_disclosure:"regulatory_filing",onboard_employee:"personnel_action",hire_employee:"personnel_action",change_employee_role:"personnel_action",promote_employee:"personnel_action",transfer_employee:"personnel_action",update_job_title:"personnel_action",terminate_employee:"employment_termination",offboard_employee:"employment_termination",deactivate_employee:"employment_termination",separate_employee:"employment_termination",adjust_salary:"compensation_change",change_compensation:"compensation_change",approve_raise:"compensation_change",grant_equity:"compensation_change",grant_stock:"compensation_change",issue_bonus:"compensation_change",update_pay_rate:"compensation_change",send_campaign:"campaign_send",launch_campaign:"campaign_send",schedule_campaign:"campaign_send",send_bulk_email:"campaign_send",send_marketing_email:"campaign_send",send_newsletter:"campaign_send",blast_email:"campaign_send",publish_post:"content_publish",publish_content:"content_publish",publish_blog:"content_publish",post_to_social:"content_publish",schedule_post:"content_publish",adjust_inventory:"inventory_adjustment",write_off_inventory:"inventory_adjustment",update_stock_level:"inventory_adjustment",reconcile_inventory:"inventory_adjustment",fulfill_order:"order_fulfillment",ship_order:"order_fulfillment",dispatch_order:"order_fulfillment",mark_order_shipped:"order_fulfillment",update_customer_account:"account_servicing",modify_customer_account:"account_servicing",update_customer_contact:"account_servicing",change_customer_settings:"account_servicing",reset_customer_password:"credential_reset",reset_password:"credential_reset",force_password_reset:"credential_reset",reset_mfa:"credential_reset",unlock_account:"credential_reset",reset_customer_credentials:"credential_reset",merge_pull_request:"code_change",merge_pr:"code_change",merge_branch:"code_change",push_to_branch:"code_change",push_to_main:"code_change",push_code:"code_change",commit_code:"code_change",force_push:"code_change",provision_infrastructure:"infrastructure_provision",provision_resource:"infrastructure_provision",create_instance:"infrastructure_provision",terminate_instance:"infrastructure_provision",spin_up_server:"infrastructure_provision",tear_down_server:"infrastructure_provision",destroy_resource:"infrastructure_provision",create_cluster:"infrastructure_provision"};function Vn(e){let t=rt(e);return t===null?"other":Un[t]||(/^(delete|remove|purge|drop|destroy|wipe)_/.test(t)?"record_delete":/^(export|download|extract|dump)_/.test(t)?"data_export":/^(create|add|insert)_/.test(t)?"record_create":/^(update|edit|modify|patch|set)_/.test(t)?"record_update":t==="send_email"||t==="send_sms"||/^(notify|email|sms)_/.test(t)?"communication_send":/^(read|get|list|search|fetch|view|query)_/.test(t)||t==="read"||t==="get"?"read_only":"other")}var Ze={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 zn(e){let t=rt(e);return t===null?"other":Ze[t]??Ze[t.replace(/_/g,"")]??"other"}function ke(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=Vn(t.action)),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=zn(t.targetApp)),n.context=r}return n}var Je=64,Gn=64,D={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function it(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var Kn=new Set(["deny","approval_required","escalate"]);function P(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>Je?r.slice(0,Je):r}function Xe(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function J(e){return typeof e=="string"&&e.length>0?e:null}function at(e,t){let n=Xe(t.data_categories),r=J(t.classification),i=Xe(t.taint),a=J(t.action_class),o=a&&Bn.includes(a)?a:null,l=J(t.target_app),c=J(t.decision),s={...e.action_counts};if(o)if(o in s)s[o]=(s[o]??0)+1;else if(Object.keys(s).length<Gn)s[o]=1;else{let d=Object.keys(s).sort(),f=d[d.length-1];f!==void 0&&o<f&&(delete s[f],s[o]=1)}return{retrieved_data_categories:P(e.retrieved_data_categories,n),retrieved_classifications:P(e.retrieved_classifications,r?[r]:[]),taint:P(e.taint,i),action_classes:P(e.action_classes,o?[o]:[]),action_counts:s,denied_count:e.denied_count+(c==="deny"?1:0),inhibited_count:e.inhibited_count+(c&&Kn.has(c)?1:0),event_count:e.event_count+1,target_apps:P(e.target_apps,l?[l]:[])}}var ot={minEvents:12,minClasses:3,concentrationSigma:2,dominanceRatio:4,dominanceShare:.5,frictionRatio:.75,minFrictionEvents:6};function Wn(e){let t=null,n=0;for(let r of Object.keys(e).sort()){let i=Math.max(0,e[r]??0);i>n&&(n=i,t=r)}return{label:t,count:n}}function Ie(e){let t=e.length;if(t===0)return 0;let n=t>>1;return t%2===1?e[n]:(e[n-1]+e[n])/2}function X(e){return Number.isFinite(e)?Math.round(e*1e3)/1e3:0}var Hn=.5;function Qn(e){let t=e.length;if(t===0)return 0;let n=[...e].sort((l,c)=>l-c),r=Ie(n),i=n[t-1],a=n.map(l=>Math.abs(l-r)).sort((l,c)=>l-c),o=Ie(a);return o>0?.6745*(i-r)/o:i===r?0:.6745*(i-r)/Hn}function Se(e,t){let n={...ot,...t.config},r=e.action_counts??{},i=Math.max(0,e.event_count??0),a=Math.max(0,e.denied_count??0),o=Math.max(0,e.inhibited_count??0),l=Wn(r),c={};for(let m of Object.keys(r).sort()){let g=Math.max(0,r[m]??0);g>0&&(c[m]=g)}let s=Object.values(c),d=s.reduce((m,g)=>m+g,0),f=[...s].sort((m,g)=>m-g),_=Ie(f),y=Qn(s),S=_>0?l.count/_:0,A=d>0?l.count/d:0,h=i>0?(a+o)/i:0,v={action_class:null,repeats:l.count,event_count:i,denied_count:a,inhibited_count:o,class_count:s.length,class_counts:c,concentration_score:X(y),dominance_ratio:X(S),dominance_share:X(A),friction_score:X(h),signals:[]};if(i<n.minEvents)return{verdict:"allow",signals:[],evidence:v};let w=[],I=null;return s.length>=n.minClasses&&y>=n.concentrationSigma&&S>=n.dominanceRatio&&A>=n.dominanceShare&&(w.push("concentration"),I=l.label),h>=n.frictionRatio&&a+o>=n.minFrictionEvents&&w.push("friction"),w.length===0?{verdict:"allow",signals:[],evidence:v}:{verdict:t.failMode==="closed"?"deny":"hold",signals:[...w],evidence:{...v,action_class:I,signals:[...w]}}}var st="generic",lt=[{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:st,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."}],Yn=lt.map(e=>e.id),Hi=new Map(lt.map(e=>[e.id,e])),Qi=new Set(Yn);function ct(e){return Array.isArray(e)&&e.length>0?[...e]:[st]}var Zn=/^[a-z][a-z0-9_]*$/;function ut(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Zn.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Jn=["narrow","moderate","broad","unbounded","unknown"];function dt(e){return typeof e=="string"&&Jn.includes(e)}function pt(e){return e==="open"||e==="closed"?e:null}var Xn=["action","retrieval","delegation"];function er(e){return typeof e=="string"&&Xn.includes(e)}var tr=new Set(["rules"]);function ft(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!tr.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(er):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{z as ae}from"zod";var nr="[REDACTED]",At=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];function It(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 rr(e){let t=e.replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let i=0;i<n.length;i++){let a=n[i],o=a>="A"&&a<="Z"?String(a.charCodeAt(0)-55):a;for(let l=0;l<o.length;l++)r=(r*10+(o.charCodeAt(l)-48))%97}return r===1}function ir(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 ar=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&It(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:rr},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:ir}],b=Object.fromEntries(At.map(e=>[e.name,e.re.source])),kt=["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","email","us_phone","ipv4","mac_address"],te={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
6
+ MIIEv\u2026
7
+ -----END PRIVATE KEY-----`,template:{pattern:b.private_key,mode:"full"},defaultEnabled:!0},jwt:{id:"jwt",label:"JWT / bearer tokens",description:"JSON Web Tokens (base64url header.payload.signature).",category:"secret",example:"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.dBjftJeZ4CVP",template:{pattern:b.jwt,mode:"full"},defaultEnabled:!0},aws_access_key:{id:"aws_access_key",label:"AWS access key IDs",description:"AWS access / identity key ids (AKIA / ASIA / AROA \u2026).",category:"secret",example:"AKIAIOSFODNN7EXAMPLE",template:{pattern:b.aws_access_key,mode:"full"},defaultEnabled:!0},github_token:{id:"github_token",label:"GitHub tokens",description:"GitHub personal / OAuth tokens (classic ghp_\u2026 + fine-grained).",category:"secret",example:"ghp_0123456789abcdef0123456789abcdef0123",template:{pattern:b.github_token,mode:"full"},defaultEnabled:!0},slack_token:{id:"slack_token",label:"Slack tokens",description:"Slack bot / user / app tokens (xoxb- / xoxp- \u2026).",category:"secret",example:"xoxb-1234567890-abcdefghijkl",template:{pattern:b.slack_token,mode:"full"},defaultEnabled:!0},stripe_secret:{id:"stripe_secret",label:"Stripe secret keys",description:"Stripe live secret / restricted keys (sk_live_ / rk_live_).",category:"secret",example:"sk_live_0123456789abcdefABCDEF",template:{pattern:b.stripe_secret,mode:"full"},defaultEnabled:!0},google_api_key:{id:"google_api_key",label:"Google API keys",description:"Google API keys (AIza\u2026).",category:"secret",example:"AIzaSyA1234567890abcdefghijklmnopqrstuv",template:{pattern:b.google_api_key,mode:"full"},defaultEnabled:!0},llm_api_key:{id:"llm_api_key",label:"LLM provider API keys",description:"OpenAI / Anthropic secret keys (sk-\u2026, sk-proj-\u2026, sk-ant-\u2026).",category:"secret",example:"sk-ant-api03-AbCdEf0123456789AbCdEf01",template:{pattern:b.llm_api_key,mode:"full"},defaultEnabled:!0},bearer_token:{id:"bearer_token",label:"Authorization bearer tokens",description:"Credentials following an HTTP `Authorization: Bearer \u2026` header.",category:"secret",example:"Bearer abcdef0123456789abcdef0123456789",template:{pattern:b.bearer_token,mode:"full"},defaultEnabled:!0},connection_string:{id:"connection_string",label:"Connection strings (with password)",description:"Database / broker DSNs carrying an inline password (scheme://user:pass@host).",category:"secret",example:"postgres://app:s3cr3t@db.internal:5432/main",template:{pattern:b.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS).",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\b\\d{13,19}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){10,30}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:"\\b\\d{9}\\b",mode:"full"},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX).",category:"financial",example:"12-3456789",template:{pattern:b.us_ein,mode:"full"},defaultEnabled:!0},swift_bic:{id:"swift_bic",label:"SWIFT / BIC codes",description:"Bank SWIFT/BIC codes (8 or 11 chars). DEFAULT-OFF (matches uppercase tokens).",category:"financial",example:"DEUTDEFF500",template:{pattern:b.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789).",category:"pii",example:"123-45-6789",template:{pattern:b.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept).",category:"pii",example:"alice@acme.com",template:{pattern:b.email,mode:"email"},defaultEnabled:!0},us_phone:{id:"us_phone",label:"US phone numbers",description:"US phone numbers in common formats. DEFAULT-OFF (10-digit false-positive surface).",category:"pii",example:"(415) 555-0132",template:{pattern:b.us_phone,mode:"partial",keepLast:4},defaultEnabled:!1},ipv4:{id:"ipv4",label:"IPv4 addresses",description:"Dotted-quad IPv4 addresses. DEFAULT-OFF (common + usually benign).",category:"identifier",example:"203.0.113.42",template:{pattern:b.ipv4,mode:"full"},defaultEnabled:!1},mac_address:{id:"mac_address",label:"MAC addresses",description:"Hardware MAC addresses. DEFAULT-OFF.",category:"identifier",example:"3c:22:fb:1a:2b:3c",template:{pattern:b.mac_address,mode:"full"},defaultEnabled:!1}},Xi=new Set(kt.filter(e=>!te[e].defaultEnabled));function or(e,t){let n=new Set;for(let r of kt)(te[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function sr(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=e;for(let{name:a,re:o}of At){let l=a;n.has(l)||(i=i.replace(o,()=>(r?.(l),t)))}for(let{name:a,re:o,normalize:l,validate:c}of ar)n.has(a)||(i=i.replace(o,s=>c(l(s))?(r?.(a),t):s));return i}function St(e,t=nr,n,r){let i=new Set,a=or(n,r),o=!a.has("pan"),l=s=>{i.add(s)},c=s=>{if(typeof s=="string")return sr(s,t,a,l);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!o)return s;let d=String(s);return d.length>=13&&d.length<=19&&It(d)?(i.add("pan"),t):s}if(Array.isArray(s))return s.map(d=>c(d));if(s!==null&&typeof s=="object"){let d=s,f={};for(let _ of Object.keys(d))f[_]=c(d[_]);return f}return s};return{value:c(e),detectors:[...i].sort()}}function lr(e){let{value:t,detectors:n}=St(e),r=n.some(i=>te[i].category==="secret");return{detectors:n,blocked:r,redacted:t}}function ne(e,t){let{blocked:n,redacted:r,detectors:i}=lr(e);return n?t.failMode==="closed"?{verdict:"block",redacted:r,detectors:i}:{verdict:"redact",redacted:r,detectors:i}:{verdict:"allow",redacted:r,detectors:i}}var cr=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Et=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"}),ur=new RegExp(`[${Object.keys(Et).join("")}]`,"gu"),dr=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),Ct="\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",pr=Object.freeze(Object.fromEntries([...Ct].map((e,t)=>[e,String.fromCharCode(97+t)]))),fr=new RegExp(`[${Ct}\u2800]`,"g"),Tt=/[⠀-⣿]/;function gr(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 mr(e){return e.replace(cr,"")}function Nt(e){return e.replace(ur,t=>Et[t]??t)}function hr(e){return e.replace(/[4@31!05$79(8]/g,t=>dr[t]??t)}function _r(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 yr(e){return Tt.test(e)?e.replace(fr,t=>t==="\u2800"?" ":pr[t]??t):e}function gt(e){let t;try{t=gr(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=mr(t),t=Nt(t),t}var br=/^[A-Za-z0-9+/]{16,}={0,2}$/,vr=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,mt=/[A-Za-z0-9+/]{20,}={0,2}/g;function Te(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 Rt=new TextDecoder("utf-8",{fatal:!1});function xt(e){let t;try{t=atob(e)}catch{return[]}let n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i)&255;let r=Rt.decode(n);return t===r?[t]:[r,t]}function wr(e){let t=e.replace(/\s+/g,"");if(t.length===0||t.length%2!==0)return[];let n=new Uint8Array(t.length/2);for(let a=0;a<n.length;a++){let o=Number.parseInt(t.slice(a*2,a*2+2),16);if(Number.isNaN(o))return[];n[a]=o}let r="";for(let a=0;a<n.length;a++)r+=String.fromCharCode(n[a]);let i=Rt.decode(n);return r===i?[r]:[i,r]}function ht(e){let t=e.trim(),n=[];if(vr.test(t))for(let r of wr(t))n.push({decoded:r,textiness:Te(r)});if(br.test(t)&&t.length%4===0)for(let r of xt(t))n.push({decoded:r,textiness:Te(r)});return n}function _t(e,t){let n=[],r;for(mt.lastIndex=0;(r=mt.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of xt(i))n.push({decoded:a,textiness:Te(a)})}return n}var Ar=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function Ot(e,t=Ar){if(typeof e!="string"||e.length===0)return{views:[],anyDecoded:!1,truncated:!1,nodes:0,maxDepthSeen:0};let{maxDepth:n,byteCap:r,maxNodes:i,maxBlobsPerNode:a}=t,o=new Set,l=y=>{y.length>0&&y.length<=r&&o.add(y)},c=!1,s=!1,d=0,f=0,_=[{s:e,depth:0}];for(;_.length>0;){if(d>=i){s=!0;break}let y=_.pop();if(y===void 0)break;let{s:S,depth:A}=y;if(S.length>r){s=!0;continue}d++,A>f&&(f=A);let h=gt(S);l(h);let v=hr(h);if(v!==h&&l(v),l(_r(h)),Tt.test(S)&&l(yr(h)),A>=n){let I=gt(S);(ht(I).length>0||_t(I,a).length>0)&&(s=!0);continue}let w=[...ht(h),..._t(h,a)];for(let I of w){if(c=!0,I.decoded.length>r){s=!0;continue}I.textiness>=.85&&I.decoded!==h?_.push({s:I.decoded,depth:A+1}):l(I.decoded)}}return{views:[...o],anyDecoded:c,truncated:s,nodes:d,maxDepthSeen:f}}var $t=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],Ir=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),kr=8,Sr=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),yt=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function Er(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||Sr.has(i)&&yt(t[r-1])&&yt(t[r+1])&&(n++,n>=kr))return!0}return!1}var Cr=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function Tr(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(Cr.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Nr=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Rr(e){for(let t of Nr)if(e>=t.lo&&e<=t.hi)return t.name;return null}function xr(e){for(let t of e.split(/\s+/)){if(t.length<4)continue;let n=0,r=0,i=!0;for(let a of t){let o=Rr(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:Nt(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var bt=Object.freeze({signals:[],contributes:!1});function Or(e){if(typeof e!="string"||e.length===0)return{...bt,signals:[]};let t=new Set;try{Er(e)&&t.add("hidden_text_carrier"),Tr(e)&&t.add("injected_turn_boundary"),xr(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=Ot(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...bt,signals:[]}}return{signals:[...$t.filter(n=>t.has(n))],contributes:Ir.some(n=>t.has(n))}}var re=[{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 vt(e){return typeof e!="string"||e.length===0?[]:re.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function $r(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(vt(e)),{views:n}=Ot(e);for(let r of n)for(let i of vt(r))t.add(i);return re.filter(r=>t.has(r.name)).map(r=>r.name)}function Lr(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let l of $r(a))t.add(l);let o=Or(a);for(let l of o.signals)n.add(l);o.contributes&&(r=!0);return}if(Array.isArray(a)){for(let o of a)i(o);return}if(typeof a=="object")for(let o of Object.values(a))i(o)}};return i(e),{matched:t.size>0||r,signatures:re.filter(a=>t.has(a.name)).map(a=>a.name),structural:$t.filter(a=>n.has(a))}}function Mr(e){return Lr(e).matched}var ea=re.map(e=>e.name);var Pr=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Dr="i:injection";function Lt(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=St(e.content);for(let a of i){let o=te[a]?.category;o&&t.add(`c:${o}`)}Mr(e.content)&&t.add(Dr)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Pr.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var Ee="(?: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))",ta=[{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${Ee}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${Ee}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${Ee}\\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}],wt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Fr=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${wt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${wt}|programming|training))`,jr="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",Ce="(?:\\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|\\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)",qr="(?:ignore|disregard|forget|override|overrule|bypass|act|behave|respond|reply|answer|pretend|roleplay|role-play|assume|impersonate|only|always|never|no\\s+longer|instead|obey|comply\\s+with|follow\\s+(?:only|my|these))",na=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${jr}${Fr}\\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}?${Ce}`,"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)\\s+(?:${qr}|(?:a|an|the)\\b[\\s\\S]{0,40}?${Ce}|${Ce})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var ra=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var N=e=>`[^.!?;\\n]{0,${e}}?`,Br=["\\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("|"),Mt="(?: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)",ia=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Br})\\s${N(40)}\\b${Mt}\\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${N(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${N(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${N(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${N(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${N(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")}]),aa=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${N(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${N(30)}\\b${Mt}\\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 F=e=>`[^.!?;\\n]{0,${e}}?`,oa=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${F(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${F(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${F(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${F(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${F(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 Ne="[REDACTED]",x="\u2022",ee=e=>/[A-Za-z0-9]/.test(e);function Pt(e,t,n,r){let i=Array.from(e),a=i.length,o=Math.max(0,Math.floor(t)||0),l=Math.max(0,Math.floor(n)||0),c=r.length>0?r:x,s=o+l>=a;return i.map((d,f)=>!s&&(f<o||f>=a-l)?d:ee(d)?c:d).join("")}function Ur(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Pt(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:x;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(o=>ee(o)?a:o).join(""))+i}function Vr(e,t,n){let r=n.length>0?n:x,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let s=new RegExp(t,"g"),d;for(;(d=s.exec(e))!==null;){if(d[0].length===0){s.lastIndex++;continue}for(let f=d.index;f<d.index+d[0].length;f++)i[f]=!0}}catch{}let a=!1,o=!0;for(let s=0;s<e.length;s++)if(ee(e[s])&&(a=!0,!i[s])){o=!1;break}let l=a&&o,c="";for(let s=0;s<e.length;s++){let d=e[s];!l&&i[s]||!ee(d)?c+=d:c+=r}return c}function Dt(e,t){let n=t.mode??"full";return n==="partial"?Pt(e,t.keepFirst??0,t.keepLast??0,t.maskChar??x):n==="email"?Ur(e,t.maskChar??x):n==="custom"?Vr(e,t.keepPattern,t.maskChar??x):t.replacement??Ne}function zr(e,t){return typeof e=="string"?Dt(e,t):t.replacement??Ne}function Ft(e){let t=[],n=e.replacement??Ne;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:a=>Dt(a,r)})}return t}function jt(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(o){let l=o instanceof Error?o.message:String(o);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${l}`)}n=n.replace(a,o=>i(o))}return n}function ie(e,t){return e==null?e:typeof e=="string"?Gr(e,t):typeof e=="object"?Kr(e,t):e}function Gr(e,t){if(typeof e!="string")return e;let n=Ft(t);return n.length===0?e:jt(e,n)}function Kr(e,t){let n=new Map;for(let l of t.fields??[])typeof l=="string"&&l.length>0&&n.set(l,{field:l,mode:"full",replacement:t.replacement});for(let l of t.directives??[])typeof l.field=="string"&&l.field.length>0&&n.set(l.field,l);let r=Ft(t),i=n.size>0,a=r.length>0,o=l=>{if(l==null)return l;if(Array.isArray(l))return l.map(c=>o(c));if(typeof l=="object"){let c=l,s=Object.create(Object.getPrototypeOf(c));for(let d of Object.keys(c)){let f=i?n.get(d):void 0;if(f){s[d]=zr(c[d],f);continue}s[d]=o(c[d])}return s}return typeof l=="string"&&a?jt(l,r):l};return o(e)}var qt=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Wr(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:qt(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:qt(t.spawn.prompt)}),t}function Hr(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 Qr=1440*60*1e3,Yr="VISIQ_BUNDLE_GRACE_TTL_MS",Zr="VISIQ_BUNDLE_CACHE_DISABLED",Jr="VISIQ_CACHE_DIR",Xr=ae.object({graceTtlMs:ae.number().int().nonnegative().optional(),disabled:ae.boolean().optional(),cacheDir:ae.string().min(1).optional()}).strict();function ei(e){return e==null?{}:Xr.parse(e)}function ti(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Yr];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Qr}function ni(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Zr]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var Bt;function ri(){if(Bt!==void 0)return Bt;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function ii(e){return JSON.stringify(xe(e))}function xe(e){if(Array.isArray(e))return e.map(xe);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=xe(t[r]);return n}return e}function ai(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function oi(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 Ht(){if(!ri())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 Qt(e,t){return e.createHash("sha256").update(ii(t)).digest("hex")}function si(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Jr]?.trim();if(r)return r;let i=process.env.XDG_CACHE_HOME?.trim();if(i)return e.path.join(i,"visiq");let a="";try{a=e.os.homedir()}catch{a=""}return a?e.path.join(a,".cache","visiq"):e.path.join(e.os.tmpdir(),"visiq-cache")}function li(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function Yt(e,t,n){return e.path.join(si(e,n),"bundles",`${li(e,t)}.json`)}async function ci(e,t,n,r={}){let i=await Ht();if(i)try{let a=Yt(i,e,r),o=i.path.dirname(a);await i.fs.mkdir(o,{recursive:!0,mode:448});let l={fetchedAt:r.now??Date.now(),version:n,contentHash:Qt(i.crypto,t),body:t},c=`${a}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(c,JSON.stringify(l),{mode:384});try{await i.fs.rename(c,a)}catch(s){throw await i.fs.rm(c,{force:!0}).catch(()=>{}),s}}catch{}}async function ui(e,t={}){let n=await Ht();if(!n)return null;try{let r=await n.fs.readFile(Yt(n,e,t),"utf-8"),i=oi(JSON.parse(r));return!i||Qt(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var j;async function di(){if(j!==void 0)return j;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;j=typeof t=="function"?t:null}catch{j=null}return j}var pi=5e3,fi=1e4,gi=25,Ut=1e3,mi=5e3,hi=100,Vt=2e3,_i=512,yi=1800*1e3,bi="monitor",vi="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",zt="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.",wi="open";function Gt(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Ai(e,t){return Lt({content:e,resourceMetadata:t})}var Ii=p.object({operations:p.array(p.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:p.string().min(1,"agentId is required"),sessionId:p.string().min(1).max(255).optional(),toolName:p.string().optional(),toolArgs:p.record(p.unknown()).optional(),targetResource:p.string().optional(),resourceType:p.string().optional(),resourceMetadata:p.record(p.unknown()).optional(),normalized:p.record(p.unknown()).optional(),query:p.string().optional(),contentPreview:p.string().optional(),telemetry:p.record(p.unknown()).optional(),context:p.record(p.unknown()).optional()}),ki=p.object({version:p.string().min(1),dialect_version:p.number().int().optional(),min_dialect:p.number().int().optional(),shutdown:p.boolean().optional(),agent_mode:p.enum(["enforce","monitor","off"]).optional(),cognition_capture:p.boolean().optional(),agent_mode_by_operation:p.object({action:p.string().optional(),retrieval:p.string().optional(),delegation:p.string().optional()}).partial().optional(),agent_attributes:p.object({trust_tier:p.string().nullable().optional(),categories:p.array(p.string()).optional(),business_function:p.string().nullable().optional(),business_functions:p.array(p.string()).nullable().optional(),blast_radius_tier:p.string().nullable().optional(),no_coverage:p.string().nullable().optional(),fail_mode:p.string().nullable().optional()}).optional(),rules:p.array(p.record(p.unknown())),no_coverage:p.object({no_coverage_defaults:p.record(p.string()),autopilot_enabled:p.boolean(),enduser_hitl_enabled:p.boolean(),hitl_timeout_seconds:p.number().optional()}).optional()});function Si(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=ct(ut(n));return{trust_tier:et(t)?t:null,categories:nt(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&dt(e.blast_radius_tier)?e.blast_radius_tier:null}}function Ei(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 Ci(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Oe=new Set,Kt=!1;async function Wt(e){let t=[];for(let n of Oe){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 Ti(){if(!Kt&&!(typeof process>"u"||typeof process.once!="function")){Kt=!0,process.once("beforeExit",()=>{Wt(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await Wt(!0)}finally{process.kill(process.pid,e)}})()})}}var Zt=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=bi;agentModeByOperation=null;rawBundle=null;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=Gt(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??wi;governedFailMode=null;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;constructor(e,t,n,r,i,a,o,l){let c=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,s=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,d=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=c,this.resolvedEndpoint=s,this.resolvedAgentId=d,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=o,this.originalFetch=globalThis.fetch.bind(globalThis);let f=ei(l);if(this.bundleCacheDisabled=ni(f.disabled),this.bundleGraceTtlMs=ti(f.graceTtlMs),this.bundleCacheDirOverride=f.cacheDir,this.cacheIdentity=c&&s&&!this.bundleCacheDisabled?{endpoint:s,agentId:d,apiKey:c}:null,c&&s){let _={apiKey:c,agentId:d,endpoint:s,mode:"enforce",timeoutMs:Hr(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new me(_,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},pi),Re(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},fi),Re(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},mi),Re(this.cognitionTimer),Oe.add(this),Ti()}else this.client=null}async evaluate(e){let t=Ii.parse(e),n=Date.now();if(this.operatorShutdown){let s=this.denyAll(t,vi);return this.applyAgentMode(s,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,zt,n);let s=this.denyAll(t,zt);return this.applyAgentMode(s,"enforce",t,n)}if(t.operations.every(s=>this.modeFor(s)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let s;if(this.agentModeConfirmed?s=this.agentMode:this.bundleApplyFailed?s="enforce":s="monitor",s==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let d=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(d,s,t,n)}let r=this.readSession(t.sessionId),i=await di();if(!i||!this.rawBundle){if(this.failMode==="open")return this.failOpen(t,"governance core (@visiq/core-wasm) unavailable",n);throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)")}let a=t.operations.includes("action")||t.operations.includes("delegation")?ke(t.normalized??{},{action:t.toolName??"",targetApp:t.targetResource??t.toolName??""}):t.normalized,o={...t,normalized:a,session:r,at:Date.now()},l={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},c;try{c=i(o,l)}catch(s){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${s instanceof Error?s.message:String(s)}`,n);throw s}return this.foldSession(t,c.enforced?c.decision:"permit"),c.enforced&&c.action.decision==="approval_required"&&await this.registerHitl(t,c),this.bufferTelemetry(t,c,Date.now()-n,c.enforced),c}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return D;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>yi?(this.sessions.delete(e),D):t.state:D}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),o=e.operations.includes("action")||e.operations.includes("delegation"),l=o?ke(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},c=at(r===D?it():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?Ai(e.contentPreview,i):void 0,action_class:o?l.action_class:void 0,target_app:o?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:c,touchedAt:Date.now()}),this.sessions.size>_i){let s=this.sessions.keys().next().value;s!==void 0&&this.sessions.delete(s)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let o={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,o,i,!0),o}let a={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,a,i,!1),a}setFailMode(e){this.failMode=e}getFailMode(){return this.failMode}getGovernedFailMode(){return this.governedFailMode}failOpen(e,t,n){let r=`fail-open: ${t} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`;console.error(`[VisIQ] FAIL-OPEN: ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`);let i=e.operations.includes("action")||e.operations.includes("delegation"),a=e.operations.includes("retrieval"),o={decision:"permit",allowed:!0,reason:r,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:i?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:a?{action:"allow"}:{action:null},failOpen:!0};return this.bufferTelemetry(e,o,Date.now()-n,!1,!0),o}reportFailOpen(e,t){try{let n={operations:["action"],agentId:this.resolvedAgentId,...t?.toolName?{toolName:t.toolName}:{},...t?.sessionId?{sessionId:t.sessionId}:{}},r={decision:"permit",allowed:!0,reason:`fail-open: ${e} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:{decision:"permit",allowed:!0},retrieval:{action:null},failOpen:!0};this.bufferTelemetry(n,r,0,!1,!0)}catch{}}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},...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=ki.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}this.dialectRefused=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(r=>ft(r)).filter(r=>r!==null),this.agentAttributes=t.agent_attributes?Si(t.agent_attributes):null,this.agentNoCoverage=pt(t.agent_attributes?.no_coverage),this.governedFailMode=Gt(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=Ei(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.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",...ge(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)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let a=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&a?this.bundleEtag=r:a||(this.bundleEtag=null),a&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await ui(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(ai(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 ci(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){this.registerEnvironment({...he(),...e?{agent_type:e}:{}})}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)));t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}bufferTelemetry(e,t,n,r,i=!1){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?Ci(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:{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}:{}},...this.harnessKind||e.context||i?{context:{...this.harnessKind?{[He]:this.harnessKind}:{},...e.context??{},...i?{fail_open:!0}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=gi&&this.flushTelemetry()}pendingTelemetryCount(){return this.telemetryBuffer.length}hasBackend(){return this.client!==null}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0);try{await this.client.sendTelemetry(e)}catch(t){console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",t)}}enforceTelemetryCap(){let e=this.telemetryBuffer.length-Ut;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Ut})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Wr(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=hi&&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-Vt;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Vt})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),Oe.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 Re(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function q(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Jt(e,t){if(e!=="sessions_spawn")return null;let n=q(t.agentId);return n?{childAgentId:n,childName:q(t.taskName)??q(t.label)??n,kind:"subagent",task:q(t.task),model:q(t.model),source:"structural"}:null}function Xt(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 R=null;function C(e){let t=`${e.apiKey}::${e.agentId}::${e.baseUrl??""}`;if(R&&R.key===t)return R.runtimes;let n=new Zt(e.apiKey,e.baseUrl,e.agentId,"cli_harness");return n.setFailMode(e.failMode),n.registerHostEnvironment(),R={key:t,runtimes:{unified:n}},R.runtimes}async function ba(){if(R)try{await R.runtimes.unified.flush()}catch{}}async function va(e){try{let t=await K();if(!t)return;let{unified:n}=C(t);await n.awaitBundleReady(e)}catch{}}function en(){return R?.runtimes.unified.getAgentMode()}function k(e){try{process.stderr.write(`[VisIQ] FAIL-OPEN (${e.stage}): ${e.detail} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.
8
+ `)}catch{}if(e.config)try{C(e.config).unified.reportFailOpen(`${e.stage}: ${e.detail}`,{...e.toolName?{toolName:e.toolName}:{},...e.sessionId?{sessionId:e.sessionId}:{}})}catch{}}function B(e,t,n){try{let r=n instanceof Error?n.message:String(n);process.stderr.write(`[VisIQ] TRACE-DEGRADED (${e}) for tool "${t}": ${r} \u2014 the governance decision was still made and enforced; only the execution-trace beat was lost.
9
+ `)}catch{}}function T(e,t){return e?.sessionKey??t?.sessionKey??t?.sessionId??"default"}var $e=class{entries=new Map;set(t,n){this.entries.set(t,n)}get(t){return this.entries.get(t)}delete(t){this.entries.delete(t)}clear(){this.entries.clear()}size(){return this.entries.size}},Le=new Map;function O(e){let t=Le.get(e);return t||(t=new $e,Le.set(e,t)),t}function tn(e){Le.delete(e)}var nn=new Set(["web_search","x_search","web_fetch","tool_search","tool_describe","get_account","get_transactions","get_devices","check_watchlist","search_knowledge"]);function Me(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}function rn(e){return nn.has(Me(e))}function Sa(){return nn}var Ni=new Set(["send","send_email","send_message","email","email_send","message","post","post_message","http_post","upload","export","export_data","share","publish","webhook"]);function an(e){return Ni.has(Me(e))}var Pe="@visiq/openclaw-plugin";function on(e){let t=[],n=[],r;for(let a of e){let{field:o,pattern:l,replacement:c}=a;o&&t.push(o),l&&n.push(l),c&&r===void 0&&(r=c)}let i={};return t.length>0&&(i.fields=t),n.length>0&&(i.patterns=n),r!==void 0&&(i.replacement=r),i}async function qa(e,t){let{config:n,failMode:r}=await Ve();if(!n){if(r==="closed")return{block:!0,blockReason:"[VisIQ] Plugin is loaded but NOT configured \u2014 VisIQ cannot govern this tool call. Set VISIQ_API_KEY + VISIQ_AGENT_ID (and optionally VISIQ_ENDPOINT), or the plugin config, then retry. Blocked because VISIQ_FAIL_MODE=closed."};k({stage:"unconfigured",detail:"no VisIQ credentials resolved (need VISIQ_API_KEY + VISIQ_AGENT_ID)",toolName:e.toolName,sessionId:T(e,t)});return}let i=C(n),a=n.agentId??t.agentId,o=T(e,t),l=t.toolCallId??e.toolCallId,s=rn(e.toolName)?["retrieval","action"]:["action"],d=Ri(e.params),f=Jt(e.toolName,e.params??{}),_;f&&a&&(be(i.unified,{agentId:a,sessionId:o,framework:"openclaw"},f),s.push("delegation"),_=Xt(f,a));let y=a?{agentId:a,sessionId:o,framework:"openclaw"}:null,S=$(e.toolName,e.params??{});if(y)try{ve(i.unified,y,{toolName:e.toolName,...S?{memory:S}:{}})}catch(m){B("step-beat",e.toolName,m)}let A=(m,g,De,Fe)=>{if(y)try{Ae(i.unified,y,{toolName:e.toolName,decision:m,...g?{ruleCode:g}:{},...De?{ruleLabel:De}:{},enforced:!0,...Fe?{harnessMessage:Fe}:{}})}catch(sn){B("intervention-beat",e.toolName,sn)}},h;try{if(await i.unified.awaitBundleReady(),!i.unified.isBundleLoaded()&&n.failMode!=="closed"){k({stage:"no-bundle",detail:"no rule bundle available after warm-up",toolName:e.toolName,sessionId:o,config:n});return}h=await i.unified.evaluate({operations:s,agentId:a,sessionId:o,toolName:e.toolName,toolArgs:e.params??{},resourceType:"tool_result",resourceMetadata:{toolName:e.toolName,runId:e.runId??t.runId},...d!==void 0?{query:d}:{},..._?{context:_}:{}})}catch(m){let g=m instanceof Error?m.message:String(m);if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ] Evaluation error \u2014 blocked (VISIQ_FAIL_MODE=closed): ${g}`};k({stage:"eval-error",detail:g,toolName:e.toolName,sessionId:o,config:n});return}if(!h.enforced)return;let{action:v}=h;if(v.decision==="approval_required")return A("approval_required",h.ruleCode??void 0,h.reason),{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:h.reason,severity:"critical",allowedDecisions:["allow-once","allow-always","deny"],pluginId:Pe}};if(!v.allowed){let g=`[VisIQ ${h.ruleCode??"DENY"}] ${h.reason}`;return A("deny",h.ruleCode??void 0,h.reason,g),{block:!0,blockReason:g}}let w;if(v.decision==="mask"&&v.argRedactionRules&&v.argRedactionRules.length>0)try{w=ie(e.params??{},on(v.argRedactionRules)),A("mask",h.ruleCode??void 0,h.reason)}catch(m){let g=m instanceof Error?m.message:String(m);if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ] Argument masking failed \u2014 blocked (VISIQ_FAIL_MODE=closed): ${g}`};k({stage:"mask-error",detail:`argument masking failed \u2014 running with UNMASKED params: ${g}`,toolName:e.toolName,sessionId:o,config:n}),w=void 0}if(s.includes("retrieval"))switch(h.retrieval.action){case"allow":case null:break;case"deny":{let m=`[VisIQ RECALL] ${h.reason}`;return A("deny",h.ruleCode??void 0,h.reason,m),{block:!0,blockReason:m}}case"redact":{if(!l){if(n.failMode==="closed")return{block:!0,blockReason:"[VisIQ RECALL] Redact decision but no toolCallId \u2014 blocked (VISIQ_FAIL_MODE=closed)"};k({stage:"redact-no-toolcallid",detail:"redact decision could not be applied (no toolCallId to correlate the result)",toolName:e.toolName,sessionId:o,config:n});break}let m=h.retrieval.redactionRules??[];m.length>0&&O(o).set(l,on(m));break}case"escalate":return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:h.reason,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:Pe}};default:{let m=h.retrieval.action;if(n.failMode==="closed")return{block:!0,blockReason:`[VisIQ RECALL] Unknown action "${String(m)}" \u2014 blocked (VISIQ_FAIL_MODE=closed)`};k({stage:"unknown-retrieval-verb",detail:`unknown retrieval action "${String(m)}" (harness/backend version skew)`,toolName:e.toolName,sessionId:o,config:n});break}}if(an(e.toolName)){let m=w??e.params??{},g=ne(m,{failMode:n.failMode==="closed"?"closed":"open"});if(g.verdict==="block")return{block:!0,blockReason:`[VisIQ OUTPUT-BLOCK] outbound content carried a live secret (${g.detectors.join(",")}) \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(g.verdict==="redact")return k({stage:"outbound-secret-redacted",detail:`outbound secret screen redacted ${g.detectors.length} detector(s): ${g.detectors.join(",")}`,toolName:e.toolName,sessionId:o,config:n}),{params:g.redacted}}if((n.sequenceAnomaly?.enabled??!0)&&typeof i.unified.getSessionState=="function"&&o){let m=i.unified.getSessionState(o),g=Se(m,{failMode:n.failMode==="closed"?"closed":"open",config:n.sequenceAnomaly?.thresholds});if(g.verdict==="deny")return{block:!0,blockReason:`[VisIQ ANOMALY] session-sequence anomaly (${g.signals.join(",")}) over ${g.evidence.event_count} events \u2014 blocked (VISIQ_FAIL_MODE=closed)`};if(g.verdict==="hold")return k({stage:"sequence-anomaly-hold",detail:`session-sequence anomaly held for approval (${g.signals.join(",")}) over ${g.evidence.event_count} events`,toolName:e.toolName,sessionId:o,config:n}),{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:`A behavioral sequence anomaly was detected in this session (${g.signals.join(",")}). Approve to proceed, or deny to stop the run.`,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:Pe}}}if(w)return{params:w}}function Ri(e){if(e)for(let t of["query","q","url","prompt"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}}function Ha(e,t){let{ready:n,config:r}=W();if(!n||!r)return;let i=T(e,t),a=e.toolName??t.toolName,o=r.agentId??t.agentId;if(a&&o)try{let f=e.message?.content,_=$(a);we(C(r).unified,{agentId:o,sessionId:i,framework:"openclaw"},{toolName:a,ok:!0,...Y(f)!==void 0?{bytes:Y(f)}:{},...Z(f)!==void 0?{itemCount:Z(f)}:{},..._?{memory:_}:{}})}catch(f){B("observation-beat",a,f)}let l=e.toolCallId??t.toolCallId;if(!l)return;let c=O(i),s=c.get(l);if(!s)return;let d={...e.message};return d.content!==void 0&&(d.content=ie(d.content,s)),c.delete(l),{message:d}}function to(e,t){let{ready:n,config:r,failMode:i}=W();if(n&&!r)return;let a=T(e,t),o=O(a);if(o.size()>0){if(o.clear(),i==="closed")return{block:!0};k({stage:"unconsumed-redaction",detail:"queued redaction was never applied to a tool result before message write",sessionId:a,config:r})}if(r&&en()==="enforce"){let l=ne(e.message,{failMode:i==="closed"?"closed":"open"});if(l.verdict==="block")return{block:!0};if(l.verdict==="redact")return k({stage:"final-message-secret-redacted",detail:`final assistant message carried a live secret \u2014 redacted ${l.detectors.length} detector(s): ${l.detectors.join(",")}`,sessionId:a,config:r}),{message:l.redacted}}}async function ro(e,t){}async function lo(e,t){try{let n=await K();if(!n)return;let r=n.agentId??t.agentId;if(!r)return;let i=e.sessionId??t.sessionId??t.sessionKey,{unified:a}=C(n);await a.awaitBundleReady(),ye(a,{agentId:r,...i?{sessionId:i}:{},framework:"openclaw"},{texts:e.assistantTexts,usage:e.usage?{tokensIn:e.usage.input,tokensOut:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite}:void 0,model:e.model||e.resolvedRef,final:!0})}catch{}}function po(e,t){tn(T(e,t))}export{z as a,ce as b,Pi as c,de as d,ji as e,ba as f,va as g,k as h,$e as i,O as j,tn as k,Me as l,rn as m,Sa as n,qa as o,Ha as p,to as q,ro as r,lo as s,po as t};
package/dist/index.d.ts CHANGED
@@ -6,26 +6,92 @@
6
6
  * 1. Environment variables: VISIQ_API_KEY / VISIQ_AGENT_ID / VISIQ_BASE_URL
7
7
  * 2. JSON config file at VISIQ_CONFIG_PATH
8
8
  * 3. ~/.openclaw/openclaw.json plugin config
9
+ * 3b. $OPENCLAW_CONFIG_PATH openclaw.json (the gateway's own config; Sigma)
9
10
  * 4. Interactive TTY prompt (only when stdout is a TTY)
10
11
  *
12
+ * The same chain also resolves the Surface E sequence-anomaly interlock's
13
+ * OPERATOR CONTROL (see SequenceAnomalySettings below):
14
+ * kill switch --sequence-anomaly <on|off> · VISIQ_SEQUENCE_ANOMALY=off ·
15
+ * `sequenceAnomaly: false` / `{ "enabled": false }` in JSON
16
+ * thresholds --sequence-anomaly-{min-events,min-classes,sigma,
17
+ * dominance-ratio,dominance-share,friction-ratio,
18
+ * min-friction-events} · the matching VISIQ_SEQUENCE_ANOMALY_*
19
+ * env vars · the same keys (camelCase or snake_case) inside the
20
+ * JSON `sequenceAnomaly` object
21
+ * Both DEFAULT to the shipped posture (enabled, detector defaults).
22
+ *
11
23
  * Behavior on missing credentials:
12
24
  * - Non-TTY context -> log a structured warning to stderr and return null
13
25
  * - TTY context -> print a single-paragraph hint with the three setup
14
26
  * options and return null
15
27
  *
16
28
  * This function NEVER throws. The plugin must remain installable / loadable
17
- * even when unconfigured; but downstream enforcement hooks FAIL-CLOSED (BLOCK)
18
- * when this function returns null (reform Phase 3, owner decision #2) — a
19
- * security harness that cannot reach its policy engine must never silently let
20
- * tool calls through. loadConfig itself just returns null + warns; the block
21
- * happens in the hooks (see before-tool-call.ts).
29
+ * even when unconfigured. Downstream enforcement hooks route a null config by
30
+ * failMode (owner decision 2026-07-15, supersedes reform-Phase-3 "owner
31
+ * decision #2"): DEFAULT `open` no-op with loud fail-open telemetry (an
32
+ * unconfigured harness must never disrupt the agent); `closed` BLOCK until
33
+ * configured. loadConfig itself just returns null + warns; the routing happens
34
+ * in the hooks (see before-tool-call.ts).
22
35
  *
23
36
  * G004: never logs the resolved apiKey value, only its presence/absence.
24
37
  */
38
+ /**
39
+ * What the plugin does when IT (not policy) fails — missing config, endpoint
40
+ * unreachable, no bundle, evaluator crash, redaction bookkeeping failure.
41
+ * `open` (DEFAULT, owner decision 2026-07-15): let the call/message proceed +
42
+ * loud fail-open telemetry — a VisIQ bug must never disrupt the agent.
43
+ * `closed`: strict blocking (opt-in via VISIQ_FAIL_MODE=closed, `--fail-mode
44
+ * closed`, or `failMode` in the plugin config).
45
+ */
46
+ export type FailMode = "open" | "closed";
47
+ export declare const DEFAULT_FAIL_MODE: FailMode;
48
+ /**
49
+ * Normalize a raw failMode value. Only (case-insensitive) `open`/`closed`
50
+ * count; anything else → undefined so the default applies. A typo'd value must
51
+ * degrade to the DEFAULT, never invent strictness.
52
+ */
53
+ export declare function normalizeFailMode(raw: unknown): FailMode | undefined;
54
+ /**
55
+ * OPERATOR CONTROL for the sequence-anomaly DETECTION interlock (Surface E).
56
+ *
57
+ * The interlock reads the LIVE per-session fold, and that fold is MONOTONE — so
58
+ * once a session trips the hold it re-fires on EVERY subsequent call in that
59
+ * session. Without a switch, the only way to stop that is to disable enforcement
60
+ * entirely, which also drops real policy denies. So the interlock gets its own
61
+ * kill switch and its own threshold overrides, resolved through the SAME
62
+ * precedence chain as the credentials (CLI > env > VISIQ_CONFIG_PATH >
63
+ * $OPENCLAW_CONFIG_PATH > ~/.openclaw/openclaw.json).
64
+ *
65
+ * DEFAULT POSTURE IS UNCHANGED: `enabled` defaults to true and `thresholds` to
66
+ * empty (i.e. DEFAULT_SEQUENCE_ANOMALY_CONFIG), so an operator who sets nothing
67
+ * gets exactly the shipped behaviour. Per G001's agent-side rule the switch is
68
+ * fail-OPEN in the sense that an unparseable value degrades to the DEFAULT — a
69
+ * typo can never silently invent strictness, nor silently disable detection.
70
+ */
71
+ export interface SequenceAnomalySettings {
72
+ /** Master kill switch. false ⇒ the interlock leg is skipped entirely. */
73
+ enabled: boolean;
74
+ /**
75
+ * Threshold overrides MERGED over the detector's defaults. Structurally typed
76
+ * (a plain numeric bag) so config.ts needs no value-import of the detector.
77
+ */
78
+ thresholds: {
79
+ minEvents?: number;
80
+ minClasses?: number;
81
+ concentrationSigma?: number;
82
+ dominanceRatio?: number;
83
+ dominanceShare?: number;
84
+ frictionRatio?: number;
85
+ minFrictionEvents?: number;
86
+ };
87
+ }
25
88
  export interface VisiqConfig {
26
89
  apiKey: string;
27
90
  agentId: string;
28
91
  baseUrl?: string;
92
+ failMode: FailMode;
93
+ /** Surface E operator control (kill switch + threshold overrides). */
94
+ sequenceAnomaly: SequenceAnomalySettings;
29
95
  }
30
96
  /**
31
97
  * Resolve plugin credentials following the documented precedence chain.
@@ -35,12 +101,34 @@ export interface VisiqConfig {
35
101
  * 1. Environment variables: VISIQ_API_KEY / VISIQ_AGENT_ID / VISIQ_BASE_URL
36
102
  * 2. JSON config file at VISIQ_CONFIG_PATH
37
103
  * 3. ~/.openclaw/openclaw.json plugin config
104
+ * 3b. $OPENCLAW_CONFIG_PATH openclaw.json (the gateway's own config; Sigma)
38
105
  * 4. Interactive TTY prompt (only when stdout is a TTY)
39
106
  *
40
107
  * Returns `null` when credentials cannot be resolved. Downstream hooks
41
108
  * MUST treat null as "plugin unconfigured, no-op" and MUST NOT crash.
42
109
  */
43
110
  export declare function loadConfig(): Promise<VisiqConfig | null>;
111
+ /** Credentials (null when unresolvable) + the failMode that applies either way. */
112
+ export interface PluginState {
113
+ config: VisiqConfig | null;
114
+ failMode: FailMode;
115
+ }
116
+ /**
117
+ * Resolve credentials AND failMode in one pass. failMode must be resolvable
118
+ * even when credentials are absent (the unconfigured no-op/deny guard consults
119
+ * it), so it is surfaced separately from the nullable config. Never throws.
120
+ */
121
+ export declare function loadPluginState(): Promise<PluginState>;
122
+ export interface FailOpenReport {
123
+ /** Which guard failed open (e.g. `unconfigured`, `no-bundle`, `eval-error`). */
124
+ stage: string;
125
+ detail: string;
126
+ toolName?: string;
127
+ sessionId?: string;
128
+ /** When present, the event is also buffered to the runtime's audit telemetry. */
129
+ config?: VisiqConfig | null;
130
+ }
131
+ export declare function reportFailOpen(report: FailOpenReport): void;
44
132
  /**
45
133
  * @visiq/redact — shared redaction primitives for VisIQ SDKs.
46
134
  *
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as w,c as g,d as _,e as d,f as k,g as f,h as e,i as t,j as h,k as i,l as s,m as l,n as a,o as u,p}from"./chunk-PS2DVYPN.js";var c=new Set(["place_hold","block_card","wire_transfer","create_case","send_notification","bank_account_lookup_tool","exec","write_file","http_post","http_put","http_delete"]),N=new Set(["sessions_list","sessions_history","sessions_send","sessions_get","sessions_create","sessions_delete","memory_search","memory_read","memory_write"]),T=["sessions_","memory_"];function I(o){let r=e(o);return N.has(r)?!0:T.some(m=>r.startsWith(m))}function x(o){return!(t(o)||I(o))}function R(o){return c.has(e(o))}function O(){return c}var n="@visiq/openclaw-plugin";function b(){return{id:n,name:"VisIQ OpenClaw Plugin",version:"0.1.7",hooks:[{pluginId:n,hookName:"before_tool_call",handler:i,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"tool_result_persist",handler:s,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"before_message_write",handler:l,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"llm_input",handler:a,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"llm_output",handler:u,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"session_end",handler:p,source:"visiq-openclaw-plugin"}]}}var S=b;export{d as RedactionLedger,_ as awaitRuntimesReady,e as bareToolName,f as clearLedger,b as createPlugin,S as default,O as getActionToolNames,k as getLedger,h as getRetrievalToolNames,x as isActionTool,R as isKnownActionTool,t as isRetrievalTool,w as loadConfig,g as shutdownRuntimes};
1
+ import{a as g,b as w,c as _,d,f,g as k,h,i as N,j as T,k as I,l as o,m as t,n as O,o as i,p as s,q as l,r as a,s as u,t as p}from"./chunk-OMXTAUEH.js";var c=new Set(["place_hold","block_card","wire_transfer","create_case","send_notification","bank_account_lookup_tool","exec","write_file","http_post","http_put","http_delete"]),x=new Set(["sessions_list","sessions_history","sessions_send","sessions_get","sessions_create","sessions_delete","memory_search","memory_read","memory_write"]),R=["sessions_","memory_"];function y(e){let r=o(e);return x.has(r)?!0:R.some(m=>r.startsWith(m))}function A(e){return!(t(e)||y(e))}function b(e){return c.has(o(e))}function v(){return c}var n="@visiq/openclaw-plugin";function L(){return{id:n,name:"VisIQ OpenClaw Plugin",version:"0.1.8",hooks:[{pluginId:n,hookName:"before_tool_call",handler:i,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"tool_result_persist",handler:s,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"before_message_write",handler:l,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"llm_input",handler:a,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"llm_output",handler:u,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"session_end",handler:p,source:"visiq-openclaw-plugin"}]}}var D=L;export{g as DEFAULT_FAIL_MODE,N as RedactionLedger,k as awaitRuntimesReady,o as bareToolName,I as clearLedger,L as createPlugin,D as default,v as getActionToolNames,T as getLedger,O as getRetrievalToolNames,A as isActionTool,b as isKnownActionTool,t as isRetrievalTool,_ as loadConfig,d as loadPluginState,w as normalizeFailMode,h as reportFailOpen,f as shutdownRuntimes};
@@ -1,5 +1,5 @@
1
- import{b as w,k as b,l as S,m as k,n as L,o as v,p as O}from"./chunk-PS2DVYPN.js";import{Type as e}from"typebox";import{definePluginEntry as D}from"openclaw/plugin-sdk/plugin-entry";import{readFileSync as x,readdirSync as A,statSync as C,existsSync as R}from"node:fs";import{join as p,dirname as $}from"node:path";import{fileURLToPath as P}from"node:url";var U="@visiq/openclaw-plugin",h=process.env.BANK_API_URL??"http://localhost:4000/api",I=$(P(import.meta.url));function c(n,i={}){return{content:[{type:"text",text:n}],details:i}}async function m(n){let i=await fetch(`${h}${n}`);return i.ok?await i.text():`[Error ${i.status}]`}async function d(n,i){let t=await fetch(`${h}${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return t.ok?await t.text():`[Error ${t.status}]`}function j(){let n=[p(I,"..","..","..","examples","langchain-agent","docs"),p(I,"..","..","examples","langchain-agent","docs"),process.env.VISIQ_KNOWLEDGE_DIR??""].filter(i=>i.length>0);for(let i of n)if(R(i))return i;return null}function N(){let n=j();if(!n)return[];let i=[];function t(o){for(let s of A(o)){let r=p(o,s);if(C(r).isDirectory())t(r);else if(s.endsWith(".txt")){let l=x(r,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(l){let a={};for(let _ of l[1].split(`
2
- `)){let[g,...y]=_.split(":");g&&y.length&&(a[g.trim()]=y.join(":").trim())}i.push({path:r,title:a.title?.replace(/"/g,"")??s,classification:a.classification??"public",source:a.source??"unknown",content:l[2].trim()})}}}}return t(n),i}var f=null;function B(){return f===null&&(f=N()),f}function T(n,i=5){let t=B(),o=n.toLowerCase().split(/\s+/).filter(r=>r.length>=3);return t.map(r=>{let u=`${r.title} ${r.content}`.toLowerCase(),l=0;for(let a of o)u.includes(a)&&(l+=a.length,r.title.toLowerCase().includes(a)&&(l+=a.length*2));return{doc:r,score:l}}).filter(r=>r.score>0).sort((r,u)=>u.score-r.score).slice(0,i).map(r=>r.doc)}function K(n){w(),n.on("before_tool_call",b,{priority:50}),n.on("tool_result_persist",S),n.on("before_message_write",k),n.on("llm_input",L),n.on("llm_output",v),n.on("session_end",O),n.registerTool({name:"get_account",label:"Get account",description:"Get account holder profile from core banking system. Input: account ID (e.g. '4821-7734'). Returns: holder name, balance, risk score, KYC status, linked cards, address.",parameters:e.Object({account_id:e.String({description:"Account ID (e.g. '4821-7734')."})}),async execute(i,t){return c(await m(`/accounts/${t.account_id}`))}}),n.registerTool({name:"get_devices",label:"Get devices",description:"Get device fingerprints and login sessions from BioCatch. Input: account ID. Returns: registered devices, recent sessions with IP/geolocation, anomaly alerts.",parameters:e.Object({account_id:e.String({description:"Account ID to fetch devices for."})}),async execute(i,t){return c(await m(`/accounts/${t.account_id}/devices`))}}),n.registerTool({name:"get_transactions",label:"Get transactions",description:"Get recent transactions from the card processor with filtering. Returns: transaction list with amounts, merchants, locations, and risk flags.",parameters:e.Object({account_id:e.String({description:"Account ID (e.g. '4821-7734')."}),lookback_hours:e.Optional(e.Integer({minimum:1,maximum:720,description:"How far back to look (1\u2013720h, default 72)."})),min_amount:e.Optional(e.Number({minimum:0,description:"Filter out transactions below this dollar amount."}))}),async execute(i,t){let o=new URLSearchParams;t.lookback_hours!==void 0&&o.set("lookback_hours",String(t.lookback_hours)),t.min_amount!==void 0&&o.set("min_amount",String(t.min_amount));let s=o.toString()?`?${o.toString()}`:"";return c(await m(`/accounts/${t.account_id}/transactions${s}`))}}),n.registerTool({name:"check_watchlist",label:"Check watchlist",description:"Screen a name or entity against OFAC SDN, EU, and UN sanctions lists. Returns: match scores and recommendation.",parameters:e.Object({name:e.String({description:"Name or entity to screen."}),country_code:e.Optional(e.String({description:"ISO 3166-1 alpha-2 country code to scope the screening (e.g. 'US')."}))}),async execute(i,t){return c(await d("/watchlists/check",{name:t.name,country_code:t.country_code}))}}),n.registerTool({name:"search_knowledge",label:"Search knowledge base",description:"Search the bank's internal knowledge base for compliance policies, prior fraud case files, triage procedures, and customer information. Input is a free-text search query.",parameters:e.Object({query:e.String({description:"Free-text knowledge base search query."})}),async execute(i,t){let o=T(t.query,5);if(o.length===0)return c("No matching knowledge base documents found.",{hitCount:0});let s=o.map(r=>`--- ${r.title} (classification=${r.classification}, source=${r.source}) ---
3
- ${r.content}`).join(`
1
+ import{e as w,o as b,p as S,q as k,r as L,s as v,t as O}from"./chunk-OMXTAUEH.js";import{Type as e}from"typebox";import{emptyPluginConfigSchema as D}from"openclaw/plugin-sdk/core";import{readFileSync as x,readdirSync as A,statSync as C,existsSync as R}from"node:fs";import{join as p,dirname as $}from"node:path";import{fileURLToPath as P}from"node:url";var U="@visiq/openclaw-plugin",h=process.env.BANK_API_URL??"http://localhost:4000/api",I=$(P(import.meta.url));function c(n,i={}){return{content:[{type:"text",text:n}],details:i}}async function m(n){let i=await fetch(`${h}${n}`);return i.ok?await i.text():`[Error ${i.status}]`}async function d(n,i){let t=await fetch(`${h}${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return t.ok?await t.text():`[Error ${t.status}]`}function j(){let n=[p(I,"..","..","..","examples","langchain-agent","docs"),p(I,"..","..","examples","langchain-agent","docs"),process.env.VISIQ_KNOWLEDGE_DIR??""].filter(i=>i.length>0);for(let i of n)if(R(i))return i;return null}function N(){let n=j();if(!n)return[];let i=[];function t(r){for(let s of A(r)){let o=p(r,s);if(C(o).isDirectory())t(o);else if(s.endsWith(".txt")){let l=x(o,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(l){let a={};for(let _ of l[1].split(`
2
+ `)){let[g,...y]=_.split(":");g&&y.length&&(a[g.trim()]=y.join(":").trim())}i.push({path:o,title:a.title?.replace(/"/g,"")??s,classification:a.classification??"public",source:a.source??"unknown",content:l[2].trim()})}}}}return t(n),i}var f=null;function B(){return f===null&&(f=N()),f}function T(n,i=5){let t=B(),r=n.toLowerCase().split(/\s+/).filter(o=>o.length>=3);return t.map(o=>{let u=`${o.title} ${o.content}`.toLowerCase(),l=0;for(let a of r)u.includes(a)&&(l+=a.length,o.title.toLowerCase().includes(a)&&(l+=a.length*2));return{doc:o,score:l}}).filter(o=>o.score>0).sort((o,u)=>u.score-o.score).slice(0,i).map(o=>o.doc)}function K(n){w(),n.on("before_tool_call",b,{priority:50}),n.on("tool_result_persist",S),n.on("before_message_write",k),n.on("llm_input",L),n.on("llm_output",v),n.on("session_end",O),n.registerTool({name:"get_account",label:"Get account",description:"Get account holder profile from core banking system. Input: account ID (e.g. '4821-7734'). Returns: holder name, balance, risk score, KYC status, linked cards, address.",parameters:e.Object({account_id:e.String({description:"Account ID (e.g. '4821-7734')."})}),async execute(i,t){return c(await m(`/accounts/${t.account_id}`))}}),n.registerTool({name:"get_devices",label:"Get devices",description:"Get device fingerprints and login sessions from BioCatch. Input: account ID. Returns: registered devices, recent sessions with IP/geolocation, anomaly alerts.",parameters:e.Object({account_id:e.String({description:"Account ID to fetch devices for."})}),async execute(i,t){return c(await m(`/accounts/${t.account_id}/devices`))}}),n.registerTool({name:"get_transactions",label:"Get transactions",description:"Get recent transactions from the card processor with filtering. Returns: transaction list with amounts, merchants, locations, and risk flags.",parameters:e.Object({account_id:e.String({description:"Account ID (e.g. '4821-7734')."}),lookback_hours:e.Optional(e.Integer({minimum:1,maximum:720,description:"How far back to look (1\u2013720h, default 72)."})),min_amount:e.Optional(e.Number({minimum:0,description:"Filter out transactions below this dollar amount."}))}),async execute(i,t){let r=new URLSearchParams;t.lookback_hours!==void 0&&r.set("lookback_hours",String(t.lookback_hours)),t.min_amount!==void 0&&r.set("min_amount",String(t.min_amount));let s=r.toString()?`?${r.toString()}`:"";return c(await m(`/accounts/${t.account_id}/transactions${s}`))}}),n.registerTool({name:"check_watchlist",label:"Check watchlist",description:"Screen a name or entity against OFAC SDN, EU, and UN sanctions lists. Returns: match scores and recommendation.",parameters:e.Object({name:e.String({description:"Name or entity to screen."}),country_code:e.Optional(e.String({description:"ISO 3166-1 alpha-2 country code to scope the screening (e.g. 'US')."}))}),async execute(i,t){return c(await d("/watchlists/check",{name:t.name,country_code:t.country_code}))}}),n.registerTool({name:"search_knowledge",label:"Search knowledge base",description:"Search the bank's internal knowledge base for compliance policies, prior fraud case files, triage procedures, and customer information. Input is a free-text search query.",parameters:e.Object({query:e.String({description:"Free-text knowledge base search query."})}),async execute(i,t){let r=T(t.query,5);if(r.length===0)return c("No matching knowledge base documents found.",{hitCount:0});let s=r.map(o=>`--- ${o.title} (classification=${o.classification}, source=${o.source}) ---
3
+ ${o.content}`).join(`
4
4
 
5
- `);return c(s,{hitCount:o.length,classifications:o.map(r=>r.classification)})}}),n.registerTool({name:"place_hold",label:"Place hold",description:"Place a temporary fraud hold on an account. Blocks outbound transactions while allowing inbound credits.",parameters:e.Object({account_id:e.String({description:"Account to place the hold on."}),amount:e.Number({minimum:0,description:"Dollar amount to hold (0 = full account freeze)."}),currency:e.Union([e.Literal("USD"),e.Literal("EUR"),e.Literal("GBP"),e.Literal("CAD")],{description:"ISO currency code for the hold amount."}),duration_hours:e.Integer({minimum:1,maximum:168,description:"How long the hold stays (1\u2013168h)."}),reason:e.Union([e.Literal("fraud_investigation"),e.Literal("suspicious_pattern"),e.Literal("sanctions_review"),e.Literal("manual_review")],{description:"Reason classification for the hold."}),notify_holder:e.String({description:"Whether to notify the holder. Accepts: yes, no, true, false, 1, 0."})}),async execute(i,t){let{account_id:o,...s}=t;return c(await d(`/accounts/${o}/hold`,s))}}),n.registerTool({name:"block_card",label:"Block card",description:"Block a debit or credit card immediately. A replacement card will be mailed.",parameters:e.Object({account_id:e.String({description:"Account ID owning the card."}),reason:e.Union([e.Literal("fraud_investigation"),e.Literal("lost"),e.Literal("stolen"),e.Literal("compromised_pin"),e.Literal("customer_request")],{description:"Reason for blocking \u2014 drives the customer notification."}),notify_holder:e.Optional(e.String({description:"Whether to notify the holder. Accepts: yes, no, true, false."}))}),async execute(i,t){return c(await d(`/accounts/${t.account_id}/card/block`,{reason:t.reason,notify_holder:t.notify_holder}))}}),n.registerTool({name:"wire_transfer",label:"Wire transfer",description:"Initiate an outbound wire transfer from an account. HIGH RISK \u2014 large or sanctioned-destination wires are blocked or escalated by VisIQ ALLOW policy.",parameters:e.Object({account_id:e.String({description:"Source account ID."}),amount:e.Number({minimum:0,description:"Dollar amount to wire."}),currency:e.Union([e.Literal("USD"),e.Literal("EUR"),e.Literal("GBP"),e.Literal("CAD")],{description:"ISO currency code."}),destination:e.String({description:"Destination account / IBAN / beneficiary identifier."}),destination_country:e.Optional(e.String({description:"ISO 3166-1 alpha-2 destination country (e.g. 'US')."})),memo:e.Optional(e.String({description:"Free-text wire memo."}))}),async execute(i,t){let{account_id:o,...s}=t;return c(await d(`/accounts/${o}/wire`,s))}}),n.registerTool({name:"create_case",label:"Create case",description:"Create a fraud investigation case. Routes to the right queue based on severity / category.",parameters:e.Object({account_id:e.String({description:"Affected account ID."}),severity:e.Union([e.Literal("low"),e.Literal("medium"),e.Literal("high"),e.Literal("critical")],{description:"Case severity \u2014 drives SLA and routing."}),category:e.Union([e.Literal("account_takeover"),e.Literal("card_fraud"),e.Literal("wire_fraud"),e.Literal("synthetic_identity"),e.Literal("sanctions_hit"),e.Literal("structuring")],{description:"Fraud category \u2014 routes to specialist queue."}),summary:e.String({description:"Free-text case summary for the analyst."}),assignee:e.Optional(e.String({description:"Specialist email to assign directly."})),sla_hours:e.Optional(e.Integer({minimum:1,maximum:168,description:"Override the default SLA (1\u2013168h)."}))}),async execute(i,t){return c(await d("/cases",t))}}),n.registerTool({name:"send_notification",label:"Send notification",description:"Send a fraud alert notification to the customer. Channel + priority drive delivery latency.",parameters:e.Object({account_id:e.String({description:"Account ID \u2014 used to look up contact methods."}),channel:e.Union([e.Literal("sms"),e.Literal("email"),e.Literal("push"),e.Literal("voice"),e.Literal("in_app")],{description:"Delivery channel."}),priority:e.Union([e.Literal("low"),e.Literal("normal"),e.Literal("high"),e.Literal("critical")],{description:"Delivery priority \u2014 critical bypasses customer quiet hours."}),subject:e.String({maxLength:120,description:"Short subject line (used for email / push title)."}),message:e.String({description:"Body text of the notification."}),locale:e.Optional(e.String({description:"BCP-47 locale (e.g. 'en-US', 'es-MX')."}))}),async execute(i,t){return c(await d("/notifications/send",t))}}),n.registerTool({name:"bank_account_lookup_tool",label:"Bank account lookup (sensitive)",description:"Look up sensitive account data for fraud investigation. account_id is the account number (e.g. '4821-7734'). include_ssn controls whether PII fields (SSN, DOB, full legal name) come back \u2014 accepts 'yes' / 'no' / 'true' / 'false' / '1' / '0'.",parameters:e.Object({account_id:e.String({description:"Account number to look up (e.g. 4821-7734)."}),include_ssn:e.String({description:"Whether to include PII fields (SSN, DOB, full legal name). Accepts: yes, no, true, false, 1, 0."})}),async execute(i,t){let s=new Set(["yes","y","true","1"]).has(String(t.include_ssn).toLowerCase().trim()),r=await fetch(`${h}/accounts/${t.account_id}`);if(!r.ok)return c(JSON.stringify({error:`Account ${t.account_id} not found`}),{status:r.status});let u=await r.json();if(!s){let{ssn:l,dob:a,full_legal_name:_,...g}=u;return c(JSON.stringify({account:g,pii_included:!1}),{pii_included:!1})}return c(JSON.stringify({account:u,pii_included:!0}),{pii_included:!0})}})}var Y=D({id:U,name:"VisIQ OpenClaw Plugin",description:"Routes tool calls and LLM I/O through VisIQ ALLOW + RECALL + RECORD",register:K});export{Y as default};
5
+ `);return c(s,{hitCount:r.length,classifications:r.map(o=>o.classification)})}}),n.registerTool({name:"place_hold",label:"Place hold",description:"Place a temporary fraud hold on an account. Blocks outbound transactions while allowing inbound credits.",parameters:e.Object({account_id:e.String({description:"Account to place the hold on."}),amount:e.Number({minimum:0,description:"Dollar amount to hold (0 = full account freeze)."}),currency:e.Union([e.Literal("USD"),e.Literal("EUR"),e.Literal("GBP"),e.Literal("CAD")],{description:"ISO currency code for the hold amount."}),duration_hours:e.Integer({minimum:1,maximum:168,description:"How long the hold stays (1\u2013168h)."}),reason:e.Union([e.Literal("fraud_investigation"),e.Literal("suspicious_pattern"),e.Literal("sanctions_review"),e.Literal("manual_review")],{description:"Reason classification for the hold."}),notify_holder:e.String({description:"Whether to notify the holder. Accepts: yes, no, true, false, 1, 0."})}),async execute(i,t){let{account_id:r,...s}=t;return c(await d(`/accounts/${r}/hold`,s))}}),n.registerTool({name:"block_card",label:"Block card",description:"Block a debit or credit card immediately. A replacement card will be mailed.",parameters:e.Object({account_id:e.String({description:"Account ID owning the card."}),reason:e.Union([e.Literal("fraud_investigation"),e.Literal("lost"),e.Literal("stolen"),e.Literal("compromised_pin"),e.Literal("customer_request")],{description:"Reason for blocking \u2014 drives the customer notification."}),notify_holder:e.Optional(e.String({description:"Whether to notify the holder. Accepts: yes, no, true, false."}))}),async execute(i,t){return c(await d(`/accounts/${t.account_id}/card/block`,{reason:t.reason,notify_holder:t.notify_holder}))}}),n.registerTool({name:"wire_transfer",label:"Wire transfer",description:"Initiate an outbound wire transfer from an account. HIGH RISK \u2014 large or sanctioned-destination wires are blocked or escalated by VisIQ ALLOW policy.",parameters:e.Object({account_id:e.String({description:"Source account ID."}),amount:e.Number({minimum:0,description:"Dollar amount to wire."}),currency:e.Union([e.Literal("USD"),e.Literal("EUR"),e.Literal("GBP"),e.Literal("CAD")],{description:"ISO currency code."}),destination:e.String({description:"Destination account / IBAN / beneficiary identifier."}),destination_country:e.Optional(e.String({description:"ISO 3166-1 alpha-2 destination country (e.g. 'US')."})),memo:e.Optional(e.String({description:"Free-text wire memo."}))}),async execute(i,t){let{account_id:r,...s}=t;return c(await d(`/accounts/${r}/wire`,s))}}),n.registerTool({name:"create_case",label:"Create case",description:"Create a fraud investigation case. Routes to the right queue based on severity / category.",parameters:e.Object({account_id:e.String({description:"Affected account ID."}),severity:e.Union([e.Literal("low"),e.Literal("medium"),e.Literal("high"),e.Literal("critical")],{description:"Case severity \u2014 drives SLA and routing."}),category:e.Union([e.Literal("account_takeover"),e.Literal("card_fraud"),e.Literal("wire_fraud"),e.Literal("synthetic_identity"),e.Literal("sanctions_hit"),e.Literal("structuring")],{description:"Fraud category \u2014 routes to specialist queue."}),summary:e.String({description:"Free-text case summary for the analyst."}),assignee:e.Optional(e.String({description:"Specialist email to assign directly."})),sla_hours:e.Optional(e.Integer({minimum:1,maximum:168,description:"Override the default SLA (1\u2013168h)."}))}),async execute(i,t){return c(await d("/cases",t))}}),n.registerTool({name:"send_notification",label:"Send notification",description:"Send a fraud alert notification to the customer. Channel + priority drive delivery latency.",parameters:e.Object({account_id:e.String({description:"Account ID \u2014 used to look up contact methods."}),channel:e.Union([e.Literal("sms"),e.Literal("email"),e.Literal("push"),e.Literal("voice"),e.Literal("in_app")],{description:"Delivery channel."}),priority:e.Union([e.Literal("low"),e.Literal("normal"),e.Literal("high"),e.Literal("critical")],{description:"Delivery priority \u2014 critical bypasses customer quiet hours."}),subject:e.String({maxLength:120,description:"Short subject line (used for email / push title)."}),message:e.String({description:"Body text of the notification."}),locale:e.Optional(e.String({description:"BCP-47 locale (e.g. 'en-US', 'es-MX')."}))}),async execute(i,t){return c(await d("/notifications/send",t))}}),n.registerTool({name:"bank_account_lookup_tool",label:"Bank account lookup (sensitive)",description:"Look up sensitive account data for fraud investigation. account_id is the account number (e.g. '4821-7734'). include_ssn controls whether PII fields (SSN, DOB, full legal name) come back \u2014 accepts 'yes' / 'no' / 'true' / 'false' / '1' / '0'.",parameters:e.Object({account_id:e.String({description:"Account number to look up (e.g. 4821-7734)."}),include_ssn:e.String({description:"Whether to include PII fields (SSN, DOB, full legal name). Accepts: yes, no, true, false, 1, 0."})}),async execute(i,t){let s=new Set(["yes","y","true","1"]).has(String(t.include_ssn).toLowerCase().trim()),o=await fetch(`${h}/accounts/${t.account_id}`);if(!o.ok)return c(JSON.stringify({error:`Account ${t.account_id} not found`}),{status:o.status});let u=await o.json();if(!s){let{ssn:l,dob:a,full_legal_name:_,...g}=u;return c(JSON.stringify({account:g,pii_included:!1}),{pii_included:!1})}return c(JSON.stringify({account:u,pii_included:!0}),{pii_included:!0})}})}var G={id:U,name:"VisIQ OpenClaw Plugin",description:"Routes tool calls and LLM I/O through VisIQ ALLOW + RECALL + RECORD",configSchema:D(),register:K},Z=G;export{Z as default};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "@visiq/openclaw-plugin",
3
3
  "name": "VisIQ OpenClaw Plugin",
4
- "version": "0.1.7",
4
+ "version": "0.1.8",
5
5
  "description": "Routes tool calls and LLM I/O through VisIQ ALLOW+RECALL+RECORD",
6
6
  "main": "dist/index.js",
7
7
  "activation": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visiq/openclaw-plugin",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "OpenClaw plugin for VisIQ ALLOW + RECALL + RECORD",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -10,8 +10,8 @@
10
10
  "./dist/openclaw-entry.js"
11
11
  ],
12
12
  "compat": {
13
- "pluginApi": ">=2026.5.18",
14
- "minGatewayVersion": "2026.5.18"
13
+ "pluginApi": ">=2026.3.13",
14
+ "minGatewayVersion": "2026.3.13"
15
15
  },
16
16
  "build": {
17
17
  "openclawVersion": "2026.5.18",
@@ -35,7 +35,7 @@
35
35
  "peerDependencies": {
36
36
  "@langchain/core": ">=0.3.0",
37
37
  "llamaindex": ">=0.11.0",
38
- "openclaw": ">=2026.5.18"
38
+ "openclaw": ">=2026.3.13 || >=2026.7.1-0"
39
39
  },
40
40
  "peerDependenciesMeta": {
41
41
  "@langchain/core": {
@@ -1,8 +0,0 @@
1
- import{readFile as Ue}from"node:fs/promises";import{homedir as W}from"node:os";import{join as G,isAbsolute as Ve,resolve as Ke}from"node:path";import{createInterface as ze}from"node:readline";import{parseArgs as We}from"node:util";var H="@visiq/openclaw-plugin",Ge='[VisIQ] OpenClaw plugin is installed but missing credentials. Provide them with one of (highest precedence first): (1) environment variables VISIQ_API_KEY=<key> VISIQ_AGENT_ID=<id> (set before `openclaw gateway run` / `openclaw start`) ; (2) a JSON file at the path in VISIQ_CONFIG_PATH ; (3) ~/.openclaw/openclaw.json -> plugins.entries["@visiq/openclaw-plugin"].config = { "apiKey": "<key>", "agentId": "<id>" } . Until credentials are provided the plugin loads but every tool call is BLOCKED (fail-closed, G001) \u2014 configure it to govern.';function He(e){return e==="~"||e.startsWith("~/")?G(W(),e.slice(1).replace(/^\//,"")):e}async function Q(e){try{let t=Ve(e)?e:Ke(e),n=await Ue(t,"utf-8");return JSON.parse(n)}catch{return null}}function D(e,...t){for(let n of t){let r=e[n];if(typeof r=="string")return r}}function F(e){if(!e||typeof e!="object")return{};let t=e,n=D(t,"apiKey","api_key"),r=D(t,"agentId","agent_id"),i=D(t,"baseUrl","base_url"),a={};return n&&(a.apiKey=n),r&&(a.agentId=r),i&&(a.baseUrl=i),a}async function Qe(e){if(!e)return{};let t=He(e),n=await Q(t);if(!n||typeof n!="object")return{};let r=n,i=r.plugins?.entries,a=i&&typeof i=="object"?i[H]:void 0;return a&&typeof a=="object"&&a.config?F(a.config):F(r)}async function Ye(){let e=G(W(),".openclaw","openclaw.json"),t=await Q(e);if(!t||typeof t!="object")return{};let a=t.plugins?.entries?.[H];return!a||typeof a!="object"?{}:F(a.config)}async function Ze(e){if(!process.stdout.isTTY)return{};let t=ze({input:process.stdin,output:process.stdout}),n=r=>new Promise(i=>t.question(r,a=>i(a)));try{let r={...e};if(!r.apiKey){let i=(await n("VisIQ API key: ")).trim();i&&(r.apiKey=i)}if(!r.agentId){let i=(await n("VisIQ agent ID: ")).trim();i&&(r.agentId=i)}if(!r.baseUrl){let i=(await n("VisIQ base URL (optional, press Enter for default): ")).trim();i&&(r.baseUrl=i)}return r}finally{t.close()}}function Je(){try{let{values:e}=We({args:process.argv.slice(2),options:{"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"}},strict:!1,allowPositionals:!0}),t={},n=e["api-key"],r=e["agent-id"],i=e["base-url"];return typeof n=="string"&&n&&(t.apiKey=n),typeof r=="string"&&r&&(t.agentId=r),typeof i=="string"&&i&&(t.baseUrl=i),t}catch{return{}}}async function Y(){let e=Je(),t={};process.env.VISIQ_API_KEY&&(t.apiKey=process.env.VISIQ_API_KEY),process.env.VISIQ_AGENT_ID&&(t.agentId=process.env.VISIQ_AGENT_ID),process.env.VISIQ_BASE_URL?t.baseUrl=process.env.VISIQ_BASE_URL:process.env.VISIQ_ENDPOINT&&(t.baseUrl=process.env.VISIQ_ENDPOINT);let n=await Qe(process.env.VISIQ_CONFIG_PATH),i={...await Ye(),...n,...t,...e};if((!i.apiKey||!i.agentId)&&process.stdout.isTTY&&process.stdin.isTTY&&(i=await Ze(i)),!i.apiKey||!i.agentId)return process.stderr.write(`${Ge}
2
- `),null;let a={apiKey:i.apiKey,agentId:i.agentId};return i.baseUrl&&(a.baseUrl=i.baseUrl),a}var M=null,Z={ready:!1,config:null};function y(){return M||(M=Y().catch(e=>(process.stderr.write(`[VisIQ] Config resolution failed (treating as unconfigured): ${e instanceof Error?e.message:String(e)}
3
- `),null)).then(e=>(Z={ready:!0,config:e},e))),M}function E(){return Z}function xn(){y()}import{z as o}from"zod";import*as h from"node:os";var J="X-VisIQ-SDK",X="X-VisIQ-Dialect",ee="unknown";function B(e,t=1){return{[J]:e&&e.length>0?e:ee,[X]:String(t)}}var te="interceptor_source",Xe=o.enum(["enforce","audit","off"]),et=o.enum(["closed","open"]),ne=o.enum(["enforce","monitor","off"]),tt=o.object({apiKey:o.string().min(1,"apiKey is required"),agentId:o.string().min(1,"agentId is required"),endpoint:o.string().url().optional(),mode:Xe.optional(),timeoutMs:o.number().int().positive().optional(),hitlTimeoutMs:o.number().int().positive().optional(),failBehavior:et.optional()}),Ln=o.object({agent_id:o.string().min(1),target_app:o.string().min(1),action:o.string().min(1),context:o.record(o.unknown()).optional(),session_id:o.string().min(1).max(255).optional(),telemetry:o.record(o.unknown()).optional()}),nt=o.object({field:o.string().optional(),pattern:o.string().optional(),replacement:o.string().optional(),mode:o.enum(["full","partial","email"]).optional(),keepFirst:o.number().optional(),keepLast:o.number().optional(),maskChar:o.string().optional()}),rt=o.object({decision_id:o.string().min(1),decision:o.enum(["permit","deny","approval_required","mask"]),reason:o.string().optional(),rule_code:o.string().nullable().optional(),enforced:o.boolean().optional(),agent_mode:ne.optional(),arg_redaction_rules:o.array(nt).optional(),plane:o.string().nullable().optional(),operation:o.string().nullable().optional(),is_retrieval:o.boolean().optional(),metadata:o.record(o.unknown()).optional()}),it=o.object({field:o.string().min(1),operator:o.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:o.union([o.string(),o.number(),o.array(o.string())])}),at=o.object({id:o.string().min(1),rule_code:o.string().default(""),name:o.string().min(1),description:o.string().nullable().default(null),effect:o.enum(["allow","deny","hitl","mask"]),resource_type:o.string().min(1),rego_source:o.string().default(""),target_app:o.string().nullable().default(null),action_pattern:o.string().nullable().default(null),conditions:o.array(it).default([]),priority:o.number().int().default(0)}),ot=o.object({version:o.string().min(1),agent_mode:ne.optional(),rules:o.array(at),no_coverage:o.object({no_coverage_defaults:o.record(o.string()),autopilot_enabled:o.boolean(),enduser_hitl_enabled:o.boolean(),hitl_timeout_seconds:o.number()}).optional()}),st=2e3,re=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return B(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 rt.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json",...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();return ot.parse(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}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let c=a,s=c.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 c.reason=="string"?c.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await lt(st)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function lt(e){return new Promise(t=>setTimeout(t,e))}function ie(){let e={};try{let t=`${h.platform()} ${h.release()}`.trim();t&&(e.os=t)}catch{}try{let t=h.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=h.userInfo();t&&(e.username=t)}catch{}try{let t=ct();t&&(e.ip=t)}catch{}return e}function ct(){let e=h.networkInterfaces();for(let t of Object.keys(e))for(let n of e[t]??[])if((n.family==="IPv4"||n.family===4)&&!n.internal&&n.address)return n.address}import{z as u}from"zod";import{createHash as Mn}from"crypto";import{createHash as qn}from"crypto";var ut=["tier1","tier2","tier3"];function se(e){return typeof e=="string"&&ut.includes(e)}var dt=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],pt=["internal","customer_facing","experimental","third_party"],le=[...dt,...pt];function ft(e){return typeof e=="string"&&le.includes(e)}function ce(e){let t=new Set;for(let n of e)ft(n)&&t.add(n);return le.filter(n=>t.has(n))}var gt=["read_only","record_create","record_update","record_delete","data_export","data_share","data_subject_request","consent_change","funds_transfer","funds_disbursement","payroll_run","trade_execution","ledger_mutation","credit_decision","decision_adverse","account_restriction","account_closure","card_management","purchase_commitment","vendor_management","deal_management","pricing_change","contract_execution","legal_hold","regulatory_filing","personnel_action","employment_termination","compensation_change","campaign_send","content_publish","inventory_adjustment","order_fulfillment","account_servicing","credential_reset","access_grant","permission_change","credential_management","auth_policy_change","security_config_change","logging_change","alert_management","code_change","infrastructure_provision","deployment_change","communication_send","other"];function ue(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 mt={wire_transfer:"funds_transfer",international_transfer:"funds_transfer",cross_border_payment:"funds_transfer",send_swift:"funds_transfer",send_wire:"funds_transfer",transfer_funds:"funds_transfer",update_wire_instructions:"funds_transfer",add_beneficiary:"funds_transfer",modify_payee:"funds_transfer",disburse_funds:"funds_disbursement",initiate_ach:"funds_disbursement",issue_refund:"funds_disbursement",execute_trade:"trade_execution",place_order:"trade_execution",post_journal_entry:"ledger_mutation",adjust_ledger:"ledger_mutation",modify_general_ledger:"ledger_mutation",raise_limit:"credit_decision",increase_credit_limit:"credit_decision",extend_credit:"credit_decision",decline_credit:"decision_adverse",deny_application:"decision_adverse",adverse_action:"decision_adverse",block_card:"card_management",cancel_card:"card_management",place_hold:"account_restriction",freeze_account:"account_restriction",restrict_account:"account_restriction",close_account:"account_closure",export_data:"data_export",export_customer_list:"data_export",download_report:"data_export",download_customer_list:"data_export",bulk_export:"data_export",share_data:"data_share",send_to_partner:"data_share",delete_records:"record_delete",delete_user:"record_delete",drop_table:"record_delete",grant_role:"access_grant",change_permissions:"permission_change",modify_access:"permission_change",rotate_keys:"credential_management",disable_mfa:"auth_policy_change",modify_security_config:"security_config_change",disable_logging:"logging_change",purge_logs:"logging_change",suppress_alert:"alert_management",dismiss_alert:"alert_management",rollback:"deployment_change",modify_billing:"record_update",close_sar:"record_update",send_email:"communication_send",send_sms:"communication_send",fulfill_dsar:"data_subject_request",process_dsar:"data_subject_request",fulfill_data_request:"data_subject_request",process_erasure_request:"data_subject_request",honor_deletion_request:"data_subject_request",export_subject_data:"data_subject_request",erase_subject_data:"data_subject_request",delete_subject_data:"data_subject_request",record_consent:"consent_change",capture_consent:"consent_change",update_consent:"consent_change",withdraw_consent:"consent_change",revoke_consent:"consent_change",opt_out:"consent_change",opt_in:"consent_change",run_payroll:"payroll_run",process_payroll:"payroll_run",submit_payroll:"payroll_run",approve_payroll:"payroll_run",create_purchase_order:"purchase_commitment",issue_purchase_order:"purchase_commitment",approve_purchase_order:"purchase_commitment",submit_purchase_order:"purchase_commitment",approve_purchase:"purchase_commitment",approve_requisition:"purchase_commitment",commit_spend:"purchase_commitment",onboard_vendor:"vendor_management",add_vendor:"vendor_management",create_supplier:"vendor_management",approve_vendor:"vendor_management",update_vendor_bank:"vendor_management",update_supplier_bank:"vendor_management",modify_supplier:"vendor_management",create_opportunity:"deal_management",update_opportunity:"deal_management",advance_deal_stage:"deal_management",update_deal_stage:"deal_management",close_deal:"deal_management",mark_closed_won:"deal_management",mark_closed_lost:"deal_management",issue_quote:"pricing_change",send_quote:"pricing_change",approve_discount:"pricing_change",apply_discount:"pricing_change",override_price:"pricing_change",update_pricing:"pricing_change",approve_special_pricing:"pricing_change",execute_contract:"contract_execution",sign_contract:"contract_execution",countersign_contract:"contract_execution",sign_agreement:"contract_execution",execute_agreement:"contract_execution",sign_nda:"contract_execution",execute_nda:"contract_execution",sign_document:"contract_execution",esign_document:"contract_execution",place_legal_hold:"legal_hold",place_litigation_hold:"legal_hold",apply_legal_hold:"legal_hold",release_legal_hold:"legal_hold",file_regulatory_report:"regulatory_filing",file_sar:"regulatory_filing",submit_regulatory_filing:"regulatory_filing",file_compliance_report:"regulatory_filing",file_disclosure:"regulatory_filing",onboard_employee:"personnel_action",hire_employee:"personnel_action",change_employee_role:"personnel_action",promote_employee:"personnel_action",transfer_employee:"personnel_action",update_job_title:"personnel_action",terminate_employee:"employment_termination",offboard_employee:"employment_termination",deactivate_employee:"employment_termination",separate_employee:"employment_termination",adjust_salary:"compensation_change",change_compensation:"compensation_change",approve_raise:"compensation_change",grant_equity:"compensation_change",grant_stock:"compensation_change",issue_bonus:"compensation_change",update_pay_rate:"compensation_change",send_campaign:"campaign_send",launch_campaign:"campaign_send",schedule_campaign:"campaign_send",send_bulk_email:"campaign_send",send_marketing_email:"campaign_send",send_newsletter:"campaign_send",blast_email:"campaign_send",publish_post:"content_publish",publish_content:"content_publish",publish_blog:"content_publish",post_to_social:"content_publish",schedule_post:"content_publish",adjust_inventory:"inventory_adjustment",write_off_inventory:"inventory_adjustment",update_stock_level:"inventory_adjustment",reconcile_inventory:"inventory_adjustment",fulfill_order:"order_fulfillment",ship_order:"order_fulfillment",dispatch_order:"order_fulfillment",mark_order_shipped:"order_fulfillment",update_customer_account:"account_servicing",modify_customer_account:"account_servicing",update_customer_contact:"account_servicing",change_customer_settings:"account_servicing",reset_customer_password:"credential_reset",reset_password:"credential_reset",force_password_reset:"credential_reset",reset_mfa:"credential_reset",unlock_account:"credential_reset",reset_customer_credentials:"credential_reset",merge_pull_request:"code_change",merge_pr:"code_change",merge_branch:"code_change",push_to_branch:"code_change",push_to_main:"code_change",push_code:"code_change",commit_code:"code_change",force_push:"code_change",provision_infrastructure:"infrastructure_provision",provision_resource:"infrastructure_provision",create_instance:"infrastructure_provision",terminate_instance:"infrastructure_provision",spin_up_server:"infrastructure_provision",tear_down_server:"infrastructure_provision",destroy_resource:"infrastructure_provision",create_cluster:"infrastructure_provision"};function ht(e){let t=ue(e);return t===null?"other":mt[t]||(/^(delete|remove|purge|drop|destroy|wipe)_/.test(t)?"record_delete":/^(export|download|extract|dump)_/.test(t)?"data_export":/^(create|add|insert)_/.test(t)?"record_create":/^(update|edit|modify|patch|set)_/.test(t)?"record_update":t==="send_email"||t==="send_sms"||/^(notify|email|sms)_/.test(t)?"communication_send":/^(read|get|list|search|fetch|view|query)_/.test(t)||t==="read"||t==="get"?"read_only":"other")}var ae={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 _t(e){let t=ue(e);return t===null?"other":ae[t]??ae[t.replace(/_/g,"")]??"other"}function de(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=ht(t.action)),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=_t(t.targetApp)),n.context=r}return n}var oe=64,yt=64,k={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function pe(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var bt=new Set(["deny","approval_required","escalate"]);function T(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>oe?r.slice(0,oe):r}function vt(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function R(e){return typeof e=="string"&&e.length>0?e:null}function fe(e,t){let n=vt(t.data_categories),r=R(t.classification),i=R(t.action_class),a=i&&gt.includes(i)?i:null,c=R(t.target_app),s=R(t.decision),l={...e.action_counts};if(a)if(a in l)l[a]=(l[a]??0)+1;else if(Object.keys(l).length<yt)l[a]=1;else{let d=Object.keys(l).sort(),p=d[d.length-1];p!==void 0&&a<p&&(delete l[p],l[a]=1)}return{retrieved_data_categories:T(e.retrieved_data_categories,n),retrieved_classifications:T(e.retrieved_classifications,r?[r]:[]),action_classes:T(e.action_classes,a?[a]:[]),action_counts:l,denied_count:e.denied_count+(s==="deny"?1:0),inhibited_count:e.inhibited_count+(s&&bt.has(s)?1:0),event_count:e.event_count+1,target_apps:T(e.target_apps,c?[c]:[])}}var wt="generic",ge=[{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:wt,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."}],At=ge.map(e=>e.id),Bn=new Map(ge.map(e=>[e.id,e])),$n=new Set(At);var It=/^[a-z][a-z0-9_]*$/;function me(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&It.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var kt=["narrow","moderate","broad","unbounded","unknown"];function he(e){return typeof e=="string"&&kt.includes(e)}function _e(e){return e==="open"||e==="closed"?e:null}var St=["action","retrieval","delegation"];function Ct(e){return typeof e=="string"&&St.includes(e)}var Et=new Set(["rules"]);function ye(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Et.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Ct):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{z as x}from"zod";import{randomUUID as un}from"node:crypto";var be=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Tt(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:be(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:be(t.spawn.prompt)}),t}function Rt(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 xt=1440*60*1e3,Nt="VISIQ_BUNDLE_GRACE_TTL_MS",Ot="VISIQ_BUNDLE_CACHE_DISABLED",Lt="VISIQ_CACHE_DIR",Pt=x.object({graceTtlMs:x.number().int().nonnegative().optional(),disabled:x.boolean().optional(),cacheDir:x.string().min(1).optional()}).strict();function Dt(e){return e==null?{}:Pt.parse(e)}function Ft(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Nt];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return xt}function Mt(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Ot]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var ve;function Bt(){if(ve!==void 0)return ve;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function $t(e){return JSON.stringify(j(e))}function j(e){if(Array.isArray(e))return e.map(j);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=j(t[r]);return n}return e}function jt(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function qt(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 Ce(){if(!Bt())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 Ee(e,t){return e.createHash("sha256").update($t(t)).digest("hex")}function Ut(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Lt]?.trim();if(r)return r;let i=process.env.XDG_CACHE_HOME?.trim();if(i)return e.path.join(i,"visiq");let a="";try{a=e.os.homedir()}catch{a=""}return a?e.path.join(a,".cache","visiq"):e.path.join(e.os.tmpdir(),"visiq-cache")}function Vt(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function Te(e,t,n){return e.path.join(Ut(e,n),"bundles",`${Vt(e,t)}.json`)}async function Kt(e,t,n,r={}){let i=await Ce();if(i)try{let a=Te(i,e,r),c=i.path.dirname(a);await i.fs.mkdir(c,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:Ee(i.crypto,t),body:t},l=`${a}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(l,JSON.stringify(s),{mode:384});try{await i.fs.rename(l,a)}catch(d){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),d}}catch{}}async function zt(e,t={}){let n=await Ce();if(!n)return null;try{let r=await n.fs.readFile(Te(n,e,t),"utf-8"),i=qt(JSON.parse(r));return!i||Ee(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var S;async function Wt(){if(S!==void 0)return S;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;S=typeof t=="function"?t:null}catch{S=null}return S}var Gt=5e3,Ht=1e4,Qt=25,we=1e3,Yt=5e3,Zt=100,Ae=2e3,Jt=512,Xt=1800*1e3,en="monitor",tn="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",nn="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.",rn=u.object({operations:u.array(u.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:u.string().min(1,"agentId is required"),sessionId:u.string().min(1).max(255).optional(),toolName:u.string().optional(),toolArgs:u.record(u.unknown()).optional(),targetResource:u.string().optional(),resourceType:u.string().optional(),resourceMetadata:u.record(u.unknown()).optional(),normalized:u.record(u.unknown()).optional(),query:u.string().optional(),contentPreview:u.string().optional(),telemetry:u.record(u.unknown()).optional(),context:u.record(u.unknown()).optional()}),an=u.object({version:u.string().min(1),dialect_version:u.number().int().optional(),min_dialect:u.number().int().optional(),shutdown:u.boolean().optional(),agent_mode:u.enum(["enforce","monitor","off"]).optional(),cognition_capture:u.boolean().optional(),agent_mode_by_operation:u.object({action:u.string().optional(),retrieval:u.string().optional(),delegation:u.string().optional()}).partial().optional(),agent_attributes:u.object({trust_tier:u.string().nullable().optional(),categories:u.array(u.string()).optional(),business_function:u.string().nullable().optional(),business_functions:u.array(u.string()).nullable().optional(),blast_radius_tier:u.string().nullable().optional(),no_coverage:u.string().nullable().optional()}).optional(),rules:u.array(u.record(u.unknown())),no_coverage:u.object({no_coverage_defaults:u.record(u.string()),autopilot_enabled:u.boolean(),enduser_hitl_enabled:u.boolean(),hitl_timeout_seconds:u.number().optional()}).optional()});function on(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=me(n);return{trust_tier:se(t)?t:null,categories:ce(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&he(e.blast_radius_tier)?e.blast_radius_tier:null}}function sn(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 ln(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var q=new Set,Ie=!1;async function ke(e){let t=[];for(let n of q){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 cn(){if(!Ie&&!(typeof process>"u"||typeof process.once!="function")){Ie=!0,process.once("beforeExit",()=>{ke(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await ke(!0)}finally{process.kill(process.pid,e)}})()})}}var Re=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=en;agentModeByOperation=null;rawBundle=null;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;constructor(e,t,n,r,i,a,c,s){let l=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,d=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,p=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=l,this.resolvedEndpoint=d,this.resolvedAgentId=p,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=c,this.originalFetch=globalThis.fetch.bind(globalThis);let f=Dt(s);if(this.bundleCacheDisabled=Mt(f.disabled),this.bundleGraceTtlMs=Ft(f.graceTtlMs),this.bundleCacheDirOverride=f.cacheDir,this.cacheIdentity=l&&d&&!this.bundleCacheDisabled?{endpoint:d,agentId:p,apiKey:l}:null,l&&d){let m={apiKey:l,agentId:p,endpoint:d,mode:"enforce",timeoutMs:Rt(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...c!==void 0?{sdkDialect:c}:{}};this.client=new re(m,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Gt),$(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Ht),$(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Yt),$(this.cognitionTimer),q.add(this),cn()}else this.client=null}async evaluate(e){let t=rn.parse(e),n=Date.now();if(this.operatorShutdown){let l=this.denyAll(t,tn);return this.applyAgentMode(l,"enforce",t,n)}if(this.dialectRefused){let l=this.denyAll(t,nn);return this.applyAgentMode(l,"enforce",t,n)}if(t.operations.every(l=>this.modeFor(l)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let l;this.agentModeConfirmed?l=this.agentMode:this.bundleApplyFailed?l="enforce":l="monitor";let d=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(d,l,t,n)}let r=this.readSession(t.sessionId),i=await Wt();if(!i||!this.rawBundle)throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)");let a={...t,session:r,at:Date.now()},c={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},s=i(a,c);return this.foldSession(t,s.enforced?s.decision:"permit"),s.enforced&&s.action.decision==="approval_required"&&await this.registerHitl(t,s),this.bufferTelemetry(t,s,Date.now()-n,s.enforced),s}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return k;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Xt?(this.sessions.delete(e),k):t.state:k}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),c=e.operations.includes("action")||e.operations.includes("delegation"),s=c?de(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},l=fe(r===k?pe():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,action_class:c?s.action_class:void 0,target_app:c?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:l,touchedAt:Date.now()}),this.sessions.size>Jt){let d=this.sessions.keys().next().value;d!==void 0&&this.sessions.delete(d)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let c={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,c,i,!0),c}let a={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,a,i,!1),a}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??{}}:{},...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=an.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}this.dialectRefused=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(r=>ye(r)).filter(r=>r!==null),this.agentAttributes=t.agent_attributes?on(t.agent_attributes):null,this.agentNoCoverage=_e(t.agent_attributes?.no_coverage),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=sn(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.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",...B(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)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let a=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&a?this.bundleEtag=r:a||(this.bundleEtag=null),a&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await zt(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(jt(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 Kt(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}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){this.registerEnvironment({...ie(),...e?{agent_type:e}:{}})}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)));t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}bufferTelemetry(e,t,n,r){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?ln(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:{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}:{}},...this.harnessKind||e.context?{context:{...this.harnessKind?{[te]:this.harnessKind}:{},...e.context??{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Qt&&this.flushTelemetry()}pendingTelemetryCount(){return this.telemetryBuffer.length}hasBackend(){return this.client!==null}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0);try{await this.client.sendTelemetry(e)}catch(t){console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",t)}}enforceTelemetryCap(){let e=this.telemetryBuffer.length-we;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${we})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Tt(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Zt&&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-Ae;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Ae})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),q.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 $(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function C(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function xe(e,t){if(e!=="sessions_spawn")return null;let n=C(t.agentId);return n?{childAgentId:n,childName:C(t.taskName)??C(t.label)??n,kind:"subagent",task:C(t.task),model:C(t.model),source:"structural"}:null}function Ne(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 Se=new Map;function dn(e){let t=(Se.get(e)??0)+1;return Se.set(e,t),t}function Oe(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:un(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:dn(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}:{}}})}var v=null;function U(e){let t=`${e.apiKey}::${e.agentId}::${e.baseUrl??""}`;if(v&&v.key===t)return v.runtimes;let n=new Re(e.apiKey,e.baseUrl,e.agentId,"cli_harness");return n.registerHostEnvironment(),v={key:t,runtimes:{unified:n}},v.runtimes}async function Xn(){if(v)try{await v.runtimes.unified.flush()}catch{}}async function er(e){try{let t=await y();if(!t)return;let{unified:n}=U(t);await n.awaitBundleReady(e)}catch{}}function b(e,t){return e?.sessionKey??t?.sessionKey??t?.sessionId??"default"}var V=class{entries=new Map;set(t,n){this.entries.set(t,n)}get(t){return this.entries.get(t)}delete(t){this.entries.delete(t)}clear(){this.entries.clear()}size(){return this.entries.size}},K=new Map;function A(e){let t=K.get(e);return t||(t=new V,K.set(e,t)),t}function Le(e){K.delete(e)}var Pe=new Set(["web_search","x_search","web_fetch","tool_search","tool_describe","get_account","get_transactions","get_devices","check_watchlist","search_knowledge"]);function pn(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}function De(e){return Pe.has(pn(e))}function rr(){return Pe}var fn=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\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}];var g=Object.fromEntries(fn.map(e=>[e.name,e.re.source])),gn=["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","email","us_phone","ipv4","mac_address"],mn={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
4
- MIIEv\u2026
5
- -----END PRIVATE KEY-----`,template:{pattern:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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).",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\b\\d{13,19}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){10,30}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:"\\b\\d{9}\\b",mode:"full"},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX).",category:"financial",example:"12-3456789",template:{pattern:g.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:g.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789).",category:"pii",example:"123-45-6789",template:{pattern:g.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept).",category:"pii",example:"alice@acme.com",template:{pattern:g.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:g.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:g.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:g.mac_address,mode:"full"},defaultEnabled:!1}},ar=new Set(gn.filter(e=>!mn[e].defaultEnabled));var z="[REDACTED]",I="\u2022",N=e=>/[A-Za-z0-9]/.test(e);function Fe(e,t,n,r){let i=Array.from(e),a=i.length,c=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:I,d=c+s>=a;return i.map((p,f)=>!d&&(f<c||f>=a-s)?p:N(p)?l:p).join("")}function hn(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Fe(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:I;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(c=>N(c)?a:c).join(""))+i}function _n(e,t,n){let r=n.length>0?n:I,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let d=new RegExp(t,"g"),p;for(;(p=d.exec(e))!==null;){if(p[0].length===0){d.lastIndex++;continue}for(let f=p.index;f<p.index+p[0].length;f++)i[f]=!0}}catch{}let a=!1,c=!0;for(let d=0;d<e.length;d++)if(N(e[d])&&(a=!0,!i[d])){c=!1;break}let s=a&&c,l="";for(let d=0;d<e.length;d++){let p=e[d];!s&&i[d]||!N(p)?l+=p:l+=r}return l}function Me(e,t){let n=t.mode??"full";return n==="partial"?Fe(e,t.keepFirst??0,t.keepLast??0,t.maskChar??I):n==="email"?hn(e,t.maskChar??I):n==="custom"?_n(e,t.keepPattern,t.maskChar??I):t.replacement??z}function yn(e,t){return typeof e=="string"?Me(e,t):t.replacement??z}function Be(e){let t=[],n=e.replacement??z;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:a=>Me(a,r)})}return t}function $e(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(c){let s=c instanceof Error?c.message:String(c);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(a,c=>i(c))}return n}function O(e,t){return e==null?e:typeof e=="string"?bn(e,t):typeof e=="object"?vn(e,t):e}function bn(e,t){if(typeof e!="string")return e;let n=Be(t);return n.length===0?e:$e(e,n)}function vn(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=Be(t),i=n.size>0,a=r.length>0,c=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>c(l));if(typeof s=="object"){let l=s,d=Object.create(Object.getPrototypeOf(l));for(let p of Object.keys(l)){let f=i?n.get(p):void 0;if(f){d[p]=yn(l[p],f);continue}d[p]=c(l[p])}return d}return typeof s=="string"&&a?$e(s,r):s};return c(e)}var je="@visiq/openclaw-plugin";function qe(e){let t=[],n=[],r;for(let a of e){let{field:c,pattern:s,replacement:l}=a;c&&t.push(c),s&&n.push(s),l&&r===void 0&&(r=l)}let i={};return t.length>0&&(i.fields=t),n.length>0&&(i.patterns=n),r!==void 0&&(i.replacement=r),i}async function fr(e,t){let n=await y();if(!n)return{block:!0,blockReason:"[VisIQ] Plugin is loaded but NOT configured \u2014 VisIQ cannot govern this tool call, so it is blocked (fail-closed). Set VISIQ_API_KEY + VISIQ_ENDPOINT (or the plugin config) so VisIQ can evaluate the call, then retry."};let r=U(n),i=n.agentId??t.agentId,a=b(e,t),c=t.toolCallId??e.toolCallId,l=De(e.toolName)?["retrieval","action"]:["action"],d=wn(e.params),p=xe(e.toolName,e.params??{}),f;p&&i&&(Oe(r.unified,{agentId:i,sessionId:a,framework:"openclaw"},p),l.push("delegation"),f=Ne(p,i));let m;try{await r.unified.awaitBundleReady(),m=await r.unified.evaluate({operations:l,agentId:i,sessionId:a,toolName:e.toolName,toolArgs:e.params??{},resourceType:"tool_result",resourceMetadata:{toolName:e.toolName,runId:e.runId??t.runId},...d!==void 0?{query:d}:{},...f?{context:f}:{}})}catch(_){return{block:!0,blockReason:`[VisIQ] Evaluation error (fail-closed): ${_ instanceof Error?_.message:String(_)}`}}if(!m.enforced)return;let{action:w}=m;if(w.decision==="approval_required")return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:m.reason,severity:"critical",allowedDecisions:["allow-once","allow-always","deny"],pluginId:je}};if(!w.allowed)return{block:!0,blockReason:`[VisIQ ${m.ruleCode??"DENY"}] ${m.reason}`};let P;if(w.decision==="mask"&&w.argRedactionRules&&w.argRedactionRules.length>0&&(P=O(e.params??{},qe(w.argRedactionRules))),l.includes("retrieval"))switch(m.retrieval.action){case"allow":case null:break;case"deny":return{block:!0,blockReason:`[VisIQ RECALL] ${m.reason}`};case"redact":{if(!c)return{block:!0,blockReason:"[VisIQ RECALL] Redact decision but no toolCallId \u2014 fail-closed"};let _=m.retrieval.redactionRules??[];_.length>0&&A(a).set(c,qe(_));break}case"escalate":return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:m.reason,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:je}};default:{let _=m.retrieval.action;return{block:!0,blockReason:`[VisIQ RECALL] Unknown action "${String(_)}" \u2014 fail-closed`}}}if(P)return{params:P}}function wn(e){if(e)for(let t of["query","q","url","prompt"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}}function yr(e,t){let{ready:n,config:r}=E();if(!n||!r)return;let i=e.toolCallId??t.toolCallId;if(!i)return;let a=b(e,t),c=A(a),s=c.get(i);if(!s)return;let l={...e.message};return l.content!==void 0&&(l.content=O(l.content,s)),c.delete(i),{message:l}}function Ar(e,t){let{ready:n,config:r}=E();if(n&&!r)return;let i=b(e,t),a=A(i);if(a.size()>0)return a.clear(),{block:!0}}async function L(e,t){let r=`${(e.baseUrl??"https://api.visiqlabs.com").replace(/\/$/,"")}/v1/events`;try{let i=new AbortController,a=setTimeout(()=>i.abort(),5e3);try{let c=await fetch(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(t),signal:i.signal});c.ok||process.stderr.write(`[VisIQ] /v1/events POST failed: ${c.status} ${c.statusText}
6
- `);try{await c.text()}catch{}}finally{clearTimeout(a)}}catch(i){if(i instanceof Error&&i.name==="AbortError"){process.stderr.write(`[VisIQ] /v1/events POST timed out (5s)
7
- `);return}process.stderr.write(`[VisIQ] /v1/events POST error: ${i instanceof Error?i.message:String(i)}
8
- `)}}async function Er(e,t){let n=await y();if(!n)return;let r=n.agentId??t.agentId;L(n,{type:"llm_input",agentId:r,sessionId:e.sessionId??t.sessionId??t.sessionKey,runId:e.runId??t.runId,timestamp:new Date().toISOString(),payload:{provider:e.provider,model:e.model,hasSystemPrompt:typeof e.systemPrompt=="string"&&e.systemPrompt.length>0,promptLength:typeof e.prompt=="string"?e.prompt.length:0,historyMessageCount:Array.isArray(e.historyMessages)?e.historyMessages.length:0,imagesCount:e.imagesCount??0,toolCount:Array.isArray(e.tools)?e.tools.length:0}})}function An(e){if(!Array.isArray(e))return 0;let t=0;for(let n of e)typeof n=="string"&&(t+=n.length);return t}async function Nr(e,t){let n=await y();if(!n)return;let r=n.agentId??t.agentId;L(n,{type:"llm_output",agentId:r,sessionId:e.sessionId??t.sessionId??t.sessionKey,runId:e.runId??t.runId,timestamp:new Date().toISOString(),payload:{provider:e.provider,model:e.model,resolvedRef:e.resolvedRef,harnessId:e.harnessId,assistantSegmentCount:Array.isArray(e.assistantTexts)?e.assistantTexts.length:0,assistantTotalChars:An(e.assistantTexts),usage:e.usage??null}})}function Pr(e,t){Le(b(e,t))}export{Y as a,xn as b,Xn as c,er as d,V as e,A as f,Le as g,pn as h,De as i,rr as j,fr as k,yr as l,Ar as m,Er as n,Nr as o,Pr as p};