@visiq/claude-code-harness 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/chunk-IT2RXQ74.js +3 -0
- package/dist/cli/hook.js +2 -2
- package/dist/index.d.ts +185 -25
- package/dist/index.js +1 -1
- package/package.json +5 -3
- package/dist/chunk-K5THPWCB.js +0 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 VisIQ Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{f as 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};
|
package/dist/cli/hook.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`)}:()=>{},
|
|
2
|
+
import{g as r,j as u,t as c,u as l,v as d}from"../chunk-IT2RXQ74.js";import{e as a}from"../chunk-3GWLCI47.js";var p=process.env.VISIQ_DEBUG==="1",m=p?(...o)=>{process.stderr.write(`${o.map(String).join(" ")}
|
|
3
|
+
`)}:()=>{},P=console;for(let o of["log","info","debug","warn","error"])P[o]=m;var h={handlePre:(o,e)=>c(o,e),handlePost:(o,e)=>l(o,e),handleSession:(o,e)=>d(o,e),write:o=>{process.stdout.write(o)}};async function f(o,e,s=h){let t=o.hook_event_name==="PreToolUse",i=n=>{t&&s.write(JSON.stringify(r(n)))};try{let n=null;switch(o.hook_event_name){case"PreToolUse":n=await s.handlePre(o,e);break;case"PostToolUse":n=await s.handlePost(o,e);break;case"SessionStart":n=await s.handleSession(o,e);break;default:n=null}n&&s.write(JSON.stringify(n))}catch(n){i(`[VisIQ] harness error (fail-closed): ${n instanceof Error?n.message:String(n)}`)}}function g(){return new Promise(o=>{if(process.stdin.isTTY){o("");return}let e=[],s=!1,t=()=>{s||(s=!0,o(Buffer.concat(e).toString("utf-8")))};setTimeout(t,15e3).unref?.(),process.stdin.on("data",n=>e.push(n)),process.stdin.on("end",t),process.stdin.on("error",t)})}async function w(){let o=u(await g());if(!o)return;let e=o.hook_event_name==="PreToolUse",s=i=>{e&&process.stdout.write(JSON.stringify(r(i)))},t=await a();if(!t){s("[VisIQ] Claude Code harness is loaded but NOT configured \u2014 set VISIQ_API_KEY + VISIQ_ENDPOINT so VisIQ can govern this tool call. Blocked (fail-closed) until configured.");return}await f(o,t)}w().then(()=>process.exit(0)).catch(()=>{try{process.stdout.write(JSON.stringify(r("[VisIQ] harness crashed before evaluating the call \u2014 blocked (fail-closed).")))}catch{}process.exit(0)});
|
package/dist/index.d.ts
CHANGED
|
@@ -73,7 +73,7 @@ export declare function bareToolName(toolName: string): string;
|
|
|
73
73
|
/** Does this tool call pull foreign content into the model's context? */
|
|
74
74
|
export declare function isRetrievalTool(toolName: string): boolean;
|
|
75
75
|
/** Governance facets to evaluate for a given tool. */
|
|
76
|
-
export type Operation = "action" | "retrieval";
|
|
76
|
+
export type Operation = "action" | "retrieval" | "delegation";
|
|
77
77
|
/**
|
|
78
78
|
* The `operations[]` to hand `UnifiedRuntime.evaluate`. Retrieval tools carry
|
|
79
79
|
* BOTH facets (an action rule can still govern a fetch); everything else is a
|
|
@@ -150,20 +150,47 @@ export type AgentCategory = (typeof AGENT_CATEGORIES)[number];
|
|
|
150
150
|
* The agent attribute bundle exposed to rules as `input.agent` on both planes.
|
|
151
151
|
* `trust_tier` may be null (unassigned → caller-supplied tier honored);
|
|
152
152
|
* `categories` defaults to an empty array (never null);
|
|
153
|
-
* `
|
|
154
|
-
* business-functions.ts)
|
|
153
|
+
* `business_functions` is the AUTHORITATIVE multi-value set — zero or more of the
|
|
154
|
+
* `BUSINESS_FUNCTION_IDS` (see business-functions.ts). An agent can serve several
|
|
155
|
+
* functions at once (e.g. an agent that is both HR and Engineering), and its set
|
|
156
|
+
* broadens over time as the AI reclassifies it. Rules test membership with the
|
|
157
|
+
* array-includes idiom (`"hr" in input.agent.business_functions`); an empty set
|
|
158
|
+
* never matches any such condition (fail-safe).
|
|
159
|
+
* `business_function` is the PRIMARY (best-fit) function — the first element of
|
|
160
|
+
* `business_functions`, or null when the set is empty — kept for backward
|
|
161
|
+
* compatibility with rules authored against the original scalar attribute.
|
|
155
162
|
*
|
|
156
|
-
* NOTE (dependency-light):
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
* trivially-importable shape it has always been.
|
|
163
|
+
* NOTE (dependency-light): both fields are typed loosely (`string`) rather than a
|
|
164
|
+
* narrowed union so this SSOT module imports nothing from business-functions.ts —
|
|
165
|
+
* the closed-set validation lives at the write/eval boundaries
|
|
166
|
+
* (isBusinessFunctionId / normalizeBusinessFunctions) + the DB CHECK, keeping this
|
|
167
|
+
* type the trivially-importable shape it has always been.
|
|
161
168
|
*/
|
|
162
169
|
export interface AgentEvalAttributes {
|
|
163
170
|
trust_tier: TrustTier | null;
|
|
164
171
|
categories: AgentCategory[];
|
|
165
|
-
/**
|
|
172
|
+
/**
|
|
173
|
+
* The AUTHORITATIVE set of the agent's business functions (0..N of
|
|
174
|
+
* BUSINESS_FUNCTION_IDS). Empty when unassigned. Rules test it with
|
|
175
|
+
* `"<id>" in input.agent.business_functions`.
|
|
176
|
+
*/
|
|
177
|
+
business_functions: string[];
|
|
178
|
+
/**
|
|
179
|
+
* The PRIMARY business function — `business_functions[0]` (best-fit), or null
|
|
180
|
+
* when the set is empty. Back-compat mirror for scalar-authored rules.
|
|
181
|
+
*/
|
|
166
182
|
business_function: string | null;
|
|
183
|
+
/**
|
|
184
|
+
* Capability-derived blast-radius tier — one of BLAST_RADIUS_TIERS
|
|
185
|
+
* (blast-radius.ts) or null when NEVER inferred (cold start). Note the
|
|
186
|
+
* distinction: `null` = not yet assessed (conditions on it don't match, like
|
|
187
|
+
* business_function); the string `"unknown"` is a REAL assessed-but-
|
|
188
|
+
* undetermined value the inference can produce. Typed `string | null` (not the
|
|
189
|
+
* narrowed union) so this SSOT stays dependency-light — the closed-set
|
|
190
|
+
* validation lives at the write/eval boundaries (toBlastRadiusTier) + the DB
|
|
191
|
+
* CHECK, exactly as business_function does.
|
|
192
|
+
*/
|
|
193
|
+
blast_radius_tier: string | null;
|
|
167
194
|
}
|
|
168
195
|
/**
|
|
169
196
|
* The session trajectory bundle exposed to rules as `input.session` on both
|
|
@@ -190,6 +217,14 @@ export interface SessionEvalState {
|
|
|
190
217
|
/** Distinct target apps touched earlier in the session. */
|
|
191
218
|
target_apps: string[];
|
|
192
219
|
}
|
|
220
|
+
/** One tool as captured at the harness bind boundary. Argument VALUES are never
|
|
221
|
+
* captured — `input_schema` is JSON Schema (shape only). */
|
|
222
|
+
export interface CapturedToolSpec {
|
|
223
|
+
name: string;
|
|
224
|
+
description?: string;
|
|
225
|
+
/** JSON Schema object describing the tool's arguments (no values). */
|
|
226
|
+
input_schema?: unknown;
|
|
227
|
+
}
|
|
193
228
|
/**
|
|
194
229
|
* Redaction directive — the shared masking primitive (SSOT).
|
|
195
230
|
*
|
|
@@ -231,6 +266,66 @@ export interface AgentEnvironment {
|
|
|
231
266
|
ip?: string;
|
|
232
267
|
/** os.userInfo().username. */
|
|
233
268
|
username?: string;
|
|
269
|
+
/**
|
|
270
|
+
* The harness-detected framework as a backend `agent_type` slug (e.g.
|
|
271
|
+
* `langchain`, `vercel_ai`). Omitted when unknown. The backend classifies a
|
|
272
|
+
* self-provisioned agent with this ONLY while its stored type is still the
|
|
273
|
+
* default `unknown` — never overwriting a management/human-set value.
|
|
274
|
+
*/
|
|
275
|
+
agent_type?: string;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Cognition beats — the Agent Cortex capture payload (thoughts, actions,
|
|
279
|
+
* observations, and SUB-AGENT SPAWNS) emitted autonomously from the harness
|
|
280
|
+
* seams and POSTed to `/allow/cognition`. This is display/graph data only; it
|
|
281
|
+
* never participates in a governance decision. Default-OFF (thoughts are
|
|
282
|
+
* sensitive) — see UnifiedRuntime.emitCognition.
|
|
283
|
+
*
|
|
284
|
+
* The shape mirrors the framework-agnostic `MindEvent` SSOT the Cortex UI reads
|
|
285
|
+
* (products/project-y/apps/web/src/components/allow/agents/cortex/types.ts).
|
|
286
|
+
*/
|
|
287
|
+
export type CognitionBeatKind = "thought" | "speech" | "action" | "observation" | "intervention" | "spawn" | "phase" | "handoff" | "lifecycle" | "error";
|
|
288
|
+
export type CognitionVisibility = "shown" | "hidden";
|
|
289
|
+
export type CognitionProvenance = "signed" | "parsed" | "proxy" | "narration";
|
|
290
|
+
/** A recognized sub-agent spawn — the Mode-B delegation edge. */
|
|
291
|
+
export interface CognitionSpawn {
|
|
292
|
+
childAgentId: string;
|
|
293
|
+
childName: string;
|
|
294
|
+
kind: "subagent" | "workflow" | "teammate";
|
|
295
|
+
model?: string;
|
|
296
|
+
prompt?: string;
|
|
297
|
+
}
|
|
298
|
+
export interface CognitionBeat {
|
|
299
|
+
/** Stable harness-minted id → server dedup key (idempotent re-sends). */
|
|
300
|
+
clientEventId: string;
|
|
301
|
+
agentId: string;
|
|
302
|
+
sessionId: string;
|
|
303
|
+
threadId: string;
|
|
304
|
+
/** Cognition DAG parent (parentUuid / parent_run_id / the spawning agent). */
|
|
305
|
+
parentId?: string;
|
|
306
|
+
/** Per-session monotone ordering (order-independent replay). */
|
|
307
|
+
seq: number;
|
|
308
|
+
/** Beat wall-clock, epoch ms. */
|
|
309
|
+
ts: number;
|
|
310
|
+
durationMs?: number;
|
|
311
|
+
kind: CognitionBeatKind;
|
|
312
|
+
visibility?: CognitionVisibility;
|
|
313
|
+
provenance?: CognitionProvenance;
|
|
314
|
+
content?: {
|
|
315
|
+
text?: string;
|
|
316
|
+
spans?: unknown[];
|
|
317
|
+
};
|
|
318
|
+
tool?: Record<string, unknown>;
|
|
319
|
+
result?: Record<string, unknown>;
|
|
320
|
+
governance?: Record<string, unknown>;
|
|
321
|
+
spawn?: CognitionSpawn;
|
|
322
|
+
phase?: Record<string, unknown>;
|
|
323
|
+
handoff?: Record<string, unknown>;
|
|
324
|
+
attribution?: Record<string, unknown>;
|
|
325
|
+
cost?: Record<string, unknown>;
|
|
326
|
+
model?: string;
|
|
327
|
+
agentRole?: string;
|
|
328
|
+
framework?: string;
|
|
234
329
|
}
|
|
235
330
|
/** The facets an event participates in (the unified `operations` tag). */
|
|
236
331
|
export type UnifiedOperation = "retrieval" | "action" | "delegation";
|
|
@@ -267,6 +362,16 @@ export interface UnifiedEvaluateEvent {
|
|
|
267
362
|
/** A snippet of the retrieved/produced content (reserved; not yet evaluated). */
|
|
268
363
|
contentPreview?: string;
|
|
269
364
|
telemetry?: Record<string, unknown>;
|
|
365
|
+
/**
|
|
366
|
+
* Caller-supplied structured context to PERSIST on the telemetry row
|
|
367
|
+
* (`allow_audit_log.context`), merged alongside the interceptor source. This is
|
|
368
|
+
* how an autonomous capture seam attaches a `delegation` object (a recognized
|
|
369
|
+
* sub-agent spawn: `{ delegation: { is_delegated, parent_agent_id, target_agent,
|
|
370
|
+
* source, spawn } }`) without any new endpoint or column — the delegation sink
|
|
371
|
+
* (`fetchAgentDelegations`) already reads `context->'delegation'`. Never used for
|
|
372
|
+
* the decision itself; display/graph data only.
|
|
373
|
+
*/
|
|
374
|
+
context?: Record<string, unknown>;
|
|
270
375
|
}
|
|
271
376
|
/** The action-facet sub-decision (null leg when the event had no action op). */
|
|
272
377
|
export interface UnifiedActionSubDecision {
|
|
@@ -360,36 +465,60 @@ declare class UnifiedRuntime {
|
|
|
360
465
|
private initialBundlePromise;
|
|
361
466
|
private refreshTimer;
|
|
362
467
|
private agentMode;
|
|
468
|
+
/** Optional per-operation mode override, shipped resolved in the bundle:
|
|
469
|
+
* `{action?, retrieval?, delegation?}` → enforce|monitor|off. An operation
|
|
470
|
+
* absent here inherits {@link agentMode}. Null ⇒ no per-op override. */
|
|
471
|
+
private agentModeByOperation;
|
|
472
|
+
/** The RAW bundle body last applied — handed VERBATIM to the Rust core
|
|
473
|
+
* (@visiq/core-wasm) on the `wasm` decision path (it re-parses rows / hydrates
|
|
474
|
+
* attributes / reads no_coverage itself, so it reproduces the TS decision
|
|
475
|
+
* byte-for-byte). `agent_mode` + `agent_mode_by_operation` are overridden at
|
|
476
|
+
* call time with the runtime's EFFECTIVE (stateful) modes. */
|
|
477
|
+
private rawBundle;
|
|
363
478
|
/** True once the backend has EXPLICITLY confirmed this agent's mode. A
|
|
364
479
|
* schema-defaulted/cold-start monitor is NOT confirmed — so a no-bundle deny
|
|
365
|
-
*
|
|
480
|
+
* for a CONFIRMED enforce agent fails closed to deny, while a NEVER-confirmed
|
|
481
|
+
* agent degrades to monitor (the onboarding fail-safe), never to enforce. */
|
|
366
482
|
private agentModeConfirmed;
|
|
483
|
+
/** True when the last applied bundle carried `shutdown: true` — the operator
|
|
484
|
+
* has shut this agent down (notebook item 1). Every {@link evaluate} then
|
|
485
|
+
* returns an immediate, always-enforced deny-all BEFORE any mode bypass / rule
|
|
486
|
+
* 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
|
+
private shutdown;
|
|
489
|
+
/** True when a bundle body was RECEIVED but FAILED to apply (malformed /
|
|
490
|
+
* schema-drifted / corrupt cache) — an ERROR, distinct from a genuinely
|
|
491
|
+
* absent bundle. On cold start this fails CLOSED (enforce the deny-all) so a
|
|
492
|
+
* corrupt or poisoned bundle can never downgrade an agent to the permissive
|
|
493
|
+
* monitor onboarding fail-safe (G001). Cleared once a body validates. */
|
|
494
|
+
private bundleApplyFailed;
|
|
367
495
|
private telemetryBuffer;
|
|
368
496
|
private telemetryTimer;
|
|
497
|
+
private cognitionBuffer;
|
|
498
|
+
private cognitionTimer;
|
|
499
|
+
/** Resolved from the bundle (`cognition_capture`, server source-of-truth) or
|
|
500
|
+
* the `VISIQ_COGNITION_CAPTURE=1` dev override. Default OFF ⇒ emitCognition is
|
|
501
|
+
* an immediate return (zero cost). The server re-checks on ingest regardless. */
|
|
502
|
+
private cognitionEnabled;
|
|
369
503
|
private envRegistered;
|
|
370
504
|
private registerPromise;
|
|
505
|
+
/** Content signature of the last reported tool surface — so a repeat visiq()
|
|
506
|
+
* wrap (same tools) doesn't re-POST. Null until the first report. */
|
|
507
|
+
private lastToolSurfaceSig;
|
|
371
508
|
constructor(apiKey?: string, endpoint?: string, agentId?: string, harnessKind?: AgentKind, timeoutMs?: number);
|
|
372
509
|
/**
|
|
373
510
|
* Evaluate one governed agent event across ALL its tagged operations and
|
|
374
511
|
* return the merged unified decision with both facet sub-decisions.
|
|
375
512
|
*/
|
|
376
513
|
evaluate(event: UnifiedEvaluateEvent): Promise<UnifiedDecision>;
|
|
514
|
+
/**
|
|
515
|
+
* Resolve the effective mode for one operation: per-op override → agent mode.
|
|
516
|
+
*/
|
|
517
|
+
private modeFor;
|
|
377
518
|
/** Read the session's PRIOR-events state; fresh/absent/expired ⇒ empty. */
|
|
378
519
|
private readSession;
|
|
379
520
|
/** Fold one decided event into its session (LRU touch + bounds enforcement). */
|
|
380
521
|
private foldSession;
|
|
381
|
-
/**
|
|
382
|
-
* Evaluate ONE operation against the cached rules, then apply that facet's
|
|
383
|
-
* uncovered semantics: action/delegation → no-coverage defaults (or
|
|
384
|
-
* fail-closed deny); retrieval → DEFAULT_DENY.
|
|
385
|
-
*/
|
|
386
|
-
private resolveOperation;
|
|
387
|
-
/** Build the facet-specific {@link UnifiedEvaluationInput} for one operation. */
|
|
388
|
-
private buildInput;
|
|
389
|
-
/** Compose the merged {@link UnifiedDecision} from the per-leg results. */
|
|
390
|
-
private buildDecision;
|
|
391
|
-
private actionSub;
|
|
392
|
-
private retrievalSub;
|
|
393
522
|
/**
|
|
394
523
|
* Apply the agent_mode envelope and record telemetry. enforce returns the
|
|
395
524
|
* real verdict; monitor forces allowed=true (observe-only) while preserving
|
|
@@ -435,12 +564,40 @@ declare class UnifiedRuntime {
|
|
|
435
564
|
getSessionState(sessionId: string): SessionEvalState;
|
|
436
565
|
/** Report the agent's environment once per runtime instance (fire-and-forget). */
|
|
437
566
|
registerEnvironment(env: AgentEnvironment): void;
|
|
438
|
-
/**
|
|
439
|
-
|
|
567
|
+
/**
|
|
568
|
+
* Capture + register the host environment (the single init entry point).
|
|
569
|
+
* `agentType` is the harness-detected framework slug (F5) — merged into the
|
|
570
|
+
* registration handshake so the backend can classify a self-provisioned agent
|
|
571
|
+
* (omitted when unknown, so it never overwrites a good value).
|
|
572
|
+
*/
|
|
573
|
+
registerHostEnvironment(agentType?: string): void;
|
|
574
|
+
/**
|
|
575
|
+
* Report the agent's captured tool surface (fire-and-forget). Drives backend
|
|
576
|
+
* blast-radius inference. Re-reports ONLY when the surface changes (content
|
|
577
|
+
* signature guard), so wrapping several agents / re-wrapping the same one in a
|
|
578
|
+
* process doesn't re-POST an identical set. No-ops without a client/agent id or
|
|
579
|
+
* on an empty set. Never throws (best-effort, must not affect the host).
|
|
580
|
+
*/
|
|
581
|
+
reportToolSurface(tools: CapturedToolSpec[]): void;
|
|
440
582
|
private bufferTelemetry;
|
|
583
|
+
/** Buffered-but-unsent decision count (for the exit-drain warning). */
|
|
584
|
+
pendingTelemetryCount(): number;
|
|
585
|
+
/** True when a backend is configured (telemetry can actually be shipped). */
|
|
586
|
+
hasBackend(): boolean;
|
|
441
587
|
private flushTelemetry;
|
|
442
588
|
private enforceTelemetryCap;
|
|
443
|
-
/**
|
|
589
|
+
/** Whether cognition capture is currently enabled (resolved from the bundle). */
|
|
590
|
+
isCognitionEnabled(): boolean;
|
|
591
|
+
/**
|
|
592
|
+
* Emit a cognition beat (thought / action / spawn / …) to the Agent Cortex
|
|
593
|
+
* sink. DEFAULT-OFF gate: an immediate `return` when disabled — zero cost, no
|
|
594
|
+
* allocation. NEVER awaits or throws into the agent's path; a size trigger
|
|
595
|
+
* bounds latency for the higher-volume cognition stream.
|
|
596
|
+
*/
|
|
597
|
+
emitCognition(beat: CognitionBeat): void;
|
|
598
|
+
private flushCognition;
|
|
599
|
+
private enforceCognitionCap;
|
|
600
|
+
/** Drain pending registration + telemetry + cognition and await it (graceful shutdown). */
|
|
444
601
|
flush(): Promise<void>;
|
|
445
602
|
dispose(): void;
|
|
446
603
|
}
|
|
@@ -615,6 +772,9 @@ export declare function buildEvaluateEvent(opts: {
|
|
|
615
772
|
cwd?: string;
|
|
616
773
|
toolUseId?: string;
|
|
617
774
|
query?: string;
|
|
775
|
+
/** Structured context to persist on allow_audit_log.context (e.g. a recognized
|
|
776
|
+
* `delegation` object for a Task sub-agent spawn). */
|
|
777
|
+
context?: Record<string, unknown>;
|
|
618
778
|
}): UnifiedEvaluateEvent;
|
|
619
779
|
/**
|
|
620
780
|
* Warm a runtime's local bundle so `evaluate()` runs offline + never spuriously
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as E,b as T,c as h,d as C,e as u,f as x,g as S}from"./chunk-6DMSMBWM.js";import{a as n,b as s,c as a,d as l,e as P,f as U,g as F,h as b,i as q,j as K,k as m,l as p,m as f,n as d,o as I,p as L,q as k,r as v,s as y,t as A,u as B,v as M}from"./chunk-
|
|
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-IT2RXQ74.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.1",
|
|
4
4
|
"description": "VisIQ governance harness for the Claude Code CLI — action monitor/block + retrieval monitor/block/redact via Claude Code hooks",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
}
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"zod": "^3.23.8"
|
|
19
|
+
"zod": "^3.23.8",
|
|
20
|
+
"@visiq/core-wasm": "^0.1.0"
|
|
20
21
|
},
|
|
21
22
|
"engines": {
|
|
22
23
|
"node": ">=20"
|
|
@@ -24,7 +25,8 @@
|
|
|
24
25
|
"license": "MIT",
|
|
25
26
|
"files": [
|
|
26
27
|
"dist",
|
|
27
|
-
"README.md"
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
28
30
|
],
|
|
29
31
|
"publishConfig": {
|
|
30
32
|
"access": "public"
|
package/dist/chunk-K5THPWCB.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{f as se,h as le,i as ce,j as ue,k as de,l as pe,m as P}from"./chunk-3GWLCI47.js";var st=new Set(["WebFetch","WebSearch","Read","Grep","Glob","LSP","NotebookRead","ListMcpResourcesTool","ReadMcpResourceTool"]),lt=/(^|_)(search|fetch|read|list|get|query|retrieve|lookup|find|describe|download|export|dump)(_|$)/i;function ct(e){if(typeof e!="string"||!e.startsWith("mcp__"))return typeof e=="string"?e:"";let t=e.lastIndexOf("__");return t>=0?e.slice(t+2):e}function z(e){return typeof e!="string"?!1:st.has(e)?!0:e.startsWith("mcp__")?lt.test(ct(e)):!1}function fe(e){return z(e)?["retrieval","action"]:["action"]}var ut=["query","q","url","prompt","pattern","file_path","path"];function L(e){if(!e||typeof e!="object")return;let t=e,n=[];for(let r of ut){let i=t[r];typeof i=="string"&&i.length>0&&n.push(i)}return n.length>0?n.join(" "):void 0}function I(e,t){let n=t?`VisIQ ${t}`:"VisIQ",r=e&&e.trim().length>0?e.trim():"blocked by policy";return`[${n}] ${r}`}function me(e){let t={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};return e&&(t.hookSpecificOutput.updatedInput=e),t}function F(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}function ge(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:e}}}function S(e,t){let n={hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}};return t&&(n.hookSpecificOutput.additionalContext=t),n}function Fn(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.hook_event_name=="string"?t:null}catch{return null}}var dt=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];var h=Object.fromEntries(dt.map(e=>[e.name,e.re.source])),pt=["private_key","jwt","aws_access_key","github_token","slack_token","stripe_secret","google_api_key","llm_api_key","bearer_token","connection_string","pan","iban","aba_routing","us_ein","swift_bic","ssn","email","us_phone","ipv4","mac_address"],ft={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
2
|
-
MIIEv\u2026
|
|
3
|
-
-----END PRIVATE KEY-----`,template:{pattern:h.private_key,mode:"full"},defaultEnabled:!0},jwt:{id:"jwt",label:"JWT / bearer tokens",description:"JSON Web Tokens (base64url header.payload.signature).",category:"secret",example:"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.dBjftJeZ4CVP",template:{pattern:h.jwt,mode:"full"},defaultEnabled:!0},aws_access_key:{id:"aws_access_key",label:"AWS access key IDs",description:"AWS access / identity key ids (AKIA / ASIA / AROA \u2026).",category:"secret",example:"AKIAIOSFODNN7EXAMPLE",template:{pattern:h.aws_access_key,mode:"full"},defaultEnabled:!0},github_token:{id:"github_token",label:"GitHub tokens",description:"GitHub personal / OAuth tokens (classic ghp_\u2026 + fine-grained).",category:"secret",example:"ghp_0123456789abcdef0123456789abcdef0123",template:{pattern:h.github_token,mode:"full"},defaultEnabled:!0},slack_token:{id:"slack_token",label:"Slack tokens",description:"Slack bot / user / app tokens (xoxb- / xoxp- \u2026).",category:"secret",example:"xoxb-1234567890-abcdefghijkl",template:{pattern:h.slack_token,mode:"full"},defaultEnabled:!0},stripe_secret:{id:"stripe_secret",label:"Stripe secret keys",description:"Stripe live secret / restricted keys (sk_live_ / rk_live_).",category:"secret",example:"sk_live_0123456789abcdefABCDEF",template:{pattern:h.stripe_secret,mode:"full"},defaultEnabled:!0},google_api_key:{id:"google_api_key",label:"Google API keys",description:"Google API keys (AIza\u2026).",category:"secret",example:"AIzaSyA1234567890abcdefghijklmnopqrstuv",template:{pattern:h.google_api_key,mode:"full"},defaultEnabled:!0},llm_api_key:{id:"llm_api_key",label:"LLM provider API keys",description:"OpenAI / Anthropic secret keys (sk-\u2026, sk-proj-\u2026, sk-ant-\u2026).",category:"secret",example:"sk-ant-api03-AbCdEf0123456789AbCdEf01",template:{pattern:h.llm_api_key,mode:"full"},defaultEnabled:!0},bearer_token:{id:"bearer_token",label:"Authorization bearer tokens",description:"Credentials following an HTTP `Authorization: Bearer \u2026` header.",category:"secret",example:"Bearer abcdef0123456789abcdef0123456789",template:{pattern:h.bearer_token,mode:"full"},defaultEnabled:!0},connection_string:{id:"connection_string",label:"Connection strings (with password)",description:"Database / broker DSNs carrying an inline password (scheme://user:pass@host).",category:"secret",example:"postgres://app:s3cr3t@db.internal:5432/main",template:{pattern:h.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS).",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\b\\d{13,19}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){10,30}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:"\\b\\d{9}\\b",mode:"full"},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX).",category:"financial",example:"12-3456789",template:{pattern:h.us_ein,mode:"full"},defaultEnabled:!0},swift_bic:{id:"swift_bic",label:"SWIFT / BIC codes",description:"Bank SWIFT/BIC codes (8 or 11 chars). DEFAULT-OFF (matches uppercase tokens).",category:"financial",example:"DEUTDEFF500",template:{pattern:h.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789).",category:"pii",example:"123-45-6789",template:{pattern:h.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept).",category:"pii",example:"alice@acme.com",template:{pattern:h.email,mode:"email"},defaultEnabled:!0},us_phone:{id:"us_phone",label:"US phone numbers",description:"US phone numbers in common formats. DEFAULT-OFF (10-digit false-positive surface).",category:"pii",example:"(415) 555-0132",template:{pattern:h.us_phone,mode:"partial",keepLast:4},defaultEnabled:!1},ipv4:{id:"ipv4",label:"IPv4 addresses",description:"Dotted-quad IPv4 addresses. DEFAULT-OFF (common + usually benign).",category:"identifier",example:"203.0.113.42",template:{pattern:h.ipv4,mode:"full"},defaultEnabled:!1},mac_address:{id:"mac_address",label:"MAC addresses",description:"Hardware MAC addresses. DEFAULT-OFF.",category:"identifier",example:"3c:22:fb:1a:2b:3c",template:{pattern:h.mac_address,mode:"full"},defaultEnabled:!1}},Mn=new Set(pt.filter(e=>!ft[e].defaultEnabled));var G="[REDACTED]",E="\u2022",D=e=>/[A-Za-z0-9]/.test(e);function _e(e,t,n,r){let i=Array.from(e),o=i.length,a=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),c=r.length>0?r:E,p=a+s>=o;return i.map((d,_)=>!p&&(_<a||_>=o-s)?d:D(d)?c:d).join("")}function mt(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return _e(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:E;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>D(a)?o:a).join(""))+i}function gt(e,t,n){let r=n.length>0?n:E,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let p=new RegExp(t,"g"),d;for(;(d=p.exec(e))!==null;){if(d[0].length===0){p.lastIndex++;continue}for(let _=d.index;_<d.index+d[0].length;_++)i[_]=!0}}catch{}let o=!1,a=!0;for(let p=0;p<e.length;p++)if(D(e[p])&&(o=!0,!i[p])){a=!1;break}let s=o&&a,c="";for(let p=0;p<e.length;p++){let d=e[p];!s&&i[p]||!D(d)?c+=d:c+=r}return c}function he(e,t){let n=t.mode??"full";return n==="partial"?_e(e,t.keepFirst??0,t.keepLast??0,t.maskChar??E):n==="email"?mt(e,t.maskChar??E):n==="custom"?gt(e,t.keepPattern,t.maskChar??E):t.replacement??G}function _t(e,t){return typeof e=="string"?he(e,t):t.replacement??G}function ye(e){let t=[],n=e.replacement??G;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:o=>he(o,r)})}return t}function be(e,t){let n=e;for(let{source:r,replacer:i}of t){let o;try{o=new RegExp(r,"g")}catch(a){let s=a instanceof Error?a.message:String(a);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(o,a=>i(a))}return n}function V(e,t){return e==null?e:typeof e=="string"?ht(e,t):typeof e=="object"?yt(e,t):e}function ht(e,t){if(typeof e!="string")return e;let n=ye(t);return n.length===0?e:be(e,n)}function yt(e,t){let n=new Map;for(let s of t.fields??[])typeof s=="string"&&s.length>0&&n.set(s,{field:s,mode:"full",replacement:t.replacement});for(let s of t.directives??[])typeof s.field=="string"&&s.field.length>0&&n.set(s.field,s);let r=ye(t),i=n.size>0,o=r.length>0,a=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(c=>a(c));if(typeof s=="object"){let c=s,p=Object.create(Object.getPrototypeOf(c));for(let d of Object.keys(c)){let _=i?n.get(d):void 0;if(_){p[d]=_t(c[d],_);continue}p[d]=a(c[d])}return p}return typeof s=="string"&&o?be(s,r):s};return a(e)}import{z as u}from"zod";import*as v from"node:os";var ve="interceptor_source",bt=u.enum(["enforce","audit","off"]),vt=u.enum(["closed","open"]),Ae=u.enum(["enforce","monitor","off"]),At=u.object({apiKey:u.string().min(1,"apiKey is required"),agentId:u.string().min(1,"agentId is required"),endpoint:u.string().url().optional(),mode:bt.optional(),timeoutMs:u.number().int().positive().optional(),hitlTimeoutMs:u.number().int().positive().optional(),failBehavior:vt.optional()}),qn=u.object({agent_id:u.string().min(1),target_app:u.string().min(1),action:u.string().min(1),context:u.record(u.unknown()).optional(),session_id:u.string().min(1).max(255).optional(),telemetry:u.record(u.unknown()).optional()}),wt=u.object({field:u.string().optional(),pattern:u.string().optional(),replacement:u.string().optional(),mode:u.enum(["full","partial","email"]).optional(),keepFirst:u.number().optional(),keepLast:u.number().optional(),maskChar:u.string().optional()}),kt=u.object({decision_id:u.string().min(1),decision:u.enum(["permit","deny","approval_required","mask"]),reason:u.string().optional(),rule_code:u.string().nullable().optional(),enforced:u.boolean().optional(),agent_mode:Ae.optional(),arg_redaction_rules:u.array(wt).optional(),plane:u.string().nullable().optional(),operation:u.string().nullable().optional(),is_retrieval:u.boolean().optional(),metadata:u.record(u.unknown()).optional()}),It=u.object({field:u.string().min(1),operator:u.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:u.union([u.string(),u.number(),u.array(u.string())])}),St=u.object({id:u.string().min(1),rule_code:u.string().default(""),name:u.string().min(1),description:u.string().nullable().default(null),effect:u.enum(["allow","deny","hitl","mask"]),resource_type:u.string().min(1),rego_source:u.string().default(""),target_app:u.string().nullable().default(null),action_pattern:u.string().nullable().default(null),conditions:u.array(It).default([]),priority:u.number().int().default(0)}),Et=u.object({version:u.string().min(1),agent_mode:Ae.optional(),rules:u.array(St),no_coverage:u.object({no_coverage_defaults:u.record(u.string()),autopilot_enabled:u.boolean(),enduser_hitl_enabled:u.boolean(),hitl_timeout_seconds:u.number()}).optional()}),Ct=2e3,we=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return kt.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json"},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();return Et.parse(o)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();if(typeof o!="object"||o===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let a=o,s=a.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof a.reason=="string"?a.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await Tt(Ct)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Tt(e){return new Promise(t=>setTimeout(t,e))}function ke(){let e={};try{let t=`${v.platform()} ${v.release()}`.trim();t&&(e.os=t)}catch{}try{let t=v.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=v.userInfo();t&&(e.username=t)}catch{}try{let t=xt();t&&(e.ip=t)}catch{}return e}function xt(){let e=v.networkInterfaces();for(let t of Object.keys(e))for(let n of e[t]??[])if((n.family==="IPv4"||n.family===4)&&!n.internal&&n.address)return n.address}import{z as f}from"zod";import{createHash as Ot}from"crypto";import{createHash as Vn}from"crypto";var Rt=class extends Error{constructor(e,t){super(`eval_conflict_error: complete rules must not produce multiple outputs for "${e}" (got ${t.map(n=>JSON.stringify(n)).join(", ")})`),this.variable=e,this.values=t,this.name="RegoConflictError"}variable;values},Ie=new Map;function Se(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function Ue(e){let t=Ot("sha256").update(e).digest("hex"),n=Ie.get(t);if(n)return n;let r=new Map,i=[],o=e.split(`
|
|
4
|
-
`).map(c=>Nt(c)).filter(c=>c.trim().length>0),a=0;for(;a<o.length;){let c=o[a].trim();if(c.startsWith("package ")||c.startsWith("import ")){a++;continue}let p=c.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(p){let l=p[1],g=p[2].trim();r.set(l,R(g)),a++;continue}let d=c.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(d){let l=d[1],g=d[2].trim(),m=d[3].trim(),y=[];if(m&&m!=="}"){let N=m.endsWith("}")?m.slice(0,-1).trim():m;N&&y.push(N),m.endsWith("}")||(a++,a=M(o,a,y))}else m==="}"||(a++,a=M(o,a,y));let k=Ce(y);i.push({variable:l,value:R(g),conditions:k,rawConditions:Se(y)}),a++;continue}let _=c.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(_){let l=_[1],g=_[2].trim(),m=[];if(g&&g!=="}"){let k=g.endsWith("}")?g.slice(0,-1).trim():g;k&&m.push(k),g.endsWith("}")||(a++,a=M(o,a,m))}else g==="}"||(a++,a=M(o,a,m));let y=Ce(m);i.push({variable:l,value:"true",conditions:y,rawConditions:Se(m)}),a++;continue}a++}let s={defaults:r,rules:i};return Ie.set(t,s),s}function qe(e,t){let n={};for(let[o,a]of e.defaults)n[o]=a;let r=-1,i={};for(let o=0;o<e.rules.length;o++){let a=e.rules[o];if(a.conditions.every(s=>Mt(s,t))){if(i[a.variable]===void 0)i[a.variable]=a.value,n[a.variable]=a.value;else if(i[a.variable]!==a.value)throw new Rt(a.variable,[i[a.variable],a.value]);r===-1&&(r=o)}}return r!==-1?{bindings:n,matched:!0,matchedRuleIndex:r}:{bindings:n,matched:!1,matchedRuleIndex:-1}}function Nt(e){let t=!1,n="";for(let r=0;r<e.length;r++){let i=e[r];if(t)i===n&&e[r-1]!=="\\"&&(t=!1);else if(i==='"'||i==="'")t=!0,n=i;else if(i==="#")return e.slice(0,r)}return e}function M(e,t,n){let r=1,i=t;for(;i<e.length&&r>0;){let o=e[i].trim();for(let a of o)a==="{"&&r++,a==="}"&&r--;if(r>0)n.push(o),i++;else{let a=o.slice(0,o.lastIndexOf("}")).trim();return a&&n.push(a),i}}return i}function R(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Pt(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}var Ee=new Map;function Lt(e){let t=Ee.get(e);if(t!==void 0)return t;let n;try{n=new RegExp(e)}catch{n=null}return Ee.set(e,n),n}function Ce(e){let t=[];for(let n of e){let r=n.split(";").map(i=>i.trim()).filter(i=>i.length>0);for(let i of r){let o=Ft(i);o&&t.push(o)}}return t}function Ft(e){let t=!1,n=e.trim();if(n.startsWith("not ")&&(t=!0,n=n.slice(4).trim()),n==="true"||n==="false")return{type:"literal_bool",negated:t,field:"",value:n==="true"};if(n.includes("[_]"))return{type:"truthy",negated:!1,field:Z,value:e.trim()};let r=n.match(/^count\(([^)]+)\)\s*(>=|<=|>|<)\s*(\d+)$/);if(r)return{type:"count_gt",negated:t,field:r[1].trim(),operator:r[2],value:parseInt(r[3],10)};let i=n.match(/^startswith\(([^,]+),\s*"([^"]*)"\)$/);if(i)return{type:"startswith",negated:t,field:i[1].trim(),value:i[2]};let o=n.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"endswith",negated:t,field:o[1].trim(),value:o[2]};let a=n.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(a)return{type:"contains",negated:t,field:a[1].trim(),value:a[2]};let s=n.match(/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:Pt(s[1])};let c=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s+in\s+((?:input|data)[^\s]*)$/);if(c)return{type:"array_includes",negated:t,field:c[2].trim(),value:$e(c[1])};let p=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(p){let y=Dt(p[2]);if(y!==null)return{type:"in_set",negated:t,field:p[1].trim(),values:y}}let d=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(d)return{type:"comparison",negated:t,field:d[1].trim(),operator:d[2],value:parseFloat(d[3])};let _=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s*==\s*((?:input|data)\S*)$/);if(_)return{type:"equality",negated:t,field:_[2].trim(),value:R(_[1].trim())};let l=n.match(/^([^\s=!]+)\s*==\s*(.+)$/);if(l)return{type:"equality",negated:t,field:l[1].trim(),value:R(l[2].trim())};let g=n.match(/^([^\s=!]+)\s*!=\s*(.+)$/);if(g)return{type:"inequality",negated:t,field:g[1].trim(),value:R(g[2].trim())};let m=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return m?{type:"truthy",negated:t,field:m[1].trim()}:{type:"truthy",negated:!1,field:Z,value:e.trim()}}var Z="__unrecognized_condition_forces_deny__";function $e(e){let t=e.trim();return t==="true"?!0:t==="false"?!1:/^-?\d+(?:\.\d+)?$/.test(t)?parseFloat(t):t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Dt(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",i=!1,o="";for(let s=0;s<t.length;s++){let c=t[s];i?(r+=c,c===o&&t[s-1]!=="\\"&&(i=!1)):c==='"'||c==="'"?(r+=c,i=!0,o=c):c===","?(n.push(r.trim()),r=""):r+=c}if(i)return null;r.trim().length>0&&n.push(r.trim());let a=[];for(let s of n){let c=s.startsWith('"')&&s.endsWith('"')&&s.length>=2||s.startsWith("'")&&s.endsWith("'")&&s.length>=2,p=/^-?\d+(?:\.\d+)?$/.test(s);if(!c&&!p&&!(s==="true"||s==="false"))return null;a.push($e(s))}return a}function Mt(e,t){if(e.field===Z)return!1;let n;switch(e.type){case"equality":{let r=b(e.field,t);n=j(r,e.value);break}case"inequality":{let r=b(e.field,t);r==null?n=!1:n=!j(r,e.value);break}case"startswith":{let r=b(e.field,t);typeof r!="string"?n=!1:n=r.startsWith(String(e.value));break}case"endswith":{let r=b(e.field,t);typeof r!="string"?n=!1:n=r.endsWith(String(e.value));break}case"contains":{let r=b(e.field,t);typeof r!="string"?n=!1:n=r.includes(String(e.value));break}case"regex_match":{let r=b(e.field,t);if(typeof r!="string")n=!1;else{let i=Lt(String(e.value??""));n=i?i.test(r):!1}break}case"truthy":{let r=b(e.field,t);n=$t(r);break}case"count_gt":{let r=b(e.field,t),i=typeof e.value=="number"?e.value:0,o=Ut(r);o===null?n=!1:n=Te(o,e.operator??">",i);break}case"comparison":{let r=b(e.field,t),i=typeof e.value=="number"?e.value:NaN,o=qt(r);Number.isNaN(o)||Number.isNaN(i)||!e.operator?n=!1:n=Te(o,e.operator,i);break}case"in_set":{let r=b(e.field,t),i=e.values??[];Y(r)?n=i.some(o=>j(r,o)):n=!1;break}case"array_includes":{let r=b(e.field,t);Array.isArray(r)?n=r.some(i=>j(i,e.value)):n=!1;break}case"literal_bool":{n=e.value===!0;break}default:n=!1}return e.negated?!n:n}function b(e,t){let n=e;n.startsWith("input.")?n=n.slice(6):n.startsWith("input[")&&(n=n.slice(5));let r=jt(n);if(r===null)return;let i=t;for(let o of r){if(i==null||typeof i!="object")return;i=i[o]}return i}function jt(e){let t=[],n=0,r="";for(;n<e.length;){let i=e[n];if(i===".")r.length>0&&(t.push(r),r=""),n++;else if(i==="["){r.length>0&&(t.push(r),r="");let o=e[n+1];if(o!=='"'&&o!=="'")return null;let a=e.indexOf(`${o}]`,n+2);if(a===-1)return null;t.push(e.slice(n+2,a)),n=a+2}else r+=i,n++}return r.length>0&&t.push(r),t}function Ut(e){return Array.isArray(e)||typeof e=="string"?e.length:e&&typeof e=="object"?Object.keys(e).length:null}function qt(e){return typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN}function Te(e,t,n){switch(t){case">":return e>n;case">=":return e>=n;case"<":return e<n;case"<=":return e<=n;default:return!1}}function Y(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function j(e,t){return!Y(e)||!Y(t)?!1:String(e)===String(t)}function $t(e){return!(e==null||e===!1||e===0||e==="")}function Bt(e){return e.trim()}function Wt(e){return e.map(Bt).filter(t=>t.length>0&&t!=="true")}function zt(e,t=0){let n=3735928559^t,r=1103547991^t;for(let i=0;i<e.length;i++){let o=e.charCodeAt(i);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}var Gt="\0";function Be(e,t){let n=[e.trim(),...Wt(t)].join(Gt);return`b_${zt(n).toString(36)}`}var Vt=["tier1","tier2","tier3"];function We(e){return typeof e=="string"&&Vt.includes(e)}var Ht=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Kt=["internal","customer_facing","experimental","third_party"],ze=[...Ht,...Kt];function Zt(e){return typeof e=="string"&&ze.includes(e)}function Ge(e){let t=new Set;for(let n of e)Zt(n)&&t.add(n);return ze.filter(n=>t.has(n))}var $={trust_tier:null,categories:[],business_function:null},Yt=["read_only","record_create","record_update","record_delete","data_export","data_share","data_subject_request","consent_change","funds_transfer","funds_disbursement","payroll_run","trade_execution","ledger_mutation","credit_decision","decision_adverse","account_restriction","account_closure","card_management","purchase_commitment","vendor_management","deal_management","pricing_change","contract_execution","legal_hold","regulatory_filing","personnel_action","employment_termination","compensation_change","campaign_send","content_publish","inventory_adjustment","order_fulfillment","account_servicing","credential_reset","access_grant","permission_change","credential_management","auth_policy_change","security_config_change","logging_change","alert_management","code_change","infrastructure_provision","deployment_change","communication_send","other"];function Ve(e){if(typeof e!="string"&&typeof e!="number")return null;let t=String(e).trim().replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return t.length>0?t:null}var Jt={wire_transfer:"funds_transfer",international_transfer:"funds_transfer",cross_border_payment:"funds_transfer",send_swift:"funds_transfer",send_wire:"funds_transfer",transfer_funds:"funds_transfer",update_wire_instructions:"funds_transfer",add_beneficiary:"funds_transfer",modify_payee:"funds_transfer",disburse_funds:"funds_disbursement",initiate_ach:"funds_disbursement",issue_refund:"funds_disbursement",execute_trade:"trade_execution",place_order:"trade_execution",post_journal_entry:"ledger_mutation",adjust_ledger:"ledger_mutation",modify_general_ledger:"ledger_mutation",raise_limit:"credit_decision",increase_credit_limit:"credit_decision",extend_credit:"credit_decision",decline_credit:"decision_adverse",deny_application:"decision_adverse",adverse_action:"decision_adverse",block_card:"card_management",cancel_card:"card_management",place_hold:"account_restriction",freeze_account:"account_restriction",restrict_account:"account_restriction",close_account:"account_closure",export_data:"data_export",export_customer_list:"data_export",download_report:"data_export",download_customer_list:"data_export",bulk_export:"data_export",share_data:"data_share",send_to_partner:"data_share",delete_records:"record_delete",delete_user:"record_delete",drop_table:"record_delete",grant_role:"access_grant",change_permissions:"permission_change",modify_access:"permission_change",rotate_keys:"credential_management",disable_mfa:"auth_policy_change",modify_security_config:"security_config_change",disable_logging:"logging_change",purge_logs:"logging_change",suppress_alert:"alert_management",dismiss_alert:"alert_management",rollback:"deployment_change",modify_billing:"record_update",close_sar:"record_update",send_email:"communication_send",send_sms:"communication_send",fulfill_dsar:"data_subject_request",process_dsar:"data_subject_request",fulfill_data_request:"data_subject_request",process_erasure_request:"data_subject_request",honor_deletion_request:"data_subject_request",export_subject_data:"data_subject_request",erase_subject_data:"data_subject_request",delete_subject_data:"data_subject_request",record_consent:"consent_change",capture_consent:"consent_change",update_consent:"consent_change",withdraw_consent:"consent_change",revoke_consent:"consent_change",opt_out:"consent_change",opt_in:"consent_change",run_payroll:"payroll_run",process_payroll:"payroll_run",submit_payroll:"payroll_run",approve_payroll:"payroll_run",create_purchase_order:"purchase_commitment",issue_purchase_order:"purchase_commitment",approve_purchase_order:"purchase_commitment",submit_purchase_order:"purchase_commitment",approve_purchase:"purchase_commitment",approve_requisition:"purchase_commitment",commit_spend:"purchase_commitment",onboard_vendor:"vendor_management",add_vendor:"vendor_management",create_supplier:"vendor_management",approve_vendor:"vendor_management",update_vendor_bank:"vendor_management",update_supplier_bank:"vendor_management",modify_supplier:"vendor_management",create_opportunity:"deal_management",update_opportunity:"deal_management",advance_deal_stage:"deal_management",update_deal_stage:"deal_management",close_deal:"deal_management",mark_closed_won:"deal_management",mark_closed_lost:"deal_management",issue_quote:"pricing_change",send_quote:"pricing_change",approve_discount:"pricing_change",apply_discount:"pricing_change",override_price:"pricing_change",update_pricing:"pricing_change",approve_special_pricing:"pricing_change",execute_contract:"contract_execution",sign_contract:"contract_execution",countersign_contract:"contract_execution",sign_agreement:"contract_execution",execute_agreement:"contract_execution",sign_nda:"contract_execution",execute_nda:"contract_execution",sign_document:"contract_execution",esign_document:"contract_execution",place_legal_hold:"legal_hold",place_litigation_hold:"legal_hold",apply_legal_hold:"legal_hold",release_legal_hold:"legal_hold",file_regulatory_report:"regulatory_filing",file_sar:"regulatory_filing",submit_regulatory_filing:"regulatory_filing",file_compliance_report:"regulatory_filing",file_disclosure:"regulatory_filing",onboard_employee:"personnel_action",hire_employee:"personnel_action",change_employee_role:"personnel_action",promote_employee:"personnel_action",transfer_employee:"personnel_action",update_job_title:"personnel_action",terminate_employee:"employment_termination",offboard_employee:"employment_termination",deactivate_employee:"employment_termination",separate_employee:"employment_termination",adjust_salary:"compensation_change",change_compensation:"compensation_change",approve_raise:"compensation_change",grant_equity:"compensation_change",grant_stock:"compensation_change",issue_bonus:"compensation_change",update_pay_rate:"compensation_change",send_campaign:"campaign_send",launch_campaign:"campaign_send",schedule_campaign:"campaign_send",send_bulk_email:"campaign_send",send_marketing_email:"campaign_send",send_newsletter:"campaign_send",blast_email:"campaign_send",publish_post:"content_publish",publish_content:"content_publish",publish_blog:"content_publish",post_to_social:"content_publish",schedule_post:"content_publish",adjust_inventory:"inventory_adjustment",write_off_inventory:"inventory_adjustment",update_stock_level:"inventory_adjustment",reconcile_inventory:"inventory_adjustment",fulfill_order:"order_fulfillment",ship_order:"order_fulfillment",dispatch_order:"order_fulfillment",mark_order_shipped:"order_fulfillment",update_customer_account:"account_servicing",modify_customer_account:"account_servicing",update_customer_contact:"account_servicing",change_customer_settings:"account_servicing",reset_customer_password:"credential_reset",reset_password:"credential_reset",force_password_reset:"credential_reset",reset_mfa:"credential_reset",unlock_account:"credential_reset",reset_customer_credentials:"credential_reset",merge_pull_request:"code_change",merge_pr:"code_change",merge_branch:"code_change",push_to_branch:"code_change",push_to_main:"code_change",push_code:"code_change",commit_code:"code_change",force_push:"code_change",provision_infrastructure:"infrastructure_provision",provision_resource:"infrastructure_provision",create_instance:"infrastructure_provision",terminate_instance:"infrastructure_provision",spin_up_server:"infrastructure_provision",tear_down_server:"infrastructure_provision",destroy_resource:"infrastructure_provision",create_cluster:"infrastructure_provision"};function Qt(e){let t=Ve(e);return t===null?"other":Jt[t]||(/^(delete|remove|purge|drop|destroy|wipe)_/.test(t)?"record_delete":/^(export|download|extract|dump)_/.test(t)?"data_export":/^(create|add|insert)_/.test(t)?"record_create":/^(update|edit|modify|patch|set)_/.test(t)?"record_update":t==="send_email"||t==="send_sms"||/^(notify|email|sms)_/.test(t)?"communication_send":/^(read|get|list|search|fetch|view|query)_/.test(t)||t==="read"||t==="get"?"read_only":"other")}var xe={github:"version_control",gitlab:"version_control",bitbucket:"version_control",stripe:"payments",adyen:"payments",braintree:"payments",paypal:"payments",square:"payments",salesforce:"crm",hubspot:"crm",pipedrive:"crm",slack:"communication",teams:"communication",twilio:"communication",sendgrid:"communication",mailgun:"communication",gmail:"communication",outlook:"communication",zoom:"communication",aws:"cloud_infra",gcp:"cloud_infra",azure:"cloud_infra",okta:"identity",auth0:"identity",entra:"identity",onelogin:"identity",duo:"identity",snowflake:"data_warehouse",bigquery:"data_warehouse",databricks:"data_warehouse",redshift:"data_warehouse",jira:"ticketing",zendesk:"ticketing",servicenow:"ticketing",freshdesk:"ticketing",linear:"ticketing",workday:"hr",bamboohr:"hr",gusto:"hr",netsuite:"finance_erp",quickbooks:"finance_erp",sap:"finance_erp",xero:"finance_erp",s3:"storage",gcs:"storage",dropbox:"storage",box:"storage",postgres:"database",postgresql:"database",mysql:"database",mongodb:"database",redis:"database"};function Xt(e){let t=Ve(e);return t===null?"other":xe[t]??xe[t.replace(/_/g,"")]??"other"}function X(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=Qt(t.action)),t.targetApp!==void 0&&t.targetApp!==null){let r=n.context&&typeof n.context=="object"&&!Array.isArray(n.context)?{...n.context}:{};r.app_category===void 0&&(r.app_category=Xt(t.targetApp)),n.context=r}return n}var Oe=64,en=64,w={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function He(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var tn=new Set(["deny","approval_required","escalate"]);function U(e,t){if(t.length===0)return[...e];let n=new Set(e);for(let i of t)n.add(i);let r=[...n].sort();return r.length>Oe?r.slice(0,Oe):r}function nn(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function q(e){return typeof e=="string"&&e.length>0?e:null}function Ke(e,t){let n=nn(t.data_categories),r=q(t.classification),i=q(t.action_class),o=i&&Yt.includes(i)?i:null,a=q(t.target_app),s=q(t.decision),c={...e.action_counts};if(o)if(o in c)c[o]=(c[o]??0)+1;else if(Object.keys(c).length<en)c[o]=1;else{let p=Object.keys(c).sort(),d=p[p.length-1];d!==void 0&&o<d&&(delete c[d],c[o]=1)}return{retrieved_data_categories:U(e.retrieved_data_categories,n),retrieved_classifications:U(e.retrieved_classifications,r?[r]:[]),action_classes:U(e.action_classes,o?[o]:[]),action_counts:c,denied_count:e.denied_count+(s==="deny"?1:0),inhibited_count:e.inhibited_count+(s&&tn.has(s)?1:0),event_count:e.event_count+1,target_apps:U(e.target_apps,a?[a]:[])}}function rn(e,t){if(!e||e.trim().length===0)return{decision:"permit",matched:!0};try{let n=Ue(e),r=qe(n,{target_app:t.target_app,action:t.action,...t.context,context:t.context,normalized:t.normalized??{},agent:t.agent??$,session:t.session??w});if(!r.matched)return{decision:"deny",matched:!1};let i=null,o=r.bindings.decision;if(o!==void 0?i=J(o):r.bindings.approval_required==="true"?i="approval_required":r.bindings.mask==="true"?i="mask":r.bindings.allow==="true"&&(i="permit"),i===null)return{decision:"deny",matched:!0};let a=i==="mask"?an(n,r.matchedRuleIndex,i):void 0;return{decision:i,matched:!0,...a?{branchId:a}:{}}}catch{return{decision:"deny",matched:!1}}}function J(e){switch(e){case"permit":case"allow":return"permit";case"deny":return"deny";case"approval_required":return"approval_required";case"mask":return"mask";default:return"deny"}}function an(e,t,n){if(t<0)return;let r=e.rules[t];if(!(!r||(r.variable==="decision"?J(r.value):J(r.variable))!==n))return Be(n,r.rawConditions)}function Re(e,t){if(!e||e.trim().length===0)return{action:"deny",matched:!1};try{let n=Ue(e),r=qe(n,{agent_id:t.agent_id,operation:t.operation,resource_type:t.resource_type,resource_metadata:t.resource_metadata,trust_tier:t.trust_tier??"",surface:t.surface??"",query:t.query??"",normalized:t.normalized??{},agent:t.agent??$,session:t.session??w});if(!r.matched)return{action:"deny",matched:!1};let i=null,o=r.bindings.action??r.bindings.decision;if(o!==void 0?i=Q(o):r.bindings.escalate==="true"?i="escalate":r.bindings.redact==="true"?i="redact":r.bindings.allow==="true"&&(i="allow"),i===null)return{action:"deny",matched:!0};let a=i==="redact"?on(n,r.matchedRuleIndex,i):void 0;return{action:i,matched:!0,...a?{branchId:a}:{}}}catch{return{action:"deny",matched:!1}}}function Q(e){switch(e){case"allow":return"allow";case"deny":return"deny";case"redact":return"redact";case"escalate":return"escalate";default:return"deny"}}function on(e,t,n){if(t<0)return;let r=e.rules[t];if(!(!r||(r.variable==="decision"||r.variable==="action"?Q(r.value):Q(r.variable))!==n))return Be(n,r.rawConditions)}var sn="generic",Ze=[{id:"finance_accounting",name:"Finance & Accounting",icon:"Landmark",description:"Payments, invoicing, ledgers, transactions, refunds, financial reporting, SOX/AML/KYC controls."},{id:"hr",name:"Human Resources",icon:"Users",description:"Employee records, payroll, hiring/recruiting, benefits, personnel actions and PII of staff."},{id:"engineering",name:"Engineering",icon:"Code",description:"Source code, build/deploy pipelines, infrastructure changes, production systems and developer tooling."},{id:"it_security",name:"IT & Security",icon:"ShieldCheck",description:"Credentials, secrets, access control, configuration, threat/exfiltration prevention and security operations."},{id:"legal",name:"Legal",icon:"Scale",description:"Contracts, NDAs, litigation, counsel communications and legal-hold material."},{id:"privacy_compliance",name:"Privacy & Compliance",icon:"BadgeCheck",description:"GDPR/CCPA/HIPAA, consent, data-subject rights, special-category data and regulatory data handling."},{id:"sales",name:"Sales",icon:"TrendingUp",description:"CRM, leads, deals, quotes, pipeline and customer commercial relationships."},{id:"marketing",name:"Marketing",icon:"Megaphone",description:"Campaigns, content, brand, social channels and prospect/audience data."},{id:"operations",name:"Operations",icon:"Cog",description:"Business operations, logistics, internal workflows, vendor/ops tooling and process automation."},{id:"customer_support",name:"Customer Support",icon:"LifeBuoy",description:"Support tickets, customer communications, account servicing and help-desk actions."},{id:"procurement",name:"Procurement",icon:"ShoppingCart",description:"Purchasing, supplier management, purchase orders, sourcing and spend approvals."},{id:sn,name:"Generic",icon:"Shapes",description:"Catch-all for cross-cutting rules or rules that do not fit a specific function. Assign when no specific function clearly applies."}],zn=Ze.map(e=>e.id),ln=new Map(Ze.map(e=>[e.id,e]));function Ye(e){return e!=null&&ln.has(e)}function cn(e,t){if(!e||e==="*")return!0;let n=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);return n.length===0?!1:n.some(r=>un(r,t))}function un(e,t){return e==="*"?!0:e.includes("*")?pn(e).test(t):e===t}function dn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ne=new Map;function pn(e){let t=Ne.get(e);if(t)return t;let n=e.split("*").map(i=>dn(i)).join(".*"),r=new RegExp(`^${n}$`);return Ne.set(e,r),r}function ee(e){return e==="open"||e==="closed"?e:null}function fn(e){let t=e.toLowerCase().replace(/[_\-.:/]+/g," ");return/\b(read|get|list|view|fetch|query|search|describe|show|export|download)\b/.test(t)?"read":/\b(delete|remove|destroy|purge|drop|truncate)\b/.test(t)?"delete":/\b(admin|configure|manage|provision|grant|revoke|assign|unassign)\b/.test(t)?"admin":"write"}function H(e,t){let n=t==="approve"?"ALLOW":t.toUpperCase();return`D-${e.toUpperCase()}-${n}`}function O(e,t,n,r="tenant"){let i=e.charAt(0).toUpperCase()+e.slice(1);return r==="agent"?t==="deny"?`${i} actions on ${n} are denied by this agent's fail-safe override`:`${i} actions on ${n} are permitted by this agent's fail-safe override`:t==="deny"?`${i} actions on ${n} are denied by default`:t==="approve"?`${i} actions on ${n} are permitted by default`:`${i} actions on ${n} require human review`}function Je(e){let t=fn(e.action),n=e.config.no_coverage_defaults??{},r=ee(e.agentNoCoverage),i={autopilot:!1,enduserHitlBypassed:!1};if(e.mode!=="enforce"){let c=n[t]??"deny";return{...i,decision:"permit",rule_code:H(t,c),reason:O(t,c,e.targetApp),hitlCategory:null}}if(e.config.autopilot_enabled&&r!=="closed")return{...i,autopilot:!0,decision:"permit",rule_code:H(t,n[t]??"deny"),reason:"Autopilot: draft rule created for engineer review; request permitted",hitlCategory:"engineer"};let o;r==="open"?o="approve":r==="closed"?o="deny":o=n[t]??"deny";let a=H(t,o),s=r!==null?"agent":"tenant";return o==="approve"?{...i,decision:"permit",rule_code:a,reason:O(t,"approve",e.targetApp,s),hitlCategory:null}:o==="ask"?e.config.enduser_hitl_enabled===!1?{...i,decision:"permit",rule_code:a,reason:`${O(t,"ask",e.targetApp)} (end-user HITL disabled \u2014 bypassed)`,hitlCategory:null,enduserHitlBypassed:!0}:{...i,decision:"approval_required",rule_code:a,reason:O(t,"ask",e.targetApp),hitlCategory:"enduser"}:{...i,decision:"deny",rule_code:a,reason:O(t,"deny",e.targetApp,s),hitlCategory:"engineer"}}var mn=["action","retrieval","delegation"];function gn(e){return typeof e=="string"&&mn.includes(e)}var _n=new Set(["rules"]);function Qe(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!_n.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(gn):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}var hn={tier1:3,tier2:2,tier3:1};function Pe(e){return e?hn[e]??null:null}function Le(e,t){if(!t)return{matched:!0,reason_code:"POLICY_ALLOW",reason:"resource has no minimum trust tier requirement"};let n=Pe(e),r=Pe(t);return n===null?{matched:!1,reason_code:"TIER_MISMATCH",reason:`agent trust tier '${e??"(none)"}' is not a recognized tier`}:r===null?{matched:!1,reason_code:"TIER_MISMATCH",reason:`resource minimum trust tier '${t}' is not a recognized tier`}:n<r?{matched:!1,reason_code:"TIER_MISMATCH",reason:`agent trust tier '${e}' (level ${n}) is below the required minimum '${t}' (level ${r})`}:{matched:!0,reason_code:"POLICY_ALLOW",reason:`agent trust tier '${e}' (level ${n}) meets the required minimum '${t}' (level ${r})`}}function Fe(e,t){return!t||t.length===0?{matched:!1,reason_code:"POLICY_ALLOW",reason:"no principal exclusions on this rule"}:t.includes(e)?{matched:!0,reason_code:"PRINCIPAL_EXCLUDED",reason:`agent '${e}' is in the principal exclusion list`}:{matched:!1,reason_code:"POLICY_ALLOW",reason:`agent '${e}' is not in the principal exclusion list`}}function De(e,t){return t?e?e===t?{matched:!0,reason_code:"SURFACE_RESTRICTION",reason:`surface '${e}' matches rule surface restriction`}:{matched:!1,reason_code:"POLICY_ALLOW",reason:`input surface '${e}' does not match rule surface '${t}'`}:{matched:!1,reason_code:"POLICY_ALLOW",reason:`no surface on input \u2014 rule surface '${t}' restriction does not apply`}:{matched:!1,reason_code:"POLICY_ALLOW",reason:"rule has no surface restriction"}}var yn={matched:!1,decision:"deny",reason:"No matching rule",reasonCode:null,ruleId:null,ruleCode:null,ruleDescription:null};function Me(e){return e==="allow"?"permit":e==="redact"||e==="escalate"||e==="deny"?e:"deny"}function bn(e,t){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&e.version===2&&typeof e.branches=="object"&&e.branches!==null&&!Array.isArray(e.branches)){let{branches:n}=e;if(t&&Array.isArray(n[t]))return n[t];let r=Object.keys(n);return r.length===1&&Array.isArray(n[r[0]])?n[r[0]]:void 0}}function te(e,t){let n=bn(e,t);if(!Array.isArray(n)||n.length===0)return;let r=n.filter(i=>i&&typeof i=="object"&&(typeof i.field=="string"||typeof i.pattern=="string"));return r.length>0?r:void 0}function A(e,t){return e.decision==="redact"&&!t.transformableResponse?{...e,decision:"deny",reason:`${e.reason} (redaction not enforceable on this call \u2014 denied fail-closed)`,redactionRules:void 0,downgraded:{from:"redact",to:"deny",why:"response not transformable at this call site"}}:e}function je(e,t,n){if(e.decision!=="redact")return e;let r=te(t.redactionSpec,n);return r?{...e,redactionRules:r}:t.failClosedOnEmptySpec?{...e,decision:"deny",reason:`${e.reason} (redact rule has no enforceable redaction_spec \u2014 denied fail-closed, G001)`,redactionRules:void 0,downgraded:{from:"redact",to:"deny",why:"redact rule has no enforceable redaction_spec"}}:e}function vn(e,t,n){if(e.decision!=="mask")return e;let r=te(t.redactionSpec,n);return r?{...e,redactionRules:r}:{...e,decision:"deny",reason:`${e.reason} (mask rule has no resolvable redaction directives \u2014 denied fail-closed, G001)`,redactionRules:void 0,downgraded:{from:"mask",to:"deny",why:"mask rule has no resolvable redaction directives"}}}function K(e,t,n){if(e.decision!=="approval_required"&&e.decision!=="escalate")return e;if(t.hitlFallback!=="mask")return{...e,hitlFallback:"deny"};let r=te(t.redactionSpec,n);return r?{...e,hitlFallback:"mask",redactionRules:r}:{...e,hitlFallback:"deny",downgraded:{from:e.decision,to:"deny",why:"hitl_fallback=mask but no enforceable redaction_spec \u2014 no-approval falls back to deny (G001)"}}}function Xe(e,t){let n=[...e].sort((l,g)=>g.priority-l.priority),r=t.resourceMetadata!==null||t.operation!==null,i=t.action!==null&&t.targetApp!==null,o=t.facets.includes("retrieval")&&r,a=(t.facets.includes("action")||t.facets.includes("delegation"))&&i,s=t.resourceMetadata??{},c=typeof s.min_trust_tier=="string"?s.min_trust_tier:null,p=Array.isArray(s.excluded_principals)?s.excluded_principals:null,d=Array.isArray(s.restricted_surfaces)?s.restricted_surfaces:null,_={agent_id:t.agentId,operation:t.operation??"retrieve",resource_type:t.resourceType??"",resource_metadata:s,trust_tier:t.trustTier,surface:t.surface,query:t.query,normalized:t.normalized,agent:t.agent,session:t.session??w};for(let l of n){if(o&&l.appliesTo.includes("retrieval")){if(l.bypassActive&&l.bypassExpiresAt&&new Date(l.bypassExpiresAt).getTime()>Date.now())return A({matched:!0,decision:"permit",reason:l.bypassReason??"Emergency bypass active",reasonCode:"EMERGENCY_BYPASS",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities);if(l.principalExclusions&&l.principalExclusions.length>0){let m=Fe(t.agentId,l.principalExclusions);if(m.matched)return A({matched:!0,decision:"deny",reason:m.reason,reasonCode:"PRINCIPAL_EXCLUDED",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities)}if(p&&p.length>0){let m=Fe(t.agentId,p);if(m.matched)return A({matched:!0,decision:"deny",reason:m.reason,reasonCode:"PRINCIPAL_EXCLUDED",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities)}if(l.surface){let m=De(t.surface,l.surface);if(m.matched){let y=Re(l.regoSource,_),k=y.matched?y.action:"deny",N=Me(k),oe=y.matched?y.branchId:void 0;return A(K(je({matched:!0,decision:N,reason:m.reason,reasonCode:k==="allow"?"POLICY_ALLOW":"SURFACE_RESTRICTION",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},l,oe),l,oe),t.capabilities)}continue}if(d&&d.length>0&&t.surface&&De(t.surface,d.includes(t.surface)?t.surface:null).matched)return A({matched:!0,decision:"deny",reason:`surface '${t.surface}' is in the restricted surfaces list for this resource`,reasonCode:"SURFACE_RESTRICTION",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities);if(l.trustTier){let m=Le(t.trustTier,l.trustTier);if(!m.matched)return A({matched:!0,decision:"deny",reason:m.reason,reasonCode:"TIER_MISMATCH",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities)}if(c){let m=Le(t.trustTier,c);if(!m.matched)return A({matched:!0,decision:"deny",reason:m.reason,reasonCode:"TIER_MISMATCH",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},t.capabilities)}let g=Re(l.regoSource,_);if(g.matched){let m=Me(g.action);return A(K(je({matched:!0,decision:m,reason:`Matched rule: ${l.name}`,reasonCode:g.action==="allow"?"POLICY_ALLOW":"POLICY_DENY",ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},l,g.branchId),l,g.branchId),t.capabilities)}}if(a&&(l.appliesTo.includes("action")||l.appliesTo.includes("delegation"))){if(l.targetApp!==null&&l.targetApp!==t.targetApp||!cn(l.actionPattern,t.action??""))continue;let g=rn(l.regoSource,{target_app:t.targetApp??"",action:t.action??"",context:t.context,normalized:t.normalized,agent:t.agent,session:t.session??w});if(g.matched)return A(K(vn({matched:!0,decision:g.decision,reason:l.description??l.name,reasonCode:null,ruleId:l.id,ruleCode:l.ruleCode,ruleDescription:l.description},l,g.branchId),l,g.branchId),t.capabilities)}}return yn}function An(e,t=process.env){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let n=t.ALLOW_TIMEOUT_MS;if(n!==void 0){let r=Number.parseInt(n,10);if(Number.isFinite(r)&&r>0)return r}return 5e3}var wn=5e3,kn=1e4,et=1e3,In=512,Sn=1800*1e3,En="monitor",Cn=f.object({operations:f.array(f.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:f.string().min(1,"agentId is required"),sessionId:f.string().min(1).max(255).optional(),toolName:f.string().optional(),toolArgs:f.record(f.unknown()).optional(),targetResource:f.string().optional(),resourceType:f.string().optional(),resourceMetadata:f.record(f.unknown()).optional(),normalized:f.record(f.unknown()).optional(),query:f.string().optional(),contentPreview:f.string().optional(),telemetry:f.record(f.unknown()).optional()}),Tn=f.object({version:f.string().min(1),agent_mode:f.enum(["enforce","monitor","off"]).optional(),agent_attributes:f.object({trust_tier:f.string().nullable().optional(),categories:f.array(f.string()).optional(),business_function:f.string().nullable().optional(),no_coverage:f.string().nullable().optional()}).optional(),rules:f.array(f.record(f.unknown())),no_coverage:f.object({no_coverage_defaults:f.record(f.string()),autopilot_enabled:f.boolean(),enduser_hitl_enabled:f.boolean(),hitl_timeout_seconds:f.number().optional()}).optional()});function xn(e){let t=e.trust_tier??null,n=e.business_function??"";return{trust_tier:We(t)?t:null,categories:Ge(e.categories??[]),business_function:Ye(n)?n:null}}function tt(e){switch(e){case"permit":return 0;case"mask":case"redact":return 3;case"approval_required":case"escalate":return 4;case"deny":return 5;default:return 5}}function ne(e){let t=null;for(let n of e)(t===null||tt(n.decision)>tt(t.decision))&&(t=n);return t}function On(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}function Rn(e){switch(e){case"permit":return"allow";case"redact":return"redact";case"escalate":return"escalate";default:return"deny"}}var rt=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;agentMode=En;agentModeConfirmed=!1;telemetryBuffer=[];telemetryTimer=null;envRegistered=!1;registerPromise=null;constructor(e,t,n,r,i){let o=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,a=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,s=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";if(this.resolvedApiKey=o,this.resolvedEndpoint=a,this.resolvedAgentId=s,this.harnessKind=r,this.originalFetch=globalThis.fetch.bind(globalThis),o&&a){let c={apiKey:o,agentId:s,endpoint:a,mode:"enforce",timeoutMs:An(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{}};this.client=new we(c,this.originalFetch),this.initialBundlePromise=this.fetchBundleBackground(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},wn),nt(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},kn),nt(this.telemetryTimer)}else this.client=null}async evaluate(e){let t=Cn.parse(e),n=Date.now(),r=this.agentMode;if(r==="off")return this.offDecision(t);if(!this.bundleLoaded){let _=this.agentModeConfirmed&&(this.agentMode==="monitor"||this.agentMode==="off")?this.agentMode:"enforce",l=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(l,_,t,n)}let i=this.readSession(t.sessionId),o=[],a=[];for(let _ of t.operations){let l=this.resolveOperation(_,t,i);_==="retrieval"?a.push(l):o.push(l)}let s=ne(o),c=ne(a),p=ne([s,c].filter(_=>_!==null)),d=this.buildDecision(p,s,c,r);return this.foldSession(t,r==="enforce"?d.decision:"permit"),d.action.decision==="approval_required"&&r==="enforce"&&await this.registerHitl(t,d),this.applyAgentMode(d,r,t,n)}readSession(e){if(!e)return w;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Sn?(this.sessions.delete(e),w):t.state:w}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=a?X(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},c=Ke(r===w?He():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,action_class:a?s.action_class:void 0,target_app:a?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:c,touchedAt:Date.now()}),this.sessions.size>In){let p=this.sessions.keys().next().value;p!==void 0&&this.sessions.delete(p)}}resolveOperation(e,t,n){let r=Xe(this.rules,this.buildInput(e,t,n));if(r.matched)return r;if(e==="retrieval")return{...r,reason:"No matching rule \u2014 retrieval default deny (G001)"};if(this.noCoverage){let i=Je({action:t.toolName??t.targetResource??"",targetApp:t.targetResource??t.toolName??"",mode:"enforce",config:this.noCoverage,agentNoCoverage:this.agentNoCoverage});return{matched:!0,decision:i.decision,reason:i.reason,reasonCode:null,ruleId:null,ruleCode:i.rule_code,ruleDescription:null}}return{...r,reason:"No matching rule and no no-coverage config \u2014 fail-closed (G001)"}}buildInput(e,t,n){let r=t.toolName??"",i=t.targetResource??t.toolName??"",o=X(t.normalized??{},{action:r,targetApp:i}),a={agentId:t.agentId,agent:this.agentAttributes??$,session:n,normalized:o},s=this.agentAttributes?.trust_tier??null;return e==="retrieval"?{...a,facets:["retrieval"],targetApp:null,action:null,context:{},operation:"retrieve",resourceType:t.resourceType??t.targetResource??"",resourceMetadata:t.resourceMetadata??{},trustTier:s,surface:null,query:t.query??null,capabilities:{transformableResponse:!0}}:{...a,facets:[e==="delegation"?"delegation":"action"],targetApp:i,action:r,context:t.toolName?{[t.toolName]:t.toolArgs??{}}:{},operation:null,resourceType:null,resourceMetadata:null,trustTier:s,surface:null,query:null,capabilities:{transformableResponse:!1}}}buildDecision(e,t,n,r){let i=e?.decision??"deny",o=t?this.actionSub(t):{decision:null,allowed:!0},a=n?this.retrievalSub(n):{action:null};return{decision:i,allowed:i==="permit"||i==="mask"||i==="redact",reason:e?.reason??"No matching rule",ruleId:e?.ruleId??null,ruleCode:e?.ruleCode??null,enforced:r==="enforce",agentMode:r,action:o,retrieval:a}}actionSub(e){let t=e.decision;return t==="mask"?{decision:"mask",allowed:!0,argRedactionRules:e.redactionRules??[]}:t==="approval_required"?{decision:"approval_required",allowed:!1,...e.hitlFallback==="mask"&&e.redactionRules?{argRedactionRules:e.redactionRules,hitlFallback:"mask"}:{}}:t==="permit"?{decision:"permit",allowed:!0}:{decision:"deny",allowed:!1}}retrievalSub(e){let t=Rn(e.decision);return t==="redact"&&e.redactionRules?{action:t,redactionRules:e.redactionRules}:t==="escalate"&&e.hitlFallback==="mask"&&e.redactionRules?{action:t,redactionRules:e.redactionRules,hitlFallback:"mask"}:{action:t}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let a={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,a,i,!0),a}let o={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,o,i,!1),o}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){let t=Tn.parse(e);this.bundleLoaded&&t.version===this.bundleVersion||(this.rules=t.rules.map(n=>Qe(n)).filter(n=>n!==null),this.agentAttributes=t.agent_attributes?xn(t.agent_attributes):null,this.agentNoCoverage=ee(t.agent_attributes?.no_coverage),this.bundleVersion=t.version,this.bundleLoaded=!0,this.noCoverage=t.no_coverage?{no_coverage_defaults:t.no_coverage.no_coverage_defaults,autopilot_enabled:t.no_coverage.autopilot_enabled,enduser_hitl_enabled:t.no_coverage.enduser_hitl_enabled}:null,t.agent_mode!==void 0&&(this.agentMode=t.agent_mode,this.agentModeConfirmed=!0))}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json"};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag");r&&(this.bundleEtag=r);let i=await n.json();this.applyBundle(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(){this.registerEnvironment(ke())}bufferTelemetry(e,t,n,r){this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:On(t.decision),reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:{agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{}},...this.harnessKind?{context:{[ve]:this.harnessKind}}:{}}),this.enforceTelemetryCap()}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0);try{await this.client.sendTelemetry(e)}catch(t){console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",t)}}enforceTelemetryCap(){let e=this.telemetryBuffer.length-et;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${et})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry()}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.flushTelemetry()}};function nt(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function re(e){let t=[],n=[],r,i=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let c={mode:a.mode};a.field&&(c.field=a.field),a.pattern&&(c.pattern=a.pattern),typeof a.keepFirst=="number"&&(c.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(c.keepLast=a.keepLast),a.maskChar&&(c.maskChar=a.maskChar),a.keepPattern&&(c.keepPattern=a.keepPattern),a.replacement!==void 0&&(c.replacement=a.replacement),i.push(c);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:s}=a;s&&r===void 0&&(r=s)}let o={};return t.length>0&&(o.fields=t),n.length>0&&(o.patterns=n),r!==void 0&&(o.replacement=r),i.length>0&&(o.directives=i),o}var Nn="[VisIQ: retrieval withheld by policy]";function B(e){return ie(e)}function ie(e){if(e==null)return e;if(typeof e=="string")return e.length>0?Nn:e;if(typeof e=="number")return 0;if(typeof e=="boolean")return!1;if(Array.isArray(e))return e.map(ie);if(typeof e=="object"){let t=Object.create(null);for(let n of Object.keys(e))t[n]=ie(e[n]);return t}return e}function it(e){return e.fields&&e.fields.length>0||e.patterns&&e.patterns.length>0?!0:!!e.directives?.some(t=>t.field&&t.field.length>0||t.pattern&&t.pattern.length>0)}function at(e,t){if(!e.enforced)return null;let{action:n,retrieval:r}=e,i=I(e.reason,e.ruleCode);if(n.decision==="deny"||r.action==="deny")return F(i);if(n.decision==="approval_required"||r.action==="escalate")return ge(i);if(n.decision==="mask"&&n.argRedactionRules&&n.argRedactionRules.length>0){let o=re(n.argRedactionRules);if(it(o)){let a=V(t,o)??t;if(JSON.stringify(a)!==JSON.stringify(t))return me(a)}return null}return null}function ot(e,t){if(!e.enforced)return null;let{retrieval:n}=e,r=I(e.reason,e.ruleCode);if(n.action==="redact"){let i=re(n.redactionRules??[]);if(!it(i))return S(B(t),r);let o=V(t,i);return JSON.stringify(o)===JSON.stringify(t)?null:S(o,r)}return n.action==="deny"?S(B(t),r):null}var Pn="cli_harness";function C(e){return new rt(e.apiKey,e.baseUrl,e.agentId,Pn)}function W(e){let t={operations:e.operations,agentId:e.agentId,toolName:e.toolName,toolArgs:e.toolInput,resourceType:"tool_result",resourceMetadata:{toolName:e.toolName,...e.toolUseId?{toolCallId:e.toolUseId}:{},...e.sessionId?{sessionId:e.sessionId}:{},...e.cwd?{cwd:e.cwd}:{}}};return e.query&&(t.query=e.query),t}async function T(e,t,n=se){let{agentId:r}=t,i=await ce(r);if(i&&le(i,n,Date.now())&&ae(e,i.body))return;let o=e.getEndpoint();if(o){let a=await de(o,t.apiKey,r);if(a&&ae(e,a.body)){await ue(r,a.body,a.version);return}}if(!(i&&ae(e,i.body)))try{await e.awaitBundleReady(2500)}catch{}}function ae(e,t){try{return e.applyBundle(t),!0}catch{return!1}}async function x(e){try{await e.flush()}catch{}try{e.dispose()}catch{}}async function pr(e,t){let n=C(t),r=e.tool_input??{};try{await pe(e.session_id)||(n.registerHostEnvironment(),await P(e.session_id)),await T(n,t);let i=W({operations:fe(e.tool_name),agentId:t.agentId,toolName:e.tool_name,toolInput:r,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:L(r)}),o=await n.evaluate(i);return at(o,r)}catch{return F(I("evaluation error (fail-closed)",null))}finally{await x(n)}}async function yr(e,t){if(!z(e.tool_name))return null;let n=C(t);try{await T(n,t);let r=e.tool_input??{},i=W({operations:["retrieval"],agentId:t.agentId,toolName:e.tool_name,toolInput:r,sessionId:e.session_id,cwd:e.cwd,toolUseId:e.tool_use_id,query:L(r)}),o=await n.evaluate(i);return ot(o,e.tool_response)}catch{return S(B(e.tool_response),I("evaluation error (fail-closed)",null))}finally{await x(n)}}async function wr(e,t){let n=C(t);try{n.registerHostEnvironment(),await T(n,t,0),await P(e.session_id)}finally{await x(n)}return null}export{ct as a,z as b,fe as c,L as d,I as e,me as f,F as g,ge as h,S as i,Fn as j,Nn as k,B as l,at as m,ot as n,Pn as o,C as p,W as q,T as r,x as s,pr as t,yr as u,wr as v};
|