@visiq/harness 0.2.0

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.
@@ -0,0 +1,184 @@
1
+ export interface VisiqOptions {
2
+ /**
3
+ * Agent identity. Optional — resolution order is this option →
4
+ * VISIQ_AGENT_ID env var → a value derived from the runtime (package name →
5
+ * hostname). The backend auto-provisions whatever id first appears (in
6
+ * monitor mode), so an unset id still works end-to-end. Set it explicitly
7
+ * for a stable, rule-friendly name.
8
+ */
9
+ agentId?: string;
10
+ /** Backend API key. Falls back to VISIQ_API_KEY env var. */
11
+ apiKey?: string;
12
+ /** Backend endpoint URL. Falls back to VISIQ_ENDPOINT env var. */
13
+ endpoint?: string;
14
+ /**
15
+ * Max time (ms) to wait for a human to resolve an ALLOW `approval_required`
16
+ * (HITL) decision before failing closed and blocking the tool call. Falls
17
+ * back to the VISIQ_HITL_TIMEOUT_MS env var, then to 300_000ms (5 min) —
18
+ * matching the backend's `allow_settings.hitl_timeout_seconds` default.
19
+ */
20
+ hitlTimeoutMs?: number;
21
+ }
22
+ export interface DelegateOptions {
23
+ /** Restrict the child's tool calls to this allow-list. `undefined` inherits parent's full scope. */
24
+ toolScope?: string[];
25
+ /** Restrict the child's resource-typed accesses to this allow-list. `undefined` inherits parent. */
26
+ contextScope?: string[];
27
+ /** Grant lifetime in seconds. Defaults to 3600 (1 hour). */
28
+ durationSeconds?: number;
29
+ /** Human-readable description of why the parent is delegating. Surfaced in the audit log. */
30
+ purpose?: string;
31
+ /** Maximum depth of further sub-delegation. `undefined` defers to backend default. */
32
+ maxDepth?: number;
33
+ /**
34
+ * If the parent itself is a child of another grant, supply the parent's own
35
+ * grant token here so the backend can enforce the scope chain (child cannot
36
+ * delegate authority it doesn't have).
37
+ */
38
+ parentGrantToken?: string;
39
+ }
40
+ /**
41
+ * Result of `visiq.delegate()` — the environment variables a child process
42
+ * must receive to operate as a delegated agent.
43
+ *
44
+ * The shape is intentionally an object (rather than just the grant ID) so that
45
+ * future fields — `VISIQ_PARENT_AGENT_ID`, lineage propagation, etc. — can be
46
+ * added without breaking callers that spread it into `process.env`.
47
+ */
48
+ export interface DelegateResult {
49
+ VISIQ_GRANT_ID: string;
50
+ }
51
+ /**
52
+ * Create a delegation grant for a child agent and return the env vars to
53
+ * propagate.
54
+ *
55
+ * The parent agent's identity comes from `VISIQ_AGENT_ID` (set by `visiq()`
56
+ * options or env). The parent's API key comes from `VISIQ_API_KEY`. Both are
57
+ * required — without them this call throws synchronously rather than silently
58
+ * failing or proceeding without proper attribution.
59
+ */
60
+ export declare function delegate(childAgentId: string, opts?: DelegateOptions): Promise<DelegateResult>;
61
+ export type AgentVendor = "visiq" | "crowdstrike" | "intune" | "sentinelone" | "unknown";
62
+ export interface FleetInstance {
63
+ instance_id: string;
64
+ instance_type: string;
65
+ platform: "linux" | "windows" | "macos" | "unknown";
66
+ state: "pending" | "running" | "stopping" | "stopped" | "shutting-down" | "terminated";
67
+ launch_time: string | null;
68
+ public_ip: string | null;
69
+ private_ip: string | null;
70
+ tags: Record<string, string>;
71
+ /** ISO timestamp of the last per-instance heartbeat; null if never seen. */
72
+ last_scanned: string | null;
73
+ /** Vendor of the agent reporting heartbeats for this instance. */
74
+ agent_vendor: AgentVendor;
75
+ }
76
+ export interface FleetHeartbeat {
77
+ bucket: string;
78
+ key: string;
79
+ last_seen_at: string | null;
80
+ age_seconds: number | null;
81
+ }
82
+ export interface FleetStatusResponse {
83
+ tenant_id: string;
84
+ aws_account_id: string;
85
+ aws_region: string;
86
+ instances: FleetInstance[];
87
+ heartbeat: FleetHeartbeat;
88
+ }
89
+ export interface DeployFleetInput {
90
+ includeMac?: boolean;
91
+ }
92
+ export interface DeployFleetResponse {
93
+ tenant_id: string;
94
+ launched_instance_ids: string[];
95
+ include_mac: boolean;
96
+ /**
97
+ * Always `null` on the deploy response: new instances start with
98
+ * `last_scanned = null` until the on-host delivery agent posts its first
99
+ * heartbeat. Kept in the shape for backward compatibility with 0.1.x.
100
+ */
101
+ heartbeat: null;
102
+ }
103
+ /**
104
+ * Per-instance heartbeat input.
105
+ *
106
+ * BREAKING from 0.1.x: `heartbeat()` no longer accepts zero arguments.
107
+ * Each call now corresponds to a single instance; callers iterating a
108
+ * fleet must invoke once per instance.
109
+ */
110
+ export interface HeartbeatInput {
111
+ instanceId: string;
112
+ vendor: AgentVendor;
113
+ }
114
+ export interface HeartbeatResponse {
115
+ tenant_id: string;
116
+ bucket: string;
117
+ key: string;
118
+ written_at: string;
119
+ instance_id: string;
120
+ }
121
+ export interface StopFleetResponse {
122
+ tenant_id: string;
123
+ stopped_instance_ids: string[];
124
+ }
125
+ export declare class FleetClient {
126
+ private readonly transport;
127
+ constructor(transport: Transport);
128
+ deploy(input?: DeployFleetInput): Promise<DeployFleetResponse>;
129
+ status(): Promise<FleetStatusResponse>;
130
+ heartbeat(input: HeartbeatInput): Promise<HeartbeatResponse>;
131
+ stop(): Promise<StopFleetResponse>;
132
+ }
133
+ export interface ConnectAwsInput {
134
+ awsAccountId: string;
135
+ awsRegion: string;
136
+ }
137
+ export interface ConnectAwsResponse {
138
+ tenant_id: string;
139
+ aws_account_id: string;
140
+ aws_region: string;
141
+ created_at: string;
142
+ updated_at: string;
143
+ }
144
+ export declare class IntegrationsClient {
145
+ private readonly transport;
146
+ constructor(transport: Transport);
147
+ connectAws(input: ConnectAwsInput): Promise<ConnectAwsResponse>;
148
+ }
149
+ export interface CreateVisiqClientOptions {
150
+ /** Base URL of the Project Y web app (e.g. http://localhost:3000). */
151
+ baseUrl: string;
152
+ /** Supabase access token (`session.access_token`). Sent as Bearer auth. */
153
+ accessToken?: string;
154
+ /** Pre-built Cookie header (`sb-<ref>-auth-token=...`). */
155
+ cookieHeader?: string;
156
+ /** Optional `fetch` override (defaults to global fetch). */
157
+ fetchImpl?: typeof fetch;
158
+ }
159
+ export interface VisiqClient {
160
+ fleet: FleetClient;
161
+ integrations: IntegrationsClient;
162
+ }
163
+ export declare function createVisiqClient(opts: CreateVisiqClientOptions): VisiqClient;
164
+ export interface Transport {
165
+ baseUrl: string;
166
+ accessToken?: string;
167
+ cookieHeader?: string;
168
+ fetchImpl: typeof fetch;
169
+ }
170
+ /**
171
+ * Callable + namespaced `visiq` entry point.
172
+ *
173
+ * The function form is the ALLOW/RECALL/ORCHESTRATE tool & framework wrap
174
+ * (`visiq(target, { agentId })`). `visiq.delegate(child, opts)` mints a
175
+ * delegation grant and returns the env vars the child process needs.
176
+ */
177
+ export interface VisiqFunction {
178
+ <T extends object>(target: T, options?: VisiqOptions): T;
179
+ /** Mint an ORCHESTRATE delegation grant for a child agent. */
180
+ delegate: typeof delegate;
181
+ }
182
+ export declare const visiq: VisiqFunction;
183
+
184
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ import{randomUUID as nn}from"node:crypto";import*as H from"node:fs";import*as K from"node:path";import*as je from"node:os";import{z as w}from"zod";import{z as u}from"zod";import{createHash as Be}from"crypto";var re=new Map;function Qe(e){let t=Be("sha256").update(e).digest("hex"),r=re.get(t);if(r)return r;let n=new Map,o=[],i=e.split(`
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};
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@visiq/harness",
3
+ "version": "0.2.0",
4
+ "description": "VisIQ SDK — AI agent governance harness",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "dependencies": {
15
+ "@open-policy-agent/opa-wasm": "^1.9.0",
16
+ "zod": "^3.23.8"
17
+ },
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "license": "MIT",
25
+ "files": [
26
+ "dist",
27
+ "README.md"
28
+ ],
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/VISIQ-LABS/xy.git",
32
+ "directory": "packages/visiq-sdk-ts"
33
+ },
34
+ "keywords": [
35
+ "visiq",
36
+ "ai-agent",
37
+ "sdk",
38
+ "governance",
39
+ "harness"
40
+ ],
41
+ "peerDependencies": {
42
+ "@langchain/core": ">=0.3.0",
43
+ "llamaindex": ">=0.11.0"
44
+ },
45
+ "peerDependenciesMeta": {
46
+ "@langchain/core": {
47
+ "optional": true
48
+ },
49
+ "llamaindex": {
50
+ "optional": true
51
+ }
52
+ }
53
+ }