@visiq/claude-code-harness 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VisIQ Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ import{f as W,h as H,i as V,j as G,k as K,l as Z,m as I}from"./chunk-3GWLCI47.js";var qe=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),ze=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function We(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 L(e){return typeof e!="string"?!1:qe.has(e)?!0:e.startsWith("mcp__")?ze.test(We(e)):!1}function Y(e){return L(e)?["retrieval","action"]:["action"]}var He=["query","q","url","prompt","pattern","file_path","path"];function S(e){if(!e||typeof e!="object")return;let t=e,n=[];for(let r of He){let i=t[r];typeof i=="string"&&i.length>0&&n.push(i)}return n.length>0?n.join(" "):void 0}function h(e,t){let n=t?`VisIQ ${t}`:"VisIQ",r=e&&e.trim().length>0?e.trim():"blocked by policy";return`[${n}] ${r}`}function J(e){let t={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};return e&&(t.hookSpecificOutput.updatedInput=e),t}function E(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}function Q(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:e}}}function _(e,t){let n={hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}};return t&&(n.hookSpecificOutput.additionalContext=t),n}function hn(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.hook_event_name=="string"?t:null}catch{return null}}var Ve=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];var f=Object.fromEntries(Ve.map(e=>[e.name,e.re.source])),Ge=["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","pan","iban","aba_routing","us_ein","swift_bic","ssn","email","us_phone","ipv4","mac_address"],Ke={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
2
+ MIIEv\u2026
3
+ -----END PRIVATE KEY-----`,template:{pattern:f.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:f.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:f.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:f.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:f.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:f.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:f.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:f.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:f.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:f.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS).",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\b\\d{13,19}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){10,30}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:"\\b\\d{9}\\b",mode:"full"},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX).",category:"financial",example:"12-3456789",template:{pattern:f.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:f.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789).",category:"pii",example:"123-45-6789",template:{pattern:f.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept).",category:"pii",example:"alice@acme.com",template:{pattern:f.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:f.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:f.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:f.mac_address,mode:"full"},defaultEnabled:!1}},yn=new Set(Ge.filter(e=>!Ke[e].defaultEnabled));var P="[REDACTED]",y="\u2022",C=e=>/[A-Za-z0-9]/.test(e);function X(e,t,n,r){let i=Array.from(e),a=i.length,o=Math.max(0,Math.floor(t)||0),c=Math.max(0,Math.floor(n)||0),l=r.length>0?r:y,d=o+c>=a;return i.map((p,g)=>!d&&(g<o||g>=a-c)?p:C(p)?l:p).join("")}function Ze(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return X(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:y;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(o=>C(o)?a:o).join(""))+i}function Ye(e,t,n){let r=n.length>0?n:y,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 g=p.index;g<p.index+p[0].length;g++)i[g]=!0}}catch{}let a=!1,o=!0;for(let d=0;d<e.length;d++)if(C(e[d])&&(a=!0,!i[d])){o=!1;break}let c=a&&o,l="";for(let d=0;d<e.length;d++){let p=e[d];!c&&i[d]||!C(p)?l+=p:l+=r}return l}function ee(e,t){let n=t.mode??"full";return n==="partial"?X(e,t.keepFirst??0,t.keepLast??0,t.maskChar??y):n==="email"?Ze(e,t.maskChar??y):n==="custom"?Ye(e,t.keepPattern,t.maskChar??y):t.replacement??P}function Je(e,t){return typeof e=="string"?ee(e,t):t.replacement??P}function te(e){let t=[],n=e.replacement??P;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=>ee(a,r)})}return t}function ne(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${c}`)}n=n.replace(a,o=>i(o))}return n}function D(e,t){return e==null?e:typeof e=="string"?Qe(e,t):typeof e=="object"?Xe(e,t):e}function Qe(e,t){if(typeof e!="string")return e;let n=te(t);return n.length===0?e:ne(e,n)}function Xe(e,t){let n=new Map;for(let c of t.fields??[])typeof c=="string"&&c.length>0&&n.set(c,{field:c,mode:"full",replacement:t.replacement});for(let c of t.directives??[])typeof c.field=="string"&&c.field.length>0&&n.set(c.field,c);let r=te(t),i=n.size>0,a=r.length>0,o=c=>{if(c==null)return c;if(Array.isArray(c))return c.map(l=>o(l));if(typeof c=="object"){let l=c,d=Object.create(Object.getPrototypeOf(l));for(let p of Object.keys(l)){let g=i?n.get(p):void 0;if(g){d[p]=Je(l[p],g);continue}d[p]=o(l[p])}return d}return typeof c=="string"&&a?ne(c,r):c};return o(e)}import{z as s}from"zod";import*as m from"node:os";var re="X-VisIQ-SDK",ie="X-VisIQ-Dialect",ae="unknown";function F(e,t=1){return{[re]:e&&e.length>0?e:ae,[ie]:String(t)}}var oe="interceptor_source",et=s.enum(["enforce","audit","off"]),tt=s.enum(["closed","open"]),se=s.enum(["enforce","monitor","off"]),nt=s.object({apiKey:s.string().min(1,"apiKey is required"),agentId:s.string().min(1,"agentId is required"),endpoint:s.string().url().optional(),mode:et.optional(),timeoutMs:s.number().int().positive().optional(),hitlTimeoutMs:s.number().int().positive().optional(),failBehavior:tt.optional()}),wn=s.object({agent_id:s.string().min(1),target_app:s.string().min(1),action:s.string().min(1),context:s.record(s.unknown()).optional(),session_id:s.string().min(1).max(255).optional(),telemetry:s.record(s.unknown()).optional()}),rt=s.object({field:s.string().optional(),pattern:s.string().optional(),replacement:s.string().optional(),mode:s.enum(["full","partial","email"]).optional(),keepFirst:s.number().optional(),keepLast:s.number().optional(),maskChar:s.string().optional()}),it=s.object({decision_id:s.string().min(1),decision:s.enum(["permit","deny","approval_required","mask"]),reason:s.string().optional(),rule_code:s.string().nullable().optional(),enforced:s.boolean().optional(),agent_mode:se.optional(),arg_redaction_rules:s.array(rt).optional(),plane:s.string().nullable().optional(),operation:s.string().nullable().optional(),is_retrieval:s.boolean().optional(),metadata:s.record(s.unknown()).optional()}),at=s.object({field:s.string().min(1),operator:s.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:s.union([s.string(),s.number(),s.array(s.string())])}),ot=s.object({id:s.string().min(1),rule_code:s.string().default(""),name:s.string().min(1),description:s.string().nullable().default(null),effect:s.enum(["allow","deny","hitl","mask"]),resource_type:s.string().min(1),rego_source:s.string().default(""),target_app:s.string().nullable().default(null),action_pattern:s.string().nullable().default(null),conditions:s.array(at).default([]),priority:s.number().int().default(0)}),st=s.object({version:s.string().min(1),agent_mode:se.optional(),rules:s.array(ot),no_coverage:s.object({no_coverage_defaults:s.record(s.string()),autopilot_enabled:s.boolean(),enduser_hitl_enabled:s.boolean(),hitl_timeout_seconds:s.number()}).optional()}),lt=2e3,le=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return F(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 it.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 st.parse(a)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let o=a,c=o.hitl_result;if(c==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(c==="rejected")return{decision_id:e,decision:"deny",reason:typeof o.reason=="string"?o.reason:"Rejected by human reviewer"};if(c==="timeout"||c==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await ct(lt)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function ct(e){return new Promise(t=>setTimeout(t,e))}function ce(){let e={};try{let t=`${m.platform()} ${m.release()}`.trim();t&&(e.os=t)}catch{}try{let t=m.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=m.userInfo();t&&(e.username=t)}catch{}try{let t=ut();t&&(e.ip=t)}catch{}return e}function ut(){let e=m.networkInterfaces();for(let t of Object.keys(e))for(let n of e[t]??[])if((n.family==="IPv4"||n.family===4)&&!n.internal&&n.address)return n.address}import{z as u}from"zod";import{createHash as Sn}from"crypto";import{createHash as On}from"crypto";var dt=["tier1","tier2","tier3"];function pe(e){return typeof e=="string"&&dt.includes(e)}var pt=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],ft=["internal","customer_facing","experimental","third_party"],fe=[...pt,...ft];function gt(e){return typeof e=="string"&&fe.includes(e)}function ge(e){let t=new Set;for(let n of e)gt(n)&&t.add(n);return fe.filter(n=>t.has(n))}var mt=["read_only","record_create","record_update","record_delete","data_export","data_share","data_subject_request","consent_change","funds_transfer","funds_disbursement","payroll_run","trade_execution","ledger_mutation","credit_decision","decision_adverse","account_restriction","account_closure","card_management","purchase_commitment","vendor_management","deal_management","pricing_change","contract_execution","legal_hold","regulatory_filing","personnel_action","employment_termination","compensation_change","campaign_send","content_publish","inventory_adjustment","order_fulfillment","account_servicing","credential_reset","access_grant","permission_change","credential_management","auth_policy_change","security_config_change","logging_change","alert_management","code_change","infrastructure_provision","deployment_change","communication_send","other"];function me(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 ht={wire_transfer:"funds_transfer",international_transfer:"funds_transfer",cross_border_payment:"funds_transfer",send_swift:"funds_transfer",send_wire:"funds_transfer",transfer_funds:"funds_transfer",update_wire_instructions:"funds_transfer",add_beneficiary:"funds_transfer",modify_payee:"funds_transfer",disburse_funds:"funds_disbursement",initiate_ach:"funds_disbursement",issue_refund:"funds_disbursement",execute_trade:"trade_execution",place_order:"trade_execution",post_journal_entry:"ledger_mutation",adjust_ledger:"ledger_mutation",modify_general_ledger:"ledger_mutation",raise_limit:"credit_decision",increase_credit_limit:"credit_decision",extend_credit:"credit_decision",decline_credit:"decision_adverse",deny_application:"decision_adverse",adverse_action:"decision_adverse",block_card:"card_management",cancel_card:"card_management",place_hold:"account_restriction",freeze_account:"account_restriction",restrict_account:"account_restriction",close_account:"account_closure",export_data:"data_export",export_customer_list:"data_export",download_report:"data_export",download_customer_list:"data_export",bulk_export:"data_export",share_data:"data_share",send_to_partner:"data_share",delete_records:"record_delete",delete_user:"record_delete",drop_table:"record_delete",grant_role:"access_grant",change_permissions:"permission_change",modify_access:"permission_change",rotate_keys:"credential_management",disable_mfa:"auth_policy_change",modify_security_config:"security_config_change",disable_logging:"logging_change",purge_logs:"logging_change",suppress_alert:"alert_management",dismiss_alert:"alert_management",rollback:"deployment_change",modify_billing:"record_update",close_sar:"record_update",send_email:"communication_send",send_sms:"communication_send",fulfill_dsar:"data_subject_request",process_dsar:"data_subject_request",fulfill_data_request:"data_subject_request",process_erasure_request:"data_subject_request",honor_deletion_request:"data_subject_request",export_subject_data:"data_subject_request",erase_subject_data:"data_subject_request",delete_subject_data:"data_subject_request",record_consent:"consent_change",capture_consent:"consent_change",update_consent:"consent_change",withdraw_consent:"consent_change",revoke_consent:"consent_change",opt_out:"consent_change",opt_in:"consent_change",run_payroll:"payroll_run",process_payroll:"payroll_run",submit_payroll:"payroll_run",approve_payroll:"payroll_run",create_purchase_order:"purchase_commitment",issue_purchase_order:"purchase_commitment",approve_purchase_order:"purchase_commitment",submit_purchase_order:"purchase_commitment",approve_purchase:"purchase_commitment",approve_requisition:"purchase_commitment",commit_spend:"purchase_commitment",onboard_vendor:"vendor_management",add_vendor:"vendor_management",create_supplier:"vendor_management",approve_vendor:"vendor_management",update_vendor_bank:"vendor_management",update_supplier_bank:"vendor_management",modify_supplier:"vendor_management",create_opportunity:"deal_management",update_opportunity:"deal_management",advance_deal_stage:"deal_management",update_deal_stage:"deal_management",close_deal:"deal_management",mark_closed_won:"deal_management",mark_closed_lost:"deal_management",issue_quote:"pricing_change",send_quote:"pricing_change",approve_discount:"pricing_change",apply_discount:"pricing_change",override_price:"pricing_change",update_pricing:"pricing_change",approve_special_pricing:"pricing_change",execute_contract:"contract_execution",sign_contract:"contract_execution",countersign_contract:"contract_execution",sign_agreement:"contract_execution",execute_agreement:"contract_execution",sign_nda:"contract_execution",execute_nda:"contract_execution",sign_document:"contract_execution",esign_document:"contract_execution",place_legal_hold:"legal_hold",place_litigation_hold:"legal_hold",apply_legal_hold:"legal_hold",release_legal_hold:"legal_hold",file_regulatory_report:"regulatory_filing",file_sar:"regulatory_filing",submit_regulatory_filing:"regulatory_filing",file_compliance_report:"regulatory_filing",file_disclosure:"regulatory_filing",onboard_employee:"personnel_action",hire_employee:"personnel_action",change_employee_role:"personnel_action",promote_employee:"personnel_action",transfer_employee:"personnel_action",update_job_title:"personnel_action",terminate_employee:"employment_termination",offboard_employee:"employment_termination",deactivate_employee:"employment_termination",separate_employee:"employment_termination",adjust_salary:"compensation_change",change_compensation:"compensation_change",approve_raise:"compensation_change",grant_equity:"compensation_change",grant_stock:"compensation_change",issue_bonus:"compensation_change",update_pay_rate:"compensation_change",send_campaign:"campaign_send",launch_campaign:"campaign_send",schedule_campaign:"campaign_send",send_bulk_email:"campaign_send",send_marketing_email:"campaign_send",send_newsletter:"campaign_send",blast_email:"campaign_send",publish_post:"content_publish",publish_content:"content_publish",publish_blog:"content_publish",post_to_social:"content_publish",schedule_post:"content_publish",adjust_inventory:"inventory_adjustment",write_off_inventory:"inventory_adjustment",update_stock_level:"inventory_adjustment",reconcile_inventory:"inventory_adjustment",fulfill_order:"order_fulfillment",ship_order:"order_fulfillment",dispatch_order:"order_fulfillment",mark_order_shipped:"order_fulfillment",update_customer_account:"account_servicing",modify_customer_account:"account_servicing",update_customer_contact:"account_servicing",change_customer_settings:"account_servicing",reset_customer_password:"credential_reset",reset_password:"credential_reset",force_password_reset:"credential_reset",reset_mfa:"credential_reset",unlock_account:"credential_reset",reset_customer_credentials:"credential_reset",merge_pull_request:"code_change",merge_pr:"code_change",merge_branch:"code_change",push_to_branch:"code_change",push_to_main:"code_change",push_code:"code_change",commit_code:"code_change",force_push:"code_change",provision_infrastructure:"infrastructure_provision",provision_resource:"infrastructure_provision",create_instance:"infrastructure_provision",terminate_instance:"infrastructure_provision",spin_up_server:"infrastructure_provision",tear_down_server:"infrastructure_provision",destroy_resource:"infrastructure_provision",create_cluster:"infrastructure_provision"};function _t(e){let t=me(e);return t===null?"other":ht[t]||(/^(delete|remove|purge|drop|destroy|wipe)_/.test(t)?"record_delete":/^(export|download|extract|dump)_/.test(t)?"data_export":/^(create|add|insert)_/.test(t)?"record_create":/^(update|edit|modify|patch|set)_/.test(t)?"record_update":t==="send_email"||t==="send_sms"||/^(notify|email|sms)_/.test(t)?"communication_send":/^(read|get|list|search|fetch|view|query)_/.test(t)||t==="read"||t==="get"?"read_only":"other")}var ue={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 yt(e){let t=me(e);return t===null?"other":ue[t]??ue[t.replace(/_/g,"")]??"other"}function he(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=_t(t.action)),t.targetApp!==void 0&&t.targetApp!==null){let r=n.context&&typeof n.context=="object"&&!Array.isArray(n.context)?{...n.context}:{};r.app_category===void 0&&(r.app_category=yt(t.targetApp)),n.context=r}return n}var de=64,bt=64,k={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function _e(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var vt=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>de?r.slice(0,de):r}function wt(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function O(e){return typeof e=="string"&&e.length>0?e:null}function ye(e,t){let n=wt(t.data_categories),r=O(t.classification),i=O(t.action_class),a=i&&mt.includes(i)?i:null,o=O(t.target_app),c=O(t.decision),l={...e.action_counts};if(a)if(a in l)l[a]=(l[a]??0)+1;else if(Object.keys(l).length<bt)l[a]=1;else{let d=Object.keys(l).sort(),p=d[d.length-1];p!==void 0&&a<p&&(delete l[p],l[a]=1)}return{retrieved_data_categories:T(e.retrieved_data_categories,n),retrieved_classifications:T(e.retrieved_classifications,r?[r]:[]),action_classes:T(e.action_classes,a?[a]:[]),action_counts:l,denied_count:e.denied_count+(c==="deny"?1:0),inhibited_count:e.inhibited_count+(c&&vt.has(c)?1:0),event_count:e.event_count+1,target_apps:T(e.target_apps,o?[o]:[])}}var kt="generic",be=[{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:kt,name:"Generic",icon:"Shapes",description:"Catch-all for cross-cutting rules or rules that do not fit a specific function. Assign when no specific function clearly applies."}],At=be.map(e=>e.id),En=new Map(be.map(e=>[e.id,e])),Cn=new Set(At);var It=/^[a-z][a-z0-9_]*$/;function ve(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&It.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var St=["narrow","moderate","broad","unbounded","unknown"];function we(e){return typeof e=="string"&&St.includes(e)}function ke(e){return e==="open"||e==="closed"?e:null}var Et=["action","retrieval","delegation"];function Ct(e){return typeof e=="string"&&Et.includes(e)}var Tt=new Set(["rules"]);function Ae(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Tt.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Ct):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{z as x}from"zod";import{randomUUID as dn}from"node:crypto";var Ie=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Ot(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:Ie(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:Ie(t.spawn.prompt)}),t}function xt(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 Rt=1440*60*1e3,Nt="VISIQ_BUNDLE_GRACE_TTL_MS",Lt="VISIQ_BUNDLE_CACHE_DISABLED",Pt="VISIQ_CACHE_DIR",Dt=x.object({graceTtlMs:x.number().int().nonnegative().optional(),disabled:x.boolean().optional(),cacheDir:x.string().min(1).optional()}).strict();function Ft(e){return e==null?{}:Dt.parse(e)}function Ut(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Nt];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Rt}function Bt(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Lt]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var Se;function jt(){if(Se!==void 0)return Se;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Mt(e){return JSON.stringify(j(e))}function j(e){if(Array.isArray(e))return e.map(j);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=j(t[r]);return n}return e}function $t(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function qt(e){if(e!==null&&typeof e=="object"&&typeof e.fetchedAt=="number"&&typeof e.contentHash=="string"&&"body"in e){let t=e;return{fetchedAt:t.fetchedAt,version:typeof t.version=="string"?t.version:null,contentHash:t.contentHash,body:t.body}}return null}async function Re(){if(!jt())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 Ne(e,t){return e.createHash("sha256").update(Mt(t)).digest("hex")}function zt(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Pt]?.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 Wt(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function Le(e,t,n){return e.path.join(zt(e,n),"bundles",`${Wt(e,t)}.json`)}async function Ht(e,t,n,r={}){let i=await Re();if(i)try{let a=Le(i,e,r),o=i.path.dirname(a);await i.fs.mkdir(o,{recursive:!0,mode:448});let c={fetchedAt:r.now??Date.now(),version:n,contentHash:Ne(i.crypto,t),body:t},l=`${a}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(l,JSON.stringify(c),{mode:384});try{await i.fs.rename(l,a)}catch(d){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),d}}catch{}}async function Vt(e,t={}){let n=await Re();if(!n)return null;try{let r=await n.fs.readFile(Le(n,e,t),"utf-8"),i=qt(JSON.parse(r));return!i||Ne(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var A;async function Gt(){if(A!==void 0)return A;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;A=typeof t=="function"?t:null}catch{A=null}return A}var Kt=5e3,Zt=1e4,Yt=25,Ee=1e3,Jt=5e3,Qt=100,Ce=2e3,Xt=512,en=1800*1e3,tn="monitor",nn="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",rn="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.",an=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()}),on=u.object({version:u.string().min(1),dialect_version:u.number().int().optional(),min_dialect:u.number().int().optional(),shutdown:u.boolean().optional(),agent_mode:u.enum(["enforce","monitor","off"]).optional(),cognition_capture:u.boolean().optional(),agent_mode_by_operation:u.object({action:u.string().optional(),retrieval:u.string().optional(),delegation:u.string().optional()}).partial().optional(),agent_attributes:u.object({trust_tier:u.string().nullable().optional(),categories:u.array(u.string()).optional(),business_function:u.string().nullable().optional(),business_functions:u.array(u.string()).nullable().optional(),blast_radius_tier:u.string().nullable().optional(),no_coverage:u.string().nullable().optional()}).optional(),rules:u.array(u.record(u.unknown())),no_coverage:u.object({no_coverage_defaults:u.record(u.string()),autopilot_enabled:u.boolean(),enduser_hitl_enabled:u.boolean(),hitl_timeout_seconds:u.number().optional()}).optional()});function sn(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=ve(n);return{trust_tier:pe(t)?t:null,categories:ge(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&we(e.blast_radius_tier)?e.blast_radius_tier:null}}function ln(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 cn(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var M=new Set,Te=!1;async function Oe(e){let t=[];for(let n of M){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 un(){if(!Te&&!(typeof process>"u"||typeof process.once!="function")){Te=!0,process.once("beforeExit",()=>{Oe(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await Oe(!0)}finally{process.kill(process.pid,e)}})()})}}var Pe=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=tn;agentModeByOperation=null;rawBundle=null;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;constructor(e,t,n,r,i,a,o,c){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 g=Ft(c);if(this.bundleCacheDisabled=Bt(g.disabled),this.bundleGraceTtlMs=Ut(g.graceTtlMs),this.bundleCacheDirOverride=g.cacheDir,this.cacheIdentity=l&&d&&!this.bundleCacheDisabled?{endpoint:d,agentId:p,apiKey:l}:null,l&&d){let $e={apiKey:l,agentId:p,endpoint:d,mode:"enforce",timeoutMs:xt(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...o!==void 0?{sdkDialect:o}:{}};this.client=new le($e,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Kt),U(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Zt),U(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Jt),U(this.cognitionTimer),M.add(this),un()}else this.client=null}async evaluate(e){let t=an.parse(e),n=Date.now();if(this.operatorShutdown){let l=this.denyAll(t,nn);return this.applyAgentMode(l,"enforce",t,n)}if(this.dialectRefused){let l=this.denyAll(t,rn);return this.applyAgentMode(l,"enforce",t,n)}if(t.operations.every(l=>this.modeFor(l)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let l;this.agentModeConfirmed?l=this.agentMode:this.bundleApplyFailed?l="enforce":l="monitor";let d=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(d,l,t,n)}let r=this.readSession(t.sessionId),i=await Gt();if(!i||!this.rawBundle)throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)");let a={...t,session:r,at:Date.now()},o={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},c=i(a,o);return this.foldSession(t,c.enforced?c.decision:"permit"),c.enforced&&c.action.decision==="approval_required"&&await this.registerHitl(t,c),this.bufferTelemetry(t,c,Date.now()-n,c.enforced),c}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return k;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>en?(this.sessions.delete(e),k):t.state:k}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),o=e.operations.includes("action")||e.operations.includes("delegation"),c=o?he(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},l=ye(r===k?_e():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,action_class:o?c.action_class:void 0,target_app:o?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:l,touchedAt:Date.now()}),this.sessions.size>Xt){let d=this.sessions.keys().next().value;d!==void 0&&this.sessions.delete(d)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let 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}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=on.parse(e);this.bundleApplyFailed=!1;let n=this.sdkDialect??1;if(t.min_dialect!==void 0&&t.min_dialect>n){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle requires dialect ${t.min_dialect} but this SDK speaks ${n} \u2014 refusing the bundle and failing closed (deny-all, G001). Upgrade the VisIQ SDK.`);return}this.dialectRefused=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(r=>Ae(r)).filter(r=>r!==null),this.agentAttributes=t.agent_attributes?sn(t.agent_attributes):null,this.agentNoCoverage=ke(t.agent_attributes?.no_coverage),this.bundleVersion=t.version,this.bundleLoaded=!0,this.noCoverage=t.no_coverage?{no_coverage_defaults:t.no_coverage.no_coverage_defaults,autopilot_enabled:t.no_coverage.autopilot_enabled,enduser_hitl_enabled:t.no_coverage.enduser_hitl_enabled}:null,t.agent_mode!==void 0&&(this.agentMode=t.agent_mode,this.agentModeConfirmed=!0),this.agentModeByOperation=ln(t.agent_mode_by_operation),process.env.VISIQ_COGNITION_CAPTURE==="1"?this.cognitionEnabled=!0:typeof t.cognition_capture=="boolean"&&(this.cognitionEnabled=t.cognition_capture),this.operatorShutdown=t.shutdown===!0,this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json",...F(this.sdkVersion,this.sdkDialect)};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let a=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&a?this.bundleEtag=r:a||(this.bundleEtag=null),a&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await Vt(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if($t(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 Ht(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e){this.registerEnvironment({...ce(),...e?{agent_type:e}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}bufferTelemetry(e,t,n,r){this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:r?cn(t.decision):"permit",reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:{agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{}},...this.harnessKind||e.context?{context:{...this.harnessKind?{[oe]:this.harnessKind}:{},...e.context??{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Yt&&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-Ee;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Ee})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Ot(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Qt&&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-Ce;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Ce})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),M.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 U(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 De(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,source:"structural"}}function Fe(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}var xe=new Map;function pn(e){let t=(xe.get(e)??0)+1;return xe.set(e,t),t}function Ue(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId: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}:{}}})}function $(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:c}=o;c&&r===void 0&&(r=c)}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 fn="[VisIQ: retrieval withheld by policy]";function R(e){return q(e)}function q(e){if(e==null)return e;if(typeof e=="string")return e.length>0?fn:e;if(typeof e=="number")return 0;if(typeof e=="boolean")return!1;if(Array.isArray(e))return e.map(q);if(typeof e=="object"){let t=Object.create(null);for(let n of Object.keys(e))t[n]=q(e[n]);return t}return e}function Be(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 je(e,t){if(!e.enforced)return null;let{action:n,retrieval:r}=e,i=h(e.reason,e.ruleCode);if(n.decision==="deny"||r.action==="deny")return E(i);if(n.decision==="approval_required"||r.action==="escalate")return Q(i);if(n.decision==="mask"&&n.argRedactionRules&&n.argRedactionRules.length>0){let a=$(n.argRedactionRules);if(Be(a)){let o=D(t,a)??t;if(JSON.stringify(o)!==JSON.stringify(t))return J(o)}return null}return null}function Me(e,t){if(!e.enforced)return null;let{retrieval:n}=e,r=h(e.reason,e.ruleCode);if(n.action==="redact"){let i=$(n.redactionRules??[]);if(!Be(i))return _(R(t),r);let a=D(t,i);return JSON.stringify(a)===JSON.stringify(t)?null:_(a,r)}return n.action==="deny"?_(R(t),r):null}var gn="cli_harness";function b(e){return new Pe(e.apiKey,e.baseUrl,e.agentId,gn)}function N(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 v(e,t,n=W){let{agentId:r}=t,i=await V(r);if(i&&H(i,n,Date.now())&&z(e,i.body))return;let a=e.getEndpoint();if(a){let o=await K(a,t.apiKey,r);if(o&&z(e,o.body)){await G(r,o.body,o.version);return}}if(!(i&&z(e,i.body)))try{await e.awaitBundleReady(2500)}catch{}}function z(e,t){try{return e.applyBundle(t),!0}catch{return!1}}async function w(e){try{await e.flush()}catch{}try{e.dispose()}catch{}}async function Qn(e,t){let n=b(t),r=e.tool_input??{};try{await Z(e.session_id)||(n.registerHostEnvironment(),await I(e.session_id)),await v(n,t);let i=De(e.tool_name,r),a=Y(e.tool_name),o;i&&(Ue(n,{agentId:t.agentId,sessionId:e.session_id,framework:"claude-code"},i),a=Array.from(new Set([...a,"delegation"])),o=Fe(i,t.agentId));let c=N({operations:a,agentId:t.agentId,toolName:e.tool_name,toolInput:r,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:S(r),...o?{context:o}:{}}),l=await n.evaluate(c);return je(l,r)}catch{return E(h("evaluation error (fail-closed)",null))}finally{await w(n)}}async function ir(e,t){if(!L(e.tool_name))return null;let n=b(t);try{await v(n,t);let r=e.tool_input??{},i=N({operations:["retrieval"],agentId:t.agentId,toolName:e.tool_name,toolInput:r,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:S(r)}),a=await n.evaluate(i);return Me(a,e.tool_response)}catch{return _(R(e.tool_response),h("evaluation error (fail-closed)",null))}finally{await w(n)}}async function lr(e,t){let n=b(t);try{n.registerHostEnvironment(),await v(n,t,0),await I(e.session_id)}finally{await w(n)}return null}export{We as a,L as b,Y as c,S as d,h as e,J as f,E as g,Q as h,_ as i,hn as j,fn as k,R as l,je as m,Me as n,gn as o,b as p,N as q,v as r,w as s,Qn as t,ir as u,lr as v};
package/dist/cli/hook.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{j as r,t as i,u as a,v as u}from"../chunk-K5THPWCB.js";import{e as s}from"../chunk-3GWLCI47.js";var p=process.env.VISIQ_DEBUG==="1",f=p?(...o)=>{process.stderr.write(`${o.map(String).join(" ")}
3
- `)}:()=>{},d=console;for(let o of["log","info","debug","warn","error"])d[o]=f;function l(){return new Promise(o=>{if(process.stdin.isTTY){o("");return}let t=[],n=!1,e=()=>{n||(n=!0,o(Buffer.concat(t).toString("utf-8")))};setTimeout(e,15e3).unref?.(),process.stdin.on("data",c=>t.push(c)),process.stdin.on("end",e),process.stdin.on("error",e)})}async function m(){let o=r(await l());if(!o)return;let t=await s();if(!t)return;let n=null;switch(o.hook_event_name){case"PreToolUse":n=await i(o,t);break;case"PostToolUse":n=await a(o,t);break;case"SessionStart":n=await u(o,t);break;default:n=null}n&&process.stdout.write(JSON.stringify(n))}m().then(()=>process.exit(0)).catch(()=>process.exit(0));
2
+ import{g as r,j as u,t as c,u as l,v as d}from"../chunk-42FZPLOF.js";import{e as a}from"../chunk-3GWLCI47.js";var p=process.env.VISIQ_DEBUG==="1",m=p?(...o)=>{process.stderr.write(`${o.map(String).join(" ")}
3
+ `)}:()=>{},P=console;for(let o of["log","info","debug","warn","error"])P[o]=m;var h={handlePre:(o,e)=>c(o,e),handlePost:(o,e)=>l(o,e),handleSession:(o,e)=>d(o,e),write:o=>{process.stdout.write(o)}};async function f(o,e,s=h){let t=o.hook_event_name==="PreToolUse",i=n=>{t&&s.write(JSON.stringify(r(n)))};try{let n=null;switch(o.hook_event_name){case"PreToolUse":n=await s.handlePre(o,e);break;case"PostToolUse":n=await s.handlePost(o,e);break;case"SessionStart":n=await s.handleSession(o,e);break;default:n=null}n&&s.write(JSON.stringify(n))}catch(n){i(`[VisIQ] harness error (fail-closed): ${n instanceof Error?n.message:String(n)}`)}}function g(){return new Promise(o=>{if(process.stdin.isTTY){o("");return}let e=[],s=!1,t=()=>{s||(s=!0,o(Buffer.concat(e).toString("utf-8")))};setTimeout(t,15e3).unref?.(),process.stdin.on("data",n=>e.push(n)),process.stdin.on("end",t),process.stdin.on("error",t)})}async function w(){let o=u(await g());if(!o)return;let e=o.hook_event_name==="PreToolUse",s=i=>{e&&process.stdout.write(JSON.stringify(r(i)))},t=await a();if(!t){s("[VisIQ] Claude Code harness is loaded but NOT configured \u2014 set VISIQ_API_KEY + VISIQ_ENDPOINT so VisIQ can govern this tool call. Blocked (fail-closed) until configured.");return}await f(o,t)}w().then(()=>process.exit(0)).catch(()=>{try{process.stdout.write(JSON.stringify(r("[VisIQ] harness crashed before evaluating the call \u2014 blocked (fail-closed).")))}catch{}process.exit(0)});
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { z } from 'zod';
2
+
1
3
  /**
2
4
  * Credential + config-dir resolution for the VisIQ Claude Code harness.
3
5
  *
@@ -73,7 +75,7 @@ export declare function bareToolName(toolName: string): string;
73
75
  /** Does this tool call pull foreign content into the model's context? */
74
76
  export declare function isRetrievalTool(toolName: string): boolean;
75
77
  /** Governance facets to evaluate for a given tool. */
76
- export type Operation = "action" | "retrieval";
78
+ export type Operation = "action" | "retrieval" | "delegation";
77
79
  /**
78
80
  * The `operations[]` to hand `UnifiedRuntime.evaluate`. Retrieval tools carry
79
81
  * BOTH facets (an action rule can still govern a fetch); everything else is a
@@ -150,20 +152,47 @@ export type AgentCategory = (typeof AGENT_CATEGORIES)[number];
150
152
  * The agent attribute bundle exposed to rules as `input.agent` on both planes.
151
153
  * `trust_tier` may be null (unassigned → caller-supplied tier honored);
152
154
  * `categories` defaults to an empty array (never null);
153
- * `business_function` is one of the `BUSINESS_FUNCTION_IDS` (see
154
- * business-functions.ts) or null (unassigned conditions on it don't match).
155
+ * `business_functions` is the AUTHORITATIVE multi-value set — zero or more of the
156
+ * `BUSINESS_FUNCTION_IDS` (see business-functions.ts). An agent can serve several
157
+ * functions at once (e.g. an agent that is both HR and Engineering), and its set
158
+ * broadens over time as the AI reclassifies it. Rules test membership with the
159
+ * array-includes idiom (`"hr" in input.agent.business_functions`); an empty set
160
+ * never matches any such condition (fail-safe).
161
+ * `business_function` is the PRIMARY (best-fit) function — the first element of
162
+ * `business_functions`, or null when the set is empty — kept for backward
163
+ * compatibility with rules authored against the original scalar attribute.
155
164
  *
156
- * NOTE (dependency-light): `business_function` is typed `string | null` rather
157
- * than a narrowed union so this SSOT module imports nothing from
158
- * business-functions.ts — the closed-set validation lives at the write/eval
159
- * boundaries (isBusinessFunctionId) + the DB CHECK, keeping this type the
160
- * trivially-importable shape it has always been.
165
+ * NOTE (dependency-light): both fields are typed loosely (`string`) rather than a
166
+ * narrowed union so this SSOT module imports nothing from business-functions.ts —
167
+ * the closed-set validation lives at the write/eval boundaries
168
+ * (isBusinessFunctionId / normalizeBusinessFunctions) + the DB CHECK, keeping this
169
+ * type the trivially-importable shape it has always been.
161
170
  */
162
171
  export interface AgentEvalAttributes {
163
172
  trust_tier: TrustTier | null;
164
173
  categories: AgentCategory[];
165
- /** One of BUSINESS_FUNCTION_IDS, or null when unassigned. */
174
+ /**
175
+ * The AUTHORITATIVE set of the agent's business functions (0..N of
176
+ * BUSINESS_FUNCTION_IDS). Empty when unassigned. Rules test it with
177
+ * `"<id>" in input.agent.business_functions`.
178
+ */
179
+ business_functions: string[];
180
+ /**
181
+ * The PRIMARY business function — `business_functions[0]` (best-fit), or null
182
+ * when the set is empty. Back-compat mirror for scalar-authored rules.
183
+ */
166
184
  business_function: string | null;
185
+ /**
186
+ * Capability-derived blast-radius tier — one of BLAST_RADIUS_TIERS
187
+ * (blast-radius.ts) or null when NEVER inferred (cold start). Note the
188
+ * distinction: `null` = not yet assessed (conditions on it don't match, like
189
+ * business_function); the string `"unknown"` is a REAL assessed-but-
190
+ * undetermined value the inference can produce. Typed `string | null` (not the
191
+ * narrowed union) so this SSOT stays dependency-light — the closed-set
192
+ * validation lives at the write/eval boundaries (toBlastRadiusTier) + the DB
193
+ * CHECK, exactly as business_function does.
194
+ */
195
+ blast_radius_tier: string | null;
167
196
  }
168
197
  /**
169
198
  * The session trajectory bundle exposed to rules as `input.session` on both
@@ -190,6 +219,14 @@ export interface SessionEvalState {
190
219
  /** Distinct target apps touched earlier in the session. */
191
220
  target_apps: string[];
192
221
  }
222
+ /** One tool as captured at the harness bind boundary. Argument VALUES are never
223
+ * captured — `input_schema` is JSON Schema (shape only). */
224
+ export interface CapturedToolSpec {
225
+ name: string;
226
+ description?: string;
227
+ /** JSON Schema object describing the tool's arguments (no values). */
228
+ input_schema?: unknown;
229
+ }
193
230
  /**
194
231
  * Redaction directive — the shared masking primitive (SSOT).
195
232
  *
@@ -231,7 +268,84 @@ export interface AgentEnvironment {
231
268
  ip?: string;
232
269
  /** os.userInfo().username. */
233
270
  username?: string;
271
+ /**
272
+ * The harness-detected framework as a backend `agent_type` slug (e.g.
273
+ * `langchain`, `vercel_ai`). Omitted when unknown. The backend classifies a
274
+ * self-provisioned agent with this ONLY while its stored type is still the
275
+ * default `unknown` — never overwriting a management/human-set value.
276
+ */
277
+ agent_type?: string;
234
278
  }
279
+ /**
280
+ * Cognition beats — the Agent Cortex capture payload (thoughts, actions,
281
+ * observations, and SUB-AGENT SPAWNS) emitted autonomously from the harness
282
+ * seams and POSTed to `/allow/cognition`. This is display/graph data only; it
283
+ * never participates in a governance decision. Default-OFF (thoughts are
284
+ * sensitive) — see UnifiedRuntime.emitCognition.
285
+ *
286
+ * The shape mirrors the framework-agnostic `MindEvent` SSOT the Cortex UI reads
287
+ * (products/project-y/apps/web/src/components/allow/agents/cortex/types.ts).
288
+ */
289
+ export type CognitionBeatKind = "thought" | "speech" | "action" | "observation" | "intervention" | "spawn" | "phase" | "handoff" | "lifecycle" | "error";
290
+ export type CognitionVisibility = "shown" | "hidden";
291
+ export type CognitionProvenance = "signed" | "parsed" | "proxy" | "narration";
292
+ /** A recognized sub-agent spawn — the Mode-B delegation edge. */
293
+ export interface CognitionSpawn {
294
+ childAgentId: string;
295
+ childName: string;
296
+ kind: "subagent" | "workflow" | "teammate";
297
+ model?: string;
298
+ prompt?: string;
299
+ }
300
+ export interface CognitionBeat {
301
+ /** Stable harness-minted id → server dedup key (idempotent re-sends). */
302
+ clientEventId: string;
303
+ agentId: string;
304
+ sessionId: string;
305
+ threadId: string;
306
+ /** Cognition DAG parent (parentUuid / parent_run_id / the spawning agent). */
307
+ parentId?: string;
308
+ /** Per-session monotone ordering (order-independent replay). */
309
+ seq: number;
310
+ /** Beat wall-clock, epoch ms. */
311
+ ts: number;
312
+ durationMs?: number;
313
+ kind: CognitionBeatKind;
314
+ visibility?: CognitionVisibility;
315
+ provenance?: CognitionProvenance;
316
+ content?: {
317
+ text?: string;
318
+ spans?: unknown[];
319
+ };
320
+ tool?: Record<string, unknown>;
321
+ result?: Record<string, unknown>;
322
+ governance?: Record<string, unknown>;
323
+ spawn?: CognitionSpawn;
324
+ phase?: Record<string, unknown>;
325
+ handoff?: Record<string, unknown>;
326
+ attribution?: Record<string, unknown>;
327
+ cost?: Record<string, unknown>;
328
+ model?: string;
329
+ agentRole?: string;
330
+ framework?: string;
331
+ }
332
+ declare const bundleCacheOptionsSchema: z.ZodObject<{
333
+ /** Grace window in ms; ≥0. 0 ⇒ never serve a stale cache (fallback disabled). */
334
+ graceTtlMs: z.ZodOptional<z.ZodNumber>;
335
+ /** Disable the on-disk cache entirely. */
336
+ disabled: z.ZodOptional<z.ZodBoolean>;
337
+ /** Base cache directory override. */
338
+ cacheDir: z.ZodOptional<z.ZodString>;
339
+ }, "strict", z.ZodTypeAny, {
340
+ graceTtlMs?: number | undefined;
341
+ disabled?: boolean | undefined;
342
+ cacheDir?: string | undefined;
343
+ }, {
344
+ graceTtlMs?: number | undefined;
345
+ disabled?: boolean | undefined;
346
+ cacheDir?: string | undefined;
347
+ }>;
348
+ export type BundleCacheOptions = z.infer<typeof bundleCacheOptionsSchema>;
235
349
  /** The facets an event participates in (the unified `operations` tag). */
236
350
  export type UnifiedOperation = "retrieval" | "action" | "delegation";
237
351
  /** One governed agent event, tagged with the facets it participates in. */
@@ -267,6 +381,16 @@ export interface UnifiedEvaluateEvent {
267
381
  /** A snippet of the retrieved/produced content (reserved; not yet evaluated). */
268
382
  contentPreview?: string;
269
383
  telemetry?: Record<string, unknown>;
384
+ /**
385
+ * Caller-supplied structured context to PERSIST on the telemetry row
386
+ * (`allow_audit_log.context`), merged alongside the interceptor source. This is
387
+ * how an autonomous capture seam attaches a `delegation` object (a recognized
388
+ * sub-agent spawn: `{ delegation: { is_delegated, parent_agent_id, target_agent,
389
+ * source, spawn } }`) without any new endpoint or column — the delegation sink
390
+ * (`fetchAgentDelegations`) already reads `context->'delegation'`. Never used for
391
+ * the decision itself; display/graph data only.
392
+ */
393
+ context?: Record<string, unknown>;
270
394
  }
271
395
  /** The action-facet sub-decision (null leg when the event had no action op). */
272
396
  export interface UnifiedActionSubDecision {
@@ -333,6 +457,10 @@ declare class UnifiedRuntime {
333
457
  private readonly resolvedEndpoint;
334
458
  private readonly resolvedAgentId;
335
459
  private readonly harnessKind;
460
+ /** Human-readable SDK version for the `X-VisIQ-SDK` header (undefined → DEFAULT_SDK_VERSION). */
461
+ private readonly sdkVersion;
462
+ /** Wire-contract capability integer for the `X-VisIQ-Dialect` header (undefined → SDK_DIALECT). */
463
+ private readonly sdkDialect;
336
464
  private rules;
337
465
  /** Server-authoritative agent attributes from the bundle (null until shipped). */
338
466
  private agentAttributes;
@@ -359,37 +487,84 @@ declare class UnifiedRuntime {
359
487
  private bundleFetchInProgress;
360
488
  private initialBundlePromise;
361
489
  private refreshTimer;
490
+ /**
491
+ * On-disk bundle cache (grace-TTL outage survival). Persist every successful
492
+ * bundle; on a COLD-START fetch failure, serve the most recent cached bundle
493
+ * IF younger than {@link bundleGraceTtlMs}. Beyond grace / corrupt / absent ⇒
494
+ * the pre-existing cold-start fail-closed deny is preserved EXACTLY (G001).
495
+ * Identity is null (cache off) when no backend creds are configured.
496
+ */
497
+ private readonly cacheIdentity;
498
+ private readonly bundleCacheDisabled;
499
+ private readonly bundleGraceTtlMs;
500
+ private readonly bundleCacheDirOverride;
501
+ /** Guard so the one-time cold-start disk fallback warning isn't re-logged. */
502
+ private diskFallbackServed;
362
503
  private agentMode;
504
+ /** Optional per-operation mode override, shipped resolved in the bundle:
505
+ * `{action?, retrieval?, delegation?}` → enforce|monitor|off. An operation
506
+ * absent here inherits {@link agentMode}. Null ⇒ no per-op override. */
507
+ private agentModeByOperation;
508
+ /** The RAW bundle body last applied — handed VERBATIM to the Rust core
509
+ * (@visiq/core-wasm) on the `wasm` decision path (it re-parses rows / hydrates
510
+ * attributes / reads no_coverage itself, so it reproduces the TS decision
511
+ * byte-for-byte). `agent_mode` + `agent_mode_by_operation` are overridden at
512
+ * call time with the runtime's EFFECTIVE (stateful) modes. */
513
+ private rawBundle;
363
514
  /** True once the backend has EXPLICITLY confirmed this agent's mode. A
364
515
  * schema-defaulted/cold-start monitor is NOT confirmed — so a no-bundle deny
365
- * still fails closed to enforce rather than trusting a permissive default. */
516
+ * for a CONFIRMED enforce agent fails closed to deny, while a NEVER-confirmed
517
+ * agent degrades to monitor (the onboarding fail-safe), never to enforce. */
366
518
  private agentModeConfirmed;
519
+ /** True when the last applied bundle carried `shutdown: true` — the operator
520
+ * has shut this agent down (notebook item 1). Every {@link evaluate} then
521
+ * returns an immediate, always-enforced deny-all BEFORE any mode bypass / rule
522
+ * eval / core call. Set from the bundle on every version change (a normal
523
+ * bundle ⇒ false), so reactivation (a fresh non-shutdown bundle) clears it.
524
+ * (Named `operatorShutdown` to leave the public `shutdown()` graceful-drain
525
+ * method — added for HS-4 — an unambiguous name.) */
526
+ private operatorShutdown;
527
+ /** True when a bundle body was RECEIVED but FAILED to apply (malformed /
528
+ * schema-drifted / corrupt cache) — an ERROR, distinct from a genuinely
529
+ * absent bundle. On cold start this fails CLOSED (enforce the deny-all) so a
530
+ * corrupt or poisoned bundle can never downgrade an agent to the permissive
531
+ * monitor onboarding fail-safe (G001). Cleared once a body validates. */
532
+ private bundleApplyFailed;
533
+ /**
534
+ * True when the last bundle required a wire dialect NEWER than this SDK speaks
535
+ * (`min_dialect` > our dialect). Like {@link operatorShutdown} it forces an
536
+ * enforced deny-all on EVERY evaluate — the bundle may carry constructs we
537
+ * cannot honour, so we refuse it wholesale (MUST-UNDERSTAND, G001) rather than
538
+ * apply a subset. Cleared the instant a bundle we CAN speak applies.
539
+ */
540
+ private dialectRefused;
367
541
  private telemetryBuffer;
368
542
  private telemetryTimer;
543
+ private cognitionBuffer;
544
+ private cognitionTimer;
545
+ /** Resolved from the bundle (`cognition_capture`, server source-of-truth) or
546
+ * the `VISIQ_COGNITION_CAPTURE=1` dev override. Default OFF ⇒ emitCognition is
547
+ * an immediate return (zero cost). The server re-checks on ingest regardless. */
548
+ private cognitionEnabled;
369
549
  private envRegistered;
370
550
  private registerPromise;
371
- constructor(apiKey?: string, endpoint?: string, agentId?: string, harnessKind?: AgentKind, timeoutMs?: number);
551
+ /** Content signature of the last reported tool surface — so a repeat visiq()
552
+ * wrap (same tools) doesn't re-POST. Null until the first report. */
553
+ private lastToolSurfaceSig;
554
+ constructor(apiKey?: string, endpoint?: string, agentId?: string, harnessKind?: AgentKind, timeoutMs?: number, sdkVersion?: string, sdkDialect?: number, bundleCache?: BundleCacheOptions);
372
555
  /**
373
556
  * Evaluate one governed agent event across ALL its tagged operations and
374
557
  * return the merged unified decision with both facet sub-decisions.
375
558
  */
376
559
  evaluate(event: UnifiedEvaluateEvent): Promise<UnifiedDecision>;
560
+ /**
561
+ * Resolve the effective mode for one operation: per-op override → agent mode.
562
+ */
563
+ private modeFor;
377
564
  /** Read the session's PRIOR-events state; fresh/absent/expired ⇒ empty. */
378
565
  private readSession;
379
566
  /** Fold one decided event into its session (LRU touch + bounds enforcement). */
380
567
  private foldSession;
381
- /**
382
- * Evaluate ONE operation against the cached rules, then apply that facet's
383
- * uncovered semantics: action/delegation → no-coverage defaults (or
384
- * fail-closed deny); retrieval → DEFAULT_DENY.
385
- */
386
- private resolveOperation;
387
- /** Build the facet-specific {@link UnifiedEvaluationInput} for one operation. */
388
- private buildInput;
389
- /** Compose the merged {@link UnifiedDecision} from the per-leg results. */
390
- private buildDecision;
391
- private actionSub;
392
- private retrievalSub;
393
568
  /**
394
569
  * Apply the agent_mode envelope and record telemetry. enforce returns the
395
570
  * real verdict; monitor forces allowed=true (observe-only) while preserving
@@ -421,6 +596,28 @@ declare class UnifiedRuntime {
421
596
  */
422
597
  awaitBundleReady(timeoutMs?: number): Promise<void>;
423
598
  private fetchBundleBackground;
599
+ /**
600
+ * The initial bundle load driven at construction: attempt the network fetch
601
+ * first (the authoritative, freshest source), and ONLY if that leaves us with
602
+ * no bundle on a cold start fall back to the on-disk grace cache. This keeps
603
+ * the periodic refresh path ({@link fetchBundleBackground}) network-only, and
604
+ * confines the one-time disk fallback to startup — a warm process never reads
605
+ * the disk cache. Awaited by {@link awaitBundleReady}.
606
+ */
607
+ private initialBundleLoad;
608
+ /**
609
+ * Cold-start fallback: if the initial network fetch failed, serve the most
610
+ * recent on-disk bundle IF it exists, passes its integrity check, AND is
611
+ * younger than the grace window. The disk body is applied through the SAME
612
+ * {@link applyBundle} (Zod envelope validation + min_dialect refusal), so a
613
+ * stale/corrupt/too-new cached bundle can never be applied more permissively
614
+ * than a fresh one. Beyond grace / absent / corrupt ⇒ NOTHING is loaded and
615
+ * the runtime's cold-start fail-closed deny is preserved EXACTLY (G001).
616
+ * Best-effort; never throws.
617
+ */
618
+ private tryLoadFromDiskCache;
619
+ /** Persist the applied bundle body to the on-disk grace cache. Best-effort. */
620
+ private persistBundleToDisk;
424
621
  hasRules(): boolean;
425
622
  hasClient(): boolean;
426
623
  /** The resolved backend endpoint, for callers driving the HITL wait loop. */
@@ -435,13 +632,48 @@ declare class UnifiedRuntime {
435
632
  getSessionState(sessionId: string): SessionEvalState;
436
633
  /** Report the agent's environment once per runtime instance (fire-and-forget). */
437
634
  registerEnvironment(env: AgentEnvironment): void;
438
- /** Capture + register the host environment (the single init entry point). */
439
- registerHostEnvironment(): void;
635
+ /**
636
+ * Capture + register the host environment (the single init entry point).
637
+ * `agentType` is the harness-detected framework slug (F5) — merged into the
638
+ * registration handshake so the backend can classify a self-provisioned agent
639
+ * (omitted when unknown, so it never overwrites a good value).
640
+ */
641
+ registerHostEnvironment(agentType?: string): void;
642
+ /**
643
+ * Report the agent's captured tool surface (fire-and-forget). Drives backend
644
+ * blast-radius inference. Re-reports ONLY when the surface changes (content
645
+ * signature guard), so wrapping several agents / re-wrapping the same one in a
646
+ * process doesn't re-POST an identical set. No-ops without a client/agent id or
647
+ * on an empty set. Never throws (best-effort, must not affect the host).
648
+ */
649
+ reportToolSurface(tools: CapturedToolSpec[]): void;
440
650
  private bufferTelemetry;
651
+ /** Buffered-but-unsent decision count (for the exit-drain warning). */
652
+ pendingTelemetryCount(): number;
653
+ /** True when a backend is configured (telemetry can actually be shipped). */
654
+ hasBackend(): boolean;
441
655
  private flushTelemetry;
442
656
  private enforceTelemetryCap;
443
- /** Drain pending registration + telemetry and await it (graceful shutdown). */
657
+ /** Whether cognition capture is currently enabled (resolved from the bundle). */
658
+ isCognitionEnabled(): boolean;
659
+ /**
660
+ * Emit a cognition beat (thought / action / spawn / …) to the Agent Cortex
661
+ * sink. DEFAULT-OFF gate: an immediate `return` when disabled — zero cost, no
662
+ * allocation. NEVER awaits or throws into the agent's path; a size trigger
663
+ * bounds latency for the higher-volume cognition stream.
664
+ */
665
+ emitCognition(beat: CognitionBeat): void;
666
+ private flushCognition;
667
+ private enforceCognitionCap;
668
+ /** Drain pending registration + telemetry + cognition and await it (graceful shutdown). */
444
669
  flush(): Promise<void>;
670
+ /**
671
+ * Graceful shutdown for a long-running host: drain every pending batch, stop
672
+ * the background timers, and deregister from the process exit-drain set so the
673
+ * runtime can be GC'd. Idempotent; short-lived scripts are covered
674
+ * automatically by the beforeExit / SIGINT / SIGTERM hooks.
675
+ */
676
+ shutdown(): Promise<void>;
445
677
  dispose(): void;
446
678
  }
447
679
  /**
@@ -615,6 +847,9 @@ export declare function buildEvaluateEvent(opts: {
615
847
  cwd?: string;
616
848
  toolUseId?: string;
617
849
  query?: string;
850
+ /** Structured context to persist on allow_audit_log.context (e.g. a recognized
851
+ * `delegation` object for a Task sub-agent spawn). */
852
+ context?: Record<string, unknown>;
618
853
  }): UnifiedEvaluateEvent;
619
854
  /**
620
855
  * Warm a runtime's local bundle so `evaluate()` runs offline + never spuriously
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as E,b as T,c as h,d as C,e as u,f as x,g as S}from"./chunk-6DMSMBWM.js";import{a as n,b as s,c as a,d as l,e as P,f as U,g as F,h as b,i as q,j as K,k as m,l as p,m as f,n as d,o as I,p as L,q as k,r as v,s as y,t as A,u as B,v as M}from"./chunk-K5THPWCB.js";import{a as e,b as o,c as t,d as r,e as i,f as c,g as R,h as g,i as H,j as O,k as _,l as D,m as N}from"./chunk-3GWLCI47.js";export{c as DEFAULT_BUNDLE_TTL_MS,I as HARNESS_KIND,E as HOOK_COMMAND,T as HOOK_TIMEOUT_SECONDS,h as RETRIEVAL_MATCHER,m as WITHHELD_SENTINEL,n as bareToolName,p as blankContent,k as buildEvaluateEvent,q as buildPostRedact,U as buildPreAllow,b as buildPreAsk,F as buildPreDeny,o as configFilePath,L as createRuntime,t as envConfig,l as extractQuery,_ as fetchBundle,y as finishRuntime,P as formatReason,B as handlePostToolUse,A as handlePreToolUse,M as handleSessionStart,S as hooksInstalled,u as installHooks,g as isFresh,s as isRetrievalTool,D as isSessionRegistered,C as isVisiqGroup,i as loadConfig,d as mapPostRedaction,f as mapPreDecision,N as markSessionRegistered,r as mergeConfig,K as parseHookInput,H as readBundleCache,R as sanitizeId,a as toolOperations,x as uninstallHooks,e as visiqHomeDir,v as warmFromCache,O as writeBundleCache};
1
+ import{a as E,b as T,c as h,d as C,e as u,f as x,g as S}from"./chunk-6DMSMBWM.js";import{a as n,b as s,c as a,d as l,e as P,f as U,g as F,h as b,i as q,j as K,k as m,l as p,m as f,n as d,o as I,p as L,q as k,r as v,s as y,t as A,u as B,v as M}from"./chunk-42FZPLOF.js";import{a as e,b as o,c as t,d as r,e as i,f as c,g as R,h as g,i as H,j as O,k as _,l as D,m as N}from"./chunk-3GWLCI47.js";export{c as DEFAULT_BUNDLE_TTL_MS,I as HARNESS_KIND,E as HOOK_COMMAND,T as HOOK_TIMEOUT_SECONDS,h as RETRIEVAL_MATCHER,m as WITHHELD_SENTINEL,n as bareToolName,p as blankContent,k as buildEvaluateEvent,q as buildPostRedact,U as buildPreAllow,b as buildPreAsk,F as buildPreDeny,o as configFilePath,L as createRuntime,t as envConfig,l as extractQuery,_ as fetchBundle,y as finishRuntime,P as formatReason,B as handlePostToolUse,A as handlePreToolUse,M as handleSessionStart,S as hooksInstalled,u as installHooks,g as isFresh,s as isRetrievalTool,D as isSessionRegistered,C as isVisiqGroup,i as loadConfig,d as mapPostRedaction,f as mapPreDecision,N as markSessionRegistered,r as mergeConfig,K as parseHookInput,H as readBundleCache,R as sanitizeId,a as toolOperations,x as uninstallHooks,e as visiqHomeDir,v as warmFromCache,O as writeBundleCache};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visiq/claude-code-harness",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "VisIQ governance harness for the Claude Code CLI — action monitor/block + retrieval monitor/block/redact via Claude Code hooks",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -16,7 +16,8 @@
16
16
  }
17
17
  },
18
18
  "dependencies": {
19
- "zod": "^3.23.8"
19
+ "zod": "^3.23.8",
20
+ "@visiq/core-wasm": "^0.1.3"
20
21
  },
21
22
  "engines": {
22
23
  "node": ">=20"
@@ -24,7 +25,8 @@
24
25
  "license": "MIT",
25
26
  "files": [
26
27
  "dist",
27
- "README.md"
28
+ "README.md",
29
+ "LICENSE"
28
30
  ],
29
31
  "publishConfig": {
30
32
  "access": "public"
@@ -1,4 +0,0 @@
1
- import{f as se,h as le,i as ce,j as ue,k as de,l as pe,m as P}from"./chunk-3GWLCI47.js";var st=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),lt=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function ct(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 z(e){return typeof e!="string"?!1:st.has(e)?!0:e.startsWith("mcp__")?lt.test(ct(e)):!1}function fe(e){return z(e)?["retrieval","action"]:["action"]}var ut=["query","q","url","prompt","pattern","file_path","path"];function L(e){if(!e||typeof e!="object")return;let t=e,n=[];for(let r of ut){let i=t[r];typeof i=="string"&&i.length>0&&n.push(i)}return n.length>0?n.join(" "):void 0}function I(e,t){let n=t?`VisIQ ${t}`:"VisIQ",r=e&&e.trim().length>0?e.trim():"blocked by policy";return`[${n}] ${r}`}function me(e){let t={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};return e&&(t.hookSpecificOutput.updatedInput=e),t}function F(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}function ge(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:e}}}function S(e,t){let n={hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}};return t&&(n.hookSpecificOutput.additionalContext=t),n}function Fn(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.hook_event_name=="string"?t:null}catch{return null}}var dt=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];var h=Object.fromEntries(dt.map(e=>[e.name,e.re.source])),pt=["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","pan","iban","aba_routing","us_ein","swift_bic","ssn","email","us_phone","ipv4","mac_address"],ft={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
2
- MIIEv\u2026
3
- -----END PRIVATE KEY-----`,template:{pattern:h.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:h.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:h.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:h.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:h.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:h.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:h.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:h.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:h.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:h.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS).",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\b\\d{13,19}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){10,30}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:"\\b\\d{9}\\b",mode:"full"},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX).",category:"financial",example:"12-3456789",template:{pattern:h.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:h.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789).",category:"pii",example:"123-45-6789",template:{pattern:h.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept).",category:"pii",example:"alice@acme.com",template:{pattern:h.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:h.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:h.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:h.mac_address,mode:"full"},defaultEnabled:!1}},Mn=new Set(pt.filter(e=>!ft[e].defaultEnabled));var G="[REDACTED]",E="\u2022",D=e=>/[A-Za-z0-9]/.test(e);function _e(e,t,n,r){let i=Array.from(e),o=i.length,a=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),c=r.length>0?r:E,p=a+s>=o;return i.map((d,_)=>!p&&(_<a||_>=o-s)?d:D(d)?c:d).join("")}function mt(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return _e(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:E;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>D(a)?o:a).join(""))+i}function gt(e,t,n){let r=n.length>0?n:E,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let p=new RegExp(t,"g"),d;for(;(d=p.exec(e))!==null;){if(d[0].length===0){p.lastIndex++;continue}for(let _=d.index;_<d.index+d[0].length;_++)i[_]=!0}}catch{}let o=!1,a=!0;for(let p=0;p<e.length;p++)if(D(e[p])&&(o=!0,!i[p])){a=!1;break}let s=o&&a,c="";for(let p=0;p<e.length;p++){let d=e[p];!s&&i[p]||!D(d)?c+=d:c+=r}return c}function he(e,t){let n=t.mode??"full";return n==="partial"?_e(e,t.keepFirst??0,t.keepLast??0,t.maskChar??E):n==="email"?mt(e,t.maskChar??E):n==="custom"?gt(e,t.keepPattern,t.maskChar??E):t.replacement??G}function _t(e,t){return typeof e=="string"?he(e,t):t.replacement??G}function ye(e){let t=[],n=e.replacement??G;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:o=>he(o,r)})}return t}function be(e,t){let n=e;for(let{source:r,replacer:i}of t){let o;try{o=new RegExp(r,"g")}catch(a){let s=a instanceof Error?a.message:String(a);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(o,a=>i(a))}return n}function V(e,t){return e==null?e:typeof e=="string"?ht(e,t):typeof e=="object"?yt(e,t):e}function ht(e,t){if(typeof e!="string")return e;let n=ye(t);return n.length===0?e:be(e,n)}function yt(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=ye(t),i=n.size>0,o=r.length>0,a=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(c=>a(c));if(typeof s=="object"){let c=s,p=Object.create(Object.getPrototypeOf(c));for(let d of Object.keys(c)){let _=i?n.get(d):void 0;if(_){p[d]=_t(c[d],_);continue}p[d]=a(c[d])}return p}return typeof s=="string"&&o?be(s,r):s};return a(e)}import{z as u}from"zod";import*as v from"node:os";var ve="interceptor_source",bt=u.enum(["enforce","audit","off"]),vt=u.enum(["closed","open"]),Ae=u.enum(["enforce","monitor","off"]),At=u.object({apiKey:u.string().min(1,"apiKey is required"),agentId:u.string().min(1,"agentId is required"),endpoint:u.string().url().optional(),mode:bt.optional(),timeoutMs:u.number().int().positive().optional(),hitlTimeoutMs:u.number().int().positive().optional(),failBehavior:vt.optional()}),qn=u.object({agent_id:u.string().min(1),target_app:u.string().min(1),action:u.string().min(1),context:u.record(u.unknown()).optional(),session_id:u.string().min(1).max(255).optional(),telemetry:u.record(u.unknown()).optional()}),wt=u.object({field:u.string().optional(),pattern:u.string().optional(),replacement:u.string().optional(),mode:u.enum(["full","partial","email"]).optional(),keepFirst:u.number().optional(),keepLast:u.number().optional(),maskChar:u.string().optional()}),kt=u.object({decision_id:u.string().min(1),decision:u.enum(["permit","deny","approval_required","mask"]),reason:u.string().optional(),rule_code:u.string().nullable().optional(),enforced:u.boolean().optional(),agent_mode:Ae.optional(),arg_redaction_rules:u.array(wt).optional(),plane:u.string().nullable().optional(),operation:u.string().nullable().optional(),is_retrieval:u.boolean().optional(),metadata:u.record(u.unknown()).optional()}),It=u.object({field:u.string().min(1),operator:u.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:u.union([u.string(),u.number(),u.array(u.string())])}),St=u.object({id:u.string().min(1),rule_code:u.string().default(""),name:u.string().min(1),description:u.string().nullable().default(null),effect:u.enum(["allow","deny","hitl","mask"]),resource_type:u.string().min(1),rego_source:u.string().default(""),target_app:u.string().nullable().default(null),action_pattern:u.string().nullable().default(null),conditions:u.array(It).default([]),priority:u.number().int().default(0)}),Et=u.object({version:u.string().min(1),agent_mode:Ae.optional(),rules:u.array(St),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()}),Ct=2e3,we=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}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}`},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 kt.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"},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();return Et.parse(o)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.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}`},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}`},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}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration 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}`},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();if(typeof o!="object"||o===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let a=o,s=a.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof a.reason=="string"?a.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await Tt(Ct)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Tt(e){return new Promise(t=>setTimeout(t,e))}function ke(){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=xt();t&&(e.ip=t)}catch{}return e}function xt(){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}import{z as f}from"zod";import{createHash as Ot}from"crypto";import{createHash as Vn}from"crypto";var Rt=class extends Error{constructor(e,t){super(`eval_conflict_error: complete rules must not produce multiple outputs for "${e}" (got ${t.map(n=>JSON.stringify(n)).join(", ")})`),this.variable=e,this.values=t,this.name="RegoConflictError"}variable;values},Ie=new Map;function Se(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function Ue(e){let t=Ot("sha256").update(e).digest("hex"),n=Ie.get(t);if(n)return n;let r=new Map,i=[],o=e.split(`
4
- `).map(c=>Nt(c)).filter(c=>c.trim().length>0),a=0;for(;a<o.length;){let c=o[a].trim();if(c.startsWith("package ")||c.startsWith("import ")){a++;continue}let p=c.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(p){let l=p[1],g=p[2].trim();r.set(l,R(g)),a++;continue}let d=c.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(d){let l=d[1],g=d[2].trim(),m=d[3].trim(),y=[];if(m&&m!=="}"){let N=m.endsWith("}")?m.slice(0,-1).trim():m;N&&y.push(N),m.endsWith("}")||(a++,a=M(o,a,y))}else m==="}"||(a++,a=M(o,a,y));let k=Ce(y);i.push({variable:l,value:R(g),conditions:k,rawConditions:Se(y)}),a++;continue}let _=c.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(_){let l=_[1],g=_[2].trim(),m=[];if(g&&g!=="}"){let k=g.endsWith("}")?g.slice(0,-1).trim():g;k&&m.push(k),g.endsWith("}")||(a++,a=M(o,a,m))}else g==="}"||(a++,a=M(o,a,m));let y=Ce(m);i.push({variable:l,value:"true",conditions:y,rawConditions:Se(m)}),a++;continue}a++}let s={defaults:r,rules:i};return Ie.set(t,s),s}function qe(e,t){let n={};for(let[o,a]of e.defaults)n[o]=a;let r=-1,i={};for(let o=0;o<e.rules.length;o++){let a=e.rules[o];if(a.conditions.every(s=>Mt(s,t))){if(i[a.variable]===void 0)i[a.variable]=a.value,n[a.variable]=a.value;else if(i[a.variable]!==a.value)throw new Rt(a.variable,[i[a.variable],a.value]);r===-1&&(r=o)}}return r!==-1?{bindings:n,matched:!0,matchedRuleIndex:r}:{bindings:n,matched:!1,matchedRuleIndex:-1}}function Nt(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 o=e[i].trim();for(let a of o)a==="{"&&r++,a==="}"&&r--;if(r>0)n.push(o),i++;else{let a=o.slice(0,o.lastIndexOf("}")).trim();return a&&n.push(a),i}}return i}function R(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Pt(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}var Ee=new Map;function Lt(e){let t=Ee.get(e);if(t!==void 0)return t;let n;try{n=new RegExp(e)}catch{n=null}return Ee.set(e,n),n}function Ce(e){let t=[];for(let n of e){let r=n.split(";").map(i=>i.trim()).filter(i=>i.length>0);for(let i of r){let o=Ft(i);o&&t.push(o)}}return t}function Ft(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:Z,value:e.trim()};let r=n.match(/^count\(([^)]+)\)\s*(>=|<=|>|<)\s*(\d+)$/);if(r)return{type:"count_gt",negated:t,field:r[1].trim(),operator:r[2],value:parseInt(r[3],10)};let i=n.match(/^startswith\(([^,]+),\s*"([^"]*)"\)$/);if(i)return{type:"startswith",negated:t,field:i[1].trim(),value:i[2]};let o=n.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"endswith",negated:t,field:o[1].trim(),value:o[2]};let a=n.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(a)return{type:"contains",negated:t,field:a[1].trim(),value:a[2]};let s=n.match(/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:Pt(s[1])};let c=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s+in\s+((?:input|data)[^\s]*)$/);if(c)return{type:"array_includes",negated:t,field:c[2].trim(),value:$e(c[1])};let p=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(p){let y=Dt(p[2]);if(y!==null)return{type:"in_set",negated:t,field:p[1].trim(),values:y}}let d=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(d)return{type:"comparison",negated:t,field:d[1].trim(),operator:d[2],value:parseFloat(d[3])};let _=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s*==\s*((?:input|data)\S*)$/);if(_)return{type:"equality",negated:t,field:_[2].trim(),value:R(_[1].trim())};let l=n.match(/^([^\s=!]+)\s*==\s*(.+)$/);if(l)return{type:"equality",negated:t,field:l[1].trim(),value:R(l[2].trim())};let g=n.match(/^([^\s=!]+)\s*!=\s*(.+)$/);if(g)return{type:"inequality",negated:t,field:g[1].trim(),value:R(g[2].trim())};let m=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return m?{type:"truthy",negated:t,field:m[1].trim()}:{type:"truthy",negated:!1,field:Z,value:e.trim()}}var Z="__unrecognized_condition_forces_deny__";function $e(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 Dt(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",i=!1,o="";for(let s=0;s<t.length;s++){let c=t[s];i?(r+=c,c===o&&t[s-1]!=="\\"&&(i=!1)):c==='"'||c==="'"?(r+=c,i=!0,o=c):c===","?(n.push(r.trim()),r=""):r+=c}if(i)return null;r.trim().length>0&&n.push(r.trim());let a=[];for(let s of n){let c=s.startsWith('"')&&s.endsWith('"')&&s.length>=2||s.startsWith("'")&&s.endsWith("'")&&s.length>=2,p=/^-?\d+(?:\.\d+)?$/.test(s);if(!c&&!p&&!(s==="true"||s==="false"))return null;a.push($e(s))}return a}function Mt(e,t){if(e.field===Z)return!1;let n;switch(e.type){case"equality":{let r=b(e.field,t);n=j(r,e.value);break}case"inequality":{let r=b(e.field,t);r==null?n=!1:n=!j(r,e.value);break}case"startswith":{let r=b(e.field,t);typeof r!="string"?n=!1:n=r.startsWith(String(e.value));break}case"endswith":{let r=b(e.field,t);typeof r!="string"?n=!1:n=r.endsWith(String(e.value));break}case"contains":{let r=b(e.field,t);typeof r!="string"?n=!1:n=r.includes(String(e.value));break}case"regex_match":{let r=b(e.field,t);if(typeof r!="string")n=!1;else{let i=Lt(String(e.value??""));n=i?i.test(r):!1}break}case"truthy":{let r=b(e.field,t);n=$t(r);break}case"count_gt":{let r=b(e.field,t),i=typeof e.value=="number"?e.value:0,o=Ut(r);o===null?n=!1:n=Te(o,e.operator??">",i);break}case"comparison":{let r=b(e.field,t),i=typeof e.value=="number"?e.value:NaN,o=qt(r);Number.isNaN(o)||Number.isNaN(i)||!e.operator?n=!1:n=Te(o,e.operator,i);break}case"in_set":{let r=b(e.field,t),i=e.values??[];Y(r)?n=i.some(o=>j(r,o)):n=!1;break}case"array_includes":{let r=b(e.field,t);Array.isArray(r)?n=r.some(i=>j(i,e.value)):n=!1;break}case"literal_bool":{n=e.value===!0;break}default:n=!1}return e.negated?!n:n}function b(e,t){let n=e;n.startsWith("input.")?n=n.slice(6):n.startsWith("input[")&&(n=n.slice(5));let r=jt(n);if(r===null)return;let i=t;for(let o of r){if(i==null||typeof i!="object")return;i=i[o]}return i}function jt(e){let t=[],n=0,r="";for(;n<e.length;){let i=e[n];if(i===".")r.length>0&&(t.push(r),r=""),n++;else if(i==="["){r.length>0&&(t.push(r),r="");let o=e[n+1];if(o!=='"'&&o!=="'")return null;let a=e.indexOf(`${o}]`,n+2);if(a===-1)return null;t.push(e.slice(n+2,a)),n=a+2}else r+=i,n++}return r.length>0&&t.push(r),t}function Ut(e){return Array.isArray(e)||typeof e=="string"?e.length:e&&typeof e=="object"?Object.keys(e).length:null}function qt(e){return typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN}function Te(e,t,n){switch(t){case">":return e>n;case">=":return e>=n;case"<":return e<n;case"<=":return e<=n;default:return!1}}function Y(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function j(e,t){return!Y(e)||!Y(t)?!1:String(e)===String(t)}function $t(e){return!(e==null||e===!1||e===0||e==="")}function Bt(e){return e.trim()}function Wt(e){return e.map(Bt).filter(t=>t.length>0&&t!=="true")}function zt(e,t=0){let n=3735928559^t,r=1103547991^t;for(let i=0;i<e.length;i++){let o=e.charCodeAt(i);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}var Gt="\0";function Be(e,t){let n=[e.trim(),...Wt(t)].join(Gt);return`b_${zt(n).toString(36)}`}var Vt=["tier1","tier2","tier3"];function We(e){return typeof e=="string"&&Vt.includes(e)}var Ht=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Kt=["internal","customer_facing","experimental","third_party"],ze=[...Ht,...Kt];function Zt(e){return typeof e=="string"&&ze.includes(e)}function Ge(e){let t=new Set;for(let n of e)Zt(n)&&t.add(n);return ze.filter(n=>t.has(n))}var $={trust_tier:null,categories:[],business_function:null},Yt=["read_only","record_create","record_update","record_delete","data_export","data_share","data_subject_request","consent_change","funds_transfer","funds_disbursement","payroll_run","trade_execution","ledger_mutation","credit_decision","decision_adverse","account_restriction","account_closure","card_management","purchase_commitment","vendor_management","deal_management","pricing_change","contract_execution","legal_hold","regulatory_filing","personnel_action","employment_termination","compensation_change","campaign_send","content_publish","inventory_adjustment","order_fulfillment","account_servicing","credential_reset","access_grant","permission_change","credential_management","auth_policy_change","security_config_change","logging_change","alert_management","code_change","infrastructure_provision","deployment_change","communication_send","other"];function Ve(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 Jt={wire_transfer:"funds_transfer",international_transfer:"funds_transfer",cross_border_payment:"funds_transfer",send_swift:"funds_transfer",send_wire:"funds_transfer",transfer_funds:"funds_transfer",update_wire_instructions:"funds_transfer",add_beneficiary:"funds_transfer",modify_payee:"funds_transfer",disburse_funds:"funds_disbursement",initiate_ach:"funds_disbursement",issue_refund:"funds_disbursement",execute_trade:"trade_execution",place_order:"trade_execution",post_journal_entry:"ledger_mutation",adjust_ledger:"ledger_mutation",modify_general_ledger:"ledger_mutation",raise_limit:"credit_decision",increase_credit_limit:"credit_decision",extend_credit:"credit_decision",decline_credit:"decision_adverse",deny_application:"decision_adverse",adverse_action:"decision_adverse",block_card:"card_management",cancel_card:"card_management",place_hold:"account_restriction",freeze_account:"account_restriction",restrict_account:"account_restriction",close_account:"account_closure",export_data:"data_export",export_customer_list:"data_export",download_report:"data_export",download_customer_list:"data_export",bulk_export:"data_export",share_data:"data_share",send_to_partner:"data_share",delete_records:"record_delete",delete_user:"record_delete",drop_table:"record_delete",grant_role:"access_grant",change_permissions:"permission_change",modify_access:"permission_change",rotate_keys:"credential_management",disable_mfa:"auth_policy_change",modify_security_config:"security_config_change",disable_logging:"logging_change",purge_logs:"logging_change",suppress_alert:"alert_management",dismiss_alert:"alert_management",rollback:"deployment_change",modify_billing:"record_update",close_sar:"record_update",send_email:"communication_send",send_sms:"communication_send",fulfill_dsar:"data_subject_request",process_dsar:"data_subject_request",fulfill_data_request:"data_subject_request",process_erasure_request:"data_subject_request",honor_deletion_request:"data_subject_request",export_subject_data:"data_subject_request",erase_subject_data:"data_subject_request",delete_subject_data:"data_subject_request",record_consent:"consent_change",capture_consent:"consent_change",update_consent:"consent_change",withdraw_consent:"consent_change",revoke_consent:"consent_change",opt_out:"consent_change",opt_in:"consent_change",run_payroll:"payroll_run",process_payroll:"payroll_run",submit_payroll:"payroll_run",approve_payroll:"payroll_run",create_purchase_order:"purchase_commitment",issue_purchase_order:"purchase_commitment",approve_purchase_order:"purchase_commitment",submit_purchase_order:"purchase_commitment",approve_purchase:"purchase_commitment",approve_requisition:"purchase_commitment",commit_spend:"purchase_commitment",onboard_vendor:"vendor_management",add_vendor:"vendor_management",create_supplier:"vendor_management",approve_vendor:"vendor_management",update_vendor_bank:"vendor_management",update_supplier_bank:"vendor_management",modify_supplier:"vendor_management",create_opportunity:"deal_management",update_opportunity:"deal_management",advance_deal_stage:"deal_management",update_deal_stage:"deal_management",close_deal:"deal_management",mark_closed_won:"deal_management",mark_closed_lost:"deal_management",issue_quote:"pricing_change",send_quote:"pricing_change",approve_discount:"pricing_change",apply_discount:"pricing_change",override_price:"pricing_change",update_pricing:"pricing_change",approve_special_pricing:"pricing_change",execute_contract:"contract_execution",sign_contract:"contract_execution",countersign_contract:"contract_execution",sign_agreement:"contract_execution",execute_agreement:"contract_execution",sign_nda:"contract_execution",execute_nda:"contract_execution",sign_document:"contract_execution",esign_document:"contract_execution",place_legal_hold:"legal_hold",place_litigation_hold:"legal_hold",apply_legal_hold:"legal_hold",release_legal_hold:"legal_hold",file_regulatory_report:"regulatory_filing",file_sar:"regulatory_filing",submit_regulatory_filing:"regulatory_filing",file_compliance_report:"regulatory_filing",file_disclosure:"regulatory_filing",onboard_employee:"personnel_action",hire_employee:"personnel_action",change_employee_role:"personnel_action",promote_employee:"personnel_action",transfer_employee:"personnel_action",update_job_title:"personnel_action",terminate_employee:"employment_termination",offboard_employee:"employment_termination",deactivate_employee:"employment_termination",separate_employee:"employment_termination",adjust_salary:"compensation_change",change_compensation:"compensation_change",approve_raise:"compensation_change",grant_equity:"compensation_change",grant_stock:"compensation_change",issue_bonus:"compensation_change",update_pay_rate:"compensation_change",send_campaign:"campaign_send",launch_campaign:"campaign_send",schedule_campaign:"campaign_send",send_bulk_email:"campaign_send",send_marketing_email:"campaign_send",send_newsletter:"campaign_send",blast_email:"campaign_send",publish_post:"content_publish",publish_content:"content_publish",publish_blog:"content_publish",post_to_social:"content_publish",schedule_post:"content_publish",adjust_inventory:"inventory_adjustment",write_off_inventory:"inventory_adjustment",update_stock_level:"inventory_adjustment",reconcile_inventory:"inventory_adjustment",fulfill_order:"order_fulfillment",ship_order:"order_fulfillment",dispatch_order:"order_fulfillment",mark_order_shipped:"order_fulfillment",update_customer_account:"account_servicing",modify_customer_account:"account_servicing",update_customer_contact:"account_servicing",change_customer_settings:"account_servicing",reset_customer_password:"credential_reset",reset_password:"credential_reset",force_password_reset:"credential_reset",reset_mfa:"credential_reset",unlock_account:"credential_reset",reset_customer_credentials:"credential_reset",merge_pull_request:"code_change",merge_pr:"code_change",merge_branch:"code_change",push_to_branch:"code_change",push_to_main:"code_change",push_code:"code_change",commit_code:"code_change",force_push:"code_change",provision_infrastructure:"infrastructure_provision",provision_resource:"infrastructure_provision",create_instance:"infrastructure_provision",terminate_instance:"infrastructure_provision",spin_up_server:"infrastructure_provision",tear_down_server:"infrastructure_provision",destroy_resource:"infrastructure_provision",create_cluster:"infrastructure_provision"};function Qt(e){let t=Ve(e);return t===null?"other":Jt[t]||(/^(delete|remove|purge|drop|destroy|wipe)_/.test(t)?"record_delete":/^(export|download|extract|dump)_/.test(t)?"data_export":/^(create|add|insert)_/.test(t)?"record_create":/^(update|edit|modify|patch|set)_/.test(t)?"record_update":t==="send_email"||t==="send_sms"||/^(notify|email|sms)_/.test(t)?"communication_send":/^(read|get|list|search|fetch|view|query)_/.test(t)||t==="read"||t==="get"?"read_only":"other")}var xe={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 Xt(e){let t=Ve(e);return t===null?"other":xe[t]??xe[t.replace(/_/g,"")]??"other"}function X(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=Qt(t.action)),t.targetApp!==void 0&&t.targetApp!==null){let r=n.context&&typeof n.context=="object"&&!Array.isArray(n.context)?{...n.context}:{};r.app_category===void 0&&(r.app_category=Xt(t.targetApp)),n.context=r}return n}var Oe=64,en=64,w={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function He(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var tn=new Set(["deny","approval_required","escalate"]);function U(e,t){if(t.length===0)return[...e];let n=new Set(e);for(let i of t)n.add(i);let r=[...n].sort();return r.length>Oe?r.slice(0,Oe):r}function nn(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function q(e){return typeof e=="string"&&e.length>0?e:null}function Ke(e,t){let n=nn(t.data_categories),r=q(t.classification),i=q(t.action_class),o=i&&Yt.includes(i)?i:null,a=q(t.target_app),s=q(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<en)c[o]=1;else{let p=Object.keys(c).sort(),d=p[p.length-1];d!==void 0&&o<d&&(delete c[d],c[o]=1)}return{retrieved_data_categories:U(e.retrieved_data_categories,n),retrieved_classifications:U(e.retrieved_classifications,r?[r]:[]),action_classes:U(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(s==="deny"?1:0),inhibited_count:e.inhibited_count+(s&&tn.has(s)?1:0),event_count:e.event_count+1,target_apps:U(e.target_apps,a?[a]:[])}}function rn(e,t){if(!e||e.trim().length===0)return{decision:"permit",matched:!0};try{let n=Ue(e),r=qe(n,{target_app:t.target_app,action:t.action,...t.context,context:t.context,normalized:t.normalized??{},agent:t.agent??$,session:t.session??w});if(!r.matched)return{decision:"deny",matched:!1};let i=null,o=r.bindings.decision;if(o!==void 0?i=J(o):r.bindings.approval_required==="true"?i="approval_required":r.bindings.mask==="true"?i="mask":r.bindings.allow==="true"&&(i="permit"),i===null)return{decision:"deny",matched:!0};let a=i==="mask"?an(n,r.matchedRuleIndex,i):void 0;return{decision:i,matched:!0,...a?{branchId:a}:{}}}catch{return{decision:"deny",matched:!1}}}function J(e){switch(e){case"permit":case"allow":return"permit";case"deny":return"deny";case"approval_required":return"approval_required";case"mask":return"mask";default:return"deny"}}function an(e,t,n){if(t<0)return;let r=e.rules[t];if(!(!r||(r.variable==="decision"?J(r.value):J(r.variable))!==n))return Be(n,r.rawConditions)}function Re(e,t){if(!e||e.trim().length===0)return{action:"deny",matched:!1};try{let n=Ue(e),r=qe(n,{agent_id:t.agent_id,operation:t.operation,resource_type:t.resource_type,resource_metadata:t.resource_metadata,trust_tier:t.trust_tier??"",surface:t.surface??"",query:t.query??"",normalized:t.normalized??{},agent:t.agent??$,session:t.session??w});if(!r.matched)return{action:"deny",matched:!1};let i=null,o=r.bindings.action??r.bindings.decision;if(o!==void 0?i=Q(o):r.bindings.escalate==="true"?i="escalate":r.bindings.redact==="true"?i="redact":r.bindings.allow==="true"&&(i="allow"),i===null)return{action:"deny",matched:!0};let a=i==="redact"?on(n,r.matchedRuleIndex,i):void 0;return{action:i,matched:!0,...a?{branchId:a}:{}}}catch{return{action:"deny",matched:!1}}}function Q(e){switch(e){case"allow":return"allow";case"deny":return"deny";case"redact":return"redact";case"escalate":return"escalate";default:return"deny"}}function on(e,t,n){if(t<0)return;let r=e.rules[t];if(!(!r||(r.variable==="decision"||r.variable==="action"?Q(r.value):Q(r.variable))!==n))return Be(n,r.rawConditions)}var sn="generic",Ze=[{id:"finance_accounting",name:"Finance & Accounting",icon:"Landmark",description:"Payments, invoicing, ledgers, transactions, refunds, financial reporting, SOX/AML/KYC controls."},{id:"hr",name:"Human Resources",icon:"Users",description:"Employee records, payroll, hiring/recruiting, benefits, personnel actions and PII of staff."},{id:"engineering",name:"Engineering",icon:"Code",description:"Source code, build/deploy pipelines, infrastructure changes, production systems and developer tooling."},{id:"it_security",name:"IT & Security",icon:"ShieldCheck",description:"Credentials, secrets, access control, configuration, threat/exfiltration prevention and security operations."},{id:"legal",name:"Legal",icon:"Scale",description:"Contracts, NDAs, litigation, counsel communications and legal-hold material."},{id:"privacy_compliance",name:"Privacy & Compliance",icon:"BadgeCheck",description:"GDPR/CCPA/HIPAA, consent, data-subject rights, special-category data and regulatory data handling."},{id:"sales",name:"Sales",icon:"TrendingUp",description:"CRM, leads, deals, quotes, pipeline and customer commercial relationships."},{id:"marketing",name:"Marketing",icon:"Megaphone",description:"Campaigns, content, brand, social channels and prospect/audience data."},{id:"operations",name:"Operations",icon:"Cog",description:"Business operations, logistics, internal workflows, vendor/ops tooling and process automation."},{id:"customer_support",name:"Customer Support",icon:"LifeBuoy",description:"Support tickets, customer communications, account servicing and help-desk actions."},{id:"procurement",name:"Procurement",icon:"ShoppingCart",description:"Purchasing, supplier management, purchase orders, sourcing and spend approvals."},{id:sn,name:"Generic",icon:"Shapes",description:"Catch-all for cross-cutting rules or rules that do not fit a specific function. Assign when no specific function clearly applies."}],zn=Ze.map(e=>e.id),ln=new Map(Ze.map(e=>[e.id,e]));function Ye(e){return e!=null&&ln.has(e)}function cn(e,t){if(!e||e==="*")return!0;let n=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);return n.length===0?!1:n.some(r=>un(r,t))}function un(e,t){return e==="*"?!0:e.includes("*")?pn(e).test(t):e===t}function dn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ne=new Map;function pn(e){let t=Ne.get(e);if(t)return t;let n=e.split("*").map(i=>dn(i)).join(".*"),r=new RegExp(`^${n}$`);return Ne.set(e,r),r}function ee(e){return e==="open"||e==="closed"?e:null}function fn(e){let t=e.toLowerCase().replace(/[_\-.:/]+/g," ");return/\b(read|get|list|view|fetch|query|search|describe|show|export|download)\b/.test(t)?"read":/\b(delete|remove|destroy|purge|drop|truncate)\b/.test(t)?"delete":/\b(admin|configure|manage|provision|grant|revoke|assign|unassign)\b/.test(t)?"admin":"write"}function H(e,t){let n=t==="approve"?"ALLOW":t.toUpperCase();return`D-${e.toUpperCase()}-${n}`}function O(e,t,n,r="tenant"){let i=e.charAt(0).toUpperCase()+e.slice(1);return r==="agent"?t==="deny"?`${i} actions on ${n} are denied by this agent's fail-safe override`:`${i} actions on ${n} are permitted by this agent's fail-safe override`:t==="deny"?`${i} actions on ${n} are denied by default`:t==="approve"?`${i} actions on ${n} are permitted by default`:`${i} actions on ${n} require human review`}function Je(e){let t=fn(e.action),n=e.config.no_coverage_defaults??{},r=ee(e.agentNoCoverage),i={autopilot:!1,enduserHitlBypassed:!1};if(e.mode!=="enforce"){let c=n[t]??"deny";return{...i,decision:"permit",rule_code:H(t,c),reason:O(t,c,e.targetApp),hitlCategory:null}}if(e.config.autopilot_enabled&&r!=="closed")return{...i,autopilot:!0,decision:"permit",rule_code:H(t,n[t]??"deny"),reason:"Autopilot: draft rule created for engineer review; request permitted",hitlCategory:"engineer"};let o;r==="open"?o="approve":r==="closed"?o="deny":o=n[t]??"deny";let a=H(t,o),s=r!==null?"agent":"tenant";return o==="approve"?{...i,decision:"permit",rule_code:a,reason:O(t,"approve",e.targetApp,s),hitlCategory:null}:o==="ask"?e.config.enduser_hitl_enabled===!1?{...i,decision:"permit",rule_code:a,reason:`${O(t,"ask",e.targetApp)} (end-user HITL disabled \u2014 bypassed)`,hitlCategory:null,enduserHitlBypassed:!0}:{...i,decision:"approval_required",rule_code:a,reason:O(t,"ask",e.targetApp),hitlCategory:"enduser"}:{...i,decision:"deny",rule_code:a,reason:O(t,"deny",e.targetApp,s),hitlCategory:"engineer"}}var mn=["action","retrieval","delegation"];function gn(e){return typeof e=="string"&&mn.includes(e)}var _n=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(!_n.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(gn):[];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}}var hn={tier1:3,tier2:2,tier3:1};function Pe(e){return e?hn[e]??null:null}function Le(e,t){if(!t)return{matched:!0,reason_code:"POLICY_ALLOW",reason:"resource has no minimum trust tier requirement"};let n=Pe(e),r=Pe(t);return n===null?{matched:!1,reason_code:"TIER_MISMATCH",reason:`agent trust tier '${e??"(none)"}' is not a recognized tier`}:r===null?{matched:!1,reason_code:"TIER_MISMATCH",reason:`resource minimum trust tier '${t}' is not a recognized tier`}:n<r?{matched:!1,reason_code:"TIER_MISMATCH",reason:`agent trust tier '${e}' (level ${n}) is below the required minimum '${t}' (level ${r})`}:{matched:!0,reason_code:"POLICY_ALLOW",reason:`agent trust tier '${e}' (level ${n}) meets the required minimum '${t}' (level ${r})`}}function Fe(e,t){return!t||t.length===0?{matched:!1,reason_code:"POLICY_ALLOW",reason:"no principal exclusions on this rule"}:t.includes(e)?{matched:!0,reason_code:"PRINCIPAL_EXCLUDED",reason:`agent '${e}' is in the principal exclusion list`}:{matched:!1,reason_code:"POLICY_ALLOW",reason:`agent '${e}' is not in the principal exclusion list`}}function De(e,t){return t?e?e===t?{matched:!0,reason_code:"SURFACE_RESTRICTION",reason:`surface '${e}' matches rule surface restriction`}:{matched:!1,reason_code:"POLICY_ALLOW",reason:`input surface '${e}' does not match rule surface '${t}'`}:{matched:!1,reason_code:"POLICY_ALLOW",reason:`no surface on input \u2014 rule surface '${t}' restriction does not apply`}:{matched:!1,reason_code:"POLICY_ALLOW",reason:"rule has no surface restriction"}}var yn={matched:!1,decision:"deny",reason:"No matching rule",reasonCode:null,ruleId:null,ruleCode:null,ruleDescription:null};function Me(e){return e==="allow"?"permit":e==="redact"||e==="escalate"||e==="deny"?e:"deny"}function bn(e,t){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&e.version===2&&typeof e.branches=="object"&&e.branches!==null&&!Array.isArray(e.branches)){let{branches:n}=e;if(t&&Array.isArray(n[t]))return n[t];let r=Object.keys(n);return r.length===1&&Array.isArray(n[r[0]])?n[r[0]]:void 0}}function te(e,t){let n=bn(e,t);if(!Array.isArray(n)||n.length===0)return;let r=n.filter(i=>i&&typeof i=="object"&&(typeof i.field=="string"||typeof i.pattern=="string"));return r.length>0?r:void 0}function A(e,t){return e.decision==="redact"&&!t.transformableResponse?{...e,decision:"deny",reason:`${e.reason} (redaction not enforceable on this call \u2014 denied fail-closed)`,redactionRules:void 0,downgraded:{from:"redact",to:"deny",why:"response not transformable at this call site"}}:e}function je(e,t,n){if(e.decision!=="redact")return e;let r=te(t.redactionSpec,n);return r?{...e,redactionRules:r}:t.failClosedOnEmptySpec?{...e,decision:"deny",reason:`${e.reason} (redact rule has no enforceable redaction_spec \u2014 denied fail-closed, G001)`,redactionRules:void 0,downgraded:{from:"redact",to:"deny",why:"redact rule has no enforceable redaction_spec"}}:e}function vn(e,t,n){if(e.decision!=="mask")return e;let r=te(t.redactionSpec,n);return r?{...e,redactionRules:r}:{...e,decision:"deny",reason:`${e.reason} (mask rule has no resolvable redaction directives \u2014 denied fail-closed, G001)`,redactionRules:void 0,downgraded:{from:"mask",to:"deny",why:"mask rule has no resolvable redaction directives"}}}function K(e,t,n){if(e.decision!=="approval_required"&&e.decision!=="escalate")return e;if(t.hitlFallback!=="mask")return{...e,hitlFallback:"deny"};let r=te(t.redactionSpec,n);return r?{...e,hitlFallback:"mask",redactionRules:r}:{...e,hitlFallback:"deny",downgraded:{from:e.decision,to:"deny",why:"hitl_fallback=mask but no enforceable redaction_spec \u2014 no-approval falls back to deny (G001)"}}}function Xe(e,t){let n=[...e].sort((l,g)=>g.priority-l.priority),r=t.resourceMetadata!==null||t.operation!==null,i=t.action!==null&&t.targetApp!==null,o=t.facets.includes("retrieval")&&r,a=(t.facets.includes("action")||t.facets.includes("delegation"))&&i,s=t.resourceMetadata??{},c=typeof s.min_trust_tier=="string"?s.min_trust_tier:null,p=Array.isArray(s.excluded_principals)?s.excluded_principals:null,d=Array.isArray(s.restricted_surfaces)?s.restricted_surfaces:null,_={agent_id:t.agentId,operation:t.operation??"retrieve",resource_type:t.resourceType??"",resource_metadata:s,trust_tier:t.trustTier,surface:t.surface,query:t.query,normalized:t.normalized,agent:t.agent,session:t.session??w};for(let l of n){if(o&&l.appliesTo.includes("retrieval")){if(l.bypassActive&&l.bypassExpiresAt&&new Date(l.bypassExpiresAt).getTime()>Date.now())return A({matched:!0,decision:"permit",reason:l.bypassReason??"Emergency bypass active",reasonCode:"EMERGENCY_BYPASS",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities);if(l.principalExclusions&&l.principalExclusions.length>0){let m=Fe(t.agentId,l.principalExclusions);if(m.matched)return A({matched:!0,decision:"deny",reason:m.reason,reasonCode:"PRINCIPAL_EXCLUDED",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities)}if(p&&p.length>0){let m=Fe(t.agentId,p);if(m.matched)return A({matched:!0,decision:"deny",reason:m.reason,reasonCode:"PRINCIPAL_EXCLUDED",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities)}if(l.surface){let m=De(t.surface,l.surface);if(m.matched){let y=Re(l.regoSource,_),k=y.matched?y.action:"deny",N=Me(k),oe=y.matched?y.branchId:void 0;return A(K(je({matched:!0,decision:N,reason:m.reason,reasonCode:k==="allow"?"POLICY_ALLOW":"SURFACE_RESTRICTION",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},l,oe),l,oe),t.capabilities)}continue}if(d&&d.length>0&&t.surface&&De(t.surface,d.includes(t.surface)?t.surface:null).matched)return A({matched:!0,decision:"deny",reason:`surface '${t.surface}' is in the restricted surfaces list for this resource`,reasonCode:"SURFACE_RESTRICTION",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities);if(l.trustTier){let m=Le(t.trustTier,l.trustTier);if(!m.matched)return A({matched:!0,decision:"deny",reason:m.reason,reasonCode:"TIER_MISMATCH",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities)}if(c){let m=Le(t.trustTier,c);if(!m.matched)return A({matched:!0,decision:"deny",reason:m.reason,reasonCode:"TIER_MISMATCH",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities)}let g=Re(l.regoSource,_);if(g.matched){let m=Me(g.action);return A(K(je({matched:!0,decision:m,reason:`Matched rule: ${l.name}`,reasonCode:g.action==="allow"?"POLICY_ALLOW":"POLICY_DENY",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},l,g.branchId),l,g.branchId),t.capabilities)}}if(a&&(l.appliesTo.includes("action")||l.appliesTo.includes("delegation"))){if(l.targetApp!==null&&l.targetApp!==t.targetApp||!cn(l.actionPattern,t.action??""))continue;let g=rn(l.regoSource,{target_app:t.targetApp??"",action:t.action??"",context:t.context,normalized:t.normalized,agent:t.agent,session:t.session??w});if(g.matched)return A(K(vn({matched:!0,decision:g.decision,reason:l.description??l.name,reasonCode:null,ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},l,g.branchId),l,g.branchId),t.capabilities)}}return yn}function An(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 wn=5e3,kn=1e4,et=1e3,In=512,Sn=1800*1e3,En="monitor",Cn=f.object({operations:f.array(f.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:f.string().min(1,"agentId is required"),sessionId:f.string().min(1).max(255).optional(),toolName:f.string().optional(),toolArgs:f.record(f.unknown()).optional(),targetResource:f.string().optional(),resourceType:f.string().optional(),resourceMetadata:f.record(f.unknown()).optional(),normalized:f.record(f.unknown()).optional(),query:f.string().optional(),contentPreview:f.string().optional(),telemetry:f.record(f.unknown()).optional()}),Tn=f.object({version:f.string().min(1),agent_mode:f.enum(["enforce","monitor","off"]).optional(),agent_attributes:f.object({trust_tier:f.string().nullable().optional(),categories:f.array(f.string()).optional(),business_function:f.string().nullable().optional(),no_coverage:f.string().nullable().optional()}).optional(),rules:f.array(f.record(f.unknown())),no_coverage:f.object({no_coverage_defaults:f.record(f.string()),autopilot_enabled:f.boolean(),enduser_hitl_enabled:f.boolean(),hitl_timeout_seconds:f.number().optional()}).optional()});function xn(e){let t=e.trust_tier??null,n=e.business_function??"";return{trust_tier:We(t)?t:null,categories:Ge(e.categories??[]),business_function:Ye(n)?n:null}}function tt(e){switch(e){case"permit":return 0;case"mask":case"redact":return 3;case"approval_required":case"escalate":return 4;case"deny":return 5;default:return 5}}function ne(e){let t=null;for(let n of e)(t===null||tt(n.decision)>tt(t.decision))&&(t=n);return t}function On(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}function Rn(e){switch(e){case"permit":return"allow";case"redact":return"redact";case"escalate":return"escalate";default:return"deny"}}var rt=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;agentMode=En;agentModeConfirmed=!1;telemetryBuffer=[];telemetryTimer=null;envRegistered=!1;registerPromise=null;constructor(e,t,n,r,i){let o=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,a=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,s=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";if(this.resolvedApiKey=o,this.resolvedEndpoint=a,this.resolvedAgentId=s,this.harnessKind=r,this.originalFetch=globalThis.fetch.bind(globalThis),o&&a){let c={apiKey:o,agentId:s,endpoint:a,mode:"enforce",timeoutMs:An(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{}};this.client=new we(c,this.originalFetch),this.initialBundlePromise=this.fetchBundleBackground(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},wn),nt(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},kn),nt(this.telemetryTimer)}else this.client=null}async evaluate(e){let t=Cn.parse(e),n=Date.now(),r=this.agentMode;if(r==="off")return this.offDecision(t);if(!this.bundleLoaded){let _=this.agentModeConfirmed&&(this.agentMode==="monitor"||this.agentMode==="off")?this.agentMode:"enforce",l=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(l,_,t,n)}let i=this.readSession(t.sessionId),o=[],a=[];for(let _ of t.operations){let l=this.resolveOperation(_,t,i);_==="retrieval"?a.push(l):o.push(l)}let s=ne(o),c=ne(a),p=ne([s,c].filter(_=>_!==null)),d=this.buildDecision(p,s,c,r);return this.foldSession(t,r==="enforce"?d.decision:"permit"),d.action.decision==="approval_required"&&r==="enforce"&&await this.registerHitl(t,d),this.applyAgentMode(d,r,t,n)}readSession(e){if(!e)return w;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Sn?(this.sessions.delete(e),w):t.state:w}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=a?X(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},c=Ke(r===w?He():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,action_class:a?s.action_class:void 0,target_app:a?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:c,touchedAt:Date.now()}),this.sessions.size>In){let p=this.sessions.keys().next().value;p!==void 0&&this.sessions.delete(p)}}resolveOperation(e,t,n){let r=Xe(this.rules,this.buildInput(e,t,n));if(r.matched)return r;if(e==="retrieval")return{...r,reason:"No matching rule \u2014 retrieval default deny (G001)"};if(this.noCoverage){let i=Je({action:t.toolName??t.targetResource??"",targetApp:t.targetResource??t.toolName??"",mode:"enforce",config:this.noCoverage,agentNoCoverage:this.agentNoCoverage});return{matched:!0,decision:i.decision,reason:i.reason,reasonCode:null,ruleId:null,ruleCode:i.rule_code,ruleDescription:null}}return{...r,reason:"No matching rule and no no-coverage config \u2014 fail-closed (G001)"}}buildInput(e,t,n){let r=t.toolName??"",i=t.targetResource??t.toolName??"",o=X(t.normalized??{},{action:r,targetApp:i}),a={agentId:t.agentId,agent:this.agentAttributes??$,session:n,normalized:o},s=this.agentAttributes?.trust_tier??null;return e==="retrieval"?{...a,facets:["retrieval"],targetApp:null,action:null,context:{},operation:"retrieve",resourceType:t.resourceType??t.targetResource??"",resourceMetadata:t.resourceMetadata??{},trustTier:s,surface:null,query:t.query??null,capabilities:{transformableResponse:!0}}:{...a,facets:[e==="delegation"?"delegation":"action"],targetApp:i,action:r,context:t.toolName?{[t.toolName]:t.toolArgs??{}}:{},operation:null,resourceType:null,resourceMetadata:null,trustTier:s,surface:null,query:null,capabilities:{transformableResponse:!1}}}buildDecision(e,t,n,r){let i=e?.decision??"deny",o=t?this.actionSub(t):{decision:null,allowed:!0},a=n?this.retrievalSub(n):{action:null};return{decision:i,allowed:i==="permit"||i==="mask"||i==="redact",reason:e?.reason??"No matching rule",ruleId:e?.ruleId??null,ruleCode:e?.ruleCode??null,enforced:r==="enforce",agentMode:r,action:o,retrieval:a}}actionSub(e){let t=e.decision;return t==="mask"?{decision:"mask",allowed:!0,argRedactionRules:e.redactionRules??[]}:t==="approval_required"?{decision:"approval_required",allowed:!1,...e.hitlFallback==="mask"&&e.redactionRules?{argRedactionRules:e.redactionRules,hitlFallback:"mask"}:{}}:t==="permit"?{decision:"permit",allowed:!0}:{decision:"deny",allowed:!1}}retrievalSub(e){let t=Rn(e.decision);return t==="redact"&&e.redactionRules?{action:t,redactionRules:e.redactionRules}:t==="escalate"&&e.hitlFallback==="mask"&&e.redactionRules?{action:t,redactionRules:e.redactionRules,hitlFallback:"mask"}:{action:t}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let a={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,a,i,!0),a}let o={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,o,i,!1),o}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){let t=Tn.parse(e);this.bundleLoaded&&t.version===this.bundleVersion||(this.rules=t.rules.map(n=>Qe(n)).filter(n=>n!==null),this.agentAttributes=t.agent_attributes?xn(t.agent_attributes):null,this.agentNoCoverage=ee(t.agent_attributes?.no_coverage),this.bundleVersion=t.version,this.bundleLoaded=!0,this.noCoverage=t.no_coverage?{no_coverage_defaults:t.no_coverage.no_coverage_defaults,autopilot_enabled:t.no_coverage.autopilot_enabled,enduser_hitl_enabled:t.no_coverage.enduser_hitl_enabled}:null,t.agent_mode!==void 0&&(this.agentMode=t.agent_mode,this.agentModeConfirmed=!0))}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"};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag");r&&(this.bundleEtag=r);let i=await n.json();this.applyBundle(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}}}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(){this.registerEnvironment(ke())}bufferTelemetry(e,t,n,r){this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:On(t.decision),reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:{agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{}},...this.harnessKind?{context:{[ve]:this.harnessKind}}:{}}),this.enforceTelemetryCap()}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})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry()}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.flushTelemetry()}};function nt(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function re(e){let t=[],n=[],r,i=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let c={mode:a.mode};a.field&&(c.field=a.field),a.pattern&&(c.pattern=a.pattern),typeof a.keepFirst=="number"&&(c.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(c.keepLast=a.keepLast),a.maskChar&&(c.maskChar=a.maskChar),a.keepPattern&&(c.keepPattern=a.keepPattern),a.replacement!==void 0&&(c.replacement=a.replacement),i.push(c);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:s}=a;s&&r===void 0&&(r=s)}let o={};return t.length>0&&(o.fields=t),n.length>0&&(o.patterns=n),r!==void 0&&(o.replacement=r),i.length>0&&(o.directives=i),o}var Nn="[VisIQ: retrieval withheld by policy]";function B(e){return ie(e)}function ie(e){if(e==null)return e;if(typeof e=="string")return e.length>0?Nn:e;if(typeof e=="number")return 0;if(typeof e=="boolean")return!1;if(Array.isArray(e))return e.map(ie);if(typeof e=="object"){let t=Object.create(null);for(let n of Object.keys(e))t[n]=ie(e[n]);return t}return e}function it(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 at(e,t){if(!e.enforced)return null;let{action:n,retrieval:r}=e,i=I(e.reason,e.ruleCode);if(n.decision==="deny"||r.action==="deny")return F(i);if(n.decision==="approval_required"||r.action==="escalate")return ge(i);if(n.decision==="mask"&&n.argRedactionRules&&n.argRedactionRules.length>0){let o=re(n.argRedactionRules);if(it(o)){let a=V(t,o)??t;if(JSON.stringify(a)!==JSON.stringify(t))return me(a)}return null}return null}function ot(e,t){if(!e.enforced)return null;let{retrieval:n}=e,r=I(e.reason,e.ruleCode);if(n.action==="redact"){let i=re(n.redactionRules??[]);if(!it(i))return S(B(t),r);let o=V(t,i);return JSON.stringify(o)===JSON.stringify(t)?null:S(o,r)}return n.action==="deny"?S(B(t),r):null}var Pn="cli_harness";function C(e){return new rt(e.apiKey,e.baseUrl,e.agentId,Pn)}function W(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),t}async function T(e,t,n=se){let{agentId:r}=t,i=await ce(r);if(i&&le(i,n,Date.now())&&ae(e,i.body))return;let o=e.getEndpoint();if(o){let a=await de(o,t.apiKey,r);if(a&&ae(e,a.body)){await ue(r,a.body,a.version);return}}if(!(i&&ae(e,i.body)))try{await e.awaitBundleReady(2500)}catch{}}function ae(e,t){try{return e.applyBundle(t),!0}catch{return!1}}async function x(e){try{await e.flush()}catch{}try{e.dispose()}catch{}}async function pr(e,t){let n=C(t),r=e.tool_input??{};try{await pe(e.session_id)||(n.registerHostEnvironment(),await P(e.session_id)),await T(n,t);let i=W({operations:fe(e.tool_name),agentId:t.agentId,toolName:e.tool_name,toolInput:r,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:L(r)}),o=await n.evaluate(i);return at(o,r)}catch{return F(I("evaluation error (fail-closed)",null))}finally{await x(n)}}async function yr(e,t){if(!z(e.tool_name))return null;let n=C(t);try{await T(n,t);let r=e.tool_input??{},i=W({operations:["retrieval"],agentId:t.agentId,toolName:e.tool_name,toolInput:r,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:L(r)}),o=await n.evaluate(i);return ot(o,e.tool_response)}catch{return S(B(e.tool_response),I("evaluation error (fail-closed)",null))}finally{await x(n)}}async function wr(e,t){let n=C(t);try{n.registerHostEnvironment(),await T(n,t,0),await P(e.session_id)}finally{await x(n)}return null}export{ct as a,z as b,fe as c,L as d,I as e,me as f,F as g,ge as h,S as i,Fn as j,Nn as k,B as l,at as m,ot as n,Pn as o,C as p,W as q,T as r,x as s,pr as t,yr as u,wr as v};