@visiq/claude-code-harness 0.1.1 → 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/dist/chunk-42FZPLOF.js +3 -0
- package/dist/cli/hook.js +1 -1
- package/dist/index.d.ts +78 -3
- package/dist/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-IT2RXQ74.js +0 -3
|
@@ -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{g as r,j as u,t as c,u as l,v as d}from"../chunk-
|
|
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
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
|
*
|
|
@@ -327,6 +329,23 @@ export interface CognitionBeat {
|
|
|
327
329
|
agentRole?: string;
|
|
328
330
|
framework?: string;
|
|
329
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>;
|
|
330
349
|
/** The facets an event participates in (the unified `operations` tag). */
|
|
331
350
|
export type UnifiedOperation = "retrieval" | "action" | "delegation";
|
|
332
351
|
/** One governed agent event, tagged with the facets it participates in. */
|
|
@@ -438,6 +457,10 @@ declare class UnifiedRuntime {
|
|
|
438
457
|
private readonly resolvedEndpoint;
|
|
439
458
|
private readonly resolvedAgentId;
|
|
440
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;
|
|
441
464
|
private rules;
|
|
442
465
|
/** Server-authoritative agent attributes from the bundle (null until shipped). */
|
|
443
466
|
private agentAttributes;
|
|
@@ -464,6 +487,19 @@ declare class UnifiedRuntime {
|
|
|
464
487
|
private bundleFetchInProgress;
|
|
465
488
|
private initialBundlePromise;
|
|
466
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;
|
|
467
503
|
private agentMode;
|
|
468
504
|
/** Optional per-operation mode override, shipped resolved in the bundle:
|
|
469
505
|
* `{action?, retrieval?, delegation?}` → enforce|monitor|off. An operation
|
|
@@ -484,14 +520,24 @@ declare class UnifiedRuntime {
|
|
|
484
520
|
* has shut this agent down (notebook item 1). Every {@link evaluate} then
|
|
485
521
|
* returns an immediate, always-enforced deny-all BEFORE any mode bypass / rule
|
|
486
522
|
* eval / core call. Set from the bundle on every version change (a normal
|
|
487
|
-
* bundle ⇒ false), so reactivation (a fresh non-shutdown bundle) clears it.
|
|
488
|
-
|
|
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;
|
|
489
527
|
/** True when a bundle body was RECEIVED but FAILED to apply (malformed /
|
|
490
528
|
* schema-drifted / corrupt cache) — an ERROR, distinct from a genuinely
|
|
491
529
|
* absent bundle. On cold start this fails CLOSED (enforce the deny-all) so a
|
|
492
530
|
* corrupt or poisoned bundle can never downgrade an agent to the permissive
|
|
493
531
|
* monitor onboarding fail-safe (G001). Cleared once a body validates. */
|
|
494
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;
|
|
495
541
|
private telemetryBuffer;
|
|
496
542
|
private telemetryTimer;
|
|
497
543
|
private cognitionBuffer;
|
|
@@ -505,7 +551,7 @@ declare class UnifiedRuntime {
|
|
|
505
551
|
/** Content signature of the last reported tool surface — so a repeat visiq()
|
|
506
552
|
* wrap (same tools) doesn't re-POST. Null until the first report. */
|
|
507
553
|
private lastToolSurfaceSig;
|
|
508
|
-
constructor(apiKey?: string, endpoint?: string, agentId?: string, harnessKind?: AgentKind, timeoutMs?: number);
|
|
554
|
+
constructor(apiKey?: string, endpoint?: string, agentId?: string, harnessKind?: AgentKind, timeoutMs?: number, sdkVersion?: string, sdkDialect?: number, bundleCache?: BundleCacheOptions);
|
|
509
555
|
/**
|
|
510
556
|
* Evaluate one governed agent event across ALL its tagged operations and
|
|
511
557
|
* return the merged unified decision with both facet sub-decisions.
|
|
@@ -550,6 +596,28 @@ declare class UnifiedRuntime {
|
|
|
550
596
|
*/
|
|
551
597
|
awaitBundleReady(timeoutMs?: number): Promise<void>;
|
|
552
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;
|
|
553
621
|
hasRules(): boolean;
|
|
554
622
|
hasClient(): boolean;
|
|
555
623
|
/** The resolved backend endpoint, for callers driving the HITL wait loop. */
|
|
@@ -599,6 +667,13 @@ declare class UnifiedRuntime {
|
|
|
599
667
|
private enforceCognitionCap;
|
|
600
668
|
/** Drain pending registration + telemetry + cognition and await it (graceful shutdown). */
|
|
601
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>;
|
|
602
677
|
dispose(): void;
|
|
603
678
|
}
|
|
604
679
|
/**
|
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-
|
|
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.
|
|
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",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
19
|
"zod": "^3.23.8",
|
|
20
|
-
"@visiq/core-wasm": "^0.1.
|
|
20
|
+
"@visiq/core-wasm": "^0.1.3"
|
|
21
21
|
},
|
|
22
22
|
"engines": {
|
|
23
23
|
"node": ">=20"
|
package/dist/chunk-IT2RXQ74.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{f as M,h as $,i as q,j as z,k as W,l as H,m as I}from"./chunk-3GWLCI47.js";var Oe=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),Re=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function Ne(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 N(e){return typeof e!="string"?!1:Oe.has(e)?!0:e.startsWith("mcp__")?Re.test(Ne(e)):!1}function V(e){return N(e)?["retrieval","action"]:["action"]}var Pe=["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 Pe){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 G(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 K(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 Mt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.hook_event_name=="string"?t:null}catch{return null}}var Le=[{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(Le.map(e=>[e.name,e.re.source])),Fe=["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"],De={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}},qt=new Set(Fe.filter(e=>!De[e].defaultEnabled));var P="[REDACTED]",y="\u2022",C=e=>/[A-Za-z0-9]/.test(e);function Z(e,t,n,r){let i=Array.from(e),o=i.length,a=Math.max(0,Math.floor(t)||0),l=Math.max(0,Math.floor(n)||0),u=r.length>0?r:y,d=a+l>=o;return i.map((p,m)=>!d&&(m<a||m>=o-l)?p:C(p)?u:p).join("")}function Ue(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Z(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:y;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>C(a)?o:a).join(""))+i}function je(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 m=p.index;m<p.index+p[0].length;m++)i[m]=!0}}catch{}let o=!1,a=!0;for(let d=0;d<e.length;d++)if(C(e[d])&&(o=!0,!i[d])){a=!1;break}let l=o&&a,u="";for(let d=0;d<e.length;d++){let p=e[d];!l&&i[d]||!C(p)?u+=p:u+=r}return u}function Y(e,t){let n=t.mode??"full";return n==="partial"?Z(e,t.keepFirst??0,t.keepLast??0,t.maskChar??y):n==="email"?Ue(e,t.maskChar??y):n==="custom"?je(e,t.keepPattern,t.maskChar??y):t.replacement??P}function Be(e,t){return typeof e=="string"?Y(e,t):t.replacement??P}function J(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:o=>Y(o,r)})}return t}function Q(e,t){let n=e;for(let{source:r,replacer:i}of t){let o;try{o=new RegExp(r,"g")}catch(a){let l=a instanceof Error?a.message:String(a);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${l}`)}n=n.replace(o,a=>i(a))}return n}function L(e,t){return e==null?e:typeof e=="string"?Me(e,t):typeof e=="object"?$e(e,t):e}function Me(e,t){if(typeof e!="string")return e;let n=J(t);return n.length===0?e:Q(e,n)}function $e(e,t){let n=new Map;for(let l of t.fields??[])typeof l=="string"&&l.length>0&&n.set(l,{field:l,mode:"full",replacement:t.replacement});for(let l of t.directives??[])typeof l.field=="string"&&l.field.length>0&&n.set(l.field,l);let r=J(t),i=n.size>0,o=r.length>0,a=l=>{if(l==null)return l;if(Array.isArray(l))return l.map(u=>a(u));if(typeof l=="object"){let u=l,d=Object.create(Object.getPrototypeOf(u));for(let p of Object.keys(u)){let m=i?n.get(p):void 0;if(m){d[p]=Be(u[p],m);continue}d[p]=a(u[p])}return d}return typeof l=="string"&&o?Q(l,r):l};return a(e)}import{z as s}from"zod";import*as g from"node:os";var X="interceptor_source",qe=s.enum(["enforce","audit","off"]),ze=s.enum(["closed","open"]),ee=s.enum(["enforce","monitor","off"]),We=s.object({apiKey:s.string().min(1,"apiKey is required"),agentId:s.string().min(1,"agentId is required"),endpoint:s.string().url().optional(),mode:qe.optional(),timeoutMs:s.number().int().positive().optional(),hitlTimeoutMs:s.number().int().positive().optional(),failBehavior:ze.optional()}),Ht=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()}),He=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()}),Ve=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:ee.optional(),arg_redaction_rules:s.array(He).optional(),plane:s.string().nullable().optional(),operation:s.string().nullable().optional(),is_retrieval:s.boolean().optional(),metadata:s.record(s.unknown()).optional()}),Ge=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())])}),Ke=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(Ge).default([]),priority:s.number().int().default(0)}),Ze=s.object({version:s.string().min(1),agent_mode:ee.optional(),rules:s.array(Ke),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()}),Ye=2e3,te=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 Ve.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 Ze.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 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}`},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}`},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}:{},...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}`},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}`},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,l=a.hitl_result;if(l==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(l==="rejected")return{decision_id:e,decision:"deny",reason:typeof a.reason=="string"?a.reason:"Rejected by human reviewer"};if(l==="timeout"||l==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await Je(Ye)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Je(e){return new Promise(t=>setTimeout(t,e))}function ne(){let e={};try{let t=`${g.platform()} ${g.release()}`.trim();t&&(e.os=t)}catch{}try{let t=g.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=g.userInfo();t&&(e.username=t)}catch{}try{let t=Qe();t&&(e.ip=t)}catch{}return e}function Qe(){let e=g.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 c}from"zod";import{createHash as Zt}from"crypto";import{createHash as Xt}from"crypto";var Xe=["tier1","tier2","tier3"];function ae(e){return typeof e=="string"&&Xe.includes(e)}var et=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],tt=["internal","customer_facing","experimental","third_party"],oe=[...et,...tt];function nt(e){return typeof e=="string"&&oe.includes(e)}function se(e){let t=new Set;for(let n of e)nt(n)&&t.add(n);return oe.filter(n=>t.has(n))}var rt=["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 le(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 it={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 at(e){let t=le(e);return t===null?"other":it[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 re={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 ot(e){let t=le(e);return t===null?"other":re[t]??re[t.replace(/_/g,"")]??"other"}function ce(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=at(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=ot(t.targetApp)),n.context=r}return n}var ie=64,st=64,k={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function ue(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var lt=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>ie?r.slice(0,ie):r}function ct(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function x(e){return typeof e=="string"&&e.length>0?e:null}function de(e,t){let n=ct(t.data_categories),r=x(t.classification),i=x(t.action_class),o=i&&rt.includes(i)?i:null,a=x(t.target_app),l=x(t.decision),u={...e.action_counts};if(o)if(o in u)u[o]=(u[o]??0)+1;else if(Object.keys(u).length<st)u[o]=1;else{let d=Object.keys(u).sort(),p=d[d.length-1];p!==void 0&&o<p&&(delete u[p],u[o]=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,o?[o]:[]),action_counts:u,denied_count:e.denied_count+(l==="deny"?1:0),inhibited_count:e.inhibited_count+(l&<.has(l)?1:0),event_count:e.event_count+1,target_apps:T(e.target_apps,a?[a]:[])}}var ut="generic",pe=[{id:"finance_accounting",name:"Finance & Accounting",icon:"Landmark",description:"Payments, invoicing, ledgers, transactions, refunds, financial reporting, SOX/AML/KYC controls."},{id:"hr",name:"Human Resources",icon:"Users",description:"Employee records, payroll, hiring/recruiting, benefits, personnel actions and PII of staff."},{id:"engineering",name:"Engineering",icon:"Code",description:"Source code, build/deploy pipelines, infrastructure changes, production systems and developer tooling."},{id:"it_security",name:"IT & Security",icon:"ShieldCheck",description:"Credentials, secrets, access control, configuration, threat/exfiltration prevention and security operations."},{id:"legal",name:"Legal",icon:"Scale",description:"Contracts, NDAs, litigation, counsel communications and legal-hold material."},{id:"privacy_compliance",name:"Privacy & Compliance",icon:"BadgeCheck",description:"GDPR/CCPA/HIPAA, consent, data-subject rights, special-category data and regulatory data handling."},{id:"sales",name:"Sales",icon:"TrendingUp",description:"CRM, leads, deals, quotes, pipeline and customer commercial relationships."},{id:"marketing",name:"Marketing",icon:"Megaphone",description:"Campaigns, content, brand, social channels and prospect/audience data."},{id:"operations",name:"Operations",icon:"Cog",description:"Business operations, logistics, internal workflows, vendor/ops tooling and process automation."},{id:"customer_support",name:"Customer Support",icon:"LifeBuoy",description:"Support tickets, customer communications, account servicing and help-desk actions."},{id:"procurement",name:"Procurement",icon:"ShoppingCart",description:"Purchasing, supplier management, purchase orders, sourcing and spend approvals."},{id:ut,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."}],dt=pe.map(e=>e.id),Yt=new Map(pe.map(e=>[e.id,e])),Jt=new Set(dt);var pt=/^[a-z][a-z0-9_]*$/;function fe(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&pt.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var ft=["narrow","moderate","broad","unbounded","unknown"];function ge(e){return typeof e=="string"&&ft.includes(e)}function me(e){return e==="open"||e==="closed"?e:null}var gt=["action","retrieval","delegation"];function mt(e){return typeof e=="string"&>.includes(e)}var ht=new Set(["rules"]);function he(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!ht.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(mt):[];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{randomUUID as Ft}from"node:crypto";var _e=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function _t(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:_e(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:_e(t.spawn.prompt)}),t}function yt(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 A;async function bt(){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 vt=5e3,wt=1e4,kt=25,ye=1e3,At=5e3,It=100,be=2e3,St=512,Et=1800*1e3,Ct="monitor",Tt="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",xt=c.object({operations:c.array(c.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:c.string().min(1,"agentId is required"),sessionId:c.string().min(1).max(255).optional(),toolName:c.string().optional(),toolArgs:c.record(c.unknown()).optional(),targetResource:c.string().optional(),resourceType:c.string().optional(),resourceMetadata:c.record(c.unknown()).optional(),normalized:c.record(c.unknown()).optional(),query:c.string().optional(),contentPreview:c.string().optional(),telemetry:c.record(c.unknown()).optional(),context:c.record(c.unknown()).optional()}),Ot=c.object({version:c.string().min(1),shutdown:c.boolean().optional(),agent_mode:c.enum(["enforce","monitor","off"]).optional(),cognition_capture:c.boolean().optional(),agent_mode_by_operation:c.object({action:c.string().optional(),retrieval:c.string().optional(),delegation:c.string().optional()}).partial().optional(),agent_attributes:c.object({trust_tier:c.string().nullable().optional(),categories:c.array(c.string()).optional(),business_function:c.string().nullable().optional(),business_functions:c.array(c.string()).nullable().optional(),blast_radius_tier:c.string().nullable().optional(),no_coverage:c.string().nullable().optional()}).optional(),rules:c.array(c.record(c.unknown())),no_coverage:c.object({no_coverage_defaults:c.record(c.string()),autopilot_enabled:c.boolean(),enduser_hitl_enabled:c.boolean(),hitl_timeout_seconds:c.number().optional()}).optional()});function Rt(e){let t=e.trust_tier??null,n=[];Array.isArray(e.business_functions)&&e.business_functions.length>0?n=e.business_functions:typeof e.business_function=="string"&&e.business_function!==""&&(n=[e.business_function]);let r=fe(n);return{trust_tier:ae(t)?t:null,categories:se(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&ge(e.blast_radius_tier)?e.blast_radius_tier:null}}function Nt(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 Pt(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var ke=new Set,ve=!1;function Lt(){ve||typeof process>"u"||typeof process.once!="function"||(ve=!0,process.once("beforeExit",()=>{for(let e of ke)if(e.pendingTelemetryCount()>0){if(!e.hasBackend()){console.warn(`[UnifiedRuntime] exiting with ${e.pendingTelemetryCount()} un-sent decision(s) and no backend \u2014 telemetry lost.`);continue}e.flush()}}))}var Ae=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=Ct;agentModeByOperation=null;rawBundle=null;agentModeConfirmed=!1;shutdown=!1;bundleApplyFailed=!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){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,l=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";if(this.resolvedApiKey=o,this.resolvedEndpoint=a,this.resolvedAgentId=l,this.harnessKind=r,this.originalFetch=globalThis.fetch.bind(globalThis),o&&a){let u={apiKey:o,agentId:l,endpoint:a,mode:"enforce",timeoutMs:yt(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{}};this.client=new te(u,this.originalFetch),this.initialBundlePromise=this.fetchBundleBackground(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},vt),F(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},wt),F(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},At),F(this.cognitionTimer),ke.add(this),Lt()}else this.client=null}async evaluate(e){let t=xt.parse(e),n=Date.now();if(this.shutdown){let u=this.denyAll(t,Tt);return this.applyAgentMode(u,"enforce",t,n)}if(t.operations.every(u=>this.modeFor(u)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let u;this.agentModeConfirmed?u=this.agentMode:this.bundleApplyFailed?u="enforce":u="monitor";let d=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(d,u,t,n)}let r=this.readSession(t.sessionId),i=await bt();if(!i||!this.rawBundle)throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)");let o={...t,session:r,at:Date.now()},a={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},l=i(o,a);return this.foldSession(t,l.enforced?l.decision:"permit"),l.enforced&&l.action.decision==="approval_required"&&await this.registerHitl(t,l),this.bufferTelemetry(t,l,Date.now()-n,l.enforced),l}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>Et?(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??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),l=a?ce(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},u=de(r===k?ue():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,action_class:a?l.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:u,touchedAt:Date.now()}),this.sessions.size>St){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 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){this.bundleApplyFailed=!0;let t=Ot.parse(e);this.bundleApplyFailed=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(n=>he(n)).filter(n=>n!==null),this.agentAttributes=t.agent_attributes?Rt(t.agent_attributes):null,this.agentNoCoverage=me(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=Nt(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.shutdown=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"};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(e){this.registerEnvironment({...ne(),...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?Pt(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?{[X]:this.harnessKind}:{},...e.context??{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=kt&&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-ye;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${ye})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(_t(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=It&&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-be;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${be})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}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 F(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function D(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Ie(e,t){if(e!=="Task"&&e!=="Agent")return null;let n=D(t.description),r=D(t.subagent_type),i=D(t.prompt),o=n??r??"sub-agent";return{childAgentId:o,childName:o,kind:"subagent",agentType:r,description:n,task:i,goal:i,source:"structural"}}function Se(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 we=new Map;function Dt(e){let t=(we.get(e)??0)+1;return we.set(e,t),t}function Ee(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:Ft(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:Dt(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 U(e){let t=[],n=[],r,i=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let u={mode:a.mode};a.field&&(u.field=a.field),a.pattern&&(u.pattern=a.pattern),typeof a.keepFirst=="number"&&(u.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(u.keepLast=a.keepLast),a.maskChar&&(u.maskChar=a.maskChar),a.keepPattern&&(u.keepPattern=a.keepPattern),a.replacement!==void 0&&(u.replacement=a.replacement),i.push(u);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:l}=a;l&&r===void 0&&(r=l)}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 Ut="[VisIQ: retrieval withheld by policy]";function O(e){return j(e)}function j(e){if(e==null)return e;if(typeof e=="string")return e.length>0?Ut:e;if(typeof e=="number")return 0;if(typeof e=="boolean")return!1;if(Array.isArray(e))return e.map(j);if(typeof e=="object"){let t=Object.create(null);for(let n of Object.keys(e))t[n]=j(e[n]);return t}return e}function Ce(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 Te(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 K(i);if(n.decision==="mask"&&n.argRedactionRules&&n.argRedactionRules.length>0){let o=U(n.argRedactionRules);if(Ce(o)){let a=L(t,o)??t;if(JSON.stringify(a)!==JSON.stringify(t))return G(a)}return null}return null}function xe(e,t){if(!e.enforced)return null;let{retrieval:n}=e,r=h(e.reason,e.ruleCode);if(n.action==="redact"){let i=U(n.redactionRules??[]);if(!Ce(i))return _(O(t),r);let o=L(t,i);return JSON.stringify(o)===JSON.stringify(t)?null:_(o,r)}return n.action==="deny"?_(O(t),r):null}var jt="cli_harness";function b(e){return new Ae(e.apiKey,e.baseUrl,e.agentId,jt)}function R(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=M){let{agentId:r}=t,i=await q(r);if(i&&$(i,n,Date.now())&&B(e,i.body))return;let o=e.getEndpoint();if(o){let a=await W(o,t.apiKey,r);if(a&&B(e,a.body)){await z(r,a.body,a.version);return}}if(!(i&&B(e,i.body)))try{await e.awaitBundleReady(2500)}catch{}}function B(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 wn(e,t){let n=b(t),r=e.tool_input??{};try{await H(e.session_id)||(n.registerHostEnvironment(),await I(e.session_id)),await v(n,t);let i=Ie(e.tool_name,r),o=V(e.tool_name),a;i&&(Ee(n,{agentId:t.agentId,sessionId:e.session_id,framework:"claude-code"},i),o=Array.from(new Set([...o,"delegation"])),a=Se(i,t.agentId));let l=R({operations:o,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?{context:a}:{}}),u=await n.evaluate(l);return Te(u,r)}catch{return E(h("evaluation error (fail-closed)",null))}finally{await w(n)}}async function Cn(e,t){if(!N(e.tool_name))return null;let n=b(t);try{await v(n,t);let r=e.tool_input??{},i=R({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)}),o=await n.evaluate(i);return xe(o,e.tool_response)}catch{return _(O(e.tool_response),h("evaluation error (fail-closed)",null))}finally{await w(n)}}async function Rn(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{Ne as a,N as b,V as c,S as d,h as e,G as f,E as g,K as h,_ as i,Mt as j,Ut as k,O as l,Te as m,xe as n,jt as o,b as p,R as q,v as r,w as s,wn as t,Cn as u,Rn as v};
|