@visiq/harness 0.2.0 → 0.2.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/dist/index.d.ts +23 -2
- package/dist/index.js +4 -6
- package/package.json +1 -2
package/dist/index.d.ts
CHANGED
|
@@ -14,10 +14,19 @@ export interface VisiqOptions {
|
|
|
14
14
|
/**
|
|
15
15
|
* Max time (ms) to wait for a human to resolve an ALLOW `approval_required`
|
|
16
16
|
* (HITL) decision before failing closed and blocking the tool call. Falls
|
|
17
|
-
* back to the VISIQ_HITL_TIMEOUT_MS env var, then to
|
|
18
|
-
* matching the backend's `
|
|
17
|
+
* back to the VISIQ_HITL_TIMEOUT_MS env var, then to 120_000ms (2 min) —
|
|
18
|
+
* matching the backend's 120s `hitl_timeout_seconds` ceiling.
|
|
19
19
|
*/
|
|
20
20
|
hitlTimeoutMs?: number;
|
|
21
|
+
/**
|
|
22
|
+
* Per-evaluate network timeout (ms) before the ALLOW pre-gate fails CLOSED
|
|
23
|
+
* (G001) on a stuck/slow backend. Falls back to the VISIQ_TIMEOUT_MS env var,
|
|
24
|
+
* then to the SDK runtime default (5s). Raise it for high-latency paths
|
|
25
|
+
* (cross-region CI → deployed backend, or the approval_required path that
|
|
26
|
+
* dispatches a channel notification inline) — fail-closed semantics are
|
|
27
|
+
* unchanged; this only sets the patience before a network failure denies.
|
|
28
|
+
*/
|
|
29
|
+
timeoutMs?: number;
|
|
21
30
|
}
|
|
22
31
|
export interface DelegateOptions {
|
|
23
32
|
/** Restrict the child's tool calls to this allow-list. `undefined` inherits parent's full scope. */
|
|
@@ -88,6 +97,18 @@ export interface FleetStatusResponse {
|
|
|
88
97
|
}
|
|
89
98
|
export interface DeployFleetInput {
|
|
90
99
|
includeMac?: boolean;
|
|
100
|
+
/**
|
|
101
|
+
* Override the tenant's discovery_settings default for whether the on-host
|
|
102
|
+
* agent auto-installs the VisIQ harness plugin into detected agentic
|
|
103
|
+
* frameworks. When omitted, the deploy route falls back to the tenant's
|
|
104
|
+
* `discovery_settings.auto_install_harness` (default false).
|
|
105
|
+
*
|
|
106
|
+
* The demo sets this to `false` explicitly so a fleet launched off a sha
|
|
107
|
+
* staged by a fleet-e2e run (which stages only the core
|
|
108
|
+
* discovery+delivery binaries, NOT the openclaw driver/plugin tarball) still
|
|
109
|
+
* boots cleanly instead of 404-ing on the missing harness artifacts.
|
|
110
|
+
*/
|
|
111
|
+
autoInstallHarness?: boolean;
|
|
91
112
|
}
|
|
92
113
|
export interface DeployFleetResponse {
|
|
93
114
|
tenant_id: string;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import{randomUUID as
|
|
2
|
-
`).map(l=>ze(l)).filter(l=>l.trim().length>0),s=0;for(;s<i.length;){let l=i[s].trim();if(l.startsWith("package ")||l.startsWith("import ")){s++;continue}let c=l.match(/^default\s+(\w+)\s*=\s*(.+)$/);if(c){let p=c[1],f=c[2].trim();n.set(p,$(f)),s++;continue}let d=l.match(/^(\w+)\s*=\s*(.+?)\s*\{(.*)$/);if(d){let p=d[1],f=d[2].trim(),y=d[3].trim(),T=[];if(y&&y!=="}"){let ne=y.endsWith("}")?y.slice(0,-1).trim():y;ne&&T.push(ne),y.endsWith("}")||(s++,s=P(i,s,T))}else y==="}"||(s++,s=P(i,s,T));let A=oe(T);o.push({variable:p,value:$(f),conditions:A}),s++;continue}let g=l.match(/^(\w+)\s*\{(.*)$/);if(g){let p=g[1],f=g[2].trim(),y=[];if(f&&f!=="}"){let A=f.endsWith("}")?f.slice(0,-1).trim():f;A&&y.push(A),f.endsWith("}")||(s++,s=P(i,s,y))}else f==="}"||(s++,s=P(i,s,y));let T=oe(y);o.push({variable:p,value:"true",conditions:T}),s++;continue}s++}let a={defaults:n,rules:o};return re.set(t,a),a}function Ue(e,t){let r={};for(let[n,o]of e.defaults)r[n]=o;for(let n=0;n<e.rules.length;n++){let o=e.rules[n];if(o.conditions.every(i=>Je(i,t)))return r[o.variable]=o.value,{bindings:r,matched:!0,matchedRuleIndex:n}}return{bindings:r,matched:!1,matchedRuleIndex:-1}}function ze(e){let t=!1,r="";for(let n=0;n<e.length;n++){let o=e[n];if(t)o===r&&e[n-1]!=="\\"&&(t=!1);else if(o==='"'||o==="'")t=!0,r=o;else if(o==="#")return e.slice(0,n)}return e}function P(e,t,r){let n=1,o=t;for(;o<e.length&&n>0;){let i=e[o].trim();for(let s of i)s==="{"&&n++,s==="}"&&n--;if(n>0)r.push(i),o++;else{let s=i.slice(0,i.lastIndexOf("}")).trim();return s&&r.push(s),o}}return o}function $(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function oe(e){let t=[];for(let r of e){let n=r.split(";").map(o=>o.trim()).filter(o=>o.length>0);for(let o of n){let i=Ye(o);i&&t.push(i)}}return t}function Ye(e){let t=!1,r=e.trim();r.startsWith("not ")&&(t=!0,r=r.slice(4).trim());let n=r.match(/^count\(([^)]+)\)\s*>\s*(\d+)$/);if(n)return{type:"count_gt",negated:t,field:n[1].trim(),value:parseInt(n[2],10)};let o=r.match(/^startswith\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"startswith",negated:t,field:o[1].trim(),value:o[2]};let i=r.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(i)return{type:"endswith",negated:t,field:i[1].trim(),value:i[2]};let s=r.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(s)return{type:"contains",negated:t,field:s[1].trim(),value:s[2]};let a=r.match(/^([^\s=!]+)\s*==\s*(.+)$/);if(a)return{type:"equality",negated:t,field:a[1].trim(),value:$(a[2].trim())};let l=r.match(/^([^\s=!]+)\s*!=\s*(.+)$/);if(l)return{type:"inequality",negated:t,field:l[1].trim(),value:$(l[2].trim())};let c=r.match(/^(input\.[a-zA-Z0-9_.]+)$/);return c?{type:"truthy",negated:t,field:c[1].trim()}:{type:"truthy",negated:!1,field:"__unrecognized_condition_forces_deny__"}}function Je(e,t){let r;switch(e.type){case"equality":{let n=_(e.field,t);r=String(n)===String(e.value);break}case"inequality":{let n=_(e.field,t);r=String(n)!==String(e.value);break}case"startswith":{let n=_(e.field,t);typeof n!="string"?r=!1:r=n.startsWith(String(e.value));break}case"endswith":{let n=_(e.field,t);typeof n!="string"?r=!1:r=n.endsWith(String(e.value));break}case"contains":{let n=_(e.field,t);typeof n!="string"?r=!1:r=n.includes(String(e.value));break}case"truthy":{let n=_(e.field,t);r=Xe(n);break}case"count_gt":{let n=_(e.field,t),o=typeof e.value=="number"?e.value:0;Array.isArray(n)||typeof n=="string"?r=n.length>o:n&&typeof n=="object"?r=Object.keys(n).length>o:r=!1;break}default:r=!1}return e.negated?!r:r}function _(e,t){let r=(e.startsWith("input.")?e.slice(6):e).split("."),n=t;for(let o of r){if(n==null||typeof n!="object")return;n=n[o]}return n}function Xe(e){return!(e==null||e===!1||e===0||e==="")}function Ze(e,t){if(!e||e.trim().length===0)return{decision:"permit",matched:!0};try{let r=Qe(e),n=Ue(r,{target_app:t.target_app,action:t.action,...t.context,normalized:t.normalized??{}});if(!n.matched)return{decision:"deny",matched:!1};let o=n.bindings.decision;return o!==void 0?{decision:et(o),matched:!0}:n.bindings.approval_required==="true"?{decision:"approval_required",matched:!0}:n.bindings.allow==="true"?{decision:"permit",matched:!0}:{decision:"deny",matched:!0}}catch{return{decision:"deny",matched:!1}}}function et(e){switch(e){case"permit":case"allow":return"permit";case"deny":return"deny";case"approval_required":return"approval_required";default:return"deny"}}function tt(e,t){if(!e||e==="*")return!0;if(e.endsWith("*")){let r=e.slice(0,-1);return t.startsWith(r)}return e===t}function ie(e,t){let r=[...e].sort((n,o)=>o.priority-n.priority);for(let n of r){if(n.target_app!==null&&n.target_app!==t.target_app||!tt(n.action_pattern,t.action))continue;let o=Ze(n.rego_source,t);if(o.matched)return{decision:o.decision,reason:n.description??n.name,rule_id:n.id,rule_code:n.rule_code,description:n.description,matchedRule:!0}}return{decision:"deny",reason:"No matching rule",rule_id:null,rule_code:null,description:null,matchedRule:!1}}var nt=w.object({agentId:w.string().min(1,"agentId is required"),toolName:w.string().min(1,"toolName is required"),toolArgs:w.record(w.unknown()),targetResource:w.string().optional(),context:w.record(w.unknown()).optional(),telemetry:w.record(w.unknown()).optional()}),yn=w.object({allowed:w.boolean(),reason:w.string(),ruleId:w.string().optional(),ruleCode:w.string().optional(),description:w.string().optional(),enforced:w.boolean().optional(),decision:w.enum(["permit","deny","approval_required"]).optional(),decisionId:w.string().optional()});var rt=u.enum(["enforce","audit","off"]),ot=u.enum(["closed","open"]),le=u.enum(["enforce","monitor","off"]),vn=u.object({apiKey:u.string().min(1,"apiKey is required"),agentId:u.string().min(1,"agentId is required"),endpoint:u.string().url().optional(),mode:rt.optional(),timeoutMs:u.number().int().positive().optional(),hitlTimeoutMs:u.number().int().positive().optional(),failBehavior:ot.optional()}),Tn=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(),telemetry:u.record(u.unknown()).optional()}),it=u.object({decision_id:u.string().min(1),decision:u.enum(["permit","deny","approval_required"]),reason:u.string().optional(),rule_code:u.string().nullable().optional(),enforced:u.boolean().optional(),agent_mode:le.optional(),metadata:u.record(u.unknown()).optional()}),st=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())])}),at=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"]),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(st).default([]),priority:u.number().int().default(0)}),lt=u.object({version:u.string().min(1),agent_mode:le.default("monitor"),rules:u.array(at)}),ct=2e3,ut=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}async evaluate(e){let t=new AbortController,r=setTimeout(()=>t.abort(),this.config.timeoutMs),n;try{n=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(r)}if(!n.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${n.status} ${n.statusText}`);let o=await n.json();return it.parse(o)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,r=new AbortController,n=setTimeout(()=>r.abort(),this.config.timeoutMs),o;try{o=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json"},signal:r.signal})}finally{clearTimeout(n)}if(!o.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${o.status} ${o.statusText}`);let i=await o.json();return lt.parse(i)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`;try{let r=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decisions:e})});r.ok||console.warn(`[ALLOW] Telemetry delivery failed: HTTP ${r.status} ${r.statusText}`)}catch(r){console.warn("[ALLOW] Telemetry delivery failed:",r)}}async reportExecutionResult(e,t,r){let n=`${this.config.endpoint}/allow/execution-events`;try{let o=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decision_id:e,result:t,details:r})});o.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${o.status}`)}catch(o){console.warn("[ALLOW] Execution result report failed:",o)}}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 r=new AbortController,n=setTimeout(()=>r.abort(),this.config.timeoutMs),o;try{o=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`},signal:r.signal})}finally{clearTimeout(n)}if(!o.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${o.status} ${o.statusText}`);let i=await o.json();if(typeof i!="object"||i===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let s=i,a=s.hitl_result;if(a==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(a==="rejected")return{decision_id:e,decision:"deny",reason:typeof s.reason=="string"?s.reason:"Rejected by human reviewer"};if(a==="timeout"||a==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await dt(ct)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function dt(e){return new Promise(t=>setTimeout(t,e))}var pt=class{endpoint;apiKey;agentId;originalFetch;onModeChanged;abortController=null;reconnectTimer=null;backoffMs=1e3;stableTimer=null;stopped=!1;constructor(e){this.endpoint=e.endpoint,this.apiKey=e.apiKey,this.agentId=e.agentId,this.originalFetch=e.originalFetch,this.onModeChanged=e.onModeChanged}start(){if(this.stopped)throw new Error("AgentModeStream cannot be restarted after stop()");this.connect()}stop(){this.stopped=!0,this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stableTimer!==null&&(clearTimeout(this.stableTimer),this.stableTimer=null),this.abortController!==null&&(this.abortController.abort(),this.abortController=null)}async connect(){if(this.stopped)return;let e=new AbortController;this.abortController=e;let t=`${this.endpoint}/allow/agents/me/stream?agent_id=${encodeURIComponent(this.agentId)}`,r;try{r=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.apiKey}`,Accept:"text/event-stream","Cache-Control":"no-cache"},signal:e.signal})}catch(n){this.scheduleReconnect(`connection failed: ${se(n)}`);return}if(!r.ok){this.scheduleReconnect(`HTTP ${r.status} ${r.statusText}`);return}if(!r.body){this.scheduleReconnect("no response body");return}this.stableTimer=setTimeout(()=>{this.backoffMs=1e3,this.stableTimer=null},3e4);try{await this.readLoop(r.body.getReader())}catch(n){if(this.stopped)return;this.scheduleReconnect(`read loop failed: ${se(n)}`);return}this.stopped||this.scheduleReconnect("stream ended")}async readLoop(e){let t=new TextDecoder("utf-8"),r="";for(;;){let{value:n,done:o}=await e.read();if(o)break;if(this.stopped)return;r+=t.decode(n,{stream:!0});let i;for(;(i=r.indexOf(`
|
|
3
|
-
|
|
4
|
-
`))!==-1;){let s=r.slice(0,i);r=r.slice(i+2),this.handleEvent(s)}}}handleEvent(e){let t="message",r=[];for(let i of e.split(`
|
|
5
|
-
`)){if(i===""||i.startsWith(":"))continue;let s=i.indexOf(":");if(s===-1)continue;let a=i.slice(0,s),l=i.slice(s+1);l.startsWith(" ")&&(l=l.slice(1)),a==="event"?t=l:a==="data"&&r.push(l)}if(r.length===0||t!=="mode_changed"&&t!=="mode_snapshot")return;let n;try{n=JSON.parse(r.join(`
|
|
6
|
-
`))}catch{return}if(n===null||typeof n!="object"||!("agent_mode"in n))return;let o=n.agent_mode;if(!(o!=="enforce"&&o!=="monitor"&&o!=="off"))try{this.onModeChanged(o)}catch(i){console.error("[ALLOW] mode_changed listener threw:",i)}}scheduleReconnect(e){if(this.stopped)return;this.stableTimer!==null&&(clearTimeout(this.stableTimer),this.stableTimer=null),this.abortController!==null&&(this.abortController=null);let t=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*2,3e4),console.warn(`[ALLOW] mode stream disconnected (${e}); reconnecting in ${t}ms`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},t),this.reconnectTimer!==null&&typeof this.reconnectTimer.unref=="function"&&this.reconnectTimer.unref()}};function se(e){return e instanceof Error?e.message:String(e)}var ft=5e3,mt=1e4,ht="monitor",ce=class{client;resolvedApiKey;resolvedEndpoint;resolvedAgentId;deferHitl;rules=[];bundleVersion=null;bundleFetchInProgress=!1;refreshTimer=null;telemetryBuffer=[];telemetryTimer=null;agentMode=ht;modeStream=null;constructor(e,t,r,n){let o=e??process.env.ALLOW_API_KEY,i=t??process.env.ALLOW_ENDPOINT,s=r??process.env.ALLOW_AGENT_ID??process.env.VISIQ_AGENT_ID??"";if(this.resolvedApiKey=o,this.resolvedEndpoint=i,this.resolvedAgentId=s,this.deferHitl=n?.deferHitl??!1,o&&i){let a={apiKey:o,agentId:s,endpoint:i,mode:"enforce",timeoutMs:5e3,hitlTimeoutMs:3e5,failBehavior:"closed"},l=globalThis.fetch.bind(globalThis);this.client=new ut(a,l),this.fetchBundleBackground(),this.refreshTimer=setInterval(()=>this.fetchBundleBackground(),ft),ae(this.refreshTimer),this.telemetryTimer=setInterval(()=>this.flushTelemetry(),mt),ae(this.telemetryTimer),s&&(this.modeStream=new pt({endpoint:i,apiKey:o,agentId:s,originalFetch:l,onModeChanged:c=>{this.agentMode=c}}),this.modeStream.start())}else this.client=null}async evaluate(e){let t=nt.parse(e),r=Date.now(),n=this.agentMode;if(n==="off")return{allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",enforced:!1};if(this.rules.length>0){let o=ie(this.toMatchable(),this.toMatchInput(t));if(o.matchedRule){if(o.decision==="approval_required"){if(this.client){let s=await this.evaluateRemote(t,r);return this.applyAgentMode(s,n,t,r,"remote")}return this.applyAgentMode({allowed:!1,reason:`${o.reason} (human approval required \u2014 no backend configured)`,...o.rule_id?{ruleId:o.rule_id}:{},...o.rule_code?{ruleCode:o.rule_code}:{},...o.description?{description:o.description}:{}},n,t,r,"local")}let i={allowed:o.decision==="permit",reason:o.reason,...o.rule_id?{ruleId:o.rule_id}:{},...o.rule_code?{ruleCode:o.rule_code}:{},...o.description?{description:o.description}:{}};return this.applyAgentMode(i,n,t,r,"local")}if(this.client){let i=await this.evaluateRemote(t,r);return this.applyAgentMode(i,n,t,r,"remote")}return this.applyAgentMode({allowed:!1,reason:"No matching ALLOW rule and no backend configured \u2014 fail-closed (G001)"},n,t,r,"local")}if(this.client){let o=await this.evaluateRemote(t,r);return this.applyAgentMode(o,n,t,r,"remote")}return this.applyAgentMode({allowed:!1,reason:"No ALLOW rules loaded and no backend configured \u2014 fail-closed (G001)"},n,t,r,"local")}hasRules(){return this.rules.length>0}hasClient(){return this.client!==null}getBundleVersion(){return this.bundleVersion}getAgentMode(){return this.agentMode}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.modeStream&&(this.modeStream.stop(),this.modeStream=null),this.flushTelemetry().catch(e=>{console.error("[AllowRuntime] final telemetry flush failed during destroy (non-fatal):",e)})}applyAgentMode(e,t,r,n,o){let i=Date.now()-n;return t==="enforce"?(this.bufferTelemetry(r,e,i,o,!0),{...e,enforced:!0}):(this.bufferTelemetry(r,e,i,o,!1),{allowed:!0,reason:e.reason,...e.ruleId!==void 0?{ruleId:e.ruleId}:{},...e.ruleCode!==void 0?{ruleCode:e.ruleCode}:{},...e.description!==void 0?{description:e.description}:{},enforced:!1})}toMatchable(){return this.rules.map(e=>({id:e.id,rule_code:e.rule_code||null,name:e.name,description:e.description,rego_source:e.rego_source??null,target_app:e.target_app??null,action_pattern:e.action_pattern??null,priority:e.priority}))}toMatchInput(e){return{target_app:e.targetResource??e.toolName,action:e.toolName,context:{[e.toolName]:e.toolArgs,...e.context??{}},normalized:{}}}async evaluateRemote(e,t){if(!this.client)return{allowed:!1,reason:"No backend configured \u2014 fail-closed (G001)"};try{let r={agent_id:e.agentId,target_app:e.targetResource??e.toolName,action:e.toolName,context:{[e.toolName]:e.toolArgs,...e.context},telemetry:e.telemetry},n=await this.client.evaluate(r);if(n.decision==="approval_required"&&n.decision_id){if(this.deferHitl)return{allowed:!1,reason:n.reason??"Human approval required",decision:"approval_required",decisionId:n.decision_id,...n.rule_code?{ruleCode:n.rule_code}:{}};let o=await this.client.waitForApproval(n.decision_id);return{allowed:o.decision==="permit",reason:o.reason??"HITL decision",...n.rule_code?{ruleCode:n.rule_code}:{}}}return{allowed:n.decision==="permit",reason:n.reason??`Backend: ${n.decision}`,...n.rule_code?{ruleCode:n.rule_code}:{}}}catch(r){return console.warn("[ALLOW] Network evaluation failed \u2014 denying (G001):",r),{allowed:!1,reason:`Network evaluation failed \u2014 fail-closed (G001) [${Date.now()-t}ms]`}}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.client)){this.bundleFetchInProgress=!0;try{let e=await this.client.fetchBundle();e.version!==this.bundleVersion&&(this.rules=e.rules,this.bundleVersion=e.version),this.agentMode=e.agent_mode}catch(e){this.bundleVersion?console.warn("[ALLOW] Bundle refresh failed (using cached rules):",e):console.warn("[ALLOW] Initial bundle fetch failed (will use network evaluation):",e)}finally{this.bundleFetchInProgress=!1}}}bufferTelemetry(e,t,r,n,o){if(n==="remote")return;let i={agent_id:e.agentId,tool_name:e.toolName,target_resource:e.targetResource,...G(e.toolArgs,e.toolName),...G(e.context??{})};this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName,action:e.toolName,decision:t.allowed?"permit":"deny",reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId??null,rule_code:t.ruleCode??null,enforced:o,agent_mode:this.agentMode,latency_ms:r,evaluation_mode:n,raw_event:i})}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("[AllowRuntime] telemetry flush failed (non-fatal):",t)}}};function G(e,t=""){let r={};for(let[n,o]of Object.entries(e)){let i=t?`${t}/${n}`:n;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(r,G(o,i)):r[i]=o}return r}function ae(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function W(e){if(e===null||typeof e!="object"||Array.isArray(e))return{input:e===void 0?"":String(e)};let t=e,r=Object.keys(t);return r.length===1&&r[0]==="context"&&t.context!==null&&typeof t.context=="object"?t.context:t}function ue(e){if(typeof e=="string"){try{let t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{input:e}}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{input:e===void 0?"":String(e)}}import{z as m}from"zod";import{z as h}from"zod";var gt=m.enum(["enforce","audit","off"]),yt=m.enum(["allow","redact","deny","escalate"]),de=m.object({agentId:m.string().min(1,"agentId is required"),agentRole:m.string().optional(),trustTier:m.number().int().min(1).max(3).optional(),operation:m.enum(["retrieve","tool_call","prompt_render"]),resourceType:m.enum(["document","tool_result","prompt"]),resourceMetadata:m.record(m.unknown()),query:m.string().optional(),contentPreview:m.string().optional(),telemetry:m.record(m.unknown()).optional()}),En=m.object({action:yt,reason:m.string(),ruleId:m.string().optional(),redactionRules:m.array(m.object({field:m.string(),pattern:m.string(),replacement:m.string()})).optional(),metadata:m.record(m.unknown()).optional()}),wt=m.object({apiKey:m.string().optional(),endpoint:m.string().url().optional(),mode:gt.optional(),wasmPath:m.string().optional(),bundleUrl:m.string().url().optional(),syncIntervalMs:m.number().int().positive().optional(),telemetryEnabled:m.boolean().optional(),timeoutMs:m.number().int().positive().optional()}),pe="https://project-y-backend-mnxz.onrender.com",fe="enforce",me=6e4,he=!0,ge=5e3;function _e(e){let t={apiKey:e.apiKey||process.env.RECALL_API_KEY||"",endpoint:e.endpoint||process.env.RECALL_ENDPOINT||pe,mode:e.mode||vt(process.env.RECALL_MODE)||fe,wasmPath:e.wasmPath||process.env.RECALL_WASM_PATH,bundleUrl:e.bundleUrl||process.env.RECALL_BUNDLE_URL,syncIntervalMs:e.syncIntervalMs!==void 0?e.syncIntervalMs:ye(process.env.RECALL_SYNC_INTERVAL_MS)??me,telemetryEnabled:e.telemetryEnabled!==void 0?e.telemetryEnabled:Tt(process.env.RECALL_TELEMETRY_ENABLED)??he,timeoutMs:e.timeoutMs!==void 0?e.timeoutMs:ye(process.env.RECALL_TIMEOUT_MS)??ge},r=wt.parse(t);return{apiKey:r.apiKey??"",endpoint:r.endpoint??pe,mode:r.mode??fe,wasmPath:r.wasmPath,bundleUrl:r.bundleUrl,syncIntervalMs:r.syncIntervalMs??me,telemetryEnabled:r.telemetryEnabled??he,timeoutMs:r.timeoutMs??ge}}function vt(e){if(e==="enforce"||e==="audit"||e==="off")return e;if(e!==void 0)throw new Error(`Invalid RECALL_MODE env var: "${e}". Must be one of: enforce, audit, off`)}function ye(e){if(e===void 0)return;let t=parseInt(e,10);if(isNaN(t)||t<=0)throw new Error(`Invalid numeric env var value: "${e}". Must be a positive integer.`);return t}function Tt(e){if(e===void 0)return;let t=e.toLowerCase().trim();return t==="true"||t==="1"||t==="yes"}function _t(e,t){let r=e;for(let n of t)try{let o=It(n.pattern);r=r.replace(o,n.replacement)}catch(o){console.warn("[RECALL] redactText: skipping malformed redaction rule:",o)}return r}function It(e){if(e instanceof RegExp){let r=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,r)}let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(t,"g")}var B={action:"deny",reason:"No RECALL policy loaded \u2014 fail-closed (G001)"},I={action:"deny",reason:"RECALL policy evaluation error \u2014 fail-closed (G001)"},Ie=class{config;client;telemetry;policy=null;policyVersion=null;policyData={};constructor(e,t=null,r=null){this.config=e,this.client=t,this.telemetry=r}async loadBundle(e,t,r){let{loadPolicy:n}=await import("@open-policy-agent/opa-wasm"),o=await n(e);o.setData(t),this.policy=o,this.policyData=t,this.policyVersion=r??null}evaluate(e){let t=de.parse(e);if(this.policy===null)return B;let r=Date.now();try{let n=we(t),o=this.policy.evaluate(n),i=ve(o);return this.recordTelemetry(t,i,Date.now()-r,"wasm"),i}catch(n){return console.warn("[RECALL] WASM policy evaluation error \u2014 denying (G001):",n),this.recordTelemetry(t,I,Date.now()-r,"wasm"),I}}async evaluateAsync(e){if(this.config.mode==="off")return{action:"allow",reason:"RECALL mode is off"};let t=de.parse(e),r=Date.now();if(this.policy!==null)try{let n=we(t),o=this.policy.evaluate(n),i=ve(o);return this.recordTelemetry(t,i,Date.now()-r,"wasm"),this.config.mode==="audit"?{action:"allow",reason:`audit: would have ${i.action}`}:i}catch(n){console.warn("[RECALL] WASM evaluation error, falling back to HTTP:",n)}if(this.client!==null)try{let n=await this.client.evaluate(t);return this.recordTelemetry(t,n,Date.now()-r,"remote"),this.config.mode==="audit"?{action:"allow",reason:`audit: would have ${n.action}`}:n}catch(n){return console.warn("[RECALL] Server-side evaluation failed \u2014 denying (G001):",n),this.recordTelemetry(t,I,Date.now()-r,"remote"),I}return this.recordTelemetry(t,B,Date.now()-r,"wasm"),B}async filterDocuments(e,t,r){if(this.config.mode==="off")return t;if(!e||e.trim()==="")return console.warn("[RECALL] filterDocuments called with empty agentId \u2014 denying all (G001)"),[];let n=[];for(let o of t){let i;try{i=r(o)}catch(l){console.warn("[RECALL] extractMeta threw \u2014 excluding document (G001):",l);continue}let s={agentId:e,operation:"retrieve",resourceType:"document",resourceMetadata:i},a;try{a=await this.evaluateAsync(s)}catch(l){console.warn("[RECALL] Unexpected error in evaluateAsync \u2014 excluding document (G001):",l);continue}switch(a.action){case"allow":case"escalate":n.push(o);break;case"redact":{if(a.redactionRules&&a.redactionRules.length>0){let l=bt(o,a.redactionRules);n.push(l)}else n.push(o);break}case"deny":break;default:{let l=a.action;break}}}return n}getPolicyVersion(){return this.policyVersion}hasPolicy(){return this.policy!==null}recordTelemetry(e,t,r,n){if(this.telemetry!==null)try{this.telemetry.record({agentId:e.agentId,evaluatedAt:new Date().toISOString(),input:e,decision:t,latencyMs:r,evaluationMode:n})}catch{}}};function we(e){return{agent_id:e.agentId,agent_role:e.agentRole,trust_tier:e.trustTier,operation:e.operation,resource_type:e.resourceType,resource_metadata:e.resourceMetadata,query:e.query,content_preview:e.contentPreview}}function ve(e){if(!Array.isArray(e)||e.length===0)return I;let t=e[0]?.result;if(t===null||typeof t!="object")return I;let r=t,{action:n}=r;if(n!=="allow"&&n!=="redact"&&n!=="deny"&&n!=="escalate")return I;let o=typeof r.reason=="string"?r.reason:"Policy decision",i=typeof r.rule_id=="string"?r.rule_id:void 0,s;if(Array.isArray(r.redaction_rules)){s=[];for(let a of r.redaction_rules)if(a!==null&&typeof a=="object"&&typeof a.field=="string"&&typeof a.pattern=="string"&&typeof a.replacement=="string"){let l=a;s.push({field:l.field,pattern:l.pattern,replacement:l.replacement})}}return{action:n,reason:o,ruleId:i,redactionRules:s}}function bt(e,t){if(e===null||typeof e!="object")return e;let r={...e};for(let n of t){let o=r[n.field];typeof o=="string"&&(r[n.field]=_t(o,[{pattern:n.pattern,replacement:n.replacement}]))}return r}var kt=h.object({decision_id:h.string().min(1),decision:h.enum(["allow","redact","deny","escalate"]),reason_code:h.string().optional(),reason:h.string().optional(),receipt_id:h.string().optional(),rule_id:h.string().optional(),redaction_rules:h.array(h.object({field:h.string().optional(),pattern:h.string().optional(),replacement:h.string().optional()})).optional()}),At=h.object({id:h.string().min(1),name:h.string().min(1),rego_source:h.string().min(1),trust_tier:h.string().nullable(),surface:h.string().nullable(),principal_exclusions:h.array(h.string()),priority:h.number()}),Rt=h.object({version:h.string().min(1),rules:h.array(At)}),be=class{config;constructor(e){this.config=e}async evaluate(e){let t=new AbortController,r=setTimeout(()=>t.abort(),this.config.timeoutMs),n=e.trustTier!==void 0?`tier${e.trustTier}`:void 0,o={agent_id:e.agentId,operation:e.operation,resource_type:e.resourceType,resource_metadata:e.resourceMetadata,trust_tier:n,surface:e.resourceMetadata?.surface,query:e.query,telemetry:e.telemetry},i;try{i=await fetch(`${this.config.endpoint}/recall/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),signal:t.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`RECALL evaluate request failed: HTTP ${i.status} ${i.statusText}`);let s=await i.json(),a=kt.parse(s),l=a.redaction_rules?.map(c=>({field:c.field??"",pattern:c.pattern??"",replacement:c.replacement??"[REDACTED]"}));return{action:a.decision,reason:a.reason??a.reason_code??"",ruleId:a.rule_id,...l?{redactionRules:l}:{}}}async fetchBundle(){let e=new AbortController,t=setTimeout(()=>e.abort(),this.config.timeoutMs),r;try{r=await fetch(`${this.config.endpoint}/recall/rules/bundle`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json"},signal:e.signal})}finally{clearTimeout(t)}if(!r.ok)throw new Error(`RECALL bundle fetch failed: HTTP ${r.status} ${r.statusText}`);let n=await r.json(),o=Rt.parse(n);return{rules:o.rules,version:o.version}}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/recall/telemetry`;try{let r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({events:e})});r.ok||console.warn(`[RECALL] Telemetry delivery failed: HTTP ${r.status} ${r.statusText}`)}catch(r){console.warn("[RECALL] Telemetry delivery failed:",r)}}};var Et=["documents","sources","results"];async function ke(e,t,r){let n=o=>({...o.metadata??{},content_preview:xt(o).slice(0,500)});if(Array.isArray(e)&&Te(e))return r.filterDocuments(t,e,n);if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let o=e,i={...o},s=!1;for(let a of Et){let l=o[a];Array.isArray(l)&&Te(l)&&(i[a]=await r.filterDocuments(t,l,n),s=!0)}if(s)return i}return e}function Te(e){return e.length===0?!1:e.every(t=>t!==null&&typeof t=="object"&&(typeof t.pageContent=="string"||typeof t.text=="string"||typeof t.content=="string"))}function xt(e){return String(e.pageContent??e.text??e.content??"")}var Ae="[REDACTED]";function Q(e,t){return e==null?e:typeof e=="string"?Re(e,t):typeof e=="object"?St(e,t):e}function Re(e,t){if(typeof e!="string")return e;let{patterns:r}=t;if(!r||r.length===0)return e;let n=t.replacement??Ae,o=e;for(let i of r){if(typeof i!="string"||i.length===0)continue;let s;try{s=new RegExp(i,"g")}catch(a){let l=a instanceof Error?a.message:String(a);throw new Error(`[visiq-redact] Invalid redaction pattern "${i}": ${l}`)}o=o.replace(s,n)}return o}function St(e,t){let r=new Set(t.fields??[]),n=t.replacement??Ae,o=r.size>0,i=(t.patterns??[]).length>0,s=a=>{if(a==null)return a;if(Array.isArray(a))return a.map(l=>s(l));if(typeof a=="object"){let l=a,c={};for(let d of Object.keys(l)){if(o&&r.has(d)){c[d]=n;continue}c[d]=s(l[d])}return c}return typeof a=="string"&&i?Re(a,t):a};return s(e)}import{z as j}from"zod";var Lt=j.object({decision:j.enum(["permit","deny"]),reason:j.string(),handoff_event_id:j.string().nullable()}),b=class extends Error{constructor(e,t,r){super(e),this.code=t,this.status=r,this.name="OrchestrateError"}code;status},R=class extends b{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},Ct="https://api.visiqlabs.com",Ot=1e4,E=class{config;fetch;constructor(e,t=globalThis.fetch){this.config={agentId:e.agentId,apiKey:e.apiKey??process.env.VISIQ_API_KEY??"",endpoint:e.endpoint??process.env.VISIQ_ENDPOINT??Ct,timeoutMs:e.timeoutMs??Ot},this.fetch=t}get headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Agent-ID":this.config.agentId}}async post(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(),this.config.timeoutMs),o;try{o=await this.fetch(`${this.config.endpoint}${e}`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:r.signal})}finally{clearTimeout(n)}let i=await o.json();if(!o.ok){let s=i?.error??`HTTP ${o.status}`;throw new b(s,"API_ERROR",o.status)}return i}async requestGrant(e){let t=await this.post("/orchestrate/grants",{parent_agent_id:e.parentAgentId,child_agent_id:e.childAgentId,tool_scope:e.toolScope??null,context_scope:e.contextScope??null,purpose:e.purpose,duration_seconds:e.durationSeconds,max_depth:e.maxDepth,parent_grant_token:e.parentGrantToken});return{grantId:t.grant_id,status:"pending",effectiveToolScope:t.effective_tool_scope,effectiveContextScope:t.effective_context_scope,acceptDeadline:t.accept_deadline}}async acceptGrant(e){let t=await this.post(`/orchestrate/grants/${e}/accept`,{});return{grantToken:t.grant_token,toolScope:t.tool_scope,contextScope:t.context_scope,expiresAt:t.expires_at}}async evaluate(e){let t=await this.post("/orchestrate/evaluate",{grant_token:e.grantToken,action:e.action,resource_type:e.resourceType,resource_metadata:e.resourceMetadata??{}}),r=Lt.parse(t);return{decision:r.decision,reason:r.reason,handoffEventId:r.handoff_event_id}}async revokeGrant(e,t){return{revokedCount:(await this.post(`/orchestrate/grants/${e}/revoke`,{reason:t})).revoked_count}}};var Ee=new Map;async function xe(e,t){if(!e||e.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: agentId is required");if(!t||t.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: grantId is required");let r=Ee.get(e);if(r)return r;let n=process.env.VISIQ_API_KEY;if(!n)throw new Error("[ORCHESTRATE] bootstrapGrant: VISIQ_API_KEY env var is required");let o=process.env.VISIQ_ENDPOINT,i=(await new E({agentId:e,apiKey:n,...o?{endpoint:o}:{}}).acceptGrant(t)).grantToken;if(!i||i.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: backend returned empty grant token");return Ee.set(e,i),i}var O=Symbol.for("visiq.orchestrate.wrapped");function Se(e,t){if(!t.agentId||t.agentId.trim()==="")throw new b("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new b("grantToken is required","CONFIG_ERROR");if(e[O]===!0)return e;let r=new E(t),n=t.failBehavior??"deny",o=async(i,s)=>{let a;try{a=await r.evaluate({grantToken:t.grantToken,action:i,resourceType:s})}catch(l){if(n==="permit"){console.warn("[ORCHESTRATE] evaluate failed \u2014 failing open (failBehavior=permit)",l);return}throw new b(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(a.decision==="deny")throw new R(a.reason,a.handoffEventId)};return new Proxy(e,{get(i,s,a){let l=Reflect.get(i,s,a);return s===O?!0:s==="_call"&&typeof l=="function"?async function(c,...d){let g=i.name;return await o(g??"_call"),l.call(this??i,c,...d)}:(s==="call"||s==="execute"||s==="run")&&typeof l=="function"?async function(c,...d){let g=i.name;return await o(g??String(s)),l.call(this??i,c,...d)}:l}})}import{AsyncLocalStorage as Mt}from"node:async_hooks";var v=new Mt,Dt=5120,Le=50;function Pt(e,t){if(typeof e!="string")return"";let r=new TextEncoder,n=r.encode(e);if(n.length<=t)return e;let i=`\u2026[truncated ${Math.ceil(n.length/1024)}KB]`,s=r.encode(i).length,a=Math.max(0,t-s),l=n.subarray(0,a);return new TextDecoder("utf-8",{fatal:!1}).decode(l)+i}function x(e){if(!e)return;let t=n=>n.length<=Le?n.slice():n.slice(n.length-Le),r=n=>Pt(n,Dt);return{session_id:e.session_id,llm_prompts:t(e.llm_prompts).map(r),llm_responses:t(e.llm_responses).map(r),tool_history:t(e.tool_history).map(n=>({name:r(n.name),input:r(n.input),...n.output!==void 0?{output:r(n.output)}:{}})),agent_reasoning:t(e.agent_reasoning).map(r)}}var $t=new Set(["approved","resolved"]),jt=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function Ft(e){return new Promise(t=>setTimeout(t,e))}function Nt(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.hitl_result;if(typeof r=="string"&&r.length>0)return r;let{hitl:n}=t;if(n&&typeof n=="object"){let{status:o}=n;if(typeof o=="string"&&o.length>0)return o==="pending"?null:o}return null}async function F(e){let{endpoint:t,apiKey:r,decisionId:n,timeoutMs:o=3e5,fetchImpl:i=globalThis.fetch,sleep:s=Ft,log:a=p=>console.warn(p)}=e;if(!t)return{resolution:"block",reason:"HITL approval cannot be confirmed (no backend endpoint) \u2014 fail-closed (G001)"};if(!n)return{resolution:"block",reason:"HITL approval cannot be confirmed (no decision id) \u2014 fail-closed (G001)"};let l=`${t.replace(/\/$/,"")}/v1/allow/decisions/${encodeURIComponent(n)}`,c={Accept:"application/json"};r&&(c.Authorization=`Bearer ${r}`);let d=Date.now()+Math.max(0,o),g=0;for(a(`[VisIQ HITL] Awaiting human approval for decision ${n} (timeout ${o}ms)`);;){if(Date.now()>=d)return a(`[VisIQ HITL] Decision ${n} timed out after ${o}ms \u2014 blocking (G001)`),{resolution:"block",reason:"HITL approval timed out"};let p=null;try{let f=new AbortController,y=setTimeout(()=>f.abort(),5e3),T;try{T=await i(l,{method:"GET",headers:c,signal:f.signal})}finally{clearTimeout(y)}if(!T.ok)throw new Error(`HTTP ${T.status} ${T.statusText}`);let A=await T.json();p=Nt(A),g=0}catch(f){g+=1;let y=f instanceof Error?f.message:String(f);if(a(`[VisIQ HITL] Poll failed for decision ${n} (${g}/3): ${y}`),g>=3)return{resolution:"block",reason:`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${y}`};await s(2e3);continue}if(p!==null){let f=p.toLowerCase();return $t.has(f)?(a(`[VisIQ HITL] Decision ${n} approved (${p}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${p})`}):jt.has(f)?(a(`[VisIQ HITL] Decision ${n} resolved as ${p} \u2014 blocking`),{resolution:"block",reason:`Blocked by human reviewer (${p})`}):(a(`[VisIQ HITL] Decision ${n} returned unknown status '${p}' \u2014 blocking (G001)`),{resolution:"block",reason:`HITL returned unknown status '${p}' \u2014 fail-closed (G001)`})}await s(2e3)}}import{randomUUID as Ce}from"node:crypto";function S(e,t){return`[VisIQ ${e}] Action blocked: ${t}. (VisIQ is a security harness installed by your developer.)`}var Vt=/https?:\/\/[^\s"'`,)}\]]+/;function U(e){let t=e.match(Vt);if(t)try{let r=new URL(t[0]);return r.hostname+r.pathname}catch{return t[0]}}var L=Symbol.for("visiq.toolexec.instrumented");function qt(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}function Oe(e){if(e===null||typeof e!="object")return null;let t=e;if(qt(t))return null;if(typeof t.generateText=="function"&&(typeof t.getTools=="function"||t.toolManager!==void 0))return"voltagent";if(typeof t.run=="function"&&typeof t.runStream=="function"&&t.agents!==void 0)return"llamaindex";if(Array.isArray(t.tools)&&t.handoffs!==void 0&&(typeof t.on=="function"||t.eventEmitter!==void 0))return"openai";if(typeof t.generate=="function"&&typeof t.getLLM=="function"&&(typeof t.listTools=="function"||typeof t.getTools=="function"))return"mastra";if(typeof t.generate=="function"){let r=t.settings;if(r&&typeof r=="object"&&r.tools!==void 0||t.tools!==void 0)return"vercel"}return null}async function Ht(e,t,r,n,o){let{agentId:i,runtime:s}=e,a=x(o),l;try{l=await s.evaluate({agentId:i,toolName:t,toolArgs:r,...n!==void 0?{targetResource:n}:{},...a?{telemetry:a}:{}})}catch(c){return S("EVAL-ERROR",`policy evaluation failed: ${c instanceof Error?c.message:String(c)}`)}if(l.decision==="approval_required"&&l.decisionId){let c=s.getApiKey()??e.apiKey,d=await F({endpoint:s.getEndpoint()??e.endpoint??"",...c?{apiKey:c}:{},decisionId:l.decisionId,timeoutMs:e.hitlTimeoutMs});return d.resolution!=="proceed"?S(l.ruleCode??"HITL-BLOCK",d.reason):null}if(!l.allowed){let c=l.ruleCode??"DENY",d=l.description??l.reason??"denied by policy";return S(c,d)}return null}async function z(e,t,r,n,o){let i=v.getStore()??e.telemetry,s=await Ht(e,t,r,U(n),i);if(s!==null)return i.tool_history.push({name:t,input:n,output:s}),s;let a=await o(),l=await ke(a,e.agentId,e.engine);return i.tool_history.push({name:t,input:n,output:en(l)}),l}function N(e,t,r){let n=e;if(n[L]||typeof n.execute!="function")return;let o=n.execute;J(n,"execute",async function(...s){let a=W(s[0]);return z(r,t,a,C(a),()=>Promise.resolve(o.apply(this,s)))}),n[L]=!0}function Kt(e,t,r){let n=e;if(n[L]||typeof n.invoke!="function")return;let o=n.invoke;J(n,"invoke",async function(...s){let a=s[1],l=ue(a),c=typeof a=="string"?a:C(l);return z(r,t,l,c,()=>Promise.resolve(o.apply(this,s)))}),n[L]=!0}function Gt(e,t){let r=e;if(r[L]||typeof r.call!="function")return;let n=r.metadata,o=typeof n?.name=="string"?n.name:"unknown",i=r.call;J(r,"call",async function(...a){let l=W(a[0]);return z(t,o,l,C(l),()=>Promise.resolve(i.apply(this,a)))}),r[L]=!0}function Me(e,t){for(let[r,n]of Object.entries(e))n!==null&&typeof n=="object"&&N(n,r,t);return e}function De(e,t,r){switch(r){case"vercel":return Wt(e,t);case"mastra":return Bt(e,t);case"openai":return zt(e,t);case"llamaindex":return Ut(e,t);case"voltagent":return Qt(e,t);default:return e}}function Wt(e,t){let r=e,n=r.settings&&typeof r.settings=="object"?r.settings:void 0,o=n?.tools??r.tools;return o&&typeof o=="object"&&Me(o,t),n&&!n.__visiq_step&&(n.__visiq_step=!0,n.onStepFinish=Y(n.onStepFinish)),V(e,["generate","stream"],async(i,s)=>(q(s,i[0]),i)),e}function Bt(e,t){let n=Xt(e);return n&&Me(n,t),V(e,["generate","stream","generateVNext","streamVNext"],async(o,i)=>{q(i,o[0]);let s=o[1]&&typeof o[1]=="object"?{...o[1]}:{};s.onStepFinish=Y(s.onStepFinish);let a=[...o];return a[1]=s,a}),e}function Qt(e,t){let r=Jt(e);if(r){for(let n of r)if(n!==null&&typeof n=="object"){let{name:o}=n;N(n,typeof o=="string"?o:"unknown",t)}}return V(e,["generateText","streamText","generateObject","streamObject"],async(n,o)=>{q(o,n[0]);let i=n[1]&&typeof n[1]=="object"?{...n[1]}:{};i.onStepFinish=Y(i.onStepFinish);let s=[...n];return s[1]=i,s}),e}function Ut(e,t){let r=e,n=i=>{let s=i?.tools;if(Array.isArray(s))for(let a of s)a!==null&&typeof a=="object"&&Gt(a,t)},{agents:o}=r;if(o instanceof Map)for(let i of o.values())n(i);else Array.isArray(r.tools)&&n(r);return V(e,["run","runStream"],async(i,s)=>(q(s,i[0]),i)),e}function zt(e,t){let r=e,{tools:n}=r;if(Array.isArray(n)){for(let o of n)if(o!==null&&typeof o=="object"){let{name:i}=o;Kt(o,typeof i=="string"?i:"unknown",t)}}return Yt(e,t),e}function Yt(e,t){let r=e;if(r.__visiq_openai_hooks||typeof r.on!="function")return;let n=r.on,{telemetry:o}=t;n.call(e,"agent_start",(...i)=>{o.session_id=Ce(),o.llm_prompts=[],o.llm_responses=[],o.tool_history=[],o.agent_reasoning=[],o.retrieverQueries=new Map;let s=i[2];s!=null&&o.llm_prompts.push(C(s).slice(0,5120))}),n.call(e,"agent_end",(...i)=>{let s=i[1];typeof s=="string"&&s&&o.llm_responses.push(s.slice(0,5120))}),r.__visiq_openai_hooks=!0}function Jt(e){let t=n=>Array.isArray(n)&&n.some(o=>o!==null&&typeof o.execute=="function");if(typeof e.getTools=="function")try{let n=e.getTools();if(t(n))return n}catch{}let r=e.toolManager;if(r&&typeof r.getAllBaseTools=="function")try{let n=r.getAllBaseTools();if(t(n))return n}catch{}return t(e.tools)?e.tools:null}function V(e,t,r){let n=e;for(let o of t){if(typeof n[o]!="function")continue;let i=`__visiq_wrapped_${o}`;if(n[i])continue;let s=n[o];n[o]=function(...a){let l=Zt();return v.run(l,async()=>{let c=await r(a,l);return s.apply(e,c)})},n[i]=!0}}function Y(e){return t=>{let r=v.getStore(),n=t;if(r&&typeof n?.text=="string"&&n.text&&r.llm_responses.push(n.text.slice(0,5120)),typeof e=="function")return e(t)}}function q(e,t){if(t==null)return;let r=t;if(typeof t=="object"){let n=t;r=n.prompt??n.messages??t}e.llm_prompts.push(C(r).slice(0,5120))}function Xt(e){for(let t of["listTools","getTools"])if(typeof e[t]=="function")try{let r=e[t]();if(r&&typeof r=="object"&&typeof r.then!="function")return r}catch{}return null}function Zt(){return{session_id:Ce(),llm_prompts:[],llm_responses:[],tool_history:[],agent_reasoning:[],retrieverQueries:new Map}}function J(e,t,r){try{e[t]=r}catch{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0,enumerable:!0})}}function C(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function en(e){return typeof e=="string"?e.slice(0,1e3):C(e).slice(0,1e3)}function Fe(e,t){let r=rn(t);if(e[O]===!0)return e;let n=an(e);if(n==="langchain-executor"||n==="langchain-graph")return ln(e,r);let o=Oe(e);if(o)return De(e,Ke(r),o);if(un(e)){let i=process.env.VISIQ_GRANT_ID;return i?dn(e,r,i):pn(e,r)}throw new Error("[VisIQ] Cannot detect agentic framework. Pass a LangChain AgentExecutor, LangGraph CompiledGraph, or a tool with one of: _call, execute, call, run, invoke.")}var X=null;function te(e,t,r){return X||(X=new ce(e,t,r,{deferHitl:!0})),X}var Z=null;function Ne(e,t){if(!Z){let r=_e({apiKey:e,endpoint:t}),n=new be(r);Z=new Ie(r,n,null)}return Z}function rn(e){return{agentId:e?.agentId??process.env.VISIQ_AGENT_ID??on(),apiKey:e?.apiKey??process.env.VISIQ_API_KEY,endpoint:e?.endpoint??process.env.VISIQ_ENDPOINT,hitlTimeoutMs:sn(e?.hitlTimeoutMs)}}function on(){let e=t=>t.toLowerCase().replace(/^@[^/]+\//,"").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,255);try{let t=process.cwd();for(let r=0;r<64;r++){let n=K.join(t,"package.json");if(H.existsSync(n)){let i=JSON.parse(H.readFileSync(n,"utf8"));if(typeof i.name=="string"&&i.name.trim()){let s=e(i.name);if(s)return s}break}let o=K.dirname(t);if(o===t)break;t=o}}catch{}try{let t=e(je.hostname());if(t)return t}catch{}return"agent"}function sn(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let t=process.env.VISIQ_HITL_TIMEOUT_MS;if(t){let r=Number(t);if(Number.isFinite(r)&&r>0)return r}return 3e5}function an(e){let t=e;return typeof t.invoke=="function"&&t.agent&&Array.isArray(t.tools)?"langchain-executor":typeof t.invoke=="function"&&t.nodes&&t.edges?"langchain-graph":"unknown"}function ln(e,t){let r=e,n=te(t.apiKey,t.endpoint,t.agentId),o=Ne(t.apiKey,t.endpoint);if(Array.isArray(r.tools))for(let s of r.tools)Ve(s,t.agentId,o),qe(s,n,t);let i=r.invoke;if(r.invoke=function(s,a){let l=ee(),c=$e(t.agentId,o),d=a?.callbacks??[];return v.run(l,()=>i.call(this,s,{...a,callbacks:[...d,c]}))},typeof r.stream=="function"){let s=r.stream;r.stream=function(a,l){let c=ee(),d=$e(t.agentId,o),g=l?.callbacks??[];return v.run(c,()=>s.call(this,a,{...l,callbacks:[...g,d]}))}}return e}function ee(){return{session_id:nn(),llm_prompts:[],llm_responses:[],tool_history:[],agent_reasoning:[],retrieverQueries:new Map}}function Ve(e,t,r){let n=e,o=Symbol.for("visiq.recall.instrumented");if(!n[o]){if(typeof n._getRelevantDocuments=="function"){let i=n._getRelevantDocuments;n._getRelevantDocuments=async function(s,a){let l=await i.call(this,s,a);return Pe(l,t,s,r)},n[o]=!0}if(typeof n.retrieve=="function"&&!n._getRelevantDocuments){let i=n.retrieve;n.retrieve=async function(s){let a=await i.call(this,s);return Pe(a,t,String(s),r)},n[o]=!0}n.retriever&&typeof n.retriever=="object"&&Ve(n.retriever,t,r)}}function cn(e){let t=[],r=[],n;for(let i of e){let{field:s,pattern:a,replacement:l}=i;s&&t.push(s),a&&r.push(a),l&&n===void 0&&(n=l)}let o={};return t.length>0&&(o.fields=t),r.length>0&&(o.patterns=r),n!==void 0&&(o.replacement=n),o}async function Pe(e,t,r,n){if(!Array.isArray(e)||e.length===0)return e;let o=[];for(let i of e){let s=i,a=String(s.pageContent??s.text??s.content??""),l=s.metadata??{},c=x(v.getStore()),d=await n.evaluateAsync({agentId:t,operation:"retrieve",resourceType:"document",resourceMetadata:l,query:r,contentPreview:a.slice(0,500),...c?{telemetry:c}:{}});if(d.action!=="deny"){if(d.action==="redact"&&d.redactionRules&&d.redactionRules.length>0){let g=cn(d.redactionRules),p={...s};for(let f of["pageContent","text","content"])typeof p[f]=="string"&&(p[f]=Q(p[f],g));p.metadata&&typeof p.metadata=="object"&&(p.metadata=Q(p.metadata,g)),o.push(p);continue}o.push(i)}}return o}function qe(e,t,r){let n=e,o=Symbol.for("visiq.allow.instrumented");if(n[o]||typeof n._getRelevantDocuments=="function"||typeof n.invoke!="function")return;let{agentId:i}=r,s=typeof n.name=="string"?n.name:"unknown",a=n.invoke;n.invoke=async function(l,...c){let d;if(typeof l=="string")d=l;else{let f=l?.input;d=f!=null?String(f):JSON.stringify(l)}let g=x(v.getStore()),p=await t.evaluate({agentId:i,toolName:s,toolArgs:typeof l=="object"&&l!==null?l:{input:d},targetResource:U(d),...g?{telemetry:g}:{}});if(p.decision==="approval_required"&&p.decisionId){let f=await F({endpoint:t.getEndpoint()??r.endpoint??"",apiKey:t.getApiKey()??r.apiKey,decisionId:p.decisionId,timeoutMs:r.hitlTimeoutMs});if(f.resolution==="proceed")return a.call(this,l,...c);let y=p.ruleCode??"HITL-BLOCK";return S(y,f.reason)}if(!p.allowed){let f=p.ruleCode??"DENY",y=p.description??p.reason??"denied by policy";return S(f,y)}return a.call(this,l,...c)},n[o]=!0}function $e(e,t){return{name:"VisiqHandler",handleLLMStart:async(r,n)=>{let o=v.getStore();o&&o.llm_prompts.push(...n)},handleLLMEnd:async r=>{let n=v.getStore();if(!n)return;let o=r?.generations;o?.[0]?.[0]?.text&&n.llm_responses.push(o[0][0].text)},handleAgentAction:async r=>{let n=v.getStore();if(!n)return;let o=typeof r.log=="string"?r.log:"";o&&n.agent_reasoning.push(o)},handleToolStart:async(r,n)=>{let o=v.getStore();if(!o)return;let i=typeof r.name=="string"?r.name:"unknown";o.tool_history.push({name:i,input:n})},handleToolEnd:async r=>{let n=v.getStore();if(!n)return;let o=n.tool_history[n.tool_history.length-1];o&&(o.output=String(r).slice(0,1e3))},handleToolError:async r=>{let n=v.getStore();if(!n)return;let o=n.tool_history[n.tool_history.length-1];o&&(o.output=`[ERROR] ${r.message}`)},handleRetrieverStart:async(r,n,o)=>{let i=v.getStore();i&&i.retrieverQueries.set(o,n??"")},handleRetrieverEnd:async(r,n)=>{let o=v.getStore();if(!o)return;let i=o.retrieverQueries.get(n)??"";if(o.retrieverQueries.delete(n),!Array.isArray(r))return;let s=x(o);for(let a of r){let l=a,c=String(l.pageContent??l.text??l.content??""),d=l.metadata??{};await t.evaluateAsync({agentId:e,operation:"retrieve",resourceType:"document",resourceMetadata:d,query:i,contentPreview:c.slice(0,500),...s?{telemetry:s}:{}})}},handleRetrieverError:async(r,n)=>{let o=v.getStore();o&&o.retrieverQueries.delete(n)}}}var He=["_call","execute","call","run","invoke"];function un(e){let t=e;for(let r of He)if(typeof t[r]=="function")return!0;return!1}function dn(e,t,r){let n=null,o=null,i=async()=>{if(n)return n;if(o)throw new R(`Failed to bootstrap grant ${r}: ${o.message}`,null);let s;try{s=await xe(t.agentId,r)}catch(a){throw o=a instanceof Error?a:new Error(String(a)),new R(`Failed to bootstrap grant ${r}: ${o.message}`,null)}return n=Se(e,{agentId:t.agentId,grantToken:s,...t.apiKey?{apiKey:t.apiKey}:{},...t.endpoint?{endpoint:t.endpoint}:{}}),n};return new Proxy(e,{get(s,a,l){if(a===O)return!0;let c=Reflect.get(s,a,l);return typeof c!="function"||typeof a!="string"||!He.includes(a)?c:async function(...d){let g=await i();return g[a].call(g,...d)}}})}function pn(e,t){let r=te(t.apiKey,t.endpoint,t.agentId);qe(e,r,t);let n=e;if(typeof n.execute=="function"){let o=typeof n.name=="string"&&n.name||typeof n.id=="string"&&n.id||"unknown";N(e,o,Ke(t))}return e}function Ke(e){return{agentId:e.agentId,runtime:te(e.apiKey,e.endpoint,e.agentId),engine:Ne(e.apiKey,e.endpoint),hitlTimeoutMs:e.hitlTimeoutMs,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:ee()}}async function Ge(e,t={}){if(!e||e.trim()==="")throw new Error("[VisIQ] visiq.delegate: childAgentId is required");let r=process.env.VISIQ_AGENT_ID;if(!r)throw new Error("[VisIQ] visiq.delegate: VISIQ_AGENT_ID env var is required. Set it to the parent agent ID before calling delegate.");let n=process.env.VISIQ_API_KEY;if(!n)throw new Error("[VisIQ] visiq.delegate: VISIQ_API_KEY env var is required");let o=process.env.VISIQ_ENDPOINT;return{VISIQ_GRANT_ID:(await new E({agentId:r,apiKey:n,...o?{endpoint:o}:{}}).requestGrant({parentAgentId:r,childAgentId:e,toolScope:t.toolScope??null,contextScope:t.contextScope??null,durationSeconds:t.durationSeconds??3600,purpose:t.purpose??`Delegated to ${e}`,...t.maxDepth!==void 0?{maxDepth:t.maxDepth}:{},...t.parentGrantToken!==void 0?{parentGrantToken:t.parentGrantToken}:{}})).grantId}}var M=class{constructor(t){this.transport=t}transport;deploy(t={}){return k(this.transport,"POST","/api/discovery/fleet/deploy",{include_mac:t.includeMac??!1})}status(){return k(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return k(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return k(this.transport,"POST","/api/discovery/fleet/stop")}};var D=class{constructor(t){this.transport=t}transport;connectAws(t){return k(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function fn(e){if(!e.baseUrl||e.baseUrl.length===0)throw new Error("[VisIQ] createVisiqClient: baseUrl is required");if(!e.accessToken&&!e.cookieHeader)throw new Error("[VisIQ] createVisiqClient: one of accessToken or cookieHeader is required");let t=e.baseUrl.replace(/\/$/,""),r=e.fetchImpl??globalThis.fetch.bind(globalThis),n={baseUrl:t,accessToken:e.accessToken,cookieHeader:e.cookieHeader,fetchImpl:r};return{fleet:new M(n),integrations:new D(n)}}async function k(e,t,r,n){let o=`${e.baseUrl}${r.startsWith("/")?r:`/${r}`}`,i={};e.cookieHeader&&(i.Cookie=e.cookieHeader),e.accessToken&&(i.Authorization=`Bearer ${e.accessToken}`);let s;n!==void 0&&(i["Content-Type"]="application/json",s=JSON.stringify(n));let a=await e.fetchImpl(o,{method:t,headers:i,body:s});if(!a.ok){let l="";try{l=await a.text()}catch{}throw new Error(`[VisIQ] ${t} ${r} failed (${a.status}): ${l||a.statusText}`)}return await a.json()}var We=Fe;We.delegate=Ge;var wr=We;export{M as FleetClient,D as IntegrationsClient,fn as createVisiqClient,Ge as delegate,wr as visiq};
|
|
1
|
+
import{randomUUID as li}from"node:crypto";import*as fe from"node:fs";import*as ge from"node:path";import*as an from"node:os";import{AsyncLocalStorage as ci}from"node:async_hooks";import{z as p}from"zod";import*as O from"node:os";var He="interceptor_source",_n=p.enum(["enforce","audit","off"]),hn=p.enum(["closed","open"]),We=p.enum(["enforce","monitor","off"]),yn=p.object({apiKey:p.string().min(1,"apiKey is required"),agentId:p.string().min(1,"agentId is required"),endpoint:p.string().url().optional(),mode:_n.optional(),timeoutMs:p.number().int().positive().optional(),hitlTimeoutMs:p.number().int().positive().optional(),failBehavior:hn.optional()}),Ai=p.object({agent_id:p.string().min(1),target_app:p.string().min(1),action:p.string().min(1),context:p.record(p.unknown()).optional(),session_id:p.string().min(1).max(255).optional(),telemetry:p.record(p.unknown()).optional()}),bn=p.object({field:p.string().optional(),pattern:p.string().optional(),replacement:p.string().optional(),mode:p.enum(["full","partial","email"]).optional(),keepFirst:p.number().optional(),keepLast:p.number().optional(),maskChar:p.string().optional()}),vn=p.object({decision_id:p.string().min(1),decision:p.enum(["permit","deny","approval_required","mask"]),reason:p.string().optional(),rule_code:p.string().nullable().optional(),enforced:p.boolean().optional(),agent_mode:We.optional(),arg_redaction_rules:p.array(bn).optional(),plane:p.string().nullable().optional(),operation:p.string().nullable().optional(),is_retrieval:p.boolean().optional(),metadata:p.record(p.unknown()).optional()}),wn=p.object({field:p.string().min(1),operator:p.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:p.union([p.string(),p.number(),p.array(p.string())])}),kn=p.object({id:p.string().min(1),rule_code:p.string().default(""),name:p.string().min(1),description:p.string().nullable().default(null),effect:p.enum(["allow","deny","hitl","mask"]),resource_type:p.string().min(1),rego_source:p.string().default(""),target_app:p.string().nullable().default(null),action_pattern:p.string().nullable().default(null),conditions:p.array(wn).default([]),priority:p.number().int().default(0)}),An=p.object({version:p.string().min(1),agent_mode:We.optional(),rules:p.array(kn),no_coverage:p.object({no_coverage_defaults:p.record(p.string()),autopilot_enabled:p.boolean(),enduser_hitl_enabled:p.boolean(),hitl_timeout_seconds:p.number()}).optional()}),Tn=2e3,Ge=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 vn.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 a=await i.json();return An.parse(a)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},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 a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let o=a,s=o.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof o.reason=="string"?o.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await In(Tn)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function In(e){return new Promise(t=>setTimeout(t,e))}function ze(){let e={};try{let t=`${O.platform()} ${O.release()}`.trim();t&&(e.os=t)}catch{}try{let t=O.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=O.userInfo();t&&(e.username=t)}catch{}try{let t=Rn();t&&(e.ip=t)}catch{}return e}function Rn(){let e=O.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 _}from"zod";import{createHash as Sn}from"crypto";import{createHash as xi}from"crypto";var En=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},Qe=new Map;function Ye(e){return e.map(t=>t.trim()).filter(t=>t.length>0&&t!=="true")}function ut(e){let t=Sn("sha256").update(e).digest("hex"),n=Qe.get(t);if(n)return n;let r=new Map,i=[],a=e.split(`
|
|
2
|
+
`).map(l=>xn(l)).filter(l=>l.trim().length>0),o=0;for(;o<a.length;){let l=a[o].trim();if(l.startsWith("package ")||l.startsWith("import ")){o++;continue}let c=l.match(/^default\s+(\w+)\s*:?=\s*(.+)$/);if(c){let d=c[1],m=c[2].trim();r.set(d,W(m)),o++;continue}let u=l.match(/^(\w+)\s*:?=\s*(.+?)(?:\s+if)?\s*\{(.*)$/);if(u){let d=u[1],m=u[2].trim(),g=u[3].trim(),h=[];if(g&&g!=="}"){let A=g.endsWith("}")?g.slice(0,-1).trim():g;A&&h.push(A),g.endsWith("}")||(o++,o=X(a,o,h))}else g==="}"||(o++,o=X(a,o,h));let b=Je(h);i.push({variable:d,value:W(m),conditions:b,rawConditions:Ye(h)}),o++;continue}let f=l.match(/^(\w+)(?:\s+if)?\s*\{(.*)$/);if(f){let d=f[1],m=f[2].trim(),g=[];if(m&&m!=="}"){let b=m.endsWith("}")?m.slice(0,-1).trim():m;b&&g.push(b),m.endsWith("}")||(o++,o=X(a,o,g))}else m==="}"||(o++,o=X(a,o,g));let h=Je(g);i.push({variable:d,value:"true",conditions:h,rawConditions:Ye(g)}),o++;continue}o++}let s={defaults:r,rules:i};return Qe.set(t,s),s}function dt(e,t){let n={};for(let[a,o]of e.defaults)n[a]=o;let r=-1,i={};for(let a=0;a<e.rules.length;a++){let o=e.rules[a];if(o.conditions.every(s=>Pn(s,t))){if(i[o.variable]===void 0)i[o.variable]=o.value,n[o.variable]=o.value;else if(i[o.variable]!==o.value)throw new En(o.variable,[i[o.variable],o.value]);r===-1&&(r=a)}}return r!==-1?{bindings:n,matched:!0,matchedRuleIndex:r}:{bindings:n,matched:!1,matchedRuleIndex:-1}}function xn(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 X(e,t,n){let r=1,i=t;for(;i<e.length&&r>0;){let a=e[i].trim();for(let o of a)o==="{"&&r++,o==="}"&&r--;if(r>0)n.push(a),i++;else{let o=a.slice(0,a.lastIndexOf("}")).trim();return o&&n.push(o),i}}return i}function W(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Cn(e){return e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}var Ze=new Map;function On(e){let t=Ze.get(e);if(t!==void 0)return t;let n;try{n=new RegExp(e)}catch{n=null}return Ze.set(e,n),n}function Je(e){let t=[];for(let n of e){let r=n.split(";").map(i=>i.trim()).filter(i=>i.length>0);for(let i of r){let a=Ln(i);a&&t.push(a)}}return t}function Ln(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:ye,value:e.trim()};let r=n.match(/^count\(([^)]+)\)\s*(>=|<=|>|<)\s*(\d+)$/);if(r)return{type:"count_gt",negated:t,field:r[1].trim(),operator:r[2],value:parseInt(r[3],10)};let i=n.match(/^startswith\(([^,]+),\s*"([^"]*)"\)$/);if(i)return{type:"startswith",negated:t,field:i[1].trim(),value:i[2]};let a=n.match(/^endswith\(([^,]+),\s*"([^"]*)"\)$/);if(a)return{type:"endswith",negated:t,field:a[1].trim(),value:a[2]};let o=n.match(/^contains\(([^,]+),\s*"([^"]*)"\)$/);if(o)return{type:"contains",negated:t,field:o[1].trim(),value:o[2]};let s=n.match(/^regex\.match\(\s*("(?:[^"\\]|\\.)*")\s*,\s*((?:input|data)[^\s)]*)\s*\)$/);if(s)return{type:"regex_match",negated:t,field:s[2].trim(),value:Cn(s[1])};let l=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s+in\s+((?:input|data)[^\s]*)$/);if(l)return{type:"array_includes",negated:t,field:l[2].trim(),value:pt(l[1])};let c=n.match(/^([^\s]+)\s+in\s+(\[.*\])$/);if(c){let h=Nn(c[2]);if(h!==null)return{type:"in_set",negated:t,field:c[1].trim(),values:h}}let u=n.match(/^([^\s=!<>]+)\s*(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/);if(u)return{type:"comparison",negated:t,field:u[1].trim(),operator:u[2],value:parseFloat(u[3])};let f=n.match(/^("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false)\s*==\s*((?:input|data)\S*)$/);if(f)return{type:"equality",negated:t,field:f[2].trim(),value:W(f[1].trim())};let d=n.match(/^([^\s=!]+)\s*==\s*(.+)$/);if(d)return{type:"equality",negated:t,field:d[1].trim(),value:W(d[2].trim())};let m=n.match(/^([^\s=!]+)\s*!=\s*(.+)$/);if(m)return{type:"inequality",negated:t,field:m[1].trim(),value:W(m[2].trim())};let g=n.match(/^(input(?:\.[a-zA-Z0-9_]+|\["[^"]+"\]|\['[^']+'\])+)$/);return g?{type:"truthy",negated:t,field:g[1].trim()}:{type:"truthy",negated:!1,field:ye,value:e.trim()}}var ye="__unrecognized_condition_forces_deny__";function pt(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 Nn(e){let t=e.trim().replace(/^\[/,"").replace(/\]$/,"").trim();if(t.length===0)return[];let n=[],r="",i=!1,a="";for(let s=0;s<t.length;s++){let l=t[s];i?(r+=l,l===a&&t[s-1]!=="\\"&&(i=!1)):l==='"'||l==="'"?(r+=l,i=!0,a=l):l===","?(n.push(r.trim()),r=""):r+=l}if(i)return null;r.trim().length>0&&n.push(r.trim());let o=[];for(let s of n){let l=s.startsWith('"')&&s.endsWith('"')&&s.length>=2||s.startsWith("'")&&s.endsWith("'")&&s.length>=2,c=/^-?\d+(?:\.\d+)?$/.test(s);if(!l&&!c&&!(s==="true"||s==="false"))return null;o.push(pt(s))}return o}function Pn(e,t){if(e.field===ye)return!1;let n;switch(e.type){case"equality":{let r=E(e.field,t);n=ee(r,e.value);break}case"inequality":{let r=E(e.field,t);r==null?n=!1:n=!ee(r,e.value);break}case"startswith":{let r=E(e.field,t);typeof r!="string"?n=!1:n=r.startsWith(String(e.value));break}case"endswith":{let r=E(e.field,t);typeof r!="string"?n=!1:n=r.endsWith(String(e.value));break}case"contains":{let r=E(e.field,t);typeof r!="string"?n=!1:n=r.includes(String(e.value));break}case"regex_match":{let r=E(e.field,t);if(typeof r!="string")n=!1;else{let i=On(String(e.value??""));n=i?i.test(r):!1}break}case"truthy":{let r=E(e.field,t);n=jn(r);break}case"count_gt":{let r=E(e.field,t),i=typeof e.value=="number"?e.value:0,a=Mn(r);a===null?n=!1:n=Xe(a,e.operator??">",i);break}case"comparison":{let r=E(e.field,t),i=typeof e.value=="number"?e.value:NaN,a=Dn(r);Number.isNaN(a)||Number.isNaN(i)||!e.operator?n=!1:n=Xe(a,e.operator,i);break}case"in_set":{let r=E(e.field,t),i=e.values??[];be(r)?n=i.some(a=>ee(r,a)):n=!1;break}case"array_includes":{let r=E(e.field,t);Array.isArray(r)?n=r.some(i=>ee(i,e.value)):n=!1;break}case"literal_bool":{n=e.value===!0;break}default:n=!1}return e.negated?!n:n}function E(e,t){let n=e;n.startsWith("input.")?n=n.slice(6):n.startsWith("input[")&&(n=n.slice(5));let r=Fn(n);if(r===null)return;let i=t;for(let a of r){if(i==null||typeof i!="object")return;i=i[a]}return i}function Fn(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 a=e[n+1];if(a!=='"'&&a!=="'")return null;let o=e.indexOf(`${a}]`,n+2);if(o===-1)return null;t.push(e.slice(n+2,o)),n=o+2}else r+=i,n++}return r.length>0&&t.push(r),t}function Mn(e){return Array.isArray(e)||typeof e=="string"?e.length:e&&typeof e=="object"?Object.keys(e).length:null}function Dn(e){return typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN}function Xe(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 be(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ee(e,t){return!be(e)||!be(t)?!1:String(e)===String(t)}function jn(e){return!(e==null||e===!1||e===0||e==="")}function qn(e){return e.trim()}function $n(e){return e.map(qn).filter(t=>t.length>0&&t!=="true")}function Un(e,t=0){let n=3735928559^t,r=1103547991^t;for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);n=Math.imul(n^a,2654435761),r=Math.imul(r^a,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 Kn="\0";function ft(e,t){let n=[e.trim(),...$n(t)].join(Kn);return`b_${Un(n).toString(36)}`}var Vn=["tier1","tier2","tier3"];function gt(e){return typeof e=="string"&&Vn.includes(e)}var Bn=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Hn=["internal","customer_facing","experimental","third_party"],mt=[...Bn,...Hn];function Wn(e){return typeof e=="string"&&mt.includes(e)}function _t(e){let t=new Set;for(let n of e)Wn(n)&&t.add(n);return mt.filter(n=>t.has(n))}var re={trust_tier:null,categories:[],business_function:null},Gn=["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 ht(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 zn={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 Qn(e){let t=ht(e);return t===null?"other":zn[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 et={github:"version_control",gitlab:"version_control",bitbucket:"version_control",stripe:"payments",adyen:"payments",braintree:"payments",paypal:"payments",square:"payments",salesforce:"crm",hubspot:"crm",pipedrive:"crm",slack:"communication",teams:"communication",twilio:"communication",sendgrid:"communication",mailgun:"communication",gmail:"communication",outlook:"communication",zoom:"communication",aws:"cloud_infra",gcp:"cloud_infra",azure:"cloud_infra",okta:"identity",auth0:"identity",entra:"identity",onelogin:"identity",duo:"identity",snowflake:"data_warehouse",bigquery:"data_warehouse",databricks:"data_warehouse",redshift:"data_warehouse",jira:"ticketing",zendesk:"ticketing",servicenow:"ticketing",freshdesk:"ticketing",linear:"ticketing",workday:"hr",bamboohr:"hr",gusto:"hr",netsuite:"finance_erp",quickbooks:"finance_erp",sap:"finance_erp",xero:"finance_erp",s3:"storage",gcs:"storage",dropbox:"storage",box:"storage",postgres:"database",postgresql:"database",mysql:"database",mongodb:"database",redis:"database"};function Yn(e){let t=ht(e);return t===null?"other":et[t]??et[t.replace(/_/g,"")]??"other"}function ke(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=Qn(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=Yn(t.targetApp)),n.context=r}return n}var tt=64,Zn=64,N={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function yt(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var Jn=new Set(["deny","approval_required","escalate"]);function te(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>tt?r.slice(0,tt):r}function Xn(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function ne(e){return typeof e=="string"&&e.length>0?e:null}function bt(e,t){let n=Xn(t.data_categories),r=ne(t.classification),i=ne(t.action_class),a=i&&Gn.includes(i)?i:null,o=ne(t.target_app),s=ne(t.decision),l={...e.action_counts};if(a)if(a in l)l[a]=(l[a]??0)+1;else if(Object.keys(l).length<Zn)l[a]=1;else{let c=Object.keys(l).sort(),u=c[c.length-1];u!==void 0&&a<u&&(delete l[u],l[a]=1)}return{retrieved_data_categories:te(e.retrieved_data_categories,n),retrieved_classifications:te(e.retrieved_classifications,r?[r]:[]),action_classes:te(e.action_classes,a?[a]:[]),action_counts:l,denied_count:e.denied_count+(s==="deny"?1:0),inhibited_count:e.inhibited_count+(s&&Jn.has(s)?1:0),event_count:e.event_count+1,target_apps:te(e.target_apps,o?[o]:[])}}function er(e,t){if(!e||e.trim().length===0)return{decision:"permit",matched:!0};try{let n=ut(e),r=dt(n,{target_app:t.target_app,action:t.action,...t.context,context:t.context,normalized:t.normalized??{},agent:t.agent??re,session:t.session??N});if(!r.matched)return{decision:"deny",matched:!1};let i=null,a=r.bindings.decision;if(a!==void 0?i=ve(a):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 o=i==="mask"?tr(n,r.matchedRuleIndex,i):void 0;return{decision:i,matched:!0,...o?{branchId:o}:{}}}catch{return{decision:"deny",matched:!1}}}function ve(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 tr(e,t,n){if(t<0)return;let r=e.rules[t];if(!(!r||(r.variable==="decision"?ve(r.value):ve(r.variable))!==n))return ft(n,r.rawConditions)}function nt(e,t){if(!e||e.trim().length===0)return{action:"deny",matched:!1};try{let n=ut(e),r=dt(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??re,session:t.session??N});if(!r.matched)return{action:"deny",matched:!1};let i=null,a=r.bindings.action??r.bindings.decision;if(a!==void 0?i=we(a):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 o=i==="redact"?nr(n,r.matchedRuleIndex,i):void 0;return{action:i,matched:!0,...o?{branchId:o}:{}}}catch{return{action:"deny",matched:!1}}}function we(e){switch(e){case"allow":return"allow";case"deny":return"deny";case"redact":return"redact";case"escalate":return"escalate";default:return"deny"}}function nr(e,t,n){if(t<0)return;let r=e.rules[t];if(!(!r||(r.variable==="decision"||r.variable==="action"?we(r.value):we(r.variable))!==n))return ft(n,r.rawConditions)}var rr="generic",vt=[{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:rr,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."}],Si=vt.map(e=>e.id),ir=new Map(vt.map(e=>[e.id,e]));function wt(e){return e!=null&&ir.has(e)}function or(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=>ar(r,t))}function ar(e,t){return e==="*"?!0:e.includes("*")?lr(e).test(t):e===t}function sr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var rt=new Map;function lr(e){let t=rt.get(e);if(t)return t;let n=e.split("*").map(i=>sr(i)).join(".*"),r=new RegExp(`^${n}$`);return rt.set(e,r),r}function Ae(e){return e==="open"||e==="closed"?e:null}function cr(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 _e(e,t){let n=t==="approve"?"ALLOW":t.toUpperCase();return`D-${e.toUpperCase()}-${n}`}function H(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 kt(e){let t=cr(e.action),n=e.config.no_coverage_defaults??{},r=Ae(e.agentNoCoverage),i={autopilot:!1,enduserHitlBypassed:!1};if(e.mode!=="enforce"){let l=n[t]??"deny";return{...i,decision:"permit",rule_code:_e(t,l),reason:H(t,l,e.targetApp),hitlCategory:null}}if(e.config.autopilot_enabled&&r!=="closed")return{...i,autopilot:!0,decision:"permit",rule_code:_e(t,n[t]??"deny"),reason:"Autopilot: draft rule created for engineer review; request permitted",hitlCategory:"engineer"};let a;r==="open"?a="approve":r==="closed"?a="deny":a=n[t]??"deny";let o=_e(t,a),s=r!==null?"agent":"tenant";return a==="approve"?{...i,decision:"permit",rule_code:o,reason:H(t,"approve",e.targetApp,s),hitlCategory:null}:a==="ask"?e.config.enduser_hitl_enabled===!1?{...i,decision:"permit",rule_code:o,reason:`${H(t,"ask",e.targetApp)} (end-user HITL disabled \u2014 bypassed)`,hitlCategory:null,enduserHitlBypassed:!0}:{...i,decision:"approval_required",rule_code:o,reason:H(t,"ask",e.targetApp),hitlCategory:"enduser"}:{...i,decision:"deny",rule_code:o,reason:H(t,"deny",e.targetApp,s),hitlCategory:"engineer"}}var ur=["action","retrieval","delegation"];function dr(e){return typeof e=="string"&&ur.includes(e)}var pr=new Set(["rules"]);function At(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!pr.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(dr):[];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 fr={tier1:3,tier2:2,tier3:1};function it(e){return e?fr[e]??null:null}function ot(e,t){if(!t)return{matched:!0,reason_code:"POLICY_ALLOW",reason:"resource has no minimum trust tier requirement"};let n=it(e),r=it(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 at(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 st(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 gr={matched:!1,decision:"deny",reason:"No matching rule",reasonCode:null,ruleId:null,ruleCode:null,ruleDescription:null};function lt(e){return e==="allow"?"permit":e==="redact"||e==="escalate"||e==="deny"?e:"deny"}function mr(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=mr(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 L(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 ct(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 _r(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 he(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 Tt(e,t){let n=[...e].sort((d,m)=>m.priority-d.priority),r=t.resourceMetadata!==null||t.operation!==null,i=t.action!==null&&t.targetApp!==null,a=t.facets.includes("retrieval")&&r,o=(t.facets.includes("action")||t.facets.includes("delegation"))&&i,s=t.resourceMetadata??{},l=typeof s.min_trust_tier=="string"?s.min_trust_tier:null,c=Array.isArray(s.excluded_principals)?s.excluded_principals:null,u=Array.isArray(s.restricted_surfaces)?s.restricted_surfaces:null,f={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??N};for(let d of n){if(a&&d.appliesTo.includes("retrieval")){if(d.bypassActive&&d.bypassExpiresAt&&new Date(d.bypassExpiresAt).getTime()>Date.now())return L({matched:!0,decision:"permit",reason:d.bypassReason??"Emergency bypass active",reasonCode:"EMERGENCY_BYPASS",ruleId:d.id,ruleCode:d.ruleCode,ruleDescription:d.description},t.capabilities);if(d.principalExclusions&&d.principalExclusions.length>0){let g=at(t.agentId,d.principalExclusions);if(g.matched)return L({matched:!0,decision:"deny",reason:g.reason,reasonCode:"PRINCIPAL_EXCLUDED",ruleId:d.id,ruleCode:d.ruleCode,ruleDescription:d.description},t.capabilities)}if(c&&c.length>0){let g=at(t.agentId,c);if(g.matched)return L({matched:!0,decision:"deny",reason:g.reason,reasonCode:"PRINCIPAL_EXCLUDED",ruleId:d.id,ruleCode:d.ruleCode,ruleDescription:d.description},t.capabilities)}if(d.surface){let g=st(t.surface,d.surface);if(g.matched){let h=nt(d.regoSource,f),b=h.matched?h.action:"deny",A=lt(b),w=h.matched?h.branchId:void 0;return L(he(ct({matched:!0,decision:A,reason:g.reason,reasonCode:b==="allow"?"POLICY_ALLOW":"SURFACE_RESTRICTION",ruleId:d.id,ruleCode:d.ruleCode,ruleDescription:d.description},d,w),d,w),t.capabilities)}continue}if(u&&u.length>0&&t.surface&&st(t.surface,u.includes(t.surface)?t.surface:null).matched)return L({matched:!0,decision:"deny",reason:`surface '${t.surface}' is in the restricted surfaces list for this resource`,reasonCode:"SURFACE_RESTRICTION",ruleId:d.id,ruleCode:d.ruleCode,ruleDescription:d.description},t.capabilities);if(d.trustTier){let g=ot(t.trustTier,d.trustTier);if(!g.matched)return L({matched:!0,decision:"deny",reason:g.reason,reasonCode:"TIER_MISMATCH",ruleId:d.id,ruleCode:d.ruleCode,ruleDescription:d.description},t.capabilities)}if(l){let g=ot(t.trustTier,l);if(!g.matched)return L({matched:!0,decision:"deny",reason:g.reason,reasonCode:"TIER_MISMATCH",ruleId:d.id,ruleCode:d.ruleCode,ruleDescription:d.description},t.capabilities)}let m=nt(d.regoSource,f);if(m.matched){let g=lt(m.action);return L(he(ct({matched:!0,decision:g,reason:`Matched rule: ${d.name}`,reasonCode:m.action==="allow"?"POLICY_ALLOW":"POLICY_DENY",ruleId:d.id,ruleCode:d.ruleCode,ruleDescription:d.description},d,m.branchId),d,m.branchId),t.capabilities)}}if(o&&(d.appliesTo.includes("action")||d.appliesTo.includes("delegation"))){if(d.targetApp!==null&&d.targetApp!==t.targetApp||!or(d.actionPattern,t.action??""))continue;let m=er(d.regoSource,{target_app:t.targetApp??"",action:t.action??"",context:t.context,normalized:t.normalized,agent:t.agent,session:t.session??N});if(m.matched)return L(he(_r({matched:!0,decision:m.decision,reason:d.description??d.name,reasonCode:null,ruleId:d.id,ruleCode:d.ruleCode,ruleDescription:d.description},d,m.branchId),d,m.branchId),t.capabilities)}}return gr}function hr(e,t=process.env){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let n=t.ALLOW_TIMEOUT_MS;if(n!==void 0){let r=Number.parseInt(n,10);if(Number.isFinite(r)&&r>0)return r}return 5e3}var yr=5e3,br=1e4,It=1e3,vr=512,wr=1800*1e3,kr="monitor",Ar=_.object({operations:_.array(_.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:_.string().min(1,"agentId is required"),sessionId:_.string().min(1).max(255).optional(),toolName:_.string().optional(),toolArgs:_.record(_.unknown()).optional(),targetResource:_.string().optional(),resourceType:_.string().optional(),resourceMetadata:_.record(_.unknown()).optional(),normalized:_.record(_.unknown()).optional(),query:_.string().optional(),contentPreview:_.string().optional(),telemetry:_.record(_.unknown()).optional()}),Tr=_.object({version:_.string().min(1),agent_mode:_.enum(["enforce","monitor","off"]).optional(),agent_attributes:_.object({trust_tier:_.string().nullable().optional(),categories:_.array(_.string()).optional(),business_function:_.string().nullable().optional(),no_coverage:_.string().nullable().optional()}).optional(),rules:_.array(_.record(_.unknown())),no_coverage:_.object({no_coverage_defaults:_.record(_.string()),autopilot_enabled:_.boolean(),enduser_hitl_enabled:_.boolean(),hitl_timeout_seconds:_.number().optional()}).optional()});function Ir(e){let t=e.trust_tier??null,n=e.business_function??"";return{trust_tier:gt(t)?t:null,categories:_t(e.categories??[]),business_function:wt(n)?n:null}}function Rt(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 Ie(e){let t=null;for(let n of e)(t===null||Rt(n.decision)>Rt(t.decision))&&(t=n);return t}function Rr(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}function Sr(e){switch(e){case"permit":return"allow";case"redact":return"redact";case"escalate":return"escalate";default:return"deny"}}var Et=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=kr;agentModeConfirmed=!1;telemetryBuffer=[];telemetryTimer=null;envRegistered=!1;registerPromise=null;constructor(e,t,n,r,i){let a=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,o=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,s=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";if(this.resolvedApiKey=a,this.resolvedEndpoint=o,this.resolvedAgentId=s,this.harnessKind=r,this.originalFetch=globalThis.fetch.bind(globalThis),a&&o){let l={apiKey:a,agentId:s,endpoint:o,mode:"enforce",timeoutMs:hr(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{}};this.client=new Ge(l,this.originalFetch),this.initialBundlePromise=this.fetchBundleBackground(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},yr),St(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},br),St(this.telemetryTimer)}else this.client=null}async evaluate(e){let t=Ar.parse(e),n=Date.now(),r=this.agentMode;if(r==="off")return this.offDecision(t);if(!this.bundleLoaded){let f=this.agentModeConfirmed&&(this.agentMode==="monitor"||this.agentMode==="off")?this.agentMode:"enforce",d=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(d,f,t,n)}let i=this.readSession(t.sessionId),a=[],o=[];for(let f of t.operations){let d=this.resolveOperation(f,t,i);f==="retrieval"?o.push(d):a.push(d)}let s=Ie(a),l=Ie(o),c=Ie([s,l].filter(f=>f!==null)),u=this.buildDecision(c,s,l,r);return this.foldSession(t,r==="enforce"?u.decision:"permit"),u.action.decision==="approval_required"&&r==="enforce"&&await this.registerHitl(t,u),this.applyAgentMode(u,r,t,n)}readSession(e){if(!e)return N;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>wr?(this.sessions.delete(e),N):t.state:N}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),o=e.operations.includes("action")||e.operations.includes("delegation"),s=o?ke(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},l=bt(r===N?yt():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,action_class:o?s.action_class:void 0,target_app:o?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:l,touchedAt:Date.now()}),this.sessions.size>vr){let c=this.sessions.keys().next().value;c!==void 0&&this.sessions.delete(c)}}resolveOperation(e,t,n){let r=Tt(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=kt({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??"",a=ke(t.normalized??{},{action:r,targetApp:i}),o={agentId:t.agentId,agent:this.agentAttributes??re,session:n,normalized:a},s=this.agentAttributes?.trust_tier??null;return e==="retrieval"?{...o,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}}:{...o,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",a=t?this.actionSub(t):{decision:null,allowed:!0},o=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:a,retrieval:o}}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=Sr(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 o={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,o,i,!0),o}let a={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,a,i,!1),a}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){let t=Tr.parse(e);this.bundleLoaded&&t.version===this.bundleVersion||(this.rules=t.rules.map(n=>At(n)).filter(n=>n!==null),this.agentAttributes=t.agent_attributes?Ir(t.agent_attributes):null,this.agentNoCoverage=Ae(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(ze())}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:Rr(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:{[He]: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-It;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${It})`))}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 St(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function Re(e){if(e===null||typeof e!="object"||Array.isArray(e))return{input:e===void 0?"":String(e)};let t=e,n=Object.keys(t);return n.length===1&&n[0]==="context"&&t.context!==null&&typeof t.context=="object"?t.context:t}function xt(e){if(typeof e=="string"){try{let t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{input:e}}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{input:e===void 0?"":String(e)}}function I(e){let t=[],n=[],r,i=[];for(let o of e){if(o.mode==="partial"||o.mode==="email"||o.mode==="custom"){let l={mode:o.mode};o.field&&(l.field=o.field),o.pattern&&(l.pattern=o.pattern),typeof o.keepFirst=="number"&&(l.keepFirst=o.keepFirst),typeof o.keepLast=="number"&&(l.keepLast=o.keepLast),o.maskChar&&(l.maskChar=o.maskChar),o.keepPattern&&(l.keepPattern=o.keepPattern),o.replacement!==void 0&&(l.replacement=o.replacement),i.push(l);continue}o.field&&t.push(o.field),o.pattern&&n.push(o.pattern);let{replacement:s}=o;s&&r===void 0&&(r=s)}let a={};return t.length>0&&(a.fields=t),n.length>0&&(a.patterns=n),r!==void 0&&(a.replacement=r),i.length>0&&(a.directives=i),a}var Er=[{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 v=Object.fromEntries(Er.map(e=>[e.name,e.re.source])),xr=["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"],Cr={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
3
|
+
MIIEv\u2026
|
|
4
|
+
-----END PRIVATE KEY-----`,template:{pattern:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.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:v.mac_address,mode:"full"},defaultEnabled:!1}},Di=new Set(xr.filter(e=>!Cr[e].defaultEnabled));var Se="[REDACTED]",U="\u2022",ie=e=>/[A-Za-z0-9]/.test(e);function Ct(e,t,n,r){let i=Array.from(e),a=i.length,o=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:U,c=o+s>=a;return i.map((u,f)=>!c&&(f<o||f>=a-s)?u:ie(u)?l:u).join("")}function Or(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Ct(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:U;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(o=>ie(o)?a:o).join(""))+i}function Lr(e,t,n){let r=n.length>0?n:U,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let c=new RegExp(t,"g"),u;for(;(u=c.exec(e))!==null;){if(u[0].length===0){c.lastIndex++;continue}for(let f=u.index;f<u.index+u[0].length;f++)i[f]=!0}}catch{}let a=!1,o=!0;for(let c=0;c<e.length;c++)if(ie(e[c])&&(a=!0,!i[c])){o=!1;break}let s=a&&o,l="";for(let c=0;c<e.length;c++){let u=e[c];!s&&i[c]||!ie(u)?l+=u:l+=r}return l}function Ot(e,t){let n=t.mode??"full";return n==="partial"?Ct(e,t.keepFirst??0,t.keepLast??0,t.maskChar??U):n==="email"?Or(e,t.maskChar??U):n==="custom"?Lr(e,t.keepPattern,t.maskChar??U):t.replacement??Se}function Nr(e,t){return typeof e=="string"?Ot(e,t):t.replacement??Se}function Lt(e){let t=[],n=e.replacement??Se;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:a=>Ot(a,r)})}return t}function Nt(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(a,o=>i(o))}return n}function R(e,t){return e==null?e:typeof e=="string"?Pr(e,t):typeof e=="object"?Fr(e,t):e}function Pr(e,t){if(typeof e!="string")return e;let n=Lt(t);return n.length===0?e:Nt(e,n)}function Fr(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=Lt(t),i=n.size>0,a=r.length>0,o=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>o(l));if(typeof s=="object"){let l=s,c=Object.create(Object.getPrototypeOf(l));for(let u of Object.keys(l)){let f=i?n.get(u):void 0;if(f){c[u]=Nr(l[u],f);continue}c[u]=o(l[u])}return c}return typeof s=="string"&&a?Nt(s,r):s};return o(e)}import{AsyncLocalStorage as Mr}from"node:async_hooks";var y=new Mr,Dr=5120,Pt=50;function jr(e,t){if(typeof e!="string")return"";let n=new TextEncoder,r=n.encode(e);if(r.length<=t)return e;let a=`\u2026[truncated ${Math.ceil(r.length/1024)}KB]`,o=n.encode(a).length,s=Math.max(0,t-o),l=r.subarray(0,s);return new TextDecoder("utf-8",{fatal:!1}).decode(l)+a}function F(e){if(!e)return;let t=r=>r.length<=Pt?r.slice():r.slice(r.length-Pt),n=r=>jr(r,Dr);return{session_id:e.session_id,llm_prompts:t(e.llm_prompts).map(n),llm_responses:t(e.llm_responses).map(n),agent_reasoning:t(e.agent_reasoning).map(n)}}function j(e){return e.enforced?{allowed:e.action.allowed,decision:e.action.decision,...e.action.decisionId!==void 0?{decisionId:e.action.decisionId}:{},...e.ruleCode!==null?{ruleCode:e.ruleCode}:{},reason:e.reason,argRedactionRules:e.action.argRedactionRules??[],...e.action.hitlFallback?{hitlFallback:e.action.hitlFallback}:{}}:{allowed:!0,decision:"permit",reason:e.reason,argRedactionRules:[]}}function Mt(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&e.retrieval.hitlFallback==="mask"&&n.length>0?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}async function ae(e,t,n){let r=y.getStore(),i=F(r),a=await e.evaluate({operations:["retrieval"],agentId:t,...r?.session_id?{sessionId:r.session_id}:{},resourceType:n.resourceType??"document",resourceMetadata:n.resourceMetadata??{},...n.query!==void 0?{query:n.query}:{},...n.contentPreview!==void 0?{contentPreview:n.contentPreview}:{},...i?{telemetry:i}:{}});return Mt(a)}async function se(e,t,n){return await e.awaitBundleReady(),ae(e,t,n)}function Dt(e,t){if(t.action==="deny")return null;if(t.action==="redact"&&t.redactionRules.length>0)try{return R(e,I(t.redactionRules))}catch{return null}return e}async function jt(e,t,n,r){if(!Array.isArray(e)||e.length===0)return e;await r.awaitBundleReady();let i=[];for(let a of e){let o=a,s=String(o.pageContent??o.text??o.content??""),l=o.metadata??{},c=await ae(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s.slice(0,500)}),u=Dt(a,c);u!==null&&i.push(u)}return i}async function qt(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await ae(n,t,{resourceType:"document",resourceMetadata:{content_preview:e.slice(0,500)},contentPreview:e.slice(0,500)})}catch{return"[RECALL] Retrieved context blocked \u2014 policy evaluation error (G001)."}switch(r.action){case"deny":return"[RECALL] Retrieved context was blocked by policy.";case"redact":{if(r.redactionRules.length===0)return e;try{return R(e,I(r.redactionRules))}catch{return"[RECALL] Retrieved context was blocked by policy."}}default:return e}}var $t=4,Ut=1e3;function oe(e){return e.length===0?!1:e.some(t=>t!==null&&typeof t=="object"&&(typeof t.pageContent=="string"||typeof t.text=="string"||typeof t.content=="string"))}async function Kt(e,t,n){let r=[];for(let i of e){let a=i,o=String(a.pageContent??a.text??a.content??""),s={...a.metadata??{},content_preview:o.slice(0,500)},l;try{l=await ae(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:o.slice(0,500)})}catch{continue}let c=Dt(i,l);c!==null&&r.push(c)}return r}async function Ee(e,t,n,r,i){if(r>$t||i.nodes++>Ut)return e;if(Array.isArray(e)){if(oe(e))return i.matched=!0,Kt(e,t,n);let a=[];for(let o of e)a.push(await Ee(o,t,n,r+1,i));return a}if(e!==null&&typeof e=="object"){let a=e,o={...a};for(let s of Object.keys(a))o[s]=await Ee(a[s],t,n,r+1,i);return o}return e}async function le(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&oe(e))return Kt(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await Ee(e,t,n,0,r);if(r.matched)return i}return e}var qr={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function xe(e,t,n){if(t>$t||n.n++>Ut)return e;if(Array.isArray(e))return oe(e)?[]:e.map(r=>xe(r,t+1,n));if(e!==null&&typeof e=="object"){if(oe([e]))return{...qr};let r=e,i={};for(let a of Object.keys(r))i[a]=xe(r[a],t+1,n);return i}return e}function Ft(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?xe(e,0,{n:0}):e}function Vt(e,t){let n=Mt(t);if(n.action==="deny")return Ft(e);if(n.action==="redact"&&n.redactionRules.length>0)try{return R(e,I(n.redactionRules))}catch{return Ft(e)}return e}import{z as ce}from"zod";var $r=ce.object({decision:ce.enum(["permit","deny"]),reason:ce.string(),handoff_event_id:ce.string().nullable()}),q=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},K=class extends q{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},Ur="https://api.visiqlabs.com",Kr=1e4,V=class{config;fetch;constructor(e,t=globalThis.fetch){this.config={agentId:e.agentId,apiKey:e.apiKey??process.env.VISIQ_API_KEY??"",endpoint:e.endpoint??process.env.VISIQ_ENDPOINT??Ur,timeoutMs:e.timeoutMs??Kr},this.fetch=t}get headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Agent-ID":this.config.agentId}}async post(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.fetch(`${this.config.endpoint}${e}`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:n.signal})}finally{clearTimeout(r)}let a=await i.json();if(!i.ok){let o=a?.error??`HTTP ${i.status}`;throw new q(o,"API_ERROR",i.status)}return a}async requestGrant(e){let t=await this.post("/orchestrate/grants",{parent_agent_id:e.parentAgentId,child_agent_id:e.childAgentId,tool_scope:e.toolScope??null,context_scope:e.contextScope??null,purpose:e.purpose,duration_seconds:e.durationSeconds,max_depth:e.maxDepth,parent_grant_token:e.parentGrantToken});return{grantId:t.grant_id,status:"pending",effectiveToolScope:t.effective_tool_scope,effectiveContextScope:t.effective_context_scope,acceptDeadline:t.accept_deadline}}async acceptGrant(e){let t=await this.post(`/orchestrate/grants/${e}/accept`,{});return{grantToken:t.grant_token,toolScope:t.tool_scope,contextScope:t.context_scope,expiresAt:t.expires_at}}async evaluate(e){let t=await this.post("/orchestrate/evaluate",{grant_token:e.grantToken,action:e.action,resource_type:e.resourceType,resource_metadata:e.resourceMetadata??{}}),n=$r.parse(t);return{decision:n.decision,reason:n.reason,handoffEventId:n.handoff_event_id}}async revokeGrant(e,t){return{revokedCount:(await this.post(`/orchestrate/grants/${e}/revoke`,{reason:t})).revoked_count}}};var Bt=new Map;async function Ht(e,t){if(!e||e.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: agentId is required");if(!t||t.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: grantId is required");let n=Bt.get(e);if(n)return n;let r=process.env.VISIQ_API_KEY;if(!r)throw new Error("[ORCHESTRATE] bootstrapGrant: VISIQ_API_KEY env var is required");let i=process.env.VISIQ_ENDPOINT,a=(await new V({agentId:e,apiKey:r,...i?{endpoint:i}:{}}).acceptGrant(t)).grantToken;if(!a||a.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: backend returned empty grant token");return Bt.set(e,a),a}var G=Symbol.for("visiq.orchestrate.wrapped");function Wt(e,t){if(!t.agentId||t.agentId.trim()==="")throw new q("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new q("grantToken is required","CONFIG_ERROR");if(e[G]===!0)return e;let n=new V(t),r=t.failBehavior??"deny",i=async(a,o)=>{let s;try{s=await n.evaluate({grantToken:t.grantToken,action:a,resourceType:o})}catch(l){if(r==="permit"){console.warn("[ORCHESTRATE] evaluate failed \u2014 failing open (failBehavior=permit)",l);return}throw new q(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new K(s.reason,s.handoffEventId)};return new Proxy(e,{get(a,o,s){let l=Reflect.get(a,o,s);return o===G?!0:o==="_call"&&typeof l=="function"?async function(c,...u){let f=a.name;return await i(f??"_call"),l.call(this??a,c,...u)}:(o==="call"||o==="execute"||o==="run")&&typeof l=="function"?async function(c,...u){let f=a.name;return await i(f??String(o)),l.call(this??a,c,...u)}:l}})}var Vr=new Set(["approved","resolved"]),Br=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function Hr(e){return new Promise(t=>setTimeout(t,e))}function Wr(e){if(typeof e!="object"||e===null)return null;let t=e,n=t.hitl_result;if(typeof n=="string"&&n.length>0)return n;let{hitl:r}=t;if(r&&typeof r=="object"){let{status:i}=r;if(typeof i=="string"&&i.length>0)return i==="pending"?null:i}return null}async function z(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=12e4,maskFallback:a=!1,fetchImpl:o=globalThis.fetch,sleep:s=Hr,log:l=g=>console.warn(g)}=e,c=g=>a?{resolution:"mask",reason:g}:{resolution:"block",reason:g};if(!t)return c("HITL approval cannot be confirmed (no backend endpoint) \u2014 fail-closed (G001)");if(!r)return c("HITL approval cannot be confirmed (no decision id) \u2014 fail-closed (G001)");let u=`${t.replace(/\/$/,"")}/v1/allow/decisions/${encodeURIComponent(r)}`,f={Accept:"application/json"};n&&(f.Authorization=`Bearer ${n}`);let d=Date.now()+Math.max(0,i),m=0;for(l(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=d)return l(`[VisIQ HITL] Decision ${r} timed out after ${i}ms \u2014 ${a?"masking":"blocking"} (G001)`),c("HITL approval timed out");let g=null;try{let h=new AbortController,b=setTimeout(()=>h.abort(),5e3),A;try{A=await o(u,{method:"GET",headers:f,signal:h.signal})}finally{clearTimeout(b)}if(!A.ok)throw new Error(`HTTP ${A.status} ${A.statusText}`);let w=await A.json();g=Wr(w),m=0}catch(h){m+=1;let b=h instanceof Error?h.message:String(h);if(l(`[VisIQ HITL] Poll failed for decision ${r} (${m}/3): ${b}`),m>=3)return c(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${b}`);await s(2e3);continue}if(g!==null){let h=g.toLowerCase();return Vr.has(h)?(l(`[VisIQ HITL] Decision ${r} approved (${g}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${g})`}):Br.has(h)?(l(`[VisIQ HITL] Decision ${r} resolved as ${g} \u2014 ${a?"masking":"blocking"}`),c(`Not approved by human reviewer (${g})`)):(l(`[VisIQ HITL] Decision ${r} returned unknown status '${g}' \u2014 ${a?"masking":"blocking"} (G001)`),c(`HITL returned unknown status '${g}' \u2014 fail-closed (G001)`))}await s(2e3)}}import{randomUUID as Yt}from"node:crypto";var Gt=Symbol.for("visiq.semantickernel.instrumented");function zt(e){if(e===null||typeof e!="object")return!1;let t=e;return(Array.isArray(t.functionInvocationFilters)||Array.isArray(t.promptRenderFilters))&&typeof t.execute!="function"&&typeof t.generate!="function"}var Ce=class{constructor(t){this.deps=t}deps;async onFunctionInvocation(t){let{agentId:n,unified:r}=this.deps,i=t.functionName??"unknown",a=t.arguments??{},o=t.pluginName;try{let u=j(await r.evaluate({operations:["action"],agentId:n,toolName:i,toolArgs:a,...o!==void 0?{targetResource:o}:{}}));if(!u.allowed){t.result=`[VisIQ ALLOW] Action blocked: ${u.reason??"policy denied"}.`;return}u.decision==="mask"&&u.argRedactionRules.length>0&&(t.arguments=R(a,I(u.argRedactionRules)))}catch(u){t.result=`[VisIQ ALLOW] Action blocked: evaluation error (fail-closed): ${u instanceof Error?u.message:String(u)}.`;return}try{let u=await se(r,n,{resourceType:"tool_result",resourceMetadata:{function_name:i,plugin_name:t.pluginName}});if(u.action==="deny"||u.action==="escalate"){t.result=`[RECALL: access denied \u2014 ${u.reason}]`;return}}catch(u){t.result=`[RECALL] Result withheld \u2014 evaluation error (fail-closed): ${u instanceof Error?u.message:String(u)}.`;return}await t.proceed();let l=(typeof t.result=="string"?t.result:(()=>{try{return JSON.stringify(t.result)??String(t.result)}catch{return String(t.result)}})()).slice(0,500),c;try{c=await se(r,n,{resourceType:"tool_result",resourceMetadata:{function_name:i,plugin_name:t.pluginName,content_preview:l},contentPreview:l})}catch{t.result="[RECALL] Result withheld \u2014 evaluation error (fail-closed).";return}if(c.action==="deny"||c.action==="escalate"){t.result=`[RECALL: access denied \u2014 ${c.reason}]`;return}if(c.action==="redact"&&c.redactionRules&&c.redactionRules.length>0&&t.result!==null&&t.result!==void 0)try{t.result=R(t.result,I(c.redactionRules))}catch{t.result="[RECALL] Result withheld \u2014 redaction error (fail-closed)."}}},Oe=class{constructor(t){this.deps=t}deps;async onPromptRender(t){await t.proceed();let n=t.renderedPrompt;if(typeof n!="string"||n.length===0)return;let r;try{r=await se(this.deps.unified,this.deps.agentId,{resourceType:"prompt",resourceMetadata:{},contentPreview:n.slice(0,500)})}catch{t.renderedPrompt="[RECALL] Prompt withheld \u2014 evaluation error (fail-closed).";return}if(r.action==="redact"&&r.redactionRules&&r.redactionRules.length>0){try{t.renderedPrompt=R(n,I(r.redactionRules))}catch{t.renderedPrompt="[RECALL] Prompt withheld \u2014 redaction error (fail-closed)."}return}(r.action==="deny"||r.action==="escalate")&&(t.renderedPrompt=`[RECALL: prompt suppressed \u2014 ${r.reason}]`)}};function Qt(e,t){let n=e;return n[Gt]===!0||(Array.isArray(n.functionInvocationFilters)||(n.functionInvocationFilters=[]),Array.isArray(n.promptRenderFilters)||(n.promptRenderFilters=[]),n.functionInvocationFilters.unshift(new Ce(t)),n.promptRenderFilters.push(new Oe(t)),n[Gt]=!0),e}function x(e,t){return`[VisIQ ${e}] Action blocked: ${t}. (VisIQ is a security harness installed by your developer.)`}var Gr=/https?:\/\/[^\s"'`,)}\]]+/;function Le(e){let t=e.match(Gr);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var B=Symbol.for("visiq.toolexec.instrumented");function zr(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}function Zt(e){if(e===null||typeof e!="object")return null;let t=e;if(zr(t))return null;if(zt(e))return"semantic-kernel";if(typeof t.generateText=="function"&&(typeof t.getTools=="function"||t.toolManager!==void 0))return"voltagent";if(typeof t.run=="function"&&typeof t.runStream=="function"&&t.agents!==void 0)return"llamaindex";if(Array.isArray(t.tools)&&t.handoffs!==void 0&&(typeof t.on=="function"||t.eventEmitter!==void 0))return"openai";if(typeof t.generate=="function"&&typeof t.getLLM=="function"&&(typeof t.listTools=="function"||typeof t.getTools=="function"))return"mastra";if(typeof t.generate=="function"){let n=t.settings;if(n&&typeof n=="object"&&n.tools!==void 0||t.tools!==void 0)return"vercel"}return null}async function Qr(e,t,n,r,i){let{agentId:a,unified:o}=e,s=F(i),l;try{await o.awaitBundleReady(),l=j(await o.evaluate({operations:["action"],agentId:a,toolName:t,toolArgs:n,...i?.session_id?{sessionId:i.session_id}:{},...r!==void 0?{targetResource:r}:{},...s?{telemetry:s}:{}}))}catch(c){return{block:x("EVAL-ERROR",`policy evaluation failed: ${c instanceof Error?c.message:String(c)}`)}}if(l.decision==="approval_required"&&l.decisionId){let c=o.getApiKey()??e.apiKey,u=await z({endpoint:o.getEndpoint()??e.endpoint??"",...c?{apiKey:c}:{},decisionId:l.decisionId,timeoutMs:e.hitlTimeoutMs});return u.resolution!=="proceed"?{block:x(l.ruleCode??"HITL-BLOCK",u.reason)}:{block:null}}if(!l.allowed){let c=l.ruleCode??"DENY",u=l.reason??"denied by policy";return{block:x(c,u)}}if(l.decision==="mask"&&l.argRedactionRules&&l.argRedactionRules.length>0)try{let c=I(l.argRedactionRules);return{block:null,maskedArgs:R(n,c)}}catch(c){return{block:x("MASK-ERROR",`argument masking failed: ${c instanceof Error?c.message:String(c)}`)}}return{block:null}}async function Ne(e,t,n,r,i){let a=y.getStore()??e.telemetry,o=await Qr(e,t,n,Le(r),a);if(o.block!==null)return o.block;let s=o.maskedArgs??n,l=await i(s);return le(l,e.agentId,e.unified)}function ue(e,t,n){let r=e;if(r[B]||typeof r.execute!="function")return;let i=r.execute;Fe(r,"execute",async function(...o){let s=Re(o[0]);return Ne(n,t,s,Y(s),l=>Promise.resolve(i.apply(this,[l,...o.slice(1)])))}),r[B]=!0}function Yr(e,t,n){let r=e;if(r[B]||typeof r.invoke!="function")return;let i=r.invoke;Fe(r,"invoke",async function(...o){let s=o[1],l=xt(s),c=typeof s=="string"?s:Y(l);return Ne(n,t,l,c,u=>{let f=typeof s=="string"?JSON.stringify(u):u;return Promise.resolve(i.apply(this,[o[0],f,...o.slice(2)]))})}),r[B]=!0}function Zr(e,t){let n=e;if(n[B]||typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",a=n.call;Fe(n,"call",async function(...s){let l=Re(s[0]);return Ne(t,i,l,Y(l),c=>Promise.resolve(a.apply(this,[c,...s.slice(1)])))}),n[B]=!0}function Jt(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&ue(r,n,t);return e}function Xt(e,t,n){switch(n){case"vercel":return Jr(e,t);case"mastra":return Xr(e,t);case"openai":return ni(e,t);case"llamaindex":return ti(e,t);case"voltagent":return ei(e,t);case"semantic-kernel":return Qt(e,t);default:return e}}function Jr(e,t){let n=e,r=n.settings&&typeof n.settings=="object"?n.settings:void 0,i=r?.tools??n.tools;return i&&typeof i=="object"&&Jt(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=Pe(r.onStepFinish)),de(e,["generate","stream"],async(a,o)=>(Q(o,a[0]),a)),e}function Xr(e,t){let r=ai(e);return r&&Jt(r,t),de(e,["generate","stream","generateVNext","streamVNext"],async(i,a)=>{Q(a,i[0]);let o=i[1]&&typeof i[1]=="object"?{...i[1]}:{};o.onStepFinish=Pe(o.onStepFinish);let s=[...i];return s[1]=o,s}),e}function ei(e,t){let n=ii(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;ue(r,typeof i=="string"?i:"unknown",t)}}return de(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{Q(i,r[0]);let a=r[1]&&typeof r[1]=="object"?{...r[1]}:{};a.onStepFinish=Pe(a.onStepFinish);let o=[...r];return o[1]=a,o}),e}function ti(e,t){let n=e,r=a=>{let o=a?.tools;if(Array.isArray(o))for(let s of o)s!==null&&typeof s=="object"&&Zr(s,t)},{agents:i}=n;if(i instanceof Map)for(let a of i.values())r(a);else Array.isArray(n.tools)&&r(n);return de(e,["run"],async(a,o)=>(Q(o,a[0]),a)),oi(e,"runStream",(a,o,s)=>{s||Q(o,a[0])}),e}function ni(e,t){let n=e,{tools:r}=n;if(Array.isArray(r)){for(let i of r)if(i!==null&&typeof i=="object"){let{name:a}=i;Yr(i,typeof a=="string"?a:"unknown",t)}}return ri(e,t),e}function ri(e,t){let n=e;if(n.__visiq_openai_hooks||typeof n.on!="function")return;let r=n.on,{telemetry:i}=t;r.call(e,"agent_start",(...a)=>{i.session_id=Yt(),i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let o=a[2];o!=null&&i.llm_prompts.push(Y(o).slice(0,5120))}),r.call(e,"agent_end",(...a)=>{let o=a[1];typeof o=="string"&&o&&i.llm_responses.push(o.slice(0,5120))}),n.__visiq_openai_hooks=!0}function ii(e){let t=r=>Array.isArray(r)&&r.some(i=>i!==null&&typeof i.execute=="function");if(typeof e.getTools=="function")try{let r=e.getTools();if(t(r))return r}catch{}let n=e.toolManager;if(n&&typeof n.getAllBaseTools=="function")try{let r=n.getAllBaseTools();if(t(r))return r}catch{}return t(e.tools)?e.tools:null}function de(e,t,n){let r=e;for(let i of t){if(typeof r[i]!="function")continue;let a=`__visiq_wrapped_${i}`;if(r[a])continue;let o=r[i];r[i]=function(...s){let l=en();return y.run(l,async()=>{let c=await n(s,l);return o.apply(e,c)})},r[a]=!0}}function oi(e,t,n){let r=e;if(typeof r[t]!="function")return;let i=`__visiq_wrapped_${t}`;if(r[i])return;let a=r[t];r[t]=function(...o){let s=y.getStore(),l=s??en();return n(o,l,s!==void 0),y.run(l,()=>a.apply(e,o))},r[i]=!0}function Pe(e){return t=>{let n=y.getStore(),r=t;if(n&&typeof r?.text=="string"&&r.text&&n.llm_responses.push(r.text.slice(0,5120)),typeof e=="function")return e(t)}}function Q(e,t){if(t==null)return;let n=t;if(typeof t=="object"){let r=t;n=r.prompt??r.messages??t}e.llm_prompts.push(Y(n).slice(0,5120))}function ai(e){for(let t of["listTools","getTools"])if(typeof e[t]=="function")try{let n=e[t]();if(n&&typeof n=="object"&&typeof n.then!="function")return n}catch{}return null}function en(){return{session_id:Yt(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Fe(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function Y(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function sn(e,t){let n=pi(t);if(e[G]===!0)return e;let r=mi(e);if(r==="langchain-executor"||r==="langchain-graph")return _i(e,n);let i=Zt(e);if(i)return Xt(e,dn(n),i);if(yi(e)){let a=process.env.VISIQ_GRANT_ID;return a?bi(e,n,a):vi(e,n)}throw new Error("[VisIQ] Cannot detect agentic framework. Pass a LangChain AgentExecutor, LangGraph CompiledGraph, or a tool with one of: _call, execute, call, run, invoke.")}var ui="\0",tn=new Map;function De(e,t,n,r){let i=[e??"",t??"",n??"",r??""].join(ui),a=tn.get(i);return a||(a=new Et(e,t,n,void 0,r),a.registerHostEnvironment(),tn.set(i,a)),a}function di(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let t=process.env.VISIQ_TIMEOUT_MS;if(t!==void 0){let n=Number.parseInt(t,10);if(Number.isFinite(n)&&n>0)return n}}function pi(e){return{agentId:e?.agentId??process.env.VISIQ_AGENT_ID??fi(),apiKey:e?.apiKey??process.env.VISIQ_API_KEY,endpoint:e?.endpoint??process.env.VISIQ_ENDPOINT,hitlTimeoutMs:gi(e?.hitlTimeoutMs),timeoutMs:di(e?.timeoutMs)}}function fi(){let e=t=>t.toLowerCase().replace(/^@[^/]+\//,"").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,255);try{let t=process.cwd();for(let n=0;n<64;n++){let r=ge.join(t,"package.json");if(fe.existsSync(r)){let a=JSON.parse(fe.readFileSync(r,"utf8"));if(typeof a.name=="string"&&a.name.trim()){let o=e(a.name);if(o)return o}break}let i=ge.dirname(t);if(i===t)break;t=i}}catch{}try{let t=e(an.hostname());if(t)return t}catch{}return"agent"}function gi(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let t=process.env.VISIQ_HITL_TIMEOUT_MS;if(t){let n=Number(t);if(Number.isFinite(n)&&n>0)return n}return 12e4}function mi(e){let t=e;return typeof t.invoke=="function"&&t.agent&&Array.isArray(t.tools)?"langchain-executor":typeof t.invoke=="function"&&t.nodes&&(t.edges||t.lg_is_pregel===!0||typeof t.builder=="object"&&t.builder!==null&&t.builder.edges)?"langchain-graph":"unknown"}function _i(e,t){let n=e,r=De(t.apiKey,t.endpoint,t.agentId,t.timeoutMs);if(Array.isArray(n.tools))for(let a of n.tools)je(a,t.agentId,r),hi(a,t.agentId,r,t),cn(a,r,t);let i=n.invoke;if(n.invoke=function(a,o){let s=Me(),l=on(t.agentId,r),c=o?.callbacks??[];return y.run(s,()=>i.call(this,a,{...o,callbacks:[...c,l]}))},typeof n.stream=="function"){let a=n.stream;n.stream=function(o,s){let l=Me(),c=on(t.agentId,r),u=s?.callbacks??[];return y.run(l,()=>a.call(this,o,{...s,callbacks:[...u,c]}))}}return e}function Me(){return{session_id:li(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function je(e,t,n){let r=e,i=Symbol.for("visiq.recall.instrumented");if(!r[i]){if(typeof r._getRelevantDocuments=="function"){let a=r._getRelevantDocuments;r._getRelevantDocuments=async function(o,s){let l=await a.call(this,o,s);return nn(l,t,o,n)},r[i]=!0}if(typeof r.retrieve=="function"&&!r._getRelevantDocuments){let a=r.retrieve;r.retrieve=async function(o){let s=await a.call(this,o);return nn(s,t,String(o),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&je(r.retriever,t,n)}}function hi(e,t,n,r){let i=e,a=Symbol.for("visiq.recall.tool-instrumented");if(i[a]||typeof i.func!="function")return;let o=typeof i.name=="string"?i.name:"",s=typeof i.retriever=="object"&&i.retriever!==null,l=o.split(/[^a-zA-Z0-9]+|(?<=[a-z])(?=[A-Z])/).map(k=>k.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),f=l.some(k=>c.has(k)),d=u.has(l[0]??""),m=f||d,g=["update","delete","create","archive","insert","remove"],h=l.some(k=>g.some(T=>k.length>T.length&&k.endsWith(T))),A=/retriev/i.test(o)||/search.*doc|knowledge/i.test(o)&&!m&&!h;if(!(s||A))return;let C=f||h;if(!C)if(s)je(i.retriever,t,n);else{let k=globalThis,T=Symbol.for("visiq.recall.closureRetrieverWarned"),M=k[T]??=new Set;M.has(o)||(M.add(o),console.warn(`[VisIQ] Retriever tool "${o||"(unnamed)"}" exposes no reachable retriever (e.g. LangChain createRetrieverTool returns a joined string). RECALL masks its output via value-shape + whole-result rules, but PER-DOCUMENT metadata/classification rules cannot apply to a metadata-less joined string. For full per-doc governance, pass the retriever to visiq() directly, or use a tool that returns a Document[].`))}let P=i.func;C?(i[ln]=!0,i.func=async function(...k){await n.awaitBundleReady();let T=k[0],M=typeof T=="object"&&T!==null?T:{input:T},qe=typeof M.query=="string"?M.query:void 0,me=y.getStore(),$e=F(me),Ue=await n.evaluate({operations:["retrieval","action"],agentId:t,...me?.session_id?{sessionId:me.session_id}:{},toolName:o||"unknown",toolArgs:M,resourceType:"document",resourceMetadata:{},...qe!==void 0?{query:qe}:{},...$e?{telemetry:$e}:{}}),S=j(Ue),gn=S.hitlFallback==="mask"&&S.argRedactionRules.length>0,Ke=k,Ve=()=>{try{return Ke=[R(M,I(S.argRedactionRules)),...k.slice(1)],null}catch{return x("MASK-ERROR","argument masking failed (fail-closed)")}};if(S.decision==="approval_required"&&S.decisionId&&r){let D=await z({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:S.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:gn});if(D.resolution==="mask"){let Be=Ve();if(Be)return Be}else if(D.resolution!=="proceed")return x(S.ruleCode??"HITL-BLOCK",D.reason)}else if(!S.allowed)return x(S.ruleCode??"DENY",S.reason);if(S.decision==="mask"&&S.argRedactionRules.length>0){let D=Ve();if(D)return D}let mn=await P.apply(this,Ke);return Vt(mn,Ue)}):i.func=async function(...k){let T=await P.apply(this,k);return typeof T=="string"?qt(T,t,n):le(T,t,n)},i[a]=!0}var ln=Symbol.for("visiq.hybrid.instrumented");async function nn(e,t,n,r){return jt(e,t,n,r)}var rn=["invoke","call","_call"],pe=new ci;function cn(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[ln]||!rn.some(c=>typeof r[c]=="function"))return;let{agentId:a}=n,o=typeof r.name=="string"?r.name:"unknown",s=Symbol("visiq.gate"),l=async(c,u,f,d,m)=>{let g=pe.getStore();if(g!==void 0&&g.gateKey===s&&!g.entered.has(m))return g.entered.add(m),c.call(u,f,...d);let h;if(typeof f=="string")h=f;else{let C=f?.input;h=C!=null?String(C):JSON.stringify(f)??""}let b=y.getStore(),A=F(b);await t.awaitBundleReady();let w=j(await t.evaluate({operations:["action"],agentId:a,...b?.session_id?{sessionId:b.session_id}:{},toolName:o,toolArgs:typeof f=="object"&&f!==null?f:{input:h},targetResource:Le(h),...A?{telemetry:A}:{}}));if(w.decision==="approval_required"&&w.decisionId){let C=w.hitlFallback==="mask"&&w.argRedactionRules.length>0,P=await z({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:w.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:C});if(P.resolution==="proceed")return pe.run({gateKey:s,entered:new Set([m])},()=>c.call(u,f,...d));if(P.resolution==="mask")try{let T=R(f,I(w.argRedactionRules));return pe.run({gateKey:s,entered:new Set([m])},()=>c.call(u,T,...d))}catch{return x("MASK-ERROR","argument masking failed (fail-closed)")}let k=w.ruleCode??"HITL-BLOCK";return x(k,P.reason)}if(!w.allowed){let C=w.ruleCode??"DENY",P=w.reason??"denied by policy";return x(C,P)}return pe.run({gateKey:s,entered:new Set([m])},()=>c.call(u,f,...d))};for(let c of rn){if(typeof r[c]!="function")continue;let u=r[c];r[c]=function(f,...d){return l(u,this,f,d,c)}}r[i]=!0}function on(e,t){return{name:"VisiqHandler",handleLLMStart:async(n,r)=>{let i=y.getStore();i&&i.llm_prompts.push(...r)},handleLLMEnd:async n=>{let r=y.getStore();if(!r)return;let i=n?.generations;i?.[0]?.[0]?.text&&r.llm_responses.push(i[0][0].text)},handleAgentAction:async n=>{let r=y.getStore();if(!r)return;let i=typeof n.log=="string"?n.log:"";i&&r.agent_reasoning.push(i)},handleRetrieverStart:async(n,r,i)=>{let a=y.getStore();a&&a.retrieverQueries.set(i,r??"")},handleRetrieverEnd:async(n,r)=>{let i=y.getStore();if(!i)return;let a=i.retrieverQueries.get(r)??"";if(i.retrieverQueries.delete(r),!Array.isArray(n))return;let o=F(i);for(let s of n){let l=s,c=String(l.pageContent??l.text??l.content??""),u=l.metadata??{};await t.evaluate({operations:["retrieval"],agentId:e,resourceType:"document",resourceMetadata:u,query:a,contentPreview:c.slice(0,500),...o?{telemetry:o}:{}})}},handleRetrieverError:async(n,r)=>{let i=y.getStore();i&&i.retrieverQueries.delete(r)}}}var un=["_call","execute","call","run","invoke"];function yi(e){let t=e;for(let n of un)if(typeof t[n]=="function")return!0;return!1}function bi(e,t,n){let r=null,i=null,a=async()=>{if(r)return r;if(i)throw new K(`Failed to bootstrap grant ${n}: ${i.message}`,null);let o;try{o=await Ht(t.agentId,n)}catch(s){throw i=s instanceof Error?s:new Error(String(s)),new K(`Failed to bootstrap grant ${n}: ${i.message}`,null)}return r=Wt(e,{agentId:t.agentId,grantToken:o,...t.apiKey?{apiKey:t.apiKey}:{},...t.endpoint?{endpoint:t.endpoint}:{}}),r};return new Proxy(e,{get(o,s,l){if(s===G)return!0;let c=Reflect.get(o,s,l);return typeof c!="function"||typeof s!="string"||!un.includes(s)?c:async function(...u){let f=await a();return f[s].call(f,...u)}}})}function vi(e,t){let n=De(t.apiKey,t.endpoint,t.agentId,t.timeoutMs);cn(e,n,t);let r=e;if(typeof r.execute=="function"){let i=typeof r.name=="string"&&r.name||typeof r.id=="string"&&r.id||"unknown";ue(e,i,dn(t))}return e}function dn(e){return{agentId:e.agentId,unified:De(e.apiKey,e.endpoint,e.agentId,e.timeoutMs),hitlTimeoutMs:e.hitlTimeoutMs,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:Me()}}async function pn(e,t={}){if(!e||e.trim()==="")throw new Error("[VisIQ] visiq.delegate: childAgentId is required");let n=process.env.VISIQ_AGENT_ID;if(!n)throw new Error("[VisIQ] visiq.delegate: VISIQ_AGENT_ID env var is required. Set it to the parent agent ID before calling delegate.");let r=process.env.VISIQ_API_KEY;if(!r)throw new Error("[VisIQ] visiq.delegate: VISIQ_API_KEY env var is required");let i=process.env.VISIQ_ENDPOINT;return{VISIQ_GRANT_ID:(await new V({agentId:n,apiKey:r,...i?{endpoint:i}:{}}).requestGrant({parentAgentId:n,childAgentId:e,toolScope:t.toolScope??null,contextScope:t.contextScope??null,durationSeconds:t.durationSeconds??3600,purpose:t.purpose??`Delegated to ${e}`,...t.maxDepth!==void 0?{maxDepth:t.maxDepth}:{},...t.parentGrantToken!==void 0?{parentGrantToken:t.parentGrantToken}:{}})).grantId}}var Z=class{constructor(t){this.transport=t}transport;deploy(t={}){let n={include_mac:t.includeMac??!1};return t.autoInstallHarness!==void 0&&(n.auto_install_harness=t.autoInstallHarness),$(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return $(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return $(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return $(this.transport,"POST","/api/discovery/fleet/stop")}};var J=class{constructor(t){this.transport=t}transport;connectAws(t){return $(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function wi(e){if(!e.baseUrl||e.baseUrl.length===0)throw new Error("[VisIQ] createVisiqClient: baseUrl is required");if(!e.accessToken&&!e.cookieHeader)throw new Error("[VisIQ] createVisiqClient: one of accessToken or cookieHeader is required");let t=e.baseUrl.replace(/\/$/,""),n=e.fetchImpl??globalThis.fetch.bind(globalThis),r={baseUrl:t,accessToken:e.accessToken,cookieHeader:e.cookieHeader,fetchImpl:n};return{fleet:new Z(r),integrations:new J(r)}}async function $(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,a={};e.cookieHeader&&(a.Cookie=e.cookieHeader),e.accessToken&&(a.Authorization=`Bearer ${e.accessToken}`);let o;r!==void 0&&(a["Content-Type"]="application/json",o=JSON.stringify(r));let s=await e.fetchImpl(i,{method:t,headers:a,body:o});if(!s.ok){let l="";try{l=await s.text()}catch{}throw new Error(`[VisIQ] ${t} ${n} failed (${s.status}): ${l||s.statusText}`)}return await s.json()}var fn=sn;fn.delegate=pn;var Mo=fn;export{Z as FleetClient,J as IntegrationsClient,wi as createVisiqClient,pn as delegate,Mo as visiq};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@visiq/harness",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "VisIQ SDK — AI agent governance harness",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -12,7 +12,6 @@
|
|
|
12
12
|
}
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@open-policy-agent/opa-wasm": "^1.9.0",
|
|
16
15
|
"zod": "^3.23.8"
|
|
17
16
|
},
|
|
18
17
|
"publishConfig": {
|