@visiq/claude-code-harness 0.1.7 → 0.1.9

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.
@@ -1,3 +1,3 @@
1
- import{c as I,i as k,j as b,k as T,l as x,m as E,n as v,o as R,p as C,q as N,s as D,t as q,u as F,v as V,w as A,x as f}from"./chunk-QGBH2FOQ.js";import{appendFile as J,mkdir as K}from"node:fs/promises";import{join as W}from"node:path";function G(){return W(I(),"fail-open.log")}async function a(e,t=!0){let o=`[VisIQ] FAIL-OPEN (${e.stage}): ${e.detail} \u2014 tool call proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`;try{process.stderr.write(`${o}
1
+ import{c as I,i as k,j as b,k as T,l as x,m as E,n as v,o as R,p as C,q as N,s as D,t as q,u as F,v as V,w as A,x as f}from"./chunk-L7EAYGFC.js";import{appendFile as J,mkdir as K}from"node:fs/promises";import{join as W}from"node:path";function G(){return W(I(),"fail-open.log")}async function a(e,t=!0){let o=`[VisIQ] FAIL-OPEN (${e.stage}): ${e.detail} \u2014 tool call proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`;try{process.stderr.write(`${o}
2
2
  `)}catch{}if(t)try{await K(I(),{recursive:!0}),await J(G(),`${JSON.stringify({at:new Date().toISOString(),...e})}
3
3
  `,{mode:384})}catch{}}async function m(e,t={}){e.failOpen===!0&&await a({stage:"runtime-fail-open",detail:e.reason,...t.toolName?{toolName:t.toolName}:{},...t.sessionId?{sessionId:t.sessionId}:{}})}var Y=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),z=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function X(e){if(typeof e!="string"||!e.startsWith("mcp__"))return typeof e=="string"?e:"";let t=e.lastIndexOf("__");return t>=0?e.slice(t+2):e}function O(e){return typeof e!="string"?!1:Y.has(e)?!0:e.startsWith("mcp__")?z.test(X(e)):!1}function L(e){return O(e)?["retrieval","action"]:["action"]}var Z=["query","q","url","prompt","pattern","file_path","path"];function g(e){if(!e||typeof e!="object")return;let t=e,o=[];for(let n of Z){let r=t[n];typeof r=="string"&&r.length>0&&o.push(r)}return o.length>0?o.join(" "):void 0}function l(e,t){let o=t?`VisIQ ${t}`:"VisIQ",n=e&&e.trim().length>0?e.trim():"blocked by policy";return`[${o}] ${n}`}function j(e){let t={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};return e&&(t.hookSpecificOutput.updatedInput=e),t}function y(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}function H(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:e}}}function u(e,t){let o={hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}};return t&&(o.hookSpecificOutput.additionalContext=t),o}function ae(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.hook_event_name=="string"?t:null}catch{return null}}var ee="[VisIQ: retrieval withheld by policy]";function w(e){return P(e)}function P(e){if(e==null)return e;if(typeof e=="string")return e.length>0?ee:e;if(typeof e=="number")return 0;if(typeof e=="boolean")return!1;if(Array.isArray(e))return e.map(P);if(typeof e=="object"){let t=Object.create(null);for(let o of Object.keys(e))t[o]=P(e[o]);return t}return e}function M(e){return e.fields&&e.fields.length>0||e.patterns&&e.patterns.length>0?!0:!!e.directives?.some(t=>t.field&&t.field.length>0||t.pattern&&t.pattern.length>0)}function B(e,t){if(!e.enforced)return null;let{action:o,retrieval:n}=e,r=l(e.reason,e.ruleCode);if(o.decision==="deny"||n.action==="deny")return y(r);if(o.decision==="approval_required"||n.action==="escalate")return H(r);if(o.decision==="mask"&&o.argRedactionRules&&o.argRedactionRules.length>0){let i=R(o.argRedactionRules);if(M(i)){let s=k(t,i)??t;if(JSON.stringify(s)!==JSON.stringify(t))return j(s)}return null}return null}function Q(e,t){if(!e.enforced)return null;let{retrieval:o}=e,n=l(e.reason,e.ruleCode);if(o.action==="redact"){let r=R(o.redactionRules??[]);if(!M(r))return u(w(t),n);let i=k(t,r);return JSON.stringify(i)===JSON.stringify(t)?null:u(i,n)}return o.action==="deny"?u(w(t),n):null}var te="cli_harness";function d(e){let t=new x(e.apiKey,e.baseUrl,e.agentId,te,void 0,C,b);return t.setFailMode(e.failMode),t}function _(e){let t={operations:e.operations,agentId:e.agentId,toolName:e.toolName,toolArgs:e.toolInput,resourceType:"tool_result",resourceMetadata:{toolName:e.toolName,...e.toolUseId?{toolCallId:e.toolUseId}:{},...e.sessionId?{sessionId:e.sessionId}:{},...e.cwd?{cwd:e.cwd}:{}}};return e.query&&(t.query=e.query),e.context&&(t.context=e.context),t}async function c(e,t,o=N){let{agentId:n}=t,r=await q(n);if(r&&D(r,o,Date.now())&&S(e,r.body))return!0;let i=e.getEndpoint();if(i){let s=await V(i,t.apiKey,n);if(s&&S(e,s.body))return await F(n,s.body,s.version),!0}if(r&&S(e,r.body))return!0;try{await e.awaitBundleReady(2500)}catch{}return e.isBundleLoaded()}function S(e,t){try{return e.applyBundle(t),!0}catch{return!1}}async function p(e){try{await e.flush()}catch{}try{e.dispose()}catch{}}async function Pe(e,t){let o=d(t),n=e.tool_input??{};try{if(await A(e.session_id)||(o.registerHostEnvironment(),await f(e.session_id)),!await c(o,t)&&t.failMode!=="closed")return await a({stage:"no-bundle",detail:"no rule bundle available (cache empty + fetch failed)",toolName:e.tool_name,sessionId:e.session_id}),null;let i=E(e.tool_name,n),s=L(e.tool_name),h;i&&(T(o,{agentId:t.agentId,sessionId:e.session_id,framework:"claude-code"},i),s=Array.from(new Set([...s,"delegation"])),h=v(i,t.agentId));let $=_({operations:s,agentId:t.agentId,toolName:e.tool_name,toolInput:n,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:g(n),...h?{context:h}:{}}),U=await o.evaluate($);return await m(U,{toolName:e.tool_name,sessionId:e.session_id}),B(U,n)}catch(r){return t.failMode==="closed"?y(l("evaluation error \u2014 blocked (VISIQ_FAIL_MODE=closed)",null)):(await a({stage:"pre-eval-error",detail:r instanceof Error?r.message:String(r),toolName:e.tool_name,sessionId:e.session_id}),null)}finally{await p(o)}}async function ve(e,t){if(!O(e.tool_name))return null;let o=d(t);try{if(!await c(o,t)&&t.failMode!=="closed")return await a({stage:"no-bundle",detail:"no rule bundle available (cache empty + fetch failed)",toolName:e.tool_name,sessionId:e.session_id}),null;let r=e.tool_input??{},i=_({operations:["retrieval"],agentId:t.agentId,toolName:e.tool_name,toolInput:r,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:g(r)}),s=await o.evaluate(i);return await m(s,{toolName:e.tool_name,sessionId:e.session_id}),Q(s,e.tool_response)}catch(n){return t.failMode==="closed"?u(w(e.tool_response),l("evaluation error \u2014 withheld (VISIQ_FAIL_MODE=closed)",null)):(await a({stage:"post-eval-error",detail:n instanceof Error?n.message:String(n),toolName:e.tool_name,sessionId:e.session_id}),null)}finally{await p(o)}}async function qe(e,t){let o=d(t);try{o.registerHostEnvironment(),await c(o,t,0),await f(e.session_id)}finally{await p(o)}return null}export{G as a,a as b,X as c,O as d,L as e,g as f,l as g,j as h,y as i,H as j,u as k,ae as l,ee as m,w as n,B as o,Q as p,te as q,d as r,_ as s,c as t,p as u,Pe as v,ve as w,qe as x};
@@ -0,0 +1,4 @@
1
+ import{readFile as zt}from"node:fs/promises";import{homedir as se}from"node:os";import{join as V,isAbsolute as qt,resolve as Vt}from"node:path";var Gt="https://api.visiqlabs.com",Wt="@visiq/claude-code-harness",le="open";function ce(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function S(){let e=process.env.VISIQ_HOME;return e&&e.trim().length>0?e:V(se(),".visiq","claude-code")}function Ht(){return V(S(),"config.json")}function Kt(e){return e==="~"||e.startsWith("~/")?V(se(),e.slice(1).replace(/^\//,"")):e}async function Zt(e){try{let t=qt(e)?e:Vt(e),n=await zt(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"&&r.length>0)return r}}function ae(e){if(!e||typeof e!="object")return{};let t=e,n={},r=D(t,"apiKey","api_key"),i=D(t,"agentId","agent_id"),a=D(t,"baseUrl","base_url"),o=ce(D(t,"failMode","fail_mode"));return r&&(n.apiKey=r),i&&(n.agentId=i),a&&(n.baseUrl=a),o&&(n.failMode=o),n}async function oe(e){if(!e)return{};let t=await Zt(Kt(e));if(!t||typeof t!="object")return{};let n=t,r=n.plugins?.entries,i=r&&typeof r=="object"?r[Wt]:void 0;return i&&typeof i=="object"&&i.config?ae(i.config):ae(n)}function Yt(e=process.env){let t={};e.VISIQ_API_KEY&&(t.apiKey=e.VISIQ_API_KEY),e.VISIQ_AGENT_ID&&(t.agentId=e.VISIQ_AGENT_ID),e.VISIQ_BASE_URL?t.baseUrl=e.VISIQ_BASE_URL:e.VISIQ_ENDPOINT&&(t.baseUrl=e.VISIQ_ENDPOINT);let n=ce(e.VISIQ_FAIL_MODE);return n&&(t.failMode=n),t}function Jt(e,t,n){let r={...e,...t,...n};if(!r.apiKey||!r.agentId)return null;let i={apiKey:r.apiKey,agentId:r.agentId,failMode:r.failMode??le};return i.baseUrl=r.baseUrl||Gt,i}async function Qt(){let e=Yt(),t=await oe(process.env.VISIQ_CONFIG_PATH),n=await oe(Ht()),r={...n,...t,...e};return{config:Jt(n,t,e),failMode:r.failMode??le}}async function aa(){return(await Qt()).config}import{mkdir as Lt,readFile as Ji,writeFile as Pt,stat as Qi}from"node:fs/promises";import{createHash as Xi}from"node:crypto";import{join as q}from"node:path";import{z as d}from"zod";import*as w from"node:os";import{randomUUID as dn}from"node:crypto";var G=1,de="X-VisIQ-SDK",pe="X-VisIQ-Dialect",fe="unknown";function C(e,t=1){return{[de]:e&&e.length>0?e:fe,[pe]:String(t)}}var me="interceptor_source",Xt=d.enum(["enforce","audit","off"]),en=d.enum(["closed","open"]),he=d.enum(["enforce","monitor","off"]),tn=d.object({apiKey:d.string().min(1,"apiKey is required"),agentId:d.string().min(1,"agentId is required"),endpoint:d.string().url().optional(),mode:Xt.optional(),timeoutMs:d.number().int().positive().optional(),hitlTimeoutMs:d.number().int().positive().optional(),failBehavior:en.optional()}),la=d.object({agent_id:d.string().min(1),target_app:d.string().min(1),action:d.string().min(1),context:d.record(d.unknown()).optional(),session_id:d.string().min(1).max(255).optional(),action_schema_id:d.string().min(1).max(128).optional(),telemetry:d.record(d.unknown()).optional()}),nn=d.object({field:d.string().optional(),pattern:d.string().optional(),replacement:d.string().optional(),mode:d.enum(["full","partial","email"]).optional(),keepFirst:d.number().optional(),keepLast:d.number().optional(),maskChar:d.string().optional()}),rn=d.object({decision_id:d.string().min(1),decision:d.enum(["permit","deny","approval_required","mask"]),reason:d.string().optional(),rule_code:d.string().nullable().optional(),enforced:d.boolean().optional(),agent_mode:he.optional(),arg_redaction_rules:d.array(nn).optional(),plane:d.string().nullable().optional(),operation:d.string().nullable().optional(),is_retrieval:d.boolean().optional(),metadata:d.record(d.unknown()).optional()}),an=d.object({field:d.string().min(1),operator:d.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:d.union([d.string(),d.number(),d.array(d.string())])}),on=d.object({id:d.string().min(1),rule_code:d.string().default(""),name:d.string().min(1),description:d.string().nullable().default(null),effect:d.enum(["allow","deny","hitl","mask"]),resource_type:d.string().min(1),rego_source:d.string().default(""),target_app:d.string().nullable().default(null),action_pattern:d.string().nullable().default(null),conditions:d.array(an).default([]),priority:d.number().int().default(0)}),sn=d.object({version:d.string().min(1),agent_mode:he.optional(),rules:d.array(on),no_coverage:d.object({no_coverage_defaults:d.record(d.string()),autopilot_enabled:d.boolean(),enduser_hitl_enabled:d.boolean(),hitl_timeout_seconds:d.number()}).optional()}),ln=2e3,ge=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return C(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 rn.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 sn.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}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let o=a,s=o.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof o.reason=="string"?o.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await cn(ln)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function cn(e){return new Promise(t=>setTimeout(t,e))}function W(){let e={};try{let t=`${w.platform()} ${w.release()}`.trim();t&&(e.os=t)}catch{}try{let t=w.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=w.userInfo();t&&(e.username=t)}catch{}try{let t=un();t&&(e.ip=t)}catch{}return e}function un(){let e=w.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}var ue=new Map;function pn(e){let t=(ue.get(e)??0)+1;return ue.set(e,t),t}function fn(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:dn(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:pn(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}:{}}})}import{z as p}from"zod";import{createHash as mn}from"crypto";import{createHash as zn}from"crypto";var _e=new Map;function ye(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function H(e){let t=mn("sha256").update(e).digest("hex"),n=_e.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
2
+ `).map(l=>hn(l)).filter(l=>l.trim().length>0),o=0;for(;o<a.length;){let l=a[o].trim();if(l.startsWith("package ")||l.startsWith("import ")){o++;continue}let c=l.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(c){let h=c[1],m=c[2].trim();r.set(h,N(m)),o++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let h=u[1],m=u[2].trim(),g=u[3].trim(),y=[];if(g&&g!=="}"){let E=g.endsWith("}")?g.slice(0,-1).trim():g;E&&y.push(E),g.endsWith("}")||(o++,o=M(a,o,y))}else g==="}"||(o++,o=M(a,o,y));let b=be(y);i.push({variable:h,value:N(m),conditions:b,rawConditions:ye(y)}),o++;continue}let f=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(f){let h=f[1],m=f[2].trim(),g=[];if(m&&m!=="}"){let b=m.endsWith("}")?m.slice(0,-1).trim():m;b&&g.push(b),m.endsWith("}")||(o++,o=M(a,o,g))}else m==="}"||(o++,o=M(a,o,g));let y=be(g);i.push({variable:h,value:"true",conditions:y,rawConditions:ye(g)}),o++;continue}o++}let s={defaults:r,rules:i};return _e.set(t,s),s}function hn(e){let t=!1,n="";for(let r=0;r<e.length;r++){let i=e[r];if(t)i===n&&e[r-1]!=="\\"&&(t=!1);else if(i==='"'||i==="'")t=!0,n=i;else if(i==="#")return e.slice(0,r)}return e}function M(e,t,n){let r=1,i=t;for(;i<e.length&&r>0;){let a=e[i].trim();for(let o of a)o==="{"&&r++,o==="}"&&r--;if(r>0)n.push(a),i++;else{let o=a.slice(0,a.lastIndexOf("}")).trim();return o&&n.push(o),i}}return i}function N(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function gn(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function be(e){let t=[];for(let n of e){let r=n.split(";").map(i=>i.trim()).filter(i=>i.length>0);for(let i of r){let a=wn(i);a&&t.push(a)}}return t}var K=/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false/,_n=new RegExp(`^(${K.source})\\s+in\\s+((?:input|data)[^\\s]*)$`),yn=new RegExp(`^(${K.source})\\s*==\\s*((?:input|data)\\S*)$`),bn=/^([^\s=!]+)\s*==\s*(.+)$/,vn=/^([^\s=!]+)\s*!=\s*(.+)$/,fa=new RegExp(`^(?:${K.source})$`);function wn(e){let t=!1,n=e.trim();if(n.startsWith("not ")&&(t=!0,n=n.slice(4).trim()),n==="true"||n==="false")return{type:"literal_bool",negated:t,field:"",value:n==="true"};if(n.includes("[_]"))return{type:"truthy",negated:!1,field:P,value:e.trim()};let r=n.match(/^count\(([^)]+)\)\s*(>=|<=|>|<)\s*(\d+)$/);if(r)return{type:"count_gt",negated:t,field:r[1].trim(),operator:r[2],value:parseInt(r[3],10)};let i=n.match(/^startswith\(([^,]+),\s*"([^"]*)"\)$/);if(i)return{type:"startswith",negated:t,field:i[1].trim(),value:i[2]};let a=n.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(a)return{type:"endswith",negated:t,field:a[1].trim(),value:a[2]};let o=n.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"contains",negated:t,field:o[1].trim(),value:o[2]};let s=n.match(/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:gn(s[1])};let l=n.match(_n);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:Ce(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let y=Sn(c[2]);if(y!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:y}}let u=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(u)return{type:"comparison",negated:t,field:u[1].trim(),operator:u[2],value:parseFloat(u[3])};let f=n.match(yn);if(f)return{type:"equality",negated:t,field:f[2].trim(),value:N(f[1].trim())};let h=n.match(bn);if(h)return{type:"equality",negated:t,field:h[1].trim(),value:N(h[2].trim())};let m=n.match(vn);if(m)return{type:"inequality",negated:t,field:m[1].trim(),value:N(m[2].trim())};let g=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return g?{type:"truthy",negated:t,field:g[1].trim()}:{type:"truthy",negated:!1,field:P,value:e.trim()}}var P="__unrecognized_condition_forces_deny__";var An=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function Ie(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==P&&An.test(r.field)&&t.push(r.field);return t}var kn=["input.normalized.","input.normalized["];function Ee(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions){let{field:i}=r;typeof i!="string"||i===P||kn.some(a=>i.startsWith(a))&&t.add(i)}return[...t].sort()}function Ce(e){let t=e.trim();return t==="true"?!0:t==="false"?!1:/^-?\d+(?:\.\d+)?$/.test(t)?parseFloat(t):t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Sn(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",i=!1,a="";for(let s=0;s<t.length;s++){let l=t[s];i?(r+=l,l===a&&t[s-1]!=="\\"&&(i=!1)):l==='"'||l==="'"?(r+=l,i=!0,a=l):l===","?(n.push(r.trim()),r=""):r+=l}if(i)return null;r.trim().length>0&&n.push(r.trim());let o=[];for(let s of n){let l=s.startsWith('"')&&s.endsWith('"')&&s.length>=2||s.startsWith("'")&&s.endsWith("'")&&s.length>=2,c=/^-?\d+(?:\.\d+)?$/.test(s);if(!l&&!c&&!(s==="true"||s==="false"))return null;o.push(Ce(s))}return o}var In=["tier1","tier2","tier3"];function Te(e){return typeof e=="string"&&In.includes(e)}var En=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Cn=["internal","customer_facing","experimental","third_party"],Ne=[...En,...Cn];function Tn(e){return typeof e=="string"&&Ne.includes(e)}function xe(e){let t=new Set;for(let n of e)Tn(n)&&t.add(n);return Ne.filter(n=>t.has(n))}var Oe=["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"],Nn=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],xn=["production","staging","development","test"],On=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function Rn(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 ve={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 $n(e){let t=Rn(e);return t===null?"other":ve[t]??ve[t.replace(/_/g,"")]??"other"}function Re(e,t){let n={...e};if(t.targetApp!==void 0&&t.targetApp!==null){let r=n.context&&typeof n.context=="object"&&!Array.isArray(n.context)?{...n.context}:{};r.app_category===void 0&&(r.app_category=$n(t.targetApp)),n.context=r}return n}var we=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],Dn=["read","write","delete","share","export","decide","execute"],Ae=["none","low","medium","high","critical"],Mn=["public","internal","confidential","restricted","credentials","api_key","private_key","password","secret","token","pan","full_pan","card_number","track_data","cvv","cvc","ssn","tax_id","national_id","passport","drivers_license","identity_document","document_number","kyc_document","bank_account","account_number","routing_number","iban","account_balance","customer_financial","credit_score","net_worth","income","financial_profile","employee_pii","payroll","compensation","material_nonpublic","pre_release_earnings","mnpi","attorney_client","legal_hold","privileged","special_category_gdpr","gdpr_special_category","biometric","ethnicity","political_opinion","health_special","religion"],Ln={action_class:Oe,operation:Dn,"context/app_category":Nn,"context/environment":xn,"context/actor_function":On,"read/classification":Mn,"read/data_categories":we,"read/data_sensitivity":Ae,"write/data_categories":we,"write/data_sensitivity":Ae};function $e(e){if(e===null||typeof e!="object")return[];let t=e,n=new Set,r=(i,a,o)=>{let s=Array.isArray(a)?a:[a];for(let l of s)typeof l!="string"||l.length===0||o.includes(l)||n.add(`${i}=${l}`)};for(let[i,a]of Object.entries(Ln)){Object.prototype.hasOwnProperty.call(t,i)&&r(i,t[i],a);let o=i.indexOf("/");if(o===-1)continue;let s=t[i.slice(0,o)];if(s!==null&&typeof s=="object"&&!Array.isArray(s)){let l=i.slice(o+1),c=s;Object.prototype.hasOwnProperty.call(c,l)&&r(i,c[l],a)}}return[...n].sort()}var ke=64,Pn=64,x={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function De(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var Fn=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>ke?r.slice(0,ke):r}function Se(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function L(e){return typeof e=="string"&&e.length>0?e:null}function Me(e,t){let n=Se(t.data_categories),r=L(t.classification),i=Se(t.taint),a=L(t.action_class),o=a&&Oe.includes(a)?a:null,s=L(t.target_app),l=L(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<Pn)c[o]=1;else{let u=Object.keys(c).sort(),f=u[u.length-1];f!==void 0&&o<f&&(delete c[f],c[o]=1)}return{retrieved_data_categories:T(e.retrieved_data_categories,n),retrieved_classifications:T(e.retrieved_classifications,r?[r]:[]),taint:T(e.taint,i),action_classes:T(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&Fn.has(l)?1:0),event_count:e.event_count+1,target_apps:T(e.target_apps,s?[s]:[])}}var Le="generic",Pe=[{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:Le,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."}],jn=Pe.map(e=>e.id),ma=new Map(Pe.map(e=>[e.id,e])),ha=new Set(jn);function Fe(e){return Array.isArray(e)&&e.length>0?[...e]:[Le]}var Bn=/^[a-z][a-z0-9_]*$/;function je(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Bn.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Un=["narrow","moderate","broad","unbounded","unknown"];function Be(e){return typeof e=="string"&&Un.includes(e)}function Ue(e){return e==="open"||e==="closed"?e:null}var qn=["tool_name","function","name","action"];function F(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)F(r,`${t}[]`,n);return}if(e!==null&&typeof e=="object"){let r=Object.entries(e);if(r.length===0){t&&n.push([t,void 0]);return}for(let[i,a]of r)F(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Vn(e){let t=[];return F(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function Gn(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function Wn(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function Hn(e,t={}){if(t.discriminatorField===null)return null;let n=[];F(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??qn;for(let i of r){let a=null;for(let[o,s]of n){if(Gn(o)!==i)continue;let l=Wn(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function ze(e,t={}){let n=zn("sha256").update(Vn(e).join(",")).digest("hex").slice(0,16),r=Hn(e,t);return r!==null?`${n}:${r}`:n}var Kn=["action","retrieval","delegation"];function Zn(e){return typeof e=="string"&&Kn.includes(e)}var Yn=new Set(["rules"]);function qe(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Yn.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Zn):[];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 U}from"zod";var rt="[REDACTED]",Q=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"in_pan_tax",re:/\b[A-Z]{3}[ABCFGHJLPTE][A-Z]\d{4}[A-Z]\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"date_of_birth",re:/\b(?:\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])|(?:0[1-9]|[12]\d|3[01])[/.](?:0[1-9]|1[0-2])[/.]\d{4}|(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12]\d|3[01])\/\d{4})\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}],ya=Q.map(({name:e,re:t})=>({name:e,source:t.source}));function Y(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 Jn(e){let t=e.replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let i=0;i<n.length;i++){let a=n[i],o=a>="A"&&a<="Z"?String(a.charCodeAt(0)-55):a;for(let s=0;s<o.length;s++)r=(r*10+(o.charCodeAt(s)-48))%97}return r===1}function Qn(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 Xn=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],er=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]];function tr(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=Xn[t][er[r%8][n[r].charCodeAt(0)-48]];return t===0}function nr(e){if(!/^\d{11}$/.test(e)||/^(\d)\1{10}$/.test(e))return!1;let t=n=>{let r=0;for(let a=0;a<n;a++)r+=(e.charCodeAt(a)-48)*(n+1-a);let i=r*10%11;return i===10?0:i};return t(9)===e.charCodeAt(9)-48&&t(10)===e.charCodeAt(10)-48}function rr(e){if(!/^\d{10}$/.test(e))return!1;let t=0;for(let i=0;i<9;i++)t+=(e.charCodeAt(i)-48)*(10-i);let n=11-t%11,r=n===11?0:n;return r!==10&&r===e.charCodeAt(9)-48}var ir=[1,4,3,7,5,8,6,9,10];function ar(e){if(!/^\d{8,9}$/.test(e))return!1;let t=0;for(let n=0;n<e.length;n++)t+=(e.charCodeAt(n)-48)*ir[n];return t%11===0}var or="TRWAGMYFPDXBNJZSQVHLCKE";function sr(e){let t=e.replace(/[\s.-]/g,"").toUpperCase(),n=/^([XYZ]?)(\d{7,8})([A-Z])$/.exec(t);if(!n)return!1;let[,r,i,a]=n;if(r===""&&i.length!==8||r!==""&&i.length!==7)return!1;let o=r===""?i:String("XYZ".indexOf(r))+i;return or[Number(o)%23]===a}var lr=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function cr(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!lr.has(t.slice(0,2)):!1}var X=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&Y(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:Jn},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Qn},{name:"uk_nino",re:/\b[A-Za-z]{2} ?\d{2} ?\d{2} ?\d{2} ?[A-Da-d]\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:(e,t)=>t!==void 0&&t===t.toLowerCase()?!1:cr(e)},{name:"in_aadhaar",re:/\b[2-9]\d{3}[ -]?\d{4}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===12&&tr(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:nr},{name:"es_dni_nie",re:/\b(?:[XYZxyz]-?)?(?:\d{7,8}|\d{1,2}[. ]\d{3}[. ]\d{3})[ -]?[A-Za-z]\b/g,normalize:e=>e.replace(/[\s.-]/g,"").toUpperCase(),validate:sr},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&Y(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:rr},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:ar}],ur=Object.fromEntries([...Q,...X].map(e=>[e.name,e.re.source])),_=ur,ba=X.map(e=>e.name),it=["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","pan","iban","aba_routing","us_ein","swift_bic","ssn","uk_nino","in_aadhaar","in_pan_tax","br_cpf","es_dni_nie","ca_sin","uk_nhs_number","au_tfn","email","us_phone","date_of_birth","ipv4","mac_address"],ee={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
3
+ MIIEv\u2026
4
+ -----END PRIVATE KEY-----`,template:{pattern:_.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:_.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:_.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:_.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:_.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:_.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:_.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:_.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:_.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:_.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS). Collision rate: MEASURED 9.8% of benign 16-digit runs \u2014 Luhn leaves ~1 in 10. Default-ON because PCI-DSS makes masking mandatory; note in_aadhaar sits at the same rate and is often proposed for removal on that basis.",category:"financial",example:"4242 4242 4242 4242",template:{pattern:_.pan,mode:"partial",keepLast:4,templateOnly:{reason:"A rego rule cannot run Luhn, so the rule masks EVERY 13-19 digit run (grouped or not) \u2014 the floor's regex without the checksum that makes it precise. ~9 in 10 of those are not card numbers.",examples:["4242 4242 4242 4243","4242424242424241"],measuredOverMaskRate:.531}},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible. Collision rate: MEASURED 1.0% \u2014 mod-97 leaves ~1 in 97, the most precise detector on this floor alongside br_cpf.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:_.iban,mode:"partial",keepLast:4,templateOnly:{reason:"A rego rule cannot run mod-97, so the rule masks EVERY IBAN-SHAPED token (2 letters, 2 digits, 10-30 alphanumerics) \u2014 and mod-97 is what makes this the most precise detector on the floor, so almost all of those are not IBANs.",examples:["DE89 3704 0044 0532 0130 01","GB00 NWBK 6016 1331 9268 19"],measuredOverMaskRate:.934}},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:_.aba_routing,mode:"full",templateOnly:{reason:"A rego rule cannot run the weighted 3-7-1 mod-10, so the rule masks EVERY bare 9-digit run \u2014 which is why this detector is default-OFF on the floor and why its rule form is broader still.",examples:["021000022","123456789"],measuredOverMaskRate:.899}},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX). Collision rate: MEASURED 100% \u2014 no checksum, so every 2-then-7 dashed digit run matches. Same trade as ssn: the punctuated shape is rare in benign traffic, not precise.",category:"financial",example:"12-3456789",template:{pattern:_.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:_.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789). Collision rate: MEASURED 100% \u2014 there is NO checksum, so every dashed 3-2-4 digit run matches. Default-ON regardless, because that punctuated shape is essentially absent from benign agent traffic; if your traffic carries 3-2-4 dashed reference codes, opt out.",category:"pii",example:"123-45-6789",template:{pattern:_.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},uk_nino:{id:"uk_nino",label:"UK National Insurance numbers",description:"UK NINOs (e.g. AB 12 34 56 C). DEFAULT-OFF \u2014 NO CHECKSUM. Precision comes only from the issued alphabet and the never-issued administrative prefixes (BG, GB, NK, KN, TN, NT, ZZ), so roughly half of tokens already shaped 2-letters/6-digits/[A-D] validate. All-lowercase candidates are rejected (git short SHAs), but that does NOT exclude uppercase business identifiers \u2014 serial, part, batch, PO, coupon and asset tags share the shape exactly and were measured being masked. Opt in when UK NINOs are expected in your traffic.",category:"pii",example:"AB 12 34 56 C",template:{pattern:"\\b(?:[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Za-ceghj-npr-tw-z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-Da-d]|[A-CEGHJ-PR-TW-Za-ceghj-pr-tw-z][A-CEGHJ-NPR-TW-Z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-Da-d]|[A-CEGHJ-PR-TW-Za-ceghj-pr-tw-z][A-CEGHJ-NPR-TW-Za-ceghj-npr-tw-z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-D])\\b",mode:"full",templateOnly:{reason:"uk_nino has no checksum, but the floor still rejects the seven NEVER-ISSUED administrative prefixes (BG GB NK KN TN NT ZZ). A rego rule cannot express that exclusion without enumerating hundreds of letter pairs (RE2 has no lookahead), so the rule masks those too.",examples:["NK 12 34 56 A","ZZ 12 34 56 C"],measuredOverMaskRate:.019}},defaultEnabled:!1},in_aadhaar:{id:"in_aadhaar",label:"Aadhaar numbers (India)",description:"12-digit UIDAI Aadhaar numbers, Verhoeff-checksum validated and constrained to the issued 2-9 leading digit. Keeps the last 4 visible. Collision rate: MEASURED 10.0% of benign 12-digit ids starting 2-9 (order/transaction numbers) \u2014 Verhoeff leaves ~1 in 10. Comparable to the long-shipped pan (10.0%) and well behind iban (1.0%); it stays default-ON because the two US identifiers this floor has always shipped, ssn and us_ein, collide at 100%.",category:"pii",example:"2345 6789 0124",template:{pattern:"\\b[2-9]\\d{3}(?:[ -]\\d{4}[ -]?\\d{4}|\\d{4}[ -]\\d{4})\\b",mode:"partial",keepLast:4,floorOnly:{reason:"The floor accepts the entirely UNPUNCTUATED 12-digit form because Verhoeff gates it (~1 in 10 survive). A rego rule cannot run Verhoeff, so a bare \\d{12} in a rule would mask every 12-digit order id and E.164 Indian mobile number in the tenant. The rule requires at least one printed separator \u2014 every half-punctuated form is covered; only the bare digit run stays floor-only.",examples:["234567890124","id=234567890124"]},templateOnly:{reason:"A rego rule cannot run the Verhoeff checksum, so the rule masks EVERY 4-4-4 grouping that starts 2-9 \u2014 including the ~9 in 10 that are not Aadhaar numbers at all.",examples:["2345 6789 0125","2345-6789-0123"],measuredOverMaskRate:.903}},defaultEnabled:!0},in_pan_tax:{id:"in_pan_tax",label:"India PAN (tax ID)",description:"India Permanent Account Number \u2014 the income-tax id (ABCPE1234F), NOT a payment-card PAN. NO CHECKSUM: the only discriminator is the holder-type letter in position 4, which removes just 15 of 26 possibilities in one position, so roughly 4 in 10 uniform 5-letter/4-digit/1-letter tokens validate. DEFAULT-OFF for that reason \u2014 an uppercase SKU or part number of the same shape is masked, and nothing in the value distinguishes it.",category:"financial",example:"ABCPE1234F",template:{pattern:_.in_pan_tax,mode:"full"},defaultEnabled:!1},br_cpf:{id:"br_cpf",label:"CPF numbers (Brazil)",description:"Brazilian CPF, closed by TWO independent mod-11 check digits. Collision rate: MEASURED 1.0% of benign 11-digit runs (~1-in-100) \u2014 the most precise detector on this floor, alongside iban. Repdigits are rejected. Keeps the last 2 visible.",category:"pii",example:"123.456.789-09",template:{pattern:"\\b\\d{3}(?:\\.\\d{3}\\.?\\d{3}-?\\d{2}|\\d{3}(?:\\.\\d{3}-?\\d{2}|\\d{3}-\\d{2}))\\b",mode:"partial",keepLast:2,floorOnly:{reason:"The floor accepts the entirely bare 11-digit form because TWO mod-11 check digits gate it (~1 in 100 survive). A rego rule cannot run mod-11, so a bare \\d{11} in a rule would mask every 11-digit identifier in the tenant. The rule requires at least one printed separator; the bare form stays floor-only.",examples:["11144477735","ref 11144477735","12345678909"]},templateOnly:{reason:"A rego rule cannot run the two mod-11 check digits, so the rule masks EVERY punctuated 3-3-3-2 digit grouping \u2014 including the ~99 in 100 that are not CPFs.",examples:["123.456.789-10","111.444.777-34"],measuredOverMaskRate:.995}},defaultEnabled:!0},es_dni_nie:{id:"es_dni_nie",label:"DNI / NIE numbers (Spain)",description:"Spanish national ID (8 digits + letter) and foreigner ID (X/Y/Z + 7 digits + letter), validated by the mod-23 check letter. Collision rate: MEASURED 4.0% of benign 8-digit-plus-letter tokens (invoice/order numbers with a suffix letter) \u2014 mod-23 leaves ~1 in 23. More precise than in_aadhaar (10.0%) and pan (10.0%); behind br_cpf (1.0%) and iban (1.0%).",category:"pii",example:"12345678Z",template:{pattern:_.es_dni_nie,mode:"full",templateOnly:{reason:"A rego rule cannot run the mod-23 check letter, so the rule masks EVERY 7-8 digit run followed by a letter \u2014 invoice and order numbers with a suffix letter included. mod-23 admits ~1 in 23; the rule admits all of them. Re-measured 0.973 \u2192 0.981 when the floor learned the printed forms (dotted DNI, hyphenated NIE): the rule now also matches those written forms, and ~22 in 23 of them are not DNI/NIEs. The FLOOR's own rate is unchanged \u2014 mod-23, not punctuation, gates it.",examples:["12345678A","X1234567H"],measuredOverMaskRate:.976}},defaultEnabled:!0},ca_sin:{id:"ca_sin",label:"SIN numbers (Canada)",description:"Canadian Social Insurance Numbers (9-digit, Luhn-validated). DEFAULT-OFF \u2014 identical shape to an ABA routing number and to any 9-digit id, with only a mod-10 pass to separate them.",category:"pii",example:"046 454 286",template:{pattern:"\\b\\d{3}(?:[- ]\\d{3}[- ]?\\d{3}|\\d{3}[- ]\\d{3})\\b",mode:"partial",keepLast:3,floorOnly:{reason:"The floor accepts the entirely bare 9-digit form because Luhn gates it. A rego rule cannot run Luhn, and a bare \\d{9} in a rule is also every ABA routing number and every 9-digit identifier, so the rule requires at least one printed separator in the 3-3-3 grouping.",examples:["046454286"]},templateOnly:{reason:"A rego rule cannot run Luhn, so the rule masks EVERY printed 3-3-3 digit grouping \u2014 including the ~9 in 10 that are not SINs.",examples:["046 454 287","123 456 789"],measuredOverMaskRate:.914}},defaultEnabled:!1},uk_nhs_number:{id:"uk_nhs_number",label:"NHS numbers (UK)",description:"UK NHS patient numbers (10-digit, weighted mod-11). DEFAULT-OFF \u2014 a 10-digit run is also every North American phone number.",category:"pii",example:"943 476 5919",template:{pattern:"\\b\\d{3}(?:[- ]\\d{3}[- ]?\\d{4}|\\d{3}[- ]\\d{4})\\b",mode:"full",floorOnly:{reason:"The floor accepts the entirely bare 10-digit form because the weighted mod-11 gates it. A rego rule cannot run mod-11, and a bare \\d{10} in a rule is also every North American phone number, so the rule requires at least one printed separator in the 3-3-4 grouping.",examples:["9434765919"]},templateOnly:{reason:"A rego rule cannot run the weighted mod-11, so the rule masks EVERY printed 3-3-4 digit grouping \u2014 every North American phone number included \u2014 not just the ~1 in 10 that are NHS numbers.",examples:["943 476 5910","123 456 7890"],measuredOverMaskRate:.899}},defaultEnabled:!1},au_tfn:{id:"au_tfn",label:"Tax File Numbers (Australia)",description:"Australian TFNs (8-9 digit, weighted mod-11). DEFAULT-OFF \u2014 collides with essentially every 8-9 digit identifier.",category:"financial",example:"123 456 782",template:{pattern:"\\b\\d{3}(?:[- ]\\d{3}[- ]?\\d{2,3}|\\d{3}[- ]\\d{2,3})\\b",mode:"full",floorOnly:{reason:"The floor accepts the entirely bare 8-9 digit form because the weighted mod-11 gates it. A rego rule cannot run mod-11, and a bare \\d{8,9} in a rule collides with essentially every identifier of that length, so the rule requires at least one printed separator. BOTH lengths are in the gap: a TFN may be 8 digits (`12345679`) or 9 (`123456782`), and the 8-digit branch went undeclared while the parity sweep derived its population from the 9-digit example alone.",examples:["12345679","123456782"]},templateOnly:{reason:"A rego rule cannot run the weighted mod-11, so the rule masks EVERY printed 3-3-2/3-3-3 digit grouping \u2014 including the ~9 in 10 that are not TFNs.",examples:["123 456 783","123 456 78"],measuredOverMaskRate:.912}},defaultEnabled:!1},date_of_birth:{id:"date_of_birth",label:"Dates of birth",description:"Dates in the common written formats. DEFAULT-OFF and heavily over-masking by nature \u2014 a DOB is indistinguishable from any other date (created_at, invoice, release). Offered because DOB is a GDPR/HIPAA identifier some regulated tenants must mask regardless.",category:"pii",example:"1985-04-12",template:{pattern:_.date_of_birth,mode:"full"},defaultEnabled:!1},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept). Collision rate: MEASURED 100% of well-formed addresses \u2014 that is BY DESIGN, not a defect: an email address is structurally unambiguous, so matching every one is correct rather than over-matching.",category:"pii",example:"alice@acme.com",template:{pattern:_.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:_.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:_.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:_.mac_address,mode:"full"},defaultEnabled:!1}};var va=new Set(it.filter(e=>!ee[e].defaultEnabled));function dr(e,t){let n=new Set;for(let r of it)(ee[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function pr(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=e;for(let{name:a,re:o}of Q){let s=a;n.has(s)||(i=i.replace(o,()=>(r?.(s),t)))}for(let{name:a,re:o,normalize:s,validate:l}of X)n.has(a)||(i=Ar(i,o,s,l,t,a,r));return i}function R(e){return e===void 0||!/[A-Za-z0-9]/.test(e)}var Ve=new Map;function fr(e){let t=Ve.get(e.source);return t===void 0&&(t=new RegExp(`^(?:${e.source})$`),Ve.set(e.source,t)),t}var mr=4096,hr=64,Ge=null;function gr(e){return Ge!==null?Ge:mr+e.length*hr}var at=!1,v={spanCalls:0,spanMisses:0,cutCalls:0,cutMisses:0,budgetExhausted:0,maxMissesInAPass:0},ot={spanBudget:0,depthCap:0};function _r(e){return{stride:e.length+1,chosen:new Map,cuts:new Map,budget:gr(e),exhausted:!1}}function st(e,t,n,r,i,a,o){v.spanCalls++;let s=t*o.stride+n.length,l=at?void 0:o.chosen.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,null;o.budget--,v.spanMisses++;let c=yr(e,t,n,r,i,a,o);return o.chosen.set(s,c),c}function yr(e,t,n,r,i,a,o){let s=fr(r),l=[];for(let u=n.length-1;u>=1;u--)if(R(n[u])){let f=n.slice(0,u);s.test(f)&&l.push(f)}let c=R(e[t+n.length])?[n,...l]:[...l,n];for(let u of c)if(a(i(u),u)&&!vr(e,t,u,r,i,a,o))return u;return null}var We=new Map;function br(e){let t=We.get(e.source);return t===void 0&&(t=new RegExp(e.source,"y"),We.set(e.source,t)),t}function vr(e,t,n,r,i,a,o){v.cutCalls++;let s=t*o.stride+n.length,l=at?void 0:o.cuts.get(s);if(l!==void 0)return l;if(o.budget<=0)return o.exhausted=!0,!0;o.budget--,v.cutMisses++;let c=wr(e,t,n,r,i,a,o);return o.cuts.set(s,c),c}function wr(e,t,n,r,i,a,o){let s=t+n.length,l=br(r);for(let c=1;c<n.length;c++){if(R(n[c])||!R(n[c-1]))continue;let u=t+c;l.lastIndex=u;let f=l.exec(e);if(f===null||f[0].length===0)continue;let h=st(e,u,f[0],r,i,a,o);if(h!==null&&u+h.length>s&&R(e[u+h.length]))return!0}return!1}function Ar(e,t,n,r,i,a,o){t.lastIndex=0;let s="",l=0,c=_r(e),u=v.spanMisses+v.cutMisses,f;for(;(f=t.exec(e))!==null;){let h=f[0],m=f.index;if(h.length===0){t.lastIndex=m+1;continue}let g;try{g=st(e,m,h,t,n,r,c)}catch(y){if(y instanceof RangeError&&/call stack/i.test(y.message))c.exhausted=!0,g=null;else throw y}if(c.exhausted)return v.budgetExhausted++,ot.spanBudget++,He(u),s+e.slice(l,m)+i;if(g!==null)o?.(a),s+=e.slice(l,m)+i,l=m+g.length,t.lastIndex=l;else{let y=h.slice(1).search(/[^A-Za-z0-9]/);t.lastIndex=y===-1?m+h.length:m+1+y+1}if(t.lastIndex>e.length)break}return He(u),s+e.slice(l)}function He(e){let t=v.spanMisses+v.cutMisses-e;t>v.maxMissesInAPass&&(v.maxMissesInAPass=t)}function lt(e,t=rt,n,r){return Sr(e,t,dr(n,r))}var kr=256;function Sr(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=(s,l)=>{if(l>kr)return ot.depthCap++,t;if(typeof s=="string")return pr(s,t,n,a);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!i)return s;let c=String(s);return c.length>=13&&c.length<=19&&Y(c)?(r.add("pan"),t):s}if(Array.isArray(s))return s.map(c=>o(c,l+1));if(s!==null&&typeof s=="object"){let c=s,u={};for(let f of Object.keys(c))u[f]=o(c[f],l+1);return u}return s};return{value:o(e,0),detectors:[...r].sort()}}function ct(e,t=rt){return lt(e,t).value}var Ir=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,ut=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"}),Er=new RegExp(`[${Object.keys(ut).join("")}]`,"gu"),Cr=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),dt="\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",Tr=Object.freeze(Object.fromEntries([...dt].map((e,t)=>[e,String.fromCharCode(97+t)]))),Nr=new RegExp(`[${dt}\u2800]`,"g"),pt=/[⠀-⣿]/;function xr(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 Or(e){return e.replace(Ir,"")}function ft(e){return e.replace(Er,t=>ut[t]??t)}function Rr(e){return e.replace(/[4@31!05$79(8]/g,t=>Cr[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 Dr(e){return pt.test(e)?e.replace(Nr,t=>t==="\u2800"?" ":Tr[t]??t):e}function Ke(e){let t;try{t=xr(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=Or(t),t=ft(t),t}var Mr=/^[A-Za-z0-9+/]{16,}={0,2}$/,Lr=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,Ze=/[A-Za-z0-9+/]{20,}={0,2}/g;function J(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 mt=new TextDecoder("utf-8",{fatal:!1});function ht(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=mt.decode(n);return t===r?[t]:[r,t]}function Pr(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=mt.decode(n);return r===i?[r]:[i,r]}function Ye(e){let t=e.trim(),n=[];if(Lr.test(t))for(let r of Pr(t))n.push({decoded:r,textiness:J(r)});if(Mr.test(t)&&t.length%4===0)for(let r of ht(t))n.push({decoded:r,textiness:J(r)});return n}function Je(e,t){let n=[],r;for(Ze.lastIndex=0;(r=Ze.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of ht(i))n.push({decoded:a,textiness:J(a)})}return n}var Fr=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function gt(e,t=Fr){if(typeof e!="string"||e.length===0)return{views:[],anyDecoded:!1,truncated:!1,nodes:0,maxDepthSeen:0};let{maxDepth:n,byteCap:r,maxNodes:i,maxBlobsPerNode:a}=t,o=new Set,s=m=>{m.length>0&&m.length<=r&&o.add(m)},l=!1,c=!1,u=0,f=0,h=[{s:e,depth:0}];for(;h.length>0;){if(u>=i){c=!0;break}let m=h.pop();if(m===void 0)break;let{s:g,depth:y}=m;if(g.length>r){c=!0;continue}u++,y>f&&(f=y);let b=Ke(g);s(b);let E=Rr(b);if(E!==b&&s(E),s($r(b)),pt.test(g)&&s(Dr(b)),y>=n){let A=Ke(g);(Ye(A).length>0||Je(A,a).length>0)&&(c=!0);continue}let Ut=[...Ye(b),...Je(b,a)];for(let A of Ut){if(l=!0,A.decoded.length>r){c=!0;continue}A.textiness>=.85&&A.decoded!==b?h.push({s:A.decoded,depth:y+1}):s(A.decoded)}}return{views:[...o],anyDecoded:l,truncated:c,nodes:u,maxDepthSeen:f}}var _t=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],jr=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),Br=8,Ur=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Qe=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function zr(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||Ur.has(i)&&Qe(t[r-1])&&Qe(t[r+1])&&(n++,n>=Br))return!0}return!1}var qr=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function Vr(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(qr.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var Gr=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function Wr(e){for(let t of Gr)if(e>=t.lo&&e<=t.hi)return t.name;return null}function Hr(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=Wr(a.codePointAt(0));if(o===null){i=!1;break}o==="latin"?n++:ft(a)!==a&&r++}if(i&&n>0&&r>0)return!0}return!1}var Xe=Object.freeze({signals:[],contributes:!1});function Kr(e){if(typeof e!="string"||e.length===0)return{...Xe,signals:[]};let t=new Set;try{zr(e)&&t.add("hidden_text_carrier"),Vr(e)&&t.add("injected_turn_boundary"),Hr(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=gt(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Xe,signals:[]}}return{signals:[..._t.filter(n=>t.has(n))],contributes:jr.some(n=>t.has(n))}}var B=[{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 et(e){return typeof e!="string"||e.length===0?[]:B.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function Zr(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(et(e)),{views:n}=gt(e);for(let r of n)for(let i of et(r))t.add(i);return B.filter(r=>t.has(r.name)).map(r=>r.name)}function Yr(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of Zr(a))t.add(s);let o=Kr(a);for(let s of o.signals)n.add(s);o.contributes&&(r=!0);return}if(Array.isArray(a)){for(let o of a)i(o);return}if(typeof a=="object")for(let o of Object.values(a))i(o)}};return i(e),{matched:t.size>0||r,signatures:B.filter(a=>t.has(a.name)).map(a=>a.name),structural:_t.filter(a=>n.has(a))}}function Jr(e){return Yr(e).matched}var wa=B.map(e=>e.name);var Qr=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Xr="i:injection";function yt(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=lt(e.content);for(let a of i){let o=ee[a]?.category;o&&t.add(`c:${o}`)}Jr(e.content)&&t.add(Xr)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Qr.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var Z="(?: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))",Aa=[{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${Z}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${Z}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${Z}\\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}],tt="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",ei=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${tt}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${tt}|programming|training))`,ti="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",nt="(?:\\b(?:unrestricted|unfiltered|uncensored|unbounded|unlimited|unchained|jailbroken|lawless|amoral)\\b|\\b(?:DAN|STAN|DUDE|AIM)\\b|\\bno\\s+(?:longer\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|boundaries|constraints?)\\b(?!\\s+(?:on|over|regarding|upon|for)\\b)|\\bwithout\\s+(?:any\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|constraints?|censorship)\\b|\\b(?:free|freed|released)\\s+from\\s+(?:your\\s+)?(?:restrictions?|limits?|rules?|guidelines?|guardrails?|programming|constraints?)\\b|\\b(?:can|will|are\\s+able\\s+to)\\s+(?:do|say)\\s+anything\\b|\\bignore\\s+(?:all\\s+)?(?:your\\s+)?(?:previous\\s+|prior\\s+|system\\s+)?(?:instructions?|rules?|guidelines?)\\b)",ni="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",ka=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${ti}${ei}\\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}?${nt}`,"i")},{name:"constraint_release",re:/\byou\s+are\s+no\s+longer\s+(?:bound|restricted|limited|constrained|obligated|governed|subject\s+to|required\s+to)\b/i},{name:"from_now_on_reassignment",re:new RegExp(`\\bfrom\\s+now\\s+on\\s*,?\\s+you\\s+(?:are|will|must|shall|have|can)\\s+(?:${ni}\\b|[\\s\\S]{0,40}?${nt})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Sa=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var k=e=>`[^.!?;\\n]{0,${e}}?`,ri=["\\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("|"),bt="(?: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([`(?:${ri})\\s${k(40)}\\b${bt}\\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${k(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${k(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${k(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${k(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${k(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")}]),Ea=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${k(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${k(30)}\\b${bt}\\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 O=e=>`[^.!?;\\n]{0,${e}}?`,Ca=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${O(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${O(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${O(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${O(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${O(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 te="[REDACTED]",I="\u2022",j=e=>/[A-Za-z0-9]/.test(e);function vt(e,t,n,r){let i=Array.from(e),a=i.length,o=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:I,c=o+s>=a;return i.map((u,f)=>!c&&(f<o||f>=a-s)?u:j(u)?l:u).join("")}function ii(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return vt(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(o=>j(o)?a:o).join(""))+i}function ai(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 c=new RegExp(t,"g"),u;for(;(u=c.exec(e))!==null;){if(u[0].length===0){c.lastIndex++;continue}for(let f=u.index;f<u.index+u[0].length;f++)i[f]=!0}}catch{}let a=!1,o=!0;for(let c=0;c<e.length;c++)if(j(e[c])&&(a=!0,!i[c])){o=!1;break}let s=a&&o,l="";for(let c=0;c<e.length;c++){let u=e[c];!s&&i[c]||!j(u)?l+=u:l+=r}return l}function wt(e,t){let n=t.mode??"full";return n==="partial"?vt(e,t.keepFirst??0,t.keepLast??0,t.maskChar??I):n==="email"?ii(e,t.maskChar??I):n==="custom"?ai(e,t.keepPattern,t.maskChar??I):t.replacement??te}function oi(e,t){return typeof e=="string"?wt(e,t):t.replacement??te}function At(e){let t=[],n=e.replacement??te;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=>wt(a,r)})}return t}function kt(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(a,o=>i(o))}return n}function Ta(e,t){return e==null?e:typeof e=="string"?si(e,t):typeof e=="object"?li(e,t):e}function si(e,t){if(typeof e!="string")return e;let n=At(t);return n.length===0?e:kt(e,n)}function li(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=At(t),i=n.size>0,a=r.length>0,o=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>o(l));if(typeof s=="object"){let l=s,c=Object.create(Object.getPrototypeOf(l));for(let u of Object.keys(l)){let f=i?n.get(u):void 0;if(f){c[u]=oi(l[u],f);continue}c[u]=o(l[u])}return c}return typeof s=="string"&&a?kt(s,r):s};return o(e)}var St=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function ci(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:St(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:St(t.spawn.prompt)}),t}function ui(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 di=1440*60*1e3,pi="VISIQ_BUNDLE_GRACE_TTL_MS",fi="VISIQ_BUNDLE_CACHE_DISABLED",mi="VISIQ_CACHE_DIR",hi=U.object({graceTtlMs:U.number().int().nonnegative().optional(),disabled:U.boolean().optional(),cacheDir:U.string().min(1).optional()}).strict();function gi(e){return e==null?{}:hi.parse(e)}function _i(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[pi];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return di}function yi(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[fi]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var It;function bi(){if(It!==void 0)return It;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function vi(e){return JSON.stringify(re(e))}function re(e){if(Array.isArray(e))return e.map(re);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=re(t[r]);return n}return e}function wi(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Ai(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 Rt(){if(!bi())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 $t(e,t){return e.createHash("sha256").update(vi(t)).digest("hex")}function ki(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[mi]?.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 Si(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function Dt(e,t,n){return e.path.join(ki(e,n),"bundles",`${Si(e,t)}.json`)}async function Ii(e,t,n,r={}){let i=await Rt();if(i)try{let a=Dt(i,e,r),o=i.path.dirname(a);await i.fs.mkdir(o,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:$t(i.crypto,t),body:t},l=`${a}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(l,JSON.stringify(s),{mode:384});try{await i.fs.rename(l,a)}catch(c){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),c}}catch{}}async function Ei(e,t={}){let n=await Rt();if(!n)return null;try{let r=await n.fs.readFile(Dt(n,e,t),"utf-8"),i=Ai(JSON.parse(r));return!i||$t(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var $;async function Ci(){if($!==void 0)return $;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;$=typeof t=="function"?t:null}catch{$=null}return $}function Ti(e){let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,i=r.rego_source;if(typeof i!="string"||i.length===0)continue;let a;try{a=H(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of Ie(a))t.push(`${o}: ${s}`)}return t}function Ni(e){let t={retrieval:new Set,action:new Set,delegation:new Set};for(let n of e){if(!n.enabled||n.bypassActive)continue;let r=n.regoSource;if(typeof r!="string"||r.length===0)continue;let i;try{i=H(r)}catch{continue}let a=Ee(i);if(a.length!==0)for(let o of n.appliesTo){let s=t[o];if(s)for(let l of a)s.add(`${n.id}: ${l}`)}}return{retrieval:[...t.retrieval].sort(),action:[...t.action].sort(),delegation:[...t.delegation].sort()}}function xi(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var Oi=5e3,Ri=600*1e3,$i=1e4,Di=25,Et=1e3,Mi=5e3,Li=100,Ct=2e3,Pi=10,Fi=512,ji=1800*1e3,Bi=.7,Ui="monitor",zi="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",Tt="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.",qi="open";function Nt(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function Vi(e,t){return yt({content:e,resourceMetadata:t})}var Gi=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(),mcpServer:p.string().min(1).max(255).optional()}),Wi=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())),action_schemas:p.array(p.object({id:p.string(),plane:p.string().optional(),field_mappings:p.array(p.record(p.unknown())).optional(),derived_fields:p.array(p.record(p.unknown())).optional(),action_class:p.string().nullable().optional(),action_class_confidence:p.number().optional()})).optional(),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 Hi(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=Fe(je(n));return{trust_tier:Te(t)?t:null,categories:xe(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&Be(e.blast_radius_tier)?e.blast_radius_tier:null}}function Ki(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 Zi(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var ie=new Set,xt=!1;async function Ot(e){let t=[];for(let n of ie){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 Yi(){if(!xt&&!(typeof process>"u"||typeof process.once!="function")){xt=!0,process.once("beforeExit",()=>{Ot(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await Ot(!0)}finally{process.kill(process.pid,e)}})()})}}var Ma=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=Ui;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=Nt(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??qi;governedFailMode=null;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastCloneCaptureSig=null;toolDescriptions=new Map;constructor(e,t,n,r,i,a,o,s){let l=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,c=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,u=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=l,this.resolvedEndpoint=c,this.resolvedAgentId=u,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=o,this.originalFetch=globalThis.fetch.bind(globalThis);let f=gi(s);if(this.bundleCacheDisabled=yi(f.disabled),this.bundleGraceTtlMs=_i(f.graceTtlMs),this.bundleCacheDirOverride=f.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let h={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:ui(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new ge(h,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Oi),ne(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},$i),ne(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Mi),ne(this.cognitionTimer),ie.add(this),Yi()}else this.client=null}async evaluate(e){let t=Gi.parse(e),n=Date.now();if(this.operatorShutdown){let m=this.denyAll(t,zi);return this.applyAgentMode(m,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,Tt,n);let m=this.denyAll(t,Tt);return this.applyAgentMode(m,"enforce",t,n)}if(t.operations.every(m=>this.modeFor(m)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let m;if(this.agentModeConfirmed?m=this.agentMode:this.bundleApplyFailed?m="enforce":m="monitor",m==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let g=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(g,m,t,n)}let r=this.readSession(t.sessionId),i=await Ci();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")?Re(t.normalized??{},{targetApp:t.targetResource??t.toolName??""}):t.normalized,o=this.buildActionSchemaEvent(t),s=t.mcpServer?{...a??{},mcp_server:t.mcpServer}:a,l={...t,normalized:s,session:r,at:Date.now(),action_schema_id:o.id,action_schema_raw:o.canonical},c={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},u;try{u=i(l,c)}catch(m){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${m instanceof Error?m.message:String(m)}`,n);throw m}let f=[...new Set(t.operations.flatMap(m=>this.normalizedRefs[m]??[]))].sort();f.length>0&&xi(t.normalized)&&(u.normalizedColdStart=f,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${f.length} loaded rule condition(s) on this event's operation(s) read input.normalized.* \u2014 those conditions resolve to undefined here, so a deny carrying one does not fire. (Builtin-derived paths such as context/app_category ARE still populated in-core, so this is a dependency report, not a proof that every listed condition was the decider.) Cold start / no action-schema mapping yet. Affected: ${f.slice(0,5).join("; ")}${f.length>5?`; +${f.length-5} more`:""}`)));let h=$e(t.normalized);return h.length>0&&(u.normalizedDrift=h,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${h.length} value(s) outside the canonical vocabulary \u2014 a builder-authored rule can only select in-vocab values, so these cannot match one, so a rule keyed on the canonical value does not fire here. Check the harness classifier's casing/spelling. Affected: ${h.slice(0,5).join("; ")}${h.length>5?`; +${h.length-5} more`:""}`))),this.foldSession(t,u.enforced?u.decision:"permit"),u.enforced&&u.action.decision==="approval_required"&&await this.registerHitl(t,u),this.bufferTelemetry(t,u,Date.now()-n,u.enforced),u}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return x;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>ji?(this.sessions.delete(e),x):t.state:x}foldActionClass(e){let t=e.normalized?.action_class;if(typeof t=="string"&&t.length>0)return t;let n=this.rawBundle?.action_schemas;if(!Array.isArray(n))return;let{id:r}=this.buildActionSchemaEvent(e),i=n.find(s=>s?.id===r);if(!i)return;let a=i.action_class,o=typeof i.action_class_confidence=="number"?i.action_class_confidence:0;if(typeof a=="string"&&a.length>0&&o>=Bi)return a}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),o=e.operations.includes("action")||e.operations.includes("delegation"),s=Me(r===x?De():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?Vi(e.contentPreview,i):void 0,action_class:o?this.foldActionClass(e):void 0,target_app:o?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>Fi){let l=this.sessions.keys().next().value;l!==void 0&&this.sessions.delete(l)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let o={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,o,i,!0),o}let a={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,a,i,!1),a}setFailMode(e){this.failMode=e}getFailMode(){return this.failMode}getGovernedFailMode(){return this.governedFailMode}failOpen(e,t,n){let r=`fail-open: ${t} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`;console.error(`[VisIQ] FAIL-OPEN: ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`);let i=e.operations.includes("action")||e.operations.includes("delegation"),a=e.operations.includes("retrieval"),o={decision:"permit",allowed:!0,reason:r,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:i?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:a?{action:"allow"}:{action:null},failOpen:!0};return this.bufferTelemetry(e,o,Date.now()-n,!1,!0),o}reportFailOpen(e,t){try{let n={operations:["action"],agentId:this.resolvedAgentId,...t?.toolName?{toolName:t.toolName}:{},...t?.sessionId?{sessionId:t.sessionId}:{}},r={decision:"permit",allowed:!0,reason:`fail-open: ${e} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:{decision:"permit",allowed:!0},retrieval:{action:null},failOpen:!0};this.bufferTelemetry(n,r,0,!1,!0)}catch{}}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},action_schema_id:this.buildActionSchemaEvent(e).id,...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=Wi.parse(e);this.bundleApplyFailed=!1;let n=this.sdkDialect??1;if(t.min_dialect!==void 0&&t.min_dialect>n){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle requires dialect ${t.min_dialect} but this SDK speaks ${n} \u2014 refusing the bundle and failing closed (deny-all, G001). Upgrade the VisIQ SDK.`);return}let r=Ti(t.rules);if(r.length>0){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle contains rego_source using a builtin the engine cannot evaluate (would silently never match \u2192 fail open): ${r.join("; ")}. Refusing the bundle and failing closed (G001). Recompile the rule without case-folding wrappers like upper()/lower().`);return}this.dialectRefused=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(i=>qe(i)).filter(i=>i!==null),this.agentAttributes=t.agent_attributes?Hi(t.agent_attributes):null,this.agentNoCoverage=Ue(t.agent_attributes?.no_coverage),this.governedFailMode=Nt(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=Ki(t.agent_mode_by_operation),process.env.VISIQ_COGNITION_CAPTURE==="1"?this.cognitionEnabled=!0:typeof t.cognition_capture=="boolean"&&(this.cognitionEnabled=t.cognition_capture),this.operatorShutdown=t.shutdown===!0,this.normalizedRefs=Ni(this.rules),this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1,this.lastNormalizedWarnRearmMs=Date.now(),this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json",...C(this.sdkVersion,this.sdkDialect)};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304){let o=Date.now();o-this.lastNormalizedWarnRearmMs>=Ri&&(this.lastNormalizedWarnRearmMs=o,this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1);return}if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let a=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&a?this.bundleEtag=r:a||(this.bundleEtag=null),a&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await Ei(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(wi(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 Ii(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}isBundleLoaded(){return this.bundleLoaded}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e,t){this.registerEnvironment({...W(),...e?{agent_type:e}:{},...t?.model?{model:t.model}:{},...t?.systemPrompt?{systemPrompt:t.systemPrompt}:{},...t?.toolSchemas&&t.toolSchemas.length>0?{toolSchemas:t.toolSchemas}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));for(let n of e)n.description&&this.toolDescriptions.set(n.name,n.description);t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}captureCloneMetadata(e){if(!this.client||!this.resolvedAgentId||!(e.model||e.systemPrompt||(e.toolSchemas?.length??0)>0))return;let t=JSON.stringify({m:e.model??"",s:e.systemPrompt??"",t:e.toolSchemas??[]});t!==this.lastCloneCaptureSig&&(this.lastCloneCaptureSig=t,this.client.registerEnvironment({...W(),...e.agentType?{agent_type:e.agentType}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{toolSchemas:e.toolSchemas}:{}}))}buildActionSchemaEvent(e){let t=e.toolName?this.toolDescriptions.get(e.toolName):void 0,n={agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{},...e.toolArgs?{tool_args:e.toolArgs}:{},...t?{tool_description:t}:{}},r=ze(n),i={...n};return e.toolArgs&&(i.tool_args=ct(e.toolArgs)),{canonical:n,id:r,rawEventForWire:i}}bufferTelemetry(e,t,n,r,i=!1){let a=this.buildActionSchemaEvent(e);this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:r?Zi(t.decision):"permit",reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:a.rawEventForWire,action_schema_id:a.id,...this.harnessKind||e.context||i||t.normalizedColdStart||t.normalizedDrift?{context:{...this.harnessKind?{[me]:this.harnessKind}:{},...e.context??{},...i?{fail_open:!0}:{},...t.normalizedColdStart?{normalized_cold_start:!0,normalized_inert_conditions:t.normalizedColdStart.length}:{},...t.normalizedDrift?{normalized_drift:!0,normalized_drift_values:t.normalizedDrift.length,normalized_drift_fields:t.normalizedDrift.slice(0,Pi)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Di&&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-Et;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Et})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(ci(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Li&&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-Ct;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Ct})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),ie.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 ne(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function z(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function La(e,t){if(e!=="Task"&&e!=="Agent")return null;let n=z(t.description),r=z(t.subagent_type),i=z(t.prompt),a=n??r??"sub-agent";return{childAgentId:a,childName:a,kind:"subagent",agentType:r,description:n,task:i,goal:i,model:z(t.model),source:"structural"}}function Pa(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}function Fa(e){let t=[],n=[],r,i=[];for(let o of e){if(o.mode==="partial"||o.mode==="email"||o.mode==="custom"){let l={mode:o.mode};o.field&&(l.field=o.field),o.pattern&&(l.pattern=o.pattern),typeof o.keepFirst=="number"&&(l.keepFirst=o.keepFirst),typeof o.keepLast=="number"&&(l.keepLast=o.keepLast),o.maskChar&&(l.maskChar=o.maskChar),o.keepPattern&&(l.keepPattern=o.keepPattern),o.replacement!==void 0&&(l.replacement=o.replacement),i.push(l);continue}o.field&&t.push(o.field),o.pattern&&n.push(o.pattern);let{replacement:s}=o;s&&r===void 0&&(r=s)}let a={};return t.length>0&&(a.fields=t),n.length>0&&(a.patterns=n),r!==void 0&&(a.replacement=r),i.length>0&&(a.directives=i),a}var Mt="0.1.9";var Ka=3e4,ea=4e3;function ta(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,200)||"default"}function Ft(e){let t=Xi("sha1").update(e).digest("hex").slice(0,10);return`${ta(e)}-${t}`}function Za(e,t,n){return n-e.fetchedAt<t}function jt(e){return q(S(),"bundles",`${Ft(e)}.json`)}function Bt(e){return q(S(),"sessions",`${Ft(e)}.registered`)}async function Ya(e){try{let t=await Ji(jt(e),"utf-8"),n=JSON.parse(t);return n&&typeof n.fetchedAt=="number"&&"body"in n?n:null}catch{return null}}async function Ja(e,t,n){try{let r=jt(e);await Lt(q(S(),"bundles"),{recursive:!0});let i={fetchedAt:Date.now(),version:n,body:t};await Pt(r,JSON.stringify(i),{mode:384})}catch{}}async function Qa(e,t,n){try{let i=`${e.replace(/\/+$/,"")}/rules/bundle?agent_id=${encodeURIComponent(n)}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...C(Mt,G)},signal:AbortSignal.timeout(ea)});if(!a.ok)return null;let o=a.headers.get("etag");return{body:await a.json(),version:o}}catch{return null}}async function Xa(e){try{return await Qi(Bt(e)),!0}catch{return!1}}async function eo(e){try{await Lt(q(S(),"sessions"),{recursive:!0}),await Pt(Bt(e),String(Date.now()),{mode:384})}catch{}}export{le as a,ce as b,S as c,Ht as d,Yt as e,Jt as f,Qt as g,aa as h,Ta as i,G as j,fn as k,Ma as l,La as m,Pa as n,Fa as o,Mt as p,Ka as q,ta as r,Za as s,Ya as t,Ja as u,Qa as v,Xa as w,eo as x};
package/dist/cli/hook.js CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import{b as a,i,l as p,v as f,w as m,x as I}from"../chunk-NGPQSN6Z.js";import{a as d,b as c,g as u}from"../chunk-QGBH2FOQ.js";var g=process.env.VISIQ_DEBUG==="1",_=g?(...e)=>{process.stderr.write(`${e.map(String).join(" ")}
2
+ import{b as a,i,l as p,v as f,w as m,x as I}from"../chunk-DDXUI3FD.js";import{a as d,b as c,g as u}from"../chunk-L7EAYGFC.js";var g=process.env.VISIQ_DEBUG==="1",_=g?(...e)=>{process.stderr.write(`${e.map(String).join(" ")}
3
3
  `)}:()=>{},S=console;for(let e of["log","info","debug","warn","error"])S[e]=_;var k={handlePre:(e,o)=>f(e,o),handlePost:(e,o)=>m(e,o),handleSession:(e,o)=>I(e,o),write:e=>{process.stdout.write(e)},reportFailOpen:e=>a(e)};async function h(e,o,s=k){let t=e.hook_event_name==="PreToolUse",r=n=>{t&&s.write(JSON.stringify(i(n)))};try{let n=null;switch(e.hook_event_name){case"PreToolUse":n=await s.handlePre(e,o);break;case"PostToolUse":n=await s.handlePost(e,o);break;case"SessionStart":n=await s.handleSession(e,o);break;default:n=null}n&&s.write(JSON.stringify(n))}catch(n){let l=n instanceof Error?n.message:String(n);o.failMode==="closed"?r(`[VisIQ] harness error \u2014 blocked (VISIQ_FAIL_MODE=closed): ${l}`):await s.reportFailOpen({stage:"handler-crash",detail:l,toolName:e.tool_name,sessionId:e.session_id})}}function v(e,o=process.env){return c(o.VISIQ_FAIL_MODE)??e}function w(e,o,s){let t=e instanceof Error?e.message:String(e),r=v(o,s.env??process.env);try{r==="closed"?s.writeOut(JSON.stringify(i("[VisIQ] harness crashed before evaluating the call \u2014 blocked (VISIQ_FAIL_MODE=closed)."))):s.writeErr(`[VisIQ] FAIL-OPEN (dispatch-crash): ${t} \u2014 tool call proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.
4
4
  `)}catch{}return r}var P=d;function E(){return new Promise(e=>{if(process.stdin.isTTY){e("");return}let o=[],s=!1,t=()=>{s||(s=!0,e(Buffer.concat(o).toString("utf-8")))};setTimeout(t,15e3).unref?.(),process.stdin.on("data",n=>o.push(n)),process.stdin.on("end",t),process.stdin.on("error",t)})}async function D(){let e=p(await E());if(!e)return;let o=e.hook_event_name==="PreToolUse",s=n=>{o&&process.stdout.write(JSON.stringify(i(n)))},{config:t,failMode:r}=await u();if(P=r,!t){r==="closed"?s("[VisIQ] Claude Code harness is loaded but NOT configured \u2014 set VISIQ_API_KEY + VISIQ_AGENT_ID (and optionally VISIQ_ENDPOINT), or run `visiq-claude-code configure`. Blocked because VISIQ_FAIL_MODE=closed."):o&&await a({stage:"unconfigured",detail:"no VisIQ credentials resolved (need VISIQ_API_KEY + VISIQ_AGENT_ID)",toolName:e.tool_name,sessionId:e.session_id},!1);return}await h(e,t)}D().then(()=>process.exit(0)).catch(e=>{w(e,P,{writeOut:o=>process.stdout.write(o),writeErr:o=>process.stderr.write(o)}),process.exit(0)});
package/dist/cli/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as f,e as m,f as w,g as d}from"../chunk-6DMSMBWM.js";import{c as l,d as u,e as g,h as p,t as y}from"../chunk-QGBH2FOQ.js";import{mkdir as I,readFile as v,writeFile as h}from"node:fs/promises";import{existsSync as j}from"node:fs";import{homedir as k}from"node:os";import{dirname as $,isAbsolute as C,join as a,resolve as Q}from"node:path";import{parseArgs as V}from"node:util";function N(){let{positionals:e,values:n}=V({args:process.argv.slice(2),options:{user:{type:"boolean"},project:{type:"boolean"},settings:{type:"string"},command:{type:"string"},"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"}},strict:!1,allowPositionals:!0});return{positionals:e,values:n}}function S(e){let n=e.settings;return typeof n=="string"&&n.length>0?C(n)?n:Q(n):e.project?a(process.cwd(),".claude","settings.json"):a(k(),".claude","settings.json")}async function c(e){if(!j(e))return{};try{let n=await v(e,"utf-8"),t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}}async function P(e,n){await I($(e),{recursive:!0}),await h(e,`${JSON.stringify(n,null,2)}
2
+ import{a as f,e as m,f as w,g as d}from"../chunk-6DMSMBWM.js";import{c as l,d as u,e as g,h as p,t as y}from"../chunk-L7EAYGFC.js";import{mkdir as I,readFile as v,writeFile as h}from"node:fs/promises";import{existsSync as j}from"node:fs";import{homedir as k}from"node:os";import{dirname as $,isAbsolute as C,join as a,resolve as Q}from"node:path";import{parseArgs as V}from"node:util";function N(){let{positionals:e,values:n}=V({args:process.argv.slice(2),options:{user:{type:"boolean"},project:{type:"boolean"},settings:{type:"string"},command:{type:"string"},"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"}},strict:!1,allowPositionals:!0});return{positionals:e,values:n}}function S(e){let n=e.settings;return typeof n=="string"&&n.length>0?C(n)?n:Q(n):e.project?a(process.cwd(),".claude","settings.json"):a(k(),".claude","settings.json")}async function c(e){if(!j(e))return{};try{let n=await v(e,"utf-8"),t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}}async function P(e,n){await I($(e),{recursive:!0}),await h(e,`${JSON.stringify(n,null,2)}
3
3
  `,"utf-8")}async function U(e){let n=S(e),t=typeof e.command=="string"?e.command:f,s=await c(n);return await P(n,m(s,t)),process.stdout.write(`[VisIQ] Installed Claude Code governance hooks \u2192 ${n}
4
4
  SessionStart + PreToolUse + PostToolUse \u2192 \`${t}\`
5
5
  Next: set credentials (\`visiq-claude-code configure\`) then start Claude Code.
package/dist/index.d.ts CHANGED
@@ -244,10 +244,13 @@ export interface CapturedToolSpec {
244
244
  * transform), and mirrors the SDK/plugin RedactionRule + `@visiq/redact` so one
245
245
  * masking primitive is used everywhere. Lifted here (zero-dep) so the shared
246
246
  * unified evaluator (`unified-evaluation.ts`) carries no backend dependency; the
247
- * backend `services/recall-engine.ts` keeps its own identical `RecallRedactionRule`
248
- * for the wire/DB shape — both must stay structurally identical.
247
+ * backend retrieval engine keeps its own structurally identical copy for the
248
+ * wire/DB shape — both must stay structurally identical. (The backend file path
249
+ * is deliberately NOT named: this JSDoc is inlined verbatim into the published
250
+ * type declarations of every harness that bundles this package, where a monorepo
251
+ * path is a customer-visible leak.)
249
252
  */
250
- export interface RecallRedactionRule {
253
+ export interface RetrievalRedactionRule {
251
254
  field?: string;
252
255
  pattern?: string;
253
256
  replacement?: string;
@@ -262,6 +265,22 @@ export interface RecallRedactionRule {
262
265
  keepLast?: number;
263
266
  maskChar?: string;
264
267
  }
268
+ /**
269
+ * @deprecated Renamed to {@link RetrievalRedactionRule}. `Recall` was the retired
270
+ * two-bucket plane name for what is now retrieval governance.
271
+ *
272
+ * KEPT ON PURPOSE, not an oversight: this name is EXPORTED from the published
273
+ * `@visiq/claude-code-harness` type surface (it reached the published type
274
+ * declarations via the decision types), and the backend keeps a copy behind the
275
+ * retired-plane deprecation window. Deleting it would be a breaking API change
276
+ * across an integration boundary, so the rename is ADDITIVE: new code uses
277
+ * `RetrievalRedactionRule`, existing importers keep compiling, and the alias is
278
+ * removed only when the plane deprecation window closes.
279
+ *
280
+ * The repo's package-metadata gate tolerates exactly this name via its
281
+ * `deprecatedAliases` allowance; any OTHER new retired-vocabulary type name reds.
282
+ */
283
+ export type RecallRedactionRule = RetrievalRedactionRule;
265
284
  export type UnifiedDecisionValue = "permit" | "deny" | "approval_required" | "redact" | "escalate" | "mask";
266
285
  /**
267
286
  * Generically-available agent environment reported ONCE at registration
@@ -297,8 +316,11 @@ export interface AgentEnvironment {
297
316
  * never participates in a governance decision. Default-OFF (thoughts are
298
317
  * sensitive) — see UnifiedRuntime.emitCognition.
299
318
  *
300
- * The shape mirrors the framework-agnostic `MindEvent` SSOT the Cortex UI reads
301
- * (products/project-y/apps/web/src/components/allow/agents/cortex/types.ts).
319
+ * The shape mirrors the framework-agnostic `MindEvent` SSOT the Cortex UI reads.
320
+ * The internal path of that SSOT is deliberately NOT named here: this JSDoc is
321
+ * inlined verbatim into the published type declarations of every harness that
322
+ * bundles @visiq/runtime, and a monorepo path there is a customer-visible leak
323
+ * (it shipped in @visiq/claude-code-harness@0.1.7).
302
324
  */
303
325
  export type CognitionBeatKind = "thought" | "speech" | "action" | "observation" | "intervention" | "spawn" | "phase" | "handoff" | "lifecycle" | "error"
304
326
  /** Long/short-term MEMORY access (read/write/search/delete on an agent store). */
@@ -488,7 +510,7 @@ export interface UnifiedRetrievalSubDecision {
488
510
  * for an `escalate` decision whose rule opted into the mask fallback, so a
489
511
  * never-approved retrieval can mask the response instead of being withheld.
490
512
  */
491
- redactionRules?: RecallRedactionRule[];
513
+ redactionRules?: RetrievalRedactionRule[];
492
514
  /**
493
515
  * No-approval policy for an `escalate` decision: 'mask' → a never-approved
494
516
  * request falls back to redacting the response (redactionRules) rather than
@@ -1076,7 +1098,8 @@ export declare function mapPostRedaction(decision: UnifiedDecision, toolResponse
1076
1098
  /**
1077
1099
  * Pure helpers to install/remove the VisIQ hooks in a Claude Code settings.json
1078
1100
  * object. Kept free of I/O so the idempotent merge is exhaustively unit-tested;
1079
- * the CLI (`cli/main.ts`) owns reading/writing the file.
1101
+ * the `visiq-claude-code` CLI bin owns reading/writing the file. (Named by BIN,
1102
+ * not by source path: this JSDoc ships inside the published type declarations.)
1080
1103
  *
1081
1104
  * The harness wires three events to ONE fast dispatcher bin:
1082
1105
  * - SessionStart (all sources) → register + pre-warm the bundle cache
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as x,b as C,c as u,d as H,e as _,f as c,g}from"./chunk-6DMSMBWM.js";import{a as l,b as p,c as m,d,e as f,f as E,g as K,h as V,i as w,j as z,k as G,l as Q,m as T,n as h,o as O,p as S,q as A,r as v,s as P,t as U,u as k,v as B,w as b,x as q}from"./chunk-NGPQSN6Z.js";import{a as e,b as o,c as t,d as r,e as i,f as a,g as n,h as s,q as D,r as F,s as R,t as L,u as y,v as I,w as M,x as N}from"./chunk-QGBH2FOQ.js";export{D as DEFAULT_BUNDLE_TTL_MS,e as DEFAULT_FAIL_MODE,A as HARNESS_KIND,x as HOOK_COMMAND,C as HOOK_TIMEOUT_SECONDS,u as RETRIEVAL_MATCHER,T as WITHHELD_SENTINEL,m as bareToolName,h as blankContent,P as buildEvaluateEvent,G as buildPostRedact,V as buildPreAllow,z as buildPreAsk,w as buildPreDeny,r as configFilePath,v as createRuntime,i as envConfig,E as extractQuery,l as failOpenLogPath,I as fetchBundle,k as finishRuntime,K as formatReason,b as handlePostToolUse,B as handlePreToolUse,q as handleSessionStart,g as hooksInstalled,_ as installHooks,R as isFresh,d as isRetrievalTool,M as isSessionRegistered,H as isVisiqGroup,s as loadConfig,n as loadHarnessState,S as mapPostRedaction,O as mapPreDecision,N as markSessionRegistered,a as mergeConfig,o as normalizeFailMode,Q as parseHookInput,L as readBundleCache,p as reportFailOpen,F as sanitizeId,f as toolOperations,c as uninstallHooks,t as visiqHomeDir,U as warmFromCache,y as writeBundleCache};
1
+ import{a as h,b as x,c as O,d as S,e as C,f as H,g as _}from"./chunk-6DMSMBWM.js";import{a as s,b as p,c as m,d,e as f,f as E,g as K,h as V,i as w,j as z,k as G,l as Q,m as R,n as u,o as T,p as c,q as N,r as A,s as P,t as U,u as k,v as B,w as q,x as b}from"./chunk-DDXUI3FD.js";import{a as e,b as o,c as t,d as r,e as i,f as a,g as n,h as l,q as g,r as D,s as F,t as y,u as L,v,w as I,x as M}from"./chunk-L7EAYGFC.js";export{g as DEFAULT_BUNDLE_TTL_MS,e as DEFAULT_FAIL_MODE,N as HARNESS_KIND,h as HOOK_COMMAND,x as HOOK_TIMEOUT_SECONDS,O as RETRIEVAL_MATCHER,R as WITHHELD_SENTINEL,m as bareToolName,u as blankContent,P as buildEvaluateEvent,G as buildPostRedact,V as buildPreAllow,z as buildPreAsk,w as buildPreDeny,r as configFilePath,A as createRuntime,i as envConfig,E as extractQuery,s as failOpenLogPath,v as fetchBundle,k as finishRuntime,K as formatReason,q as handlePostToolUse,B as handlePreToolUse,b as handleSessionStart,_ as hooksInstalled,C as installHooks,F as isFresh,d as isRetrievalTool,I as isSessionRegistered,S as isVisiqGroup,l as loadConfig,n as loadHarnessState,c as mapPostRedaction,T as mapPreDecision,M as markSessionRegistered,a as mergeConfig,o as normalizeFailMode,Q as parseHookInput,y as readBundleCache,p as reportFailOpen,D as sanitizeId,f as toolOperations,H as uninstallHooks,t as visiqHomeDir,U as warmFromCache,L as writeBundleCache};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visiq/claude-code-harness",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "VisIQ agent-governance harness for the Claude Code CLI — action governance on every tool call, retrieval governance on its built-in read tools and read-shaped MCP tools, and audit-trail reporting, installed as Claude Code hooks.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -31,6 +31,7 @@
31
31
  "publishConfig": {
32
32
  "access": "public"
33
33
  },
34
+ "homepage": "https://docs.visiqlabs.com",
34
35
  "repository": {
35
36
  "type": "git",
36
37
  "url": "https://github.com/VISIQ-LABS/xy.git",
@@ -1,4 +0,0 @@
1
- import{readFile as Ot}from"node:fs/promises";import{homedir as ne}from"node:os";import{join as z,isAbsolute as Rt,resolve as $t}from"node:path";var Dt="https://api.visiqlabs.com",Lt="@visiq/claude-code-harness",re="open";function ie(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function k(){let e=process.env.VISIQ_HOME;return e&&e.trim().length>0?e:z(ne(),".visiq","claude-code")}function Mt(){return z(k(),"config.json")}function Pt(e){return e==="~"||e.startsWith("~/")?z(ne(),e.slice(1).replace(/^\//,"")):e}async function Ft(e){try{let t=Rt(e)?e:$t(e),n=await Ot(t,"utf-8");return JSON.parse(n)}catch{return null}}function R(e,...t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function ee(e){if(!e||typeof e!="object")return{};let t=e,n={},r=R(t,"apiKey","api_key"),i=R(t,"agentId","agent_id"),a=R(t,"baseUrl","base_url"),o=ie(R(t,"failMode","fail_mode"));return r&&(n.apiKey=r),i&&(n.agentId=i),a&&(n.baseUrl=a),o&&(n.failMode=o),n}async function te(e){if(!e)return{};let t=await Ft(Pt(e));if(!t||typeof t!="object")return{};let n=t,r=n.plugins?.entries,i=r&&typeof r=="object"?r[Lt]:void 0;return i&&typeof i=="object"&&i.config?ee(i.config):ee(n)}function jt(e=process.env){let t={};e.VISIQ_API_KEY&&(t.apiKey=e.VISIQ_API_KEY),e.VISIQ_AGENT_ID&&(t.agentId=e.VISIQ_AGENT_ID),e.VISIQ_BASE_URL?t.baseUrl=e.VISIQ_BASE_URL:e.VISIQ_ENDPOINT&&(t.baseUrl=e.VISIQ_ENDPOINT);let n=ie(e.VISIQ_FAIL_MODE);return n&&(t.failMode=n),t}function Bt(e,t,n){let r={...e,...t,...n};if(!r.apiKey||!r.agentId)return null;let i={apiKey:r.apiKey,agentId:r.agentId,failMode:r.failMode??re};return i.baseUrl=r.baseUrl||Dt,i}async function Ut(){let e=jt(),t=await te(process.env.VISIQ_CONFIG_PATH),n=await te(Mt()),r={...n,...t,...e};return{config:Bt(n,t,e),failMode:r.failMode??re}}async function $i(){return(await Ut()).config}import{mkdir as It,readFile as Ii,writeFile as Et,stat as Ei}from"node:fs/promises";import{createHash as Ci}from"node:crypto";import{join as U}from"node:path";import{z as c}from"zod";import*as v from"node:os";import{randomUUID as Xt}from"node:crypto";var q=1,oe="X-VisIQ-SDK",se="X-VisIQ-Dialect",le="unknown";function E(e,t=1){return{[oe]:e&&e.length>0?e:le,[se]:String(t)}}var ce="interceptor_source",zt=c.enum(["enforce","audit","off"]),qt=c.enum(["closed","open"]),de=c.enum(["enforce","monitor","off"]),Gt=c.object({apiKey:c.string().min(1,"apiKey is required"),agentId:c.string().min(1,"agentId is required"),endpoint:c.string().url().optional(),mode:zt.optional(),timeoutMs:c.number().int().positive().optional(),hitlTimeoutMs:c.number().int().positive().optional(),failBehavior:qt.optional()}),Mi=c.object({agent_id:c.string().min(1),target_app:c.string().min(1),action:c.string().min(1),context:c.record(c.unknown()).optional(),session_id:c.string().min(1).max(255).optional(),action_schema_id:c.string().min(1).max(128).optional(),telemetry:c.record(c.unknown()).optional()}),Vt=c.object({field:c.string().optional(),pattern:c.string().optional(),replacement:c.string().optional(),mode:c.enum(["full","partial","email"]).optional(),keepFirst:c.number().optional(),keepLast:c.number().optional(),maskChar:c.string().optional()}),Wt=c.object({decision_id:c.string().min(1),decision:c.enum(["permit","deny","approval_required","mask"]),reason:c.string().optional(),rule_code:c.string().nullable().optional(),enforced:c.boolean().optional(),agent_mode:de.optional(),arg_redaction_rules:c.array(Vt).optional(),plane:c.string().nullable().optional(),operation:c.string().nullable().optional(),is_retrieval:c.boolean().optional(),metadata:c.record(c.unknown()).optional()}),Ht=c.object({field:c.string().min(1),operator:c.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:c.union([c.string(),c.number(),c.array(c.string())])}),Kt=c.object({id:c.string().min(1),rule_code:c.string().default(""),name:c.string().min(1),description:c.string().nullable().default(null),effect:c.enum(["allow","deny","hitl","mask"]),resource_type:c.string().min(1),rego_source:c.string().default(""),target_app:c.string().nullable().default(null),action_pattern:c.string().nullable().default(null),conditions:c.array(Ht).default([]),priority:c.number().int().default(0)}),Yt=c.object({version:c.string().min(1),agent_mode:de.optional(),rules:c.array(Kt),no_coverage:c.object({no_coverage_defaults:c.record(c.string()),autopilot_enabled:c.boolean(),enduser_hitl_enabled:c.boolean(),hitl_timeout_seconds:c.number()}).optional()}),Zt=2e3,ue=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return E(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 Wt.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 Yt.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}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{system_prompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{tool_schemas:e.toolSchemas}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let o=a,s=o.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof o.reason=="string"?o.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await Jt(Zt)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Jt(e){return new Promise(t=>setTimeout(t,e))}function G(){let e={};try{let t=`${v.platform()} ${v.release()}`.trim();t&&(e.os=t)}catch{}try{let t=v.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=v.userInfo();t&&(e.username=t)}catch{}try{let t=Qt();t&&(e.ip=t)}catch{}return e}function Qt(){let e=v.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}var ae=new Map;function en(e){let t=(ae.get(e)??0)+1;return ae.set(e,t),t}function tn(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:Xt(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:en(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}:{}}})}import{z as u}from"zod";import{createHash as nn}from"crypto";import{createHash as Cn}from"crypto";var pe=new Map;function fe(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function V(e){let t=nn("sha256").update(e).digest("hex"),n=pe.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
2
- `).map(l=>rn(l)).filter(l=>l.trim().length>0),o=0;for(;o<a.length;){let l=a[o].trim();if(l.startsWith("package ")||l.startsWith("import ")){o++;continue}let d=l.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(d){let h=d[1],f=d[2].trim();r.set(h,T(f)),o++;continue}let p=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(p){let h=p[1],f=p[2].trim(),g=p[3].trim(),y=[];if(g&&g!=="}"){let I=g.endsWith("}")?g.slice(0,-1).trim():g;I&&y.push(I),g.endsWith("}")||(o++,o=$(a,o,y))}else g==="}"||(o++,o=$(a,o,y));let b=me(y);i.push({variable:h,value:T(f),conditions:b,rawConditions:fe(y)}),o++;continue}let m=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(m){let h=m[1],f=m[2].trim(),g=[];if(f&&f!=="}"){let b=f.endsWith("}")?f.slice(0,-1).trim():f;b&&g.push(b),f.endsWith("}")||(o++,o=$(a,o,g))}else f==="}"||(o++,o=$(a,o,g));let y=me(g);i.push({variable:h,value:"true",conditions:y,rawConditions:fe(g)}),o++;continue}o++}let s={defaults:r,rules:i};return pe.set(t,s),s}function rn(e){let t=!1,n="";for(let r=0;r<e.length;r++){let i=e[r];if(t)i===n&&e[r-1]!=="\\"&&(t=!1);else if(i==='"'||i==="'")t=!0,n=i;else if(i==="#")return e.slice(0,r)}return e}function $(e,t,n){let r=1,i=t;for(;i<e.length&&r>0;){let a=e[i].trim();for(let o of a)o==="{"&&r++,o==="}"&&r--;if(r>0)n.push(a),i++;else{let o=a.slice(0,a.lastIndexOf("}")).trim();return o&&n.push(o),i}}return i}function T(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function an(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function me(e){let t=[];for(let n of e){let r=n.split(";").map(i=>i.trim()).filter(i=>i.length>0);for(let i of r){let a=on(i);a&&t.push(a)}}return t}function on(e){let t=!1,n=e.trim();if(n.startsWith("not ")&&(t=!0,n=n.slice(4).trim()),n==="true"||n==="false")return{type:"literal_bool",negated:t,field:"",value:n==="true"};if(n.includes("[_]"))return{type:"truthy",negated:!1,field:L,value:e.trim()};let r=n.match(/^count\(([^)]+)\)\s*(>=|<=|>|<)\s*(\d+)$/);if(r)return{type:"count_gt",negated:t,field:r[1].trim(),operator:r[2],value:parseInt(r[3],10)};let i=n.match(/^startswith\(([^,]+),\s*"([^"]*)"\)$/);if(i)return{type:"startswith",negated:t,field:i[1].trim(),value:i[2]};let a=n.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(a)return{type:"endswith",negated:t,field:a[1].trim(),value:a[2]};let o=n.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"contains",negated:t,field:o[1].trim(),value:o[2]};let s=n.match(/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:an(s[1])};let l=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s+in\s+((?:input|data)[^\s]*)$/);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:Ae(l[1])};let d=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(d){let y=cn(d[2]);if(y!==null)return{type:"in_set",negated:t,field:d[1].trim(),values:y}}let p=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(p)return{type:"comparison",negated:t,field:p[1].trim(),operator:p[2],value:parseFloat(p[3])};let m=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s*==\s*((?:input|data)\S*)$/);if(m)return{type:"equality",negated:t,field:m[2].trim(),value:T(m[1].trim())};let h=n.match(/^([^\s=!]+)\s*==\s*(.+)$/);if(h)return{type:"equality",negated:t,field:h[1].trim(),value:T(h[2].trim())};let f=n.match(/^([^\s=!]+)\s*!=\s*(.+)$/);if(f)return{type:"inequality",negated:t,field:f[1].trim(),value:T(f[2].trim())};let g=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return g?{type:"truthy",negated:t,field:g[1].trim()}:{type:"truthy",negated:!1,field:L,value:e.trim()}}var L="__unrecognized_condition_forces_deny__";var sn=/[A-Za-z_][A-Za-z0-9_.]*\s*\(/;function ve(e){let t=[];for(let n of e.rules)for(let r of n.conditions)typeof r.field=="string"&&r.field!==L&&sn.test(r.field)&&t.push(r.field);return t}var ln=["input.normalized.","input.normalized["];function we(e){let t=new Set;for(let n of e.rules)for(let r of n.conditions){let{field:i}=r;typeof i!="string"||i===L||ln.some(a=>i.startsWith(a))&&t.add(i)}return[...t].sort()}function Ae(e){let t=e.trim();return t==="true"?!0:t==="false"?!1:/^-?\d+(?:\.\d+)?$/.test(t)?parseFloat(t):t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function cn(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",i=!1,a="";for(let s=0;s<t.length;s++){let l=t[s];i?(r+=l,l===a&&t[s-1]!=="\\"&&(i=!1)):l==='"'||l==="'"?(r+=l,i=!0,a=l):l===","?(n.push(r.trim()),r=""):r+=l}if(i)return null;r.trim().length>0&&n.push(r.trim());let o=[];for(let s of n){let l=s.startsWith('"')&&s.endsWith('"')&&s.length>=2||s.startsWith("'")&&s.endsWith("'")&&s.length>=2,d=/^-?\d+(?:\.\d+)?$/.test(s);if(!l&&!d&&!(s==="true"||s==="false"))return null;o.push(Ae(s))}return o}var dn=["tier1","tier2","tier3"];function ke(e){return typeof e=="string"&&dn.includes(e)}var un=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],pn=["internal","customer_facing","experimental","third_party"],Se=[...un,...pn];function fn(e){return typeof e=="string"&&Se.includes(e)}function Ie(e){let t=new Set;for(let n of e)fn(n)&&t.add(n);return Se.filter(n=>t.has(n))}var Ee=["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"],mn=["version_control","payments","crm","communication","cloud_infra","identity","data_warehouse","ticketing","hr","finance_erp","storage","database","other"],gn=["production","staging","development","test"],hn=["security","engineering","finance","legal","compliance","hr","sales","marketing","support","operations","executive"];function _n(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 ge={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 yn(e){let t=_n(e);return t===null?"other":ge[t]??ge[t.replace(/_/g,"")]??"other"}function Ce(e,t){let n={...e};if(t.targetApp!==void 0&&t.targetApp!==null){let r=n.context&&typeof n.context=="object"&&!Array.isArray(n.context)?{...n.context}:{};r.app_category===void 0&&(r.app_category=yn(t.targetApp)),n.context=r}return n}var he=["pii","phi","pci","financial","biometric","genetic","location","communications","children","credentials","special_category_gdpr"],bn=["read","write","delete","share","export","decide","execute"],_e=["none","low","medium","high","critical"],vn=["public","internal","confidential","restricted","credentials","api_key","private_key","password","secret","token","pan","full_pan","card_number","track_data","cvv","cvc","ssn","tax_id","national_id","passport","drivers_license","identity_document","document_number","kyc_document","bank_account","account_number","routing_number","iban","account_balance","customer_financial","credit_score","net_worth","income","financial_profile","employee_pii","payroll","compensation","material_nonpublic","pre_release_earnings","mnpi","attorney_client","legal_hold","privileged","special_category_gdpr","gdpr_special_category","biometric","ethnicity","political_opinion","health_special","religion"],wn={action_class:Ee,operation:bn,"context/app_category":mn,"context/environment":gn,"context/actor_function":hn,"read/classification":vn,"read/data_categories":he,"read/data_sensitivity":_e,"write/data_categories":he,"write/data_sensitivity":_e};function Te(e){if(e===null||typeof e!="object")return[];let t=e,n=new Set,r=(i,a,o)=>{let s=Array.isArray(a)?a:[a];for(let l of s)typeof l!="string"||l.length===0||o.includes(l)||n.add(`${i}=${l}`)};for(let[i,a]of Object.entries(wn)){Object.prototype.hasOwnProperty.call(t,i)&&r(i,t[i],a);let o=i.indexOf("/");if(o===-1)continue;let s=t[i.slice(0,o)];if(s!==null&&typeof s=="object"&&!Array.isArray(s)){let l=i.slice(o+1),d=s;Object.prototype.hasOwnProperty.call(d,l)&&r(i,d[l],a)}}return[...n].sort()}var ye=64,An=64,N={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function Ne(){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 C(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>ye?r.slice(0,ye):r}function be(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function D(e){return typeof e=="string"&&e.length>0?e:null}function xe(e,t){let n=be(t.data_categories),r=D(t.classification),i=be(t.taint),a=D(t.action_class),o=a&&Ee.includes(a)?a:null,s=D(t.target_app),l=D(t.decision),d={...e.action_counts};if(o)if(o in d)d[o]=(d[o]??0)+1;else if(Object.keys(d).length<An)d[o]=1;else{let p=Object.keys(d).sort(),m=p[p.length-1];m!==void 0&&o<m&&(delete d[m],d[o]=1)}return{retrieved_data_categories:C(e.retrieved_data_categories,n),retrieved_classifications:C(e.retrieved_classifications,r?[r]:[]),taint:C(e.taint,i),action_classes:C(e.action_classes,o?[o]:[]),action_counts:d,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&&kn.has(l)?1:0),event_count:e.event_count+1,target_apps:C(e.target_apps,s?[s]:[])}}var Oe="generic",Re=[{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:Oe,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."}],Sn=Re.map(e=>e.id),Ui=new Map(Re.map(e=>[e.id,e])),zi=new Set(Sn);function $e(e){return Array.isArray(e)&&e.length>0?[...e]:[Oe]}var In=/^[a-z][a-z0-9_]*$/;function De(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&In.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var En=["narrow","moderate","broad","unbounded","unknown"];function Le(e){return typeof e=="string"&&En.includes(e)}function Me(e){return e==="open"||e==="closed"?e:null}var Tn=["tool_name","function","name","action"];function M(e,t,n){if(Array.isArray(e)){if(e.length===0){n.push([`${t}[]`,void 0]);return}for(let r of e)M(r,`${t}[]`,n);return}if(e!==null&&typeof e=="object"){let r=Object.entries(e);if(r.length===0){t&&n.push([t,void 0]);return}for(let[i,a]of r)M(a,t?`${t}.${i}`:i,n);return}t&&n.push([t,e])}function Nn(e){let t=[];return M(e,"",t),[...new Set(t.map(([n])=>n))].sort()}function xn(e){let t=e.slice(e.lastIndexOf(".")+1);return t.endsWith("[]")?t.slice(0,-2):t}function On(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().toLowerCase();return t.length>0?t:null}function Rn(e,t={}){if(t.discriminatorField===null)return null;let n=[];M(e,"",n);let r=t.discriminatorField?[t.discriminatorField]:t.discriminatorFields??Tn;for(let i of r){let a=null;for(let[o,s]of n){if(xn(o)!==i)continue;let l=On(s);l!==null&&(a===null||o<a.path)&&(a={path:o,value:l})}if(a)return a.value}return null}function Pe(e,t={}){let n=Cn("sha256").update(Nn(e).join(",")).digest("hex").slice(0,16),r=Rn(e,t);return r!==null?`${n}:${r}`:n}var $n=["action","retrieval","delegation"];function Dn(e){return typeof e=="string"&&$n.includes(e)}var Ln=new Set(["rules"]);function Fe(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Ln.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Dn):[];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 j}from"zod";var Ke="[REDACTED]",Ye=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"in_pan_tax",re:/\b[A-Z]{3}[ABCFGHJLPTE][A-Z]\d{4}[A-Z]\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"date_of_birth",re:/\b(?:\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])|(?:0[1-9]|[12]\d|3[01])[/.](?:0[1-9]|1[0-2])[/.]\d{4}|(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12]\d|3[01])\/\d{4})\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];function H(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 Mn(e){let t=e.replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let i=0;i<n.length;i++){let a=n[i],o=a>="A"&&a<="Z"?String(a.charCodeAt(0)-55):a;for(let s=0;s<o.length;s++)r=(r*10+(o.charCodeAt(s)-48))%97}return r===1}function Pn(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 Fn=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],jn=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]];function Bn(e){if(!/^\d+$/.test(e))return!1;let t=0,n=e.split("").reverse();for(let r=0;r<n.length;r++)t=Fn[t][jn[r%8][n[r].charCodeAt(0)-48]];return t===0}function Un(e){if(!/^\d{11}$/.test(e)||/^(\d)\1{10}$/.test(e))return!1;let t=n=>{let r=0;for(let a=0;a<n;a++)r+=(e.charCodeAt(a)-48)*(n+1-a);let i=r*10%11;return i===10?0:i};return t(9)===e.charCodeAt(9)-48&&t(10)===e.charCodeAt(10)-48}function zn(e){if(!/^\d{10}$/.test(e))return!1;let t=0;for(let i=0;i<9;i++)t+=(e.charCodeAt(i)-48)*(10-i);let n=11-t%11,r=n===11?0:n;return r!==10&&r===e.charCodeAt(9)-48}var qn=[1,4,3,7,5,8,6,9,10];function Gn(e){if(!/^\d{8,9}$/.test(e))return!1;let t=0;for(let n=0;n<e.length;n++)t+=(e.charCodeAt(n)-48)*qn[n];return t%11===0}var Vn="TRWAGMYFPDXBNJZSQVHLCKE";function Wn(e){let t=e.replace(/[\s-]/g,"").toUpperCase(),n=/^([XYZ]?)(\d{7,8})([A-Z])$/.exec(t);if(!n)return!1;let[,r,i,a]=n;if(r===""&&i.length!==8||r!==""&&i.length!==7)return!1;let o=r===""?i:String("XYZ".indexOf(r))+i;return Vn[Number(o)%23]===a}var Hn=new Set(["BG","GB","NK","KN","TN","NT","ZZ"]);function Kn(e){let t=e.replace(/[\s-]/g,"").toUpperCase();return/^[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z]\d{6}[A-D]$/.test(t)?!Hn.has(t.slice(0,2)):!1}var Yn=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&H(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:Mn},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Pn},{name:"uk_nino",re:/\b[A-Za-z]{2} ?\d{2} ?\d{2} ?\d{2} ?[A-Da-d]\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:(e,t)=>t!==void 0&&t===t.toLowerCase()?!1:Kn(e)},{name:"in_aadhaar",re:/\b[2-9]\d{3}[ -]?\d{4}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===12&&Bn(e)},{name:"br_cpf",re:/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,normalize:e=>e.replace(/[.-]/g,""),validate:Un},{name:"es_dni_nie",re:/\b[XYZxyz]?\d{7,8}[ -]?[A-Za-z]\b/g,normalize:e=>e.replace(/[\s-]/g,"").toUpperCase(),validate:Wn},{name:"ca_sin",re:/\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:e=>e.length===9&&H(e)},{name:"uk_nhs_number",re:/\b\d{3}[ -]?\d{3}[ -]?\d{4}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:zn},{name:"au_tfn",re:/\b\d{3}[ -]?\d{3}[ -]?\d{2,3}\b/g,normalize:e=>e.replace(/[\s-]/g,""),validate:Gn}],_=Object.fromEntries(Ye.map(e=>[e.name,e.re.source])),Ze=["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","pan","iban","aba_routing","us_ein","swift_bic","ssn","uk_nino","in_aadhaar","in_pan_tax","br_cpf","es_dni_nie","ca_sin","uk_nhs_number","au_tfn","email","us_phone","date_of_birth","ipv4","mac_address"],Y={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
3
- MIIEv\u2026
4
- -----END PRIVATE KEY-----`,template:{pattern:_.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:_.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:_.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:_.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:_.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:_.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:_.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:_.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:_.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:_.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS). Collision rate: MEASURED 9.8% of benign 16-digit runs \u2014 Luhn leaves ~1 in 10. Default-ON because PCI-DSS makes masking mandatory; note in_aadhaar sits at the same rate and is often proposed for removal on that basis.",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\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. Collision rate: MEASURED 1.0% \u2014 mod-97 leaves ~1 in 97, the most precise detector on this floor alongside br_cpf.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\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). Collision rate: MEASURED 100% \u2014 no checksum, so every 2-then-7 dashed digit run matches. Same trade as ssn: the punctuated shape is rare in benign traffic, not precise.",category:"financial",example:"12-3456789",template:{pattern:_.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:_.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789). Collision rate: MEASURED 100% \u2014 there is NO checksum, so every dashed 3-2-4 digit run matches. Default-ON regardless, because that punctuated shape is essentially absent from benign agent traffic; if your traffic carries 3-2-4 dashed reference codes, opt out.",category:"pii",example:"123-45-6789",template:{pattern:_.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},uk_nino:{id:"uk_nino",label:"UK National Insurance numbers",description:"UK NINOs (e.g. AB 12 34 56 C). DEFAULT-OFF \u2014 NO CHECKSUM. Precision comes only from the issued alphabet and the never-issued administrative prefixes (BG, GB, NK, KN, TN, NT, ZZ), so roughly half of tokens already shaped 2-letters/6-digits/[A-D] validate. All-lowercase candidates are rejected (git short SHAs), but that does NOT exclude uppercase business identifiers \u2014 serial, part, batch, PO, coupon and asset tags share the shape exactly and were measured being masked. Opt in when UK NINOs are expected in your traffic.",category:"pii",example:"AB 12 34 56 C",template:{pattern:"\\b[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-D]\\b",mode:"full"},defaultEnabled:!1},in_aadhaar:{id:"in_aadhaar",label:"Aadhaar numbers (India)",description:"12-digit UIDAI Aadhaar numbers, Verhoeff-checksum validated and constrained to the issued 2-9 leading digit. Keeps the last 4 visible. Collision rate: MEASURED 10.0% of benign 12-digit ids starting 2-9 (order/transaction numbers) \u2014 Verhoeff leaves ~1 in 10. Comparable to the long-shipped pan (10.0%) and well behind iban (1.0%); it stays default-ON because the two US identifiers this floor has always shipped, ssn and us_ein, collide at 100%.",category:"pii",example:"2345 6789 0124",template:{pattern:"\\b[2-9]\\d{3}\\s\\d{4}\\s\\d{4}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},in_pan_tax:{id:"in_pan_tax",label:"India PAN (tax ID)",description:"India Permanent Account Number \u2014 the income-tax id (ABCPE1234F), NOT a payment-card PAN. NO CHECKSUM: the only discriminator is the holder-type letter in position 4, which removes just 15 of 26 possibilities in one position, so roughly 4 in 10 uniform 5-letter/4-digit/1-letter tokens validate. DEFAULT-OFF for that reason \u2014 an uppercase SKU or part number of the same shape is masked, and nothing in the value distinguishes it.",category:"financial",example:"ABCPE1234F",template:{pattern:_.in_pan_tax,mode:"full"},defaultEnabled:!1},br_cpf:{id:"br_cpf",label:"CPF numbers (Brazil)",description:"Brazilian CPF, closed by TWO independent mod-11 check digits. Collision rate: MEASURED 1.0% of benign 11-digit runs (~1-in-100) \u2014 the most precise detector on this floor, alongside iban. Repdigits are rejected. Keeps the last 2 visible.",category:"pii",example:"123.456.789-09",template:{pattern:"\\b\\d{3}\\.\\d{3}\\.\\d{3}-\\d{2}\\b",mode:"partial",keepLast:2},defaultEnabled:!0},es_dni_nie:{id:"es_dni_nie",label:"DNI / NIE numbers (Spain)",description:"Spanish national ID (8 digits + letter) and foreigner ID (X/Y/Z + 7 digits + letter), validated by the mod-23 check letter. Collision rate: MEASURED 4.0% of benign 8-digit-plus-letter tokens (invoice/order numbers with a suffix letter) \u2014 mod-23 leaves ~1 in 23. More precise than in_aadhaar (10.0%) and pan (10.0%); behind br_cpf (1.0%) and iban (1.0%).",category:"pii",example:"12345678Z",template:{pattern:"\\b[XYZ]?\\d{7,8}[A-Z]\\b",mode:"full"},defaultEnabled:!0},ca_sin:{id:"ca_sin",label:"SIN numbers (Canada)",description:"Canadian Social Insurance Numbers (9-digit, Luhn-validated). DEFAULT-OFF \u2014 identical shape to an ABA routing number and to any 9-digit id, with only a mod-10 pass to separate them.",category:"pii",example:"046 454 286",template:{pattern:"\\b\\d{3}[- ]\\d{3}[- ]\\d{3}\\b",mode:"partial",keepLast:3},defaultEnabled:!1},uk_nhs_number:{id:"uk_nhs_number",label:"NHS numbers (UK)",description:"UK NHS patient numbers (10-digit, weighted mod-11). DEFAULT-OFF \u2014 a 10-digit run is also every North American phone number.",category:"pii",example:"943 476 5919",template:{pattern:"\\b\\d{3}[- ]\\d{3}[- ]\\d{4}\\b",mode:"full"},defaultEnabled:!1},au_tfn:{id:"au_tfn",label:"Tax File Numbers (Australia)",description:"Australian TFNs (8-9 digit, weighted mod-11). DEFAULT-OFF \u2014 collides with essentially every 8-9 digit identifier.",category:"financial",example:"123 456 782",template:{pattern:"\\b\\d{3}[- ]\\d{3}[- ]\\d{2,3}\\b",mode:"full"},defaultEnabled:!1},date_of_birth:{id:"date_of_birth",label:"Dates of birth",description:"Dates in the common written formats. DEFAULT-OFF and heavily over-masking by nature \u2014 a DOB is indistinguishable from any other date (created_at, invoice, release). Offered because DOB is a GDPR/HIPAA identifier some regulated tenants must mask regardless.",category:"pii",example:"1985-04-12",template:{pattern:_.date_of_birth,mode:"full"},defaultEnabled:!1},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept). Collision rate: MEASURED 100% of well-formed addresses \u2014 that is BY DESIGN, not a defect: an email address is structurally unambiguous, so matching every one is correct rather than over-matching.",category:"pii",example:"alice@acme.com",template:{pattern:_.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:_.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:_.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:_.mac_address,mode:"full"},defaultEnabled:!1}};var Vi=new Set(Ze.filter(e=>!Y[e].defaultEnabled));function Zn(e,t){let n=new Set;for(let r of Ze)(Y[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function Jn(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=e;for(let{name:a,re:o}of Ye){let s=a;n.has(s)||(i=i.replace(o,()=>(r?.(s),t)))}for(let{name:a,re:o,normalize:s,validate:l}of Yn)n.has(a)||(i=i.replace(o,d=>l(s(d),d)?(r?.(a),t):d));return i}function Je(e,t=Ke,n,r){return Qn(e,t,Zn(n,r))}function Qn(e,t,n){let r=new Set,i=!n.has("pan"),a=s=>{r.add(s)},o=s=>{if(typeof s=="string")return Jn(s,t,n,a);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!i)return s;let l=String(s);return l.length>=13&&l.length<=19&&H(l)?(r.add("pan"),t):s}if(Array.isArray(s))return s.map(l=>o(l));if(s!==null&&typeof s=="object"){let l=s,d={};for(let p of Object.keys(l))d[p]=o(l[p]);return d}return s};return{value:o(e),detectors:[...r].sort()}}function Qe(e,t=Ke){return Je(e,t).value}var Xn=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,Xe=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"}),er=new RegExp(`[${Object.keys(Xe).join("")}]`,"gu"),tr=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),et="\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",nr=Object.freeze(Object.fromEntries([...et].map((e,t)=>[e,String.fromCharCode(97+t)]))),rr=new RegExp(`[${et}\u2800]`,"g"),tt=/[⠀-⣿]/;function ir(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 ar(e){return e.replace(Xn,"")}function nt(e){return e.replace(er,t=>Xe[t]??t)}function or(e){return e.replace(/[4@31!05$79(8]/g,t=>tr[t]??t)}function sr(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 lr(e){return tt.test(e)?e.replace(rr,t=>t==="\u2800"?" ":nr[t]??t):e}function je(e){let t;try{t=ir(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=ar(t),t=nt(t),t}var cr=/^[A-Za-z0-9+/]{16,}={0,2}$/,dr=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,Be=/[A-Za-z0-9+/]{20,}={0,2}/g;function K(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 it(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 ur(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 Ue(e){let t=e.trim(),n=[];if(dr.test(t))for(let r of ur(t))n.push({decoded:r,textiness:K(r)});if(cr.test(t)&&t.length%4===0)for(let r of it(t))n.push({decoded:r,textiness:K(r)});return n}function ze(e,t){let n=[],r;for(Be.lastIndex=0;(r=Be.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let a of it(i))n.push({decoded:a,textiness:K(a)})}return n}var pr=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function at(e,t=pr){if(typeof e!="string"||e.length===0)return{views:[],anyDecoded:!1,truncated:!1,nodes:0,maxDepthSeen:0};let{maxDepth:n,byteCap:r,maxNodes:i,maxBlobsPerNode:a}=t,o=new Set,s=f=>{f.length>0&&f.length<=r&&o.add(f)},l=!1,d=!1,p=0,m=0,h=[{s:e,depth:0}];for(;h.length>0;){if(p>=i){d=!0;break}let f=h.pop();if(f===void 0)break;let{s:g,depth:y}=f;if(g.length>r){d=!0;continue}p++,y>m&&(m=y);let b=je(g);s(b);let I=or(b);if(I!==b&&s(I),s(sr(b)),tt.test(g)&&s(lr(b)),y>=n){let w=je(g);(Ue(w).length>0||ze(w,a).length>0)&&(d=!0);continue}let xt=[...Ue(b),...ze(b,a)];for(let w of xt){if(l=!0,w.decoded.length>r){d=!0;continue}w.textiness>=.85&&w.decoded!==b?h.push({s:w.decoded,depth:y+1}):s(w.decoded)}}return{views:[...o],anyDecoded:l,truncated:d,nodes:p,maxDepthSeen:m}}var ot=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],fr=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),mr=8,gr=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),qe=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function hr(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||gr.has(i)&&qe(t[r-1])&&qe(t[r+1])&&(n++,n>=mr))return!0}return!1}var _r=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function yr(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(_r.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var br=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function vr(e){for(let t of br)if(e>=t.lo&&e<=t.hi)return t.name;return null}function wr(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=vr(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 Ge=Object.freeze({signals:[],contributes:!1});function Ar(e){if(typeof e!="string"||e.length===0)return{...Ge,signals:[]};let t=new Set;try{hr(e)&&t.add("hidden_text_carrier"),yr(e)&&t.add("injected_turn_boundary"),wr(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=at(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Ge,signals:[]}}return{signals:[...ot.filter(n=>t.has(n))],contributes:fr.some(n=>t.has(n))}}var F=[{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 Ve(e){return typeof e!="string"||e.length===0?[]:F.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function kr(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(Ve(e)),{views:n}=at(e);for(let r of n)for(let i of Ve(r))t.add(i);return F.filter(r=>t.has(r.name)).map(r=>r.name)}function Sr(e){let t=new Set,n=new Set,r=!1,i=a=>{if(a!=null){if(typeof a=="string"){for(let s of kr(a))t.add(s);let o=Ar(a);for(let s of o.signals)n.add(s);o.contributes&&(r=!0);return}if(Array.isArray(a)){for(let o of a)i(o);return}if(typeof a=="object")for(let o of Object.values(a))i(o)}};return i(e),{matched:t.size>0||r,signatures:F.filter(a=>t.has(a.name)).map(a=>a.name),structural:ot.filter(a=>n.has(a))}}function Ir(e){return Sr(e).matched}var Wi=F.map(e=>e.name);var Er=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Cr="i:injection";function st(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=Je(e.content);for(let a of i){let o=Y[a]?.category;o&&t.add(`c:${o}`)}Ir(e.content)&&t.add(Cr)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Er.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var W="(?: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))",Hi=[{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${W}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${W}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${W}\\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}],We="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Tr=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${We}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${We}|programming|training))`,Nr="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",He="(?:\\b(?:unrestricted|unfiltered|uncensored|unbounded|unlimited|unchained|jailbroken|lawless|amoral)\\b|\\b(?:DAN|STAN|DUDE|AIM)\\b|\\bno\\s+(?:longer\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|boundaries|constraints?)\\b(?!\\s+(?:on|over|regarding|upon|for)\\b)|\\bwithout\\s+(?:any\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|constraints?|censorship)\\b|\\b(?:free|freed|released)\\s+from\\s+(?:your\\s+)?(?:restrictions?|limits?|rules?|guidelines?|guardrails?|programming|constraints?)\\b|\\b(?:can|will|are\\s+able\\s+to)\\s+(?:do|say)\\s+anything\\b|\\bignore\\s+(?:all\\s+)?(?:your\\s+)?(?:previous\\s+|prior\\s+|system\\s+)?(?:instructions?|rules?|guidelines?)\\b)",xr="(?:ignore|disregard|forget|override|overrule|bypass|obey|comply\\s+with|follow\\s+(?:only|my|these))",Ki=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${Nr}${Tr}\\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}?${He}`,"i")},{name:"constraint_release",re:/\byou\s+are\s+no\s+longer\s+(?:bound|restricted|limited|constrained|obligated|governed|subject\s+to|required\s+to)\b/i},{name:"from_now_on_reassignment",re:new RegExp(`\\bfrom\\s+now\\s+on\\s*,?\\s+you\\s+(?:are|will|must|shall|have|can)\\s+(?:${xr}\\b|[\\s\\S]{0,40}?${He})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Yi=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var A=e=>`[^.!?;\\n]{0,${e}}?`,Or=["\\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("|"),lt="(?: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)",Zi=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Or})\\s${A(40)}\\b${lt}\\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${A(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${A(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${A(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${A(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${A(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")}]),Ji=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${A(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${A(30)}\\b${lt}\\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 x=e=>`[^.!?;\\n]{0,${e}}?`,Qi=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${x(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${x(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${x(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${x(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${x(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 Z="[REDACTED]",S="\u2022",P=e=>/[A-Za-z0-9]/.test(e);function ct(e,t,n,r){let i=Array.from(e),a=i.length,o=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:S,d=o+s>=a;return i.map((p,m)=>!d&&(m<o||m>=a-s)?p:P(p)?l:p).join("")}function Rr(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return ct(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:S;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(o=>P(o)?a:o).join(""))+i}function $r(e,t,n){let r=n.length>0?n:S,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 m=p.index;m<p.index+p[0].length;m++)i[m]=!0}}catch{}let a=!1,o=!0;for(let d=0;d<e.length;d++)if(P(e[d])&&(a=!0,!i[d])){o=!1;break}let s=a&&o,l="";for(let d=0;d<e.length;d++){let p=e[d];!s&&i[d]||!P(p)?l+=p:l+=r}return l}function dt(e,t){let n=t.mode??"full";return n==="partial"?ct(e,t.keepFirst??0,t.keepLast??0,t.maskChar??S):n==="email"?Rr(e,t.maskChar??S):n==="custom"?$r(e,t.keepPattern,t.maskChar??S):t.replacement??Z}function Dr(e,t){return typeof e=="string"?dt(e,t):t.replacement??Z}function ut(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=>dt(a,r)})}return t}function pt(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(a,o=>i(o))}return n}function Xi(e,t){return e==null?e:typeof e=="string"?Lr(e,t):typeof e=="object"?Mr(e,t):e}function Lr(e,t){if(typeof e!="string")return e;let n=ut(t);return n.length===0?e:pt(e,n)}function Mr(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=ut(t),i=n.size>0,a=r.length>0,o=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>o(l));if(typeof s=="object"){let l=s,d=Object.create(Object.getPrototypeOf(l));for(let p of Object.keys(l)){let m=i?n.get(p):void 0;if(m){d[p]=Dr(l[p],m);continue}d[p]=o(l[p])}return d}return typeof s=="string"&&a?pt(s,r):s};return o(e)}var ft=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Pr(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:ft(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:ft(t.spawn.prompt)}),t}function Fr(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 jr=1440*60*1e3,Br="VISIQ_BUNDLE_GRACE_TTL_MS",Ur="VISIQ_BUNDLE_CACHE_DISABLED",zr="VISIQ_CACHE_DIR",qr=j.object({graceTtlMs:j.number().int().nonnegative().optional(),disabled:j.boolean().optional(),cacheDir:j.string().min(1).optional()}).strict();function Gr(e){return e==null?{}:qr.parse(e)}function Vr(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Br];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return jr}function Wr(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Ur]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var mt;function Hr(){if(mt!==void 0)return mt;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Kr(e){return JSON.stringify(Q(e))}function Q(e){if(Array.isArray(e))return e.map(Q);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Q(t[r]);return n}return e}function Yr(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Zr(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 wt(){if(!Hr())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 At(e,t){return e.createHash("sha256").update(Kr(t)).digest("hex")}function Jr(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[zr]?.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 Qr(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function kt(e,t,n){return e.path.join(Jr(e,n),"bundles",`${Qr(e,t)}.json`)}async function Xr(e,t,n,r={}){let i=await wt();if(i)try{let a=kt(i,e,r),o=i.path.dirname(a);await i.fs.mkdir(o,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:At(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 ei(e,t={}){let n=await wt();if(!n)return null;try{let r=await n.fs.readFile(kt(n,e,t),"utf-8"),i=Zr(JSON.parse(r));return!i||At(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var O;async function ti(){if(O!==void 0)return O;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;O=typeof t=="function"?t:null}catch{O=null}return O}function ni(e){let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,i=r.rego_source;if(typeof i!="string"||i.length===0)continue;let a;try{a=V(i)}catch{continue}let o=typeof r.id=="string"?r.id:"<rule>";for(let s of ve(a))t.push(`${o}: ${s}`)}return t}function ri(e){let t={retrieval:new Set,action:new Set,delegation:new Set};for(let n of e){if(!n.enabled||n.bypassActive)continue;let r=n.regoSource;if(typeof r!="string"||r.length===0)continue;let i;try{i=V(r)}catch{continue}let a=we(i);if(a.length!==0)for(let o of n.appliesTo){let s=t[o];if(s)for(let l of a)s.add(`${n.id}: ${l}`)}}return{retrieval:[...t.retrieval].sort(),action:[...t.action].sort(),delegation:[...t.delegation].sort()}}function ii(e){return e==null||typeof e!="object"?!0:Object.keys(e).length===0}var ai=5e3,oi=600*1e3,si=1e4,li=25,gt=1e3,ci=5e3,di=100,ht=2e3,ui=10,pi=512,fi=1800*1e3,mi=.7,gi="monitor",hi="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",_t="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.",_i="open";function yt(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function yi(e,t){return st({content:e,resourceMetadata:t})}var bi=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(),mcpServer:u.string().min(1).max(255).optional()}),vi=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(),fail_mode:u.string().nullable().optional()}).optional(),rules:u.array(u.record(u.unknown())),action_schemas:u.array(u.object({id:u.string(),plane:u.string().optional(),field_mappings:u.array(u.record(u.unknown())).optional(),derived_fields:u.array(u.record(u.unknown())).optional(),action_class:u.string().nullable().optional(),action_class_confidence:u.number().optional()})).optional(),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 wi(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=$e(De(n));return{trust_tier:ke(t)?t:null,categories:Ie(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&Le(e.blast_radius_tier)?e.blast_radius_tier:null}}function Ai(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 ki(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var X=new Set,bt=!1;async function vt(e){let t=[];for(let n of X){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 Si(){if(!bt&&!(typeof process>"u"||typeof process.once!="function")){bt=!0,process.once("beforeExit",()=>{vt(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await vt(!0)}finally{process.kill(process.pid,e)}})()})}}var oa=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=gi;agentModeByOperation=null;rawBundle=null;normalizedRefs={retrieval:[],action:[],delegation:[]};warnedNormalizedAbsent=!1;warnedNormalizedDrift=!1;lastNormalizedWarnRearmMs=0;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=yt(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??_i;governedFailMode=null;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;lastCloneCaptureSig=null;toolDescriptions=new Map;constructor(e,t,n,r,i,a,o,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=o,this.originalFetch=globalThis.fetch.bind(globalThis);let m=Gr(s);if(this.bundleCacheDisabled=Wr(m.disabled),this.bundleGraceTtlMs=Vr(m.graceTtlMs),this.bundleCacheDirOverride=m.cacheDir,this.cacheIdentity=l&&d&&!this.bundleCacheDisabled?{endpoint:d,agentId:p,apiKey:l}:null,l&&d){let h={apiKey:l,agentId:p,endpoint:d,mode:"enforce",timeoutMs:Fr(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new ue(h,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},ai),J(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},si),J(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},ci),J(this.cognitionTimer),X.add(this),Si()}else this.client=null}async evaluate(e){let t=bi.parse(e),n=Date.now();if(this.operatorShutdown){let f=this.denyAll(t,hi);return this.applyAgentMode(f,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,_t,n);let f=this.denyAll(t,_t);return this.applyAgentMode(f,"enforce",t,n)}if(t.operations.every(f=>this.modeFor(f)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let f;if(this.agentModeConfirmed?f=this.agentMode:this.bundleApplyFailed?f="enforce":f="monitor",f==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let g=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(g,f,t,n)}let r=this.readSession(t.sessionId),i=await ti();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")?Ce(t.normalized??{},{targetApp:t.targetResource??t.toolName??""}):t.normalized,o=this.buildActionSchemaEvent(t),s=t.mcpServer?{...a??{},mcp_server:t.mcpServer}:a,l={...t,normalized:s,session:r,at:Date.now(),action_schema_id:o.id,action_schema_raw:o.canonical},d={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},p;try{p=i(l,d)}catch(f){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${f instanceof Error?f.message:String(f)}`,n);throw f}let m=[...new Set(t.operations.flatMap(f=>this.normalizedRefs[f]??[]))].sort();m.length>0&&ii(t.normalized)&&(p.normalizedColdStart=m,this.warnedNormalizedAbsent||(this.warnedNormalizedAbsent=!0,console.warn(`[UNIFIED] no normalized event supplied, but ${m.length} loaded rule condition(s) on this event's operation(s) read input.normalized.* \u2014 those conditions resolve to undefined here, so a deny carrying one does not fire. (Builtin-derived paths such as context/app_category ARE still populated in-core, so this is a dependency report, not a proof that every listed condition was the decider.) Cold start / no action-schema mapping yet. Affected: ${m.slice(0,5).join("; ")}${m.length>5?`; +${m.length-5} more`:""}`)));let h=Te(t.normalized);return h.length>0&&(p.normalizedDrift=h,this.warnedNormalizedDrift||(this.warnedNormalizedDrift=!0,console.warn(`[UNIFIED] normalized event carries ${h.length} value(s) outside the canonical vocabulary \u2014 a builder-authored rule can only select in-vocab values, so these cannot match one, so a rule keyed on the canonical value does not fire here. Check the harness classifier's casing/spelling. Affected: ${h.slice(0,5).join("; ")}${h.length>5?`; +${h.length-5} more`:""}`))),this.foldSession(t,p.enforced?p.decision:"permit"),p.enforced&&p.action.decision==="approval_required"&&await this.registerHitl(t,p),this.bufferTelemetry(t,p,Date.now()-n,p.enforced),p}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return N;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>fi?(this.sessions.delete(e),N):t.state:N}foldActionClass(e){let t=e.normalized?.action_class;if(typeof t=="string"&&t.length>0)return t;let n=this.rawBundle?.action_schemas;if(!Array.isArray(n))return;let{id:r}=this.buildActionSchemaEvent(e),i=n.find(s=>s?.id===r);if(!i)return;let a=i.action_class,o=typeof i.action_class_confidence=="number"?i.action_class_confidence:0;if(typeof a=="string"&&a.length>0&&o>=mi)return a}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),o=e.operations.includes("action")||e.operations.includes("delegation"),s=xe(r===N?Ne():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,taint:a?yi(e.contentPreview,i):void 0,action_class:o?this.foldActionClass(e):void 0,target_app:o?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:s,touchedAt:Date.now()}),this.sessions.size>pi){let l=this.sessions.keys().next().value;l!==void 0&&this.sessions.delete(l)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let o={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,o,i,!0),o}let a={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,a,i,!1),a}setFailMode(e){this.failMode=e}getFailMode(){return this.failMode}getGovernedFailMode(){return this.governedFailMode}failOpen(e,t,n){let r=`fail-open: ${t} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`;console.error(`[VisIQ] FAIL-OPEN: ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`);let i=e.operations.includes("action")||e.operations.includes("delegation"),a=e.operations.includes("retrieval"),o={decision:"permit",allowed:!0,reason:r,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:i?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:a?{action:"allow"}:{action:null},failOpen:!0};return this.bufferTelemetry(e,o,Date.now()-n,!1,!0),o}reportFailOpen(e,t){try{let n={operations:["action"],agentId:this.resolvedAgentId,...t?.toolName?{toolName:t.toolName}:{},...t?.sessionId?{sessionId:t.sessionId}:{}},r={decision:"permit",allowed:!0,reason:`fail-open: ${e} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:{decision:"permit",allowed:!0},retrieval:{action:null},failOpen:!0};this.bufferTelemetry(n,r,0,!1,!0)}catch{}}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},action_schema_id:this.buildActionSchemaEvent(e).id,...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=vi.parse(e);this.bundleApplyFailed=!1;let n=this.sdkDialect??1;if(t.min_dialect!==void 0&&t.min_dialect>n){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle requires dialect ${t.min_dialect} but this SDK speaks ${n} \u2014 refusing the bundle and failing closed (deny-all, G001). Upgrade the VisIQ SDK.`);return}let r=ni(t.rules);if(r.length>0){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle contains rego_source using a builtin the engine cannot evaluate (would silently never match \u2192 fail open): ${r.join("; ")}. Refusing the bundle and failing closed (G001). Recompile the rule without case-folding wrappers like upper()/lower().`);return}this.dialectRefused=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(i=>Fe(i)).filter(i=>i!==null),this.agentAttributes=t.agent_attributes?wi(t.agent_attributes):null,this.agentNoCoverage=Me(t.agent_attributes?.no_coverage),this.governedFailMode=yt(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=Ai(t.agent_mode_by_operation),process.env.VISIQ_COGNITION_CAPTURE==="1"?this.cognitionEnabled=!0:typeof t.cognition_capture=="boolean"&&(this.cognitionEnabled=t.cognition_capture),this.operatorShutdown=t.shutdown===!0,this.normalizedRefs=ri(this.rules),this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1,this.lastNormalizedWarnRearmMs=Date.now(),this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json",...E(this.sdkVersion,this.sdkDialect)};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304){let o=Date.now();o-this.lastNormalizedWarnRearmMs>=oi&&(this.lastNormalizedWarnRearmMs=o,this.warnedNormalizedAbsent=!1,this.warnedNormalizedDrift=!1);return}if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let a=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&a?this.bundleEtag=r:a||(this.bundleEtag=null),a&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await ei(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Yr(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 Xr(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}isBundleLoaded(){return this.bundleLoaded}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e,t){this.registerEnvironment({...G(),...e?{agent_type:e}:{},...t?.model?{model:t.model}:{},...t?.systemPrompt?{systemPrompt:t.systemPrompt}:{},...t?.toolSchemas&&t.toolSchemas.length>0?{toolSchemas:t.toolSchemas}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));for(let n of e)n.description&&this.toolDescriptions.set(n.name,n.description);t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}captureCloneMetadata(e){if(!this.client||!this.resolvedAgentId||!(e.model||e.systemPrompt||(e.toolSchemas?.length??0)>0))return;let t=JSON.stringify({m:e.model??"",s:e.systemPrompt??"",t:e.toolSchemas??[]});t!==this.lastCloneCaptureSig&&(this.lastCloneCaptureSig=t,this.client.registerEnvironment({...G(),...e.agentType?{agent_type:e.agentType}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},...e.toolSchemas&&e.toolSchemas.length>0?{toolSchemas:e.toolSchemas}:{}}))}buildActionSchemaEvent(e){let t=e.toolName?this.toolDescriptions.get(e.toolName):void 0,n={agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{},...e.toolArgs?{tool_args:e.toolArgs}:{},...t?{tool_description:t}:{}},r=Pe(n),i={...n};return e.toolArgs&&(i.tool_args=Qe(e.toolArgs)),{canonical:n,id:r,rawEventForWire:i}}bufferTelemetry(e,t,n,r,i=!1){let a=this.buildActionSchemaEvent(e);this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:r?ki(t.decision):"permit",reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:a.rawEventForWire,action_schema_id:a.id,...this.harnessKind||e.context||i||t.normalizedColdStart||t.normalizedDrift?{context:{...this.harnessKind?{[ce]:this.harnessKind}:{},...e.context??{},...i?{fail_open:!0}:{},...t.normalizedColdStart?{normalized_cold_start:!0,normalized_inert_conditions:t.normalizedColdStart.length}:{},...t.normalizedDrift?{normalized_drift:!0,normalized_drift_values:t.normalizedDrift.length,normalized_drift_fields:t.normalizedDrift.slice(0,ui)}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=li&&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-gt;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${gt})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Pr(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=di&&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-ht;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${ht})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),X.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 J(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function B(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function sa(e,t){if(e!=="Task"&&e!=="Agent")return null;let n=B(t.description),r=B(t.subagent_type),i=B(t.prompt),a=n??r??"sub-agent";return{childAgentId:a,childName:a,kind:"subagent",agentType:r,description:n,task:i,goal:i,model:B(t.model),source:"structural"}}function la(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}function ca(e){let t=[],n=[],r,i=[];for(let o of e){if(o.mode==="partial"||o.mode==="email"||o.mode==="custom"){let l={mode:o.mode};o.field&&(l.field=o.field),o.pattern&&(l.pattern=o.pattern),typeof o.keepFirst=="number"&&(l.keepFirst=o.keepFirst),typeof o.keepLast=="number"&&(l.keepLast=o.keepLast),o.maskChar&&(l.maskChar=o.maskChar),o.keepPattern&&(l.keepPattern=o.keepPattern),o.replacement!==void 0&&(l.replacement=o.replacement),i.push(l);continue}o.field&&t.push(o.field),o.pattern&&n.push(o.pattern);let{replacement:s}=o;s&&r===void 0&&(r=s)}let a={};return t.length>0&&(a.fields=t),n.length>0&&(a.patterns=n),r!==void 0&&(a.replacement=r),i.length>0&&(a.directives=i),a}var St="0.1.7";var ba=3e4,Ti=4e3;function Ni(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,200)||"default"}function Ct(e){let t=Ci("sha1").update(e).digest("hex").slice(0,10);return`${Ni(e)}-${t}`}function va(e,t,n){return n-e.fetchedAt<t}function Tt(e){return U(k(),"bundles",`${Ct(e)}.json`)}function Nt(e){return U(k(),"sessions",`${Ct(e)}.registered`)}async function wa(e){try{let t=await Ii(Tt(e),"utf-8"),n=JSON.parse(t);return n&&typeof n.fetchedAt=="number"&&"body"in n?n:null}catch{return null}}async function Aa(e,t,n){try{let r=Tt(e);await It(U(k(),"bundles"),{recursive:!0});let i={fetchedAt:Date.now(),version:n,body:t};await Et(r,JSON.stringify(i),{mode:384})}catch{}}async function ka(e,t,n){try{let i=`${e.replace(/\/+$/,"")}/rules/bundle?agent_id=${encodeURIComponent(n)}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...E(St,q)},signal:AbortSignal.timeout(Ti)});if(!a.ok)return null;let o=a.headers.get("etag");return{body:await a.json(),version:o}}catch{return null}}async function Sa(e){try{return await Ei(Nt(e)),!0}catch{return!1}}async function Ia(e){try{await It(U(k(),"sessions"),{recursive:!0}),await Et(Nt(e),String(Date.now()),{mode:384})}catch{}}export{re as a,ie as b,k as c,Mt as d,jt as e,Bt as f,Ut as g,$i as h,Xi as i,q as j,tn as k,oa as l,sa as m,la as n,ca as o,St as p,ba as q,Ni as r,va as s,wa as t,Aa as u,ka as v,Sa as w,Ia as x};