@visiq/harness 0.2.3 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +83 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +2 -2
- package/package.json +3 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 VisIQ Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# @visiq/harness
|
|
2
|
+
|
|
3
|
+
**Governance for AI agents — one function, injected into your agentic framework.**
|
|
4
|
+
|
|
5
|
+
`@visiq/harness` wraps the tools and executors of your agent framework so every
|
|
6
|
+
tool call and retrieval is evaluated against your VisIQ governance rules **in
|
|
7
|
+
process, before it runs**. Decisions are made by the same compiled governance
|
|
8
|
+
core (`@visiq/core-wasm`) that powers the VisIQ platform — so what you enforce
|
|
9
|
+
locally is exactly what the control plane authored.
|
|
10
|
+
|
|
11
|
+
- **Fail-closed by design** — if a decision can't be made (core unavailable,
|
|
12
|
+
network error, malformed policy), the call is **denied**, never allowed.
|
|
13
|
+
- **One call to adopt** — `visiq(target)` wraps a framework executor or an
|
|
14
|
+
individual tool. No rewrite of your agent.
|
|
15
|
+
- **Human-in-the-loop** — an `approval_required` decision blocks the tool and
|
|
16
|
+
waits for a human to approve/deny (bounded by a timeout that itself
|
|
17
|
+
fails closed).
|
|
18
|
+
- **Retrieval redaction** — masks sensitive fields in retrieved content
|
|
19
|
+
according to policy.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @visiq/harness
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`@visiq/core-wasm` (the compiled decision core) is a **required** dependency and
|
|
28
|
+
is installed automatically. **Node.js ≥ 20** only (the core is loaded as native
|
|
29
|
+
Node WASM — not a browser build).
|
|
30
|
+
|
|
31
|
+
## Quickstart
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { visiq } from "@visiq/harness";
|
|
35
|
+
import { AgentExecutor } from "langchain/agents";
|
|
36
|
+
|
|
37
|
+
// Wrap your framework's executor — every governed tool call now flows
|
|
38
|
+
// through VisIQ before it executes.
|
|
39
|
+
const executor = visiq(new AgentExecutor({ agent, tools }));
|
|
40
|
+
|
|
41
|
+
await executor.invoke({ input: "..." });
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Wrap an individual tool with an explicit, rule-friendly agent identity:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
const search = visiq(new SearchTool(), { agentId: "research-agent" });
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Configuration
|
|
51
|
+
|
|
52
|
+
Options may be passed to `visiq(target, options)` or supplied via environment
|
|
53
|
+
variables (option takes precedence, then the env var):
|
|
54
|
+
|
|
55
|
+
| Option | Env var | Purpose |
|
|
56
|
+
|---|---|---|
|
|
57
|
+
| `apiKey` | `VISIQ_API_KEY` | Backend API key. |
|
|
58
|
+
| `endpoint` | `VISIQ_ENDPOINT` | Backend endpoint URL. |
|
|
59
|
+
| `agentId` | `VISIQ_AGENT_ID` | Stable agent identity. If unset it is derived (package name → hostname) and auto-provisioned in monitor mode. |
|
|
60
|
+
| `hitlTimeoutMs` | `VISIQ_HITL_TIMEOUT_MS` | Max wait (ms) for a human to resolve an `approval_required` decision before failing closed. Default `120000`. |
|
|
61
|
+
|
|
62
|
+
## Multi-agent delegation
|
|
63
|
+
|
|
64
|
+
For multi-agent (ORCHESTRATE) flows, mint the env a child process needs so its
|
|
65
|
+
authority is a scoped delegation of the parent's:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
const childEnv = await visiq.delegate("summarizer-agent");
|
|
69
|
+
spawn("node", ["summarizer.js"], { env: { ...process.env, ...childEnv } });
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Behavior contract
|
|
73
|
+
|
|
74
|
+
- **Deny is terminal** — a denied tool call throws before the tool runs; the
|
|
75
|
+
underlying tool is never invoked.
|
|
76
|
+
- **Approval blocks** — an `approval_required` decision suspends the call until
|
|
77
|
+
a human resolves it, or the HITL timeout elapses (then it fails closed).
|
|
78
|
+
- **Errors fail closed** — any evaluation error results in denial, never a
|
|
79
|
+
silent allow.
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
MIT © VisIQ Labs. See [LICENSE](./LICENSE).
|
package/dist/index.d.ts
CHANGED
|
@@ -27,6 +27,18 @@ export interface VisiqOptions {
|
|
|
27
27
|
* unchanged; this only sets the patience before a network failure denies.
|
|
28
28
|
*/
|
|
29
29
|
timeoutMs?: number;
|
|
30
|
+
/**
|
|
31
|
+
* What to do when `visiq()` detects an execute-based agent framework but
|
|
32
|
+
* instruments ZERO tools — the silent no-instrument failure (a moved/renamed
|
|
33
|
+
* tool bag on a framework version bump) that would let the agent run
|
|
34
|
+
* un-governed. `'warn'` (default): emit a structured telemetry event + a loud
|
|
35
|
+
* console warning, but return the (un-instrumented) agent so a legitimately
|
|
36
|
+
* TOOL-LESS LLM-only agent is not broken. `'throw'`: refuse to run
|
|
37
|
+
* un-governed (strict fail-closed) — recommended for enforcement-critical
|
|
38
|
+
* deployments where every agent is expected to expose tools. Either way the
|
|
39
|
+
* failure is now LOUD; only the silent path is removed.
|
|
40
|
+
*/
|
|
41
|
+
onInstrumentFailure?: "warn" | "throw";
|
|
30
42
|
}
|
|
31
43
|
export interface DelegateOptions {
|
|
32
44
|
/** Restrict the child's tool calls to this allow-list. `undefined` inherits parent's full scope. */
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{randomUUID as rr}from"node:crypto";import*as le from"node:fs";import*as ce from"node:path";import*as St from"node:os";import{AsyncLocalStorage as ir}from"node:async_hooks";import{z as d}from"zod";import*as x from"node:os";var Oe="interceptor_source",Mt=d.enum(["enforce","audit","off"]),jt=d.enum(["closed","open"]),Le=d.enum(["enforce","monitor","off"]),qt=d.object({apiKey:d.string().min(1,"apiKey is required"),agentId:d.string().min(1,"agentId is required"),endpoint:d.string().url().optional(),mode:Mt.optional(),timeoutMs:d.number().int().positive().optional(),hitlTimeoutMs:d.number().int().positive().optional(),failBehavior:jt.optional()}),yr=d.object({agent_id:d.string().min(1),target_app:d.string().min(1),action:d.string().min(1),context:d.record(d.unknown()).optional(),session_id:d.string().min(1).max(255).optional(),telemetry:d.record(d.unknown()).optional()}),$t=d.object({field:d.string().optional(),pattern:d.string().optional(),replacement:d.string().optional(),mode:d.enum(["full","partial","email"]).optional(),keepFirst:d.number().optional(),keepLast:d.number().optional(),maskChar:d.string().optional()}),Ut=d.object({decision_id:d.string().min(1),decision:d.enum(["permit","deny","approval_required","mask"]),reason:d.string().optional(),rule_code:d.string().nullable().optional(),enforced:d.boolean().optional(),agent_mode:Le.optional(),arg_redaction_rules:d.array($t).optional(),plane:d.string().nullable().optional(),operation:d.string().nullable().optional(),is_retrieval:d.boolean().optional(),metadata:d.record(d.unknown()).optional()}),Bt=d.object({field:d.string().min(1),operator:d.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:d.union([d.string(),d.number(),d.array(d.string())])}),Kt=d.object({id:d.string().min(1),rule_code:d.string().default(""),name:d.string().min(1),description:d.string().nullable().default(null),effect:d.enum(["allow","deny","hitl","mask"]),resource_type:d.string().min(1),rego_source:d.string().default(""),target_app:d.string().nullable().default(null),action_pattern:d.string().nullable().default(null),conditions:d.array(Bt).default([]),priority:d.number().int().default(0)}),Vt=d.object({version:d.string().min(1),agent_mode:Le.optional(),rules:d.array(Kt),no_coverage:d.object({no_coverage_defaults:d.record(d.string()),autopilot_enabled:d.boolean(),enduser_hitl_enabled:d.boolean(),hitl_timeout_seconds:d.number()}).optional()}),Ht=2e3,Ne=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 Ut.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json"},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();return Vt.parse(o)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();if(typeof o!="object"||o===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let a=o,s=a.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof a.reason=="string"?a.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await Wt(Ht)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Wt(e){return new Promise(t=>setTimeout(t,e))}function Pe(){let e={};try{let t=`${x.platform()} ${x.release()}`.trim();t&&(e.os=t)}catch{}try{let t=x.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=x.userInfo();t&&(e.username=t)}catch{}try{let t=zt();t&&(e.ip=t)}catch{}return e}function zt(){let e=x.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 p}from"zod";import{createHash as kr}from"crypto";import{createHash as Ir}from"crypto";var Gt=["tier1","tier2","tier3"];function Me(e){return typeof e=="string"&&Gt.includes(e)}var Qt=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Yt=["internal","customer_facing","experimental","third_party"],je=[...Qt,...Yt];function Zt(e){return typeof e=="string"&&je.includes(e)}function qe(e){let t=new Set;for(let n of e)Zt(n)&&t.add(n);return je.filter(n=>t.has(n))}var Jt=["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 $e(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 Xt={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 en(e){let t=$e(e);return t===null?"other":Xt[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 Fe={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 tn(e){let t=$e(e);return t===null?"other":Fe[t]??Fe[t.replace(/_/g,"")]??"other"}function Ue(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=en(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=tn(t.targetApp)),n.context=r}return n}var De=64,nn=64,B={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function Be(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var rn=new Set(["deny","approval_required","escalate"]);function Z(e,t){if(t.length===0)return[...e];let n=new Set(e);for(let i of t)n.add(i);let r=[...n].sort();return r.length>De?r.slice(0,De):r}function on(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function J(e){return typeof e=="string"&&e.length>0?e:null}function Ke(e,t){let n=on(t.data_categories),r=J(t.classification),i=J(t.action_class),o=i&&Jt.includes(i)?i:null,a=J(t.target_app),s=J(t.decision),l={...e.action_counts};if(o)if(o in l)l[o]=(l[o]??0)+1;else if(Object.keys(l).length<nn)l[o]=1;else{let c=Object.keys(l).sort(),u=c[c.length-1];u!==void 0&&o<u&&(delete l[u],l[o]=1)}return{retrieved_data_categories:Z(e.retrieved_data_categories,n),retrieved_classifications:Z(e.retrieved_classifications,r?[r]:[]),action_classes:Z(e.action_classes,o?[o]:[]),action_counts:l,denied_count:e.denied_count+(s==="deny"?1:0),inhibited_count:e.inhibited_count+(s&&rn.has(s)?1:0),event_count:e.event_count+1,target_apps:Z(e.target_apps,a?[a]:[])}}var an="generic",Ve=[{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:an,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."}],Ar=Ve.map(e=>e.id),sn=new Map(Ve.map(e=>[e.id,e]));function de(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&sn.has(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}function He(e){return de(e)[0]??null}function We(e){return e==="open"||e==="closed"?e:null}var ln=["action","retrieval","delegation"];function cn(e){return typeof e=="string"&&ln.includes(e)}var un=new Set(["rules"]);function ze(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!un.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(cn):[];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}}function dn(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 K;async function pn(){if(K!==void 0)return K;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;K=typeof t=="function"?t:null}catch{K=null}return K}var fn=5e3,gn=1e4,Ge=1e3,mn=512,_n=1800*1e3,hn="monitor",yn=p.object({operations:p.array(p.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:p.string().min(1,"agentId is required"),sessionId:p.string().min(1).max(255).optional(),toolName:p.string().optional(),toolArgs:p.record(p.unknown()).optional(),targetResource:p.string().optional(),resourceType:p.string().optional(),resourceMetadata:p.record(p.unknown()).optional(),normalized:p.record(p.unknown()).optional(),query:p.string().optional(),contentPreview:p.string().optional(),telemetry:p.record(p.unknown()).optional()}),bn=p.object({version:p.string().min(1),agent_mode:p.enum(["enforce","monitor","off"]).optional(),agent_mode_by_operation:p.object({action:p.string().optional(),retrieval:p.string().optional(),delegation:p.string().optional()}).partial().optional(),agent_attributes:p.object({trust_tier:p.string().nullable().optional(),categories:p.array(p.string()).optional(),business_function:p.string().nullable().optional(),business_functions:p.array(p.string()).nullable().optional(),no_coverage:p.string().nullable().optional()}).optional(),rules:p.array(p.record(p.unknown())),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()}).optional()});function vn(e){let t=e.trust_tier??null,n=[];Array.isArray(e.business_functions)&&e.business_functions.length>0?n=e.business_functions:typeof e.business_function=="string"&&e.business_function!==""&&(n=[e.business_function]);let r=de(n);return{trust_tier:Me(t)?t:null,categories:qe(e.categories??[]),business_functions:r,business_function:He(r)}}function wn(e){if(!e)return null;let t={};for(let n of["action","retrieval","delegation"]){let r=e[n];(r==="enforce"||r==="monitor"||r==="off")&&(t[n]=r)}return Object.keys(t).length>0?t:null}function kn(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Ye=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=hn;agentModeByOperation=null;rawBundle=null;agentModeConfirmed=!1;bundleApplyFailed=!1;telemetryBuffer=[];telemetryTimer=null;envRegistered=!1;registerPromise=null;constructor(e,t,n,r,i){let o=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,a=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,s=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";if(this.resolvedApiKey=o,this.resolvedEndpoint=a,this.resolvedAgentId=s,this.harnessKind=r,this.originalFetch=globalThis.fetch.bind(globalThis),o&&a){let l={apiKey:o,agentId:s,endpoint:a,mode:"enforce",timeoutMs:dn(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{}};this.client=new Ne(l,this.originalFetch),this.initialBundlePromise=this.fetchBundleBackground(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},fn),Qe(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},gn),Qe(this.telemetryTimer)}else this.client=null}async evaluate(e){let t=yn.parse(e),n=Date.now();if(t.operations.every(l=>this.modeFor(l)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let l;this.agentModeConfirmed?l=this.agentMode:this.bundleApplyFailed?l="enforce":l="monitor";let c=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(c,l,t,n)}let r=this.readSession(t.sessionId),i=await pn();if(!i||!this.rawBundle)throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)");let o={...t,session:r,at:Date.now()},a={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},s=i(o,a);return this.foldSession(t,s.enforced?s.decision:"permit"),s.enforced&&s.action.decision==="approval_required"&&await this.registerHitl(t,s),this.bufferTelemetry(t,s,Date.now()-n,s.enforced),s}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return B;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>_n?(this.sessions.delete(e),B):t.state:B}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=a?Ue(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},l=Ke(r===B?Be():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,action_class:a?s.action_class:void 0,target_app:a?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:l,touchedAt:Date.now()}),this.sessions.size>mn){let c=this.sessions.keys().next().value;c!==void 0&&this.sessions.delete(c)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let a={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,a,i,!0),a}let o={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,o,i,!1),o}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=bn.parse(e);this.bundleApplyFailed=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(n=>ze(n)).filter(n=>n!==null),this.agentAttributes=t.agent_attributes?vn(t.agent_attributes):null,this.agentNoCoverage=We(t.agent_attributes?.no_coverage),this.bundleVersion=t.version,this.bundleLoaded=!0,this.noCoverage=t.no_coverage?{no_coverage_defaults:t.no_coverage.no_coverage_defaults,autopilot_enabled:t.no_coverage.autopilot_enabled,enduser_hitl_enabled:t.no_coverage.enduser_hitl_enabled}:null,t.agent_mode!==void 0&&(this.agentMode=t.agent_mode,this.agentModeConfirmed=!0),this.agentModeByOperation=wn(t.agent_mode_by_operation),this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json"};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag");r&&(this.bundleEtag=r);let i=await n.json();this.applyBundle(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(){this.registerEnvironment(Pe())}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:kn(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:{[Oe]: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-Ge;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${Ge})`))}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 Qe(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function pe(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 Ze(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 w(e){let t=[],n=[],r,i=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let l={mode:a.mode};a.field&&(l.field=a.field),a.pattern&&(l.pattern=a.pattern),typeof a.keepFirst=="number"&&(l.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(l.keepLast=a.keepLast),a.maskChar&&(l.maskChar=a.maskChar),a.keepPattern&&(l.keepPattern=a.keepPattern),a.replacement!==void 0&&(l.replacement=a.replacement),i.push(l);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:s}=a;s&&r===void 0&&(r=s)}let o={};return t.length>0&&(o.fields=t),n.length>0&&(o.patterns=n),r!==void 0&&(o.replacement=r),i.length>0&&(o.directives=i),o}var An=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];var h=Object.fromEntries(An.map(e=>[e.name,e.re.source])),Tn=["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"],In={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
1
|
+
import{randomUUID as $r}from"node:crypto";import*as me from"node:fs";import*as he from"node:path";import*as Vt from"node:os";import{AsyncLocalStorage as Ur}from"node:async_hooks";import{z as d}from"zod";import*as O from"node:os";var $e="interceptor_source",en=d.enum(["enforce","audit","off"]),tn=d.enum(["closed","open"]),Ue=d.enum(["enforce","monitor","off"]),nn=d.object({apiKey:d.string().min(1,"apiKey is required"),agentId:d.string().min(1,"agentId is required"),endpoint:d.string().url().optional(),mode:en.optional(),timeoutMs:d.number().int().positive().optional(),hitlTimeoutMs:d.number().int().positive().optional(),failBehavior:tn.optional()}),ni=d.object({agent_id:d.string().min(1),target_app:d.string().min(1),action:d.string().min(1),context:d.record(d.unknown()).optional(),session_id:d.string().min(1).max(255).optional(),telemetry:d.record(d.unknown()).optional()}),rn=d.object({field:d.string().optional(),pattern:d.string().optional(),replacement:d.string().optional(),mode:d.enum(["full","partial","email"]).optional(),keepFirst:d.number().optional(),keepLast:d.number().optional(),maskChar:d.string().optional()}),on=d.object({decision_id:d.string().min(1),decision:d.enum(["permit","deny","approval_required","mask"]),reason:d.string().optional(),rule_code:d.string().nullable().optional(),enforced:d.boolean().optional(),agent_mode:Ue.optional(),arg_redaction_rules:d.array(rn).optional(),plane:d.string().nullable().optional(),operation:d.string().nullable().optional(),is_retrieval:d.boolean().optional(),metadata:d.record(d.unknown()).optional()}),an=d.object({field:d.string().min(1),operator:d.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:d.union([d.string(),d.number(),d.array(d.string())])}),sn=d.object({id:d.string().min(1),rule_code:d.string().default(""),name:d.string().min(1),description:d.string().nullable().default(null),effect:d.enum(["allow","deny","hitl","mask"]),resource_type:d.string().min(1),rego_source:d.string().default(""),target_app:d.string().nullable().default(null),action_pattern:d.string().nullable().default(null),conditions:d.array(an).default([]),priority:d.number().int().default(0)}),ln=d.object({version:d.string().min(1),agent_mode:Ue.optional(),rules:d.array(sn),no_coverage:d.object({no_coverage_defaults:d.record(d.string()),autopilot_enabled:d.boolean(),enduser_hitl_enabled:d.boolean(),hitl_timeout_seconds:d.number()}).optional()}),cn=2e3,Be=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 on.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json"},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();return ln.parse(o)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();if(typeof o!="object"||o===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let a=o,s=a.hitl_result;if(s==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(s==="rejected")return{decision_id:e,decision:"deny",reason:typeof a.reason=="string"?a.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await un(cn)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function un(e){return new Promise(t=>setTimeout(t,e))}function Ke(){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=dn();t&&(e.ip=t)}catch{}return e}function dn(){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 p}from"zod";import{createHash as ai}from"crypto";import{createHash as ui}from"crypto";var pn=["tier1","tier2","tier3"];function He(e){return typeof e=="string"&&pn.includes(e)}var fn=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],gn=["internal","customer_facing","experimental","third_party"],We=[...fn,...gn];function mn(e){return typeof e=="string"&&We.includes(e)}function Ge(e){let t=new Set;for(let n of e)mn(n)&&t.add(n);return We.filter(n=>t.has(n))}var hn=["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 Qe(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 _n={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 yn(e){let t=Qe(e);return t===null?"other":_n[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 Ve={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 bn(e){let t=Qe(e);return t===null?"other":Ve[t]??Ve[t.replace(/_/g,"")]??"other"}function Ye(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=yn(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=bn(t.targetApp)),n.context=r}return n}var ze=64,wn=64,z={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function Ze(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var vn=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>ze?r.slice(0,ze):r}function kn(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 Je(e,t){let n=kn(t.data_categories),r=ne(t.classification),i=ne(t.action_class),o=i&&hn.includes(i)?i:null,a=ne(t.target_app),s=ne(t.decision),l={...e.action_counts};if(o)if(o in l)l[o]=(l[o]??0)+1;else if(Object.keys(l).length<wn)l[o]=1;else{let c=Object.keys(l).sort(),u=c[c.length-1];u!==void 0&&o<u&&(delete l[u],l[o]=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,o?[o]:[]),action_counts:l,denied_count:e.denied_count+(s==="deny"?1:0),inhibited_count:e.inhibited_count+(s&&vn.has(s)?1:0),event_count:e.event_count+1,target_apps:te(e.target_apps,a?[a]:[])}}var An="generic",Xe=[{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:An,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."}],Tn=Xe.map(e=>e.id),si=new Map(Xe.map(e=>[e.id,e])),li=new Set(Tn);var In=/^[a-z][a-z0-9_]*$/;function et(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&In.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Sn=["narrow","moderate","broad","unbounded","unknown"];function tt(e){return typeof e=="string"&&Sn.includes(e)}function nt(e){return e==="open"||e==="closed"?e:null}var Rn=["action","retrieval","delegation"];function En(e){return typeof e=="string"&&Rn.includes(e)}var Cn=new Set(["rules"]);function rt(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Cn.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(En):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{randomUUID as Yn}from"node:crypto";var it=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function xn(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:it(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:it(t.spawn.prompt)}),t}function On(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 H;async function Nn(){if(H!==void 0)return H;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;H=typeof t=="function"?t:null}catch{H=null}return H}var Ln=5e3,Fn=1e4,Pn=25,ot=1e3,Mn=5e3,Dn=100,at=2e3,jn=512,qn=1800*1e3,$n="monitor",Un="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",Bn=p.object({operations:p.array(p.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:p.string().min(1,"agentId is required"),sessionId:p.string().min(1).max(255).optional(),toolName:p.string().optional(),toolArgs:p.record(p.unknown()).optional(),targetResource:p.string().optional(),resourceType:p.string().optional(),resourceMetadata:p.record(p.unknown()).optional(),normalized:p.record(p.unknown()).optional(),query:p.string().optional(),contentPreview:p.string().optional(),telemetry:p.record(p.unknown()).optional(),context:p.record(p.unknown()).optional()}),Kn=p.object({version:p.string().min(1),shutdown:p.boolean().optional(),agent_mode:p.enum(["enforce","monitor","off"]).optional(),cognition_capture:p.boolean().optional(),agent_mode_by_operation:p.object({action:p.string().optional(),retrieval:p.string().optional(),delegation:p.string().optional()}).partial().optional(),agent_attributes:p.object({trust_tier:p.string().nullable().optional(),categories:p.array(p.string()).optional(),business_function:p.string().nullable().optional(),business_functions:p.array(p.string()).nullable().optional(),blast_radius_tier:p.string().nullable().optional(),no_coverage:p.string().nullable().optional()}).optional(),rules:p.array(p.record(p.unknown())),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()}).optional()});function Vn(e){let t=e.trust_tier??null,n=[];Array.isArray(e.business_functions)&&e.business_functions.length>0?n=e.business_functions:typeof e.business_function=="string"&&e.business_function!==""&&(n=[e.business_function]);let r=et(n);return{trust_tier:He(t)?t:null,categories:Ge(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&tt(e.blast_radius_tier)?e.blast_radius_tier:null}}function zn(e){if(!e)return null;let t={};for(let n of["action","retrieval","delegation"]){let r=e[n];(r==="enforce"||r==="monitor"||r==="off")&&(t[n]=r)}return Object.keys(t).length>0?t:null}function Hn(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var ct=new Set,st=!1;function Wn(){st||typeof process>"u"||typeof process.once!="function"||(st=!0,process.once("beforeExit",()=>{for(let e of ct)if(e.pendingTelemetryCount()>0){if(!e.hasBackend()){console.warn(`[UnifiedRuntime] exiting with ${e.pendingTelemetryCount()} un-sent decision(s) and no backend \u2014 telemetry lost.`);continue}e.flush()}}))}var ut=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=$n;agentModeByOperation=null;rawBundle=null;agentModeConfirmed=!1;shutdown=!1;bundleApplyFailed=!1;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;constructor(e,t,n,r,i){let o=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,a=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,s=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";if(this.resolvedApiKey=o,this.resolvedEndpoint=a,this.resolvedAgentId=s,this.harnessKind=r,this.originalFetch=globalThis.fetch.bind(globalThis),o&&a){let l={apiKey:o,agentId:s,endpoint:a,mode:"enforce",timeoutMs:On(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{}};this.client=new Be(l,this.originalFetch),this.initialBundlePromise=this.fetchBundleBackground(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Ln),ye(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Fn),ye(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Mn),ye(this.cognitionTimer),ct.add(this),Wn()}else this.client=null}async evaluate(e){let t=Bn.parse(e),n=Date.now();if(this.shutdown){let l=this.denyAll(t,Un);return this.applyAgentMode(l,"enforce",t,n)}if(t.operations.every(l=>this.modeFor(l)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let l;this.agentModeConfirmed?l=this.agentMode:this.bundleApplyFailed?l="enforce":l="monitor";let c=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(c,l,t,n)}let r=this.readSession(t.sessionId),i=await Nn();if(!i||!this.rawBundle)throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)");let o={...t,session:r,at:Date.now()},a={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},s=i(o,a);return this.foldSession(t,s.enforced?s.decision:"permit"),s.enforced&&s.action.decision==="approval_required"&&await this.registerHitl(t,s),this.bufferTelemetry(t,s,Date.now()-n,s.enforced),s}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return z;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>qn?(this.sessions.delete(e),z):t.state:z}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),s=a?Ye(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},l=Je(r===z?Ze():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,action_class:a?s.action_class:void 0,target_app:a?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:l,touchedAt:Date.now()}),this.sessions.size>jn){let c=this.sessions.keys().next().value;c!==void 0&&this.sessions.delete(c)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let a={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,a,i,!0),a}let o={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,o,i,!1),o}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=Kn.parse(e);this.bundleApplyFailed=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(n=>rt(n)).filter(n=>n!==null),this.agentAttributes=t.agent_attributes?Vn(t.agent_attributes):null,this.agentNoCoverage=nt(t.agent_attributes?.no_coverage),this.bundleVersion=t.version,this.bundleLoaded=!0,this.noCoverage=t.no_coverage?{no_coverage_defaults:t.no_coverage.no_coverage_defaults,autopilot_enabled:t.no_coverage.autopilot_enabled,enduser_hitl_enabled:t.no_coverage.enduser_hitl_enabled}:null,t.agent_mode!==void 0&&(this.agentMode=t.agent_mode,this.agentModeConfirmed=!0),this.agentModeByOperation=zn(t.agent_mode_by_operation),process.env.VISIQ_COGNITION_CAPTURE==="1"?this.cognitionEnabled=!0:typeof t.cognition_capture=="boolean"&&(this.cognitionEnabled=t.cognition_capture),this.shutdown=t.shutdown===!0,this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json"};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag");r&&(this.bundleEtag=r);let i=await n.json();this.applyBundle(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e){this.registerEnvironment({...Ke(),...e?{agent_type:e}:{}})}reportToolSurface(e){if(!this.client||!this.resolvedAgentId||e.length===0)return;let t=JSON.stringify([...e].map(n=>({n:n.name,d:n.description??"",s:n.input_schema??null})).sort((n,r)=>n.n.localeCompare(r.n)));t!==this.lastToolSurfaceSig&&(this.lastToolSurfaceSig=t,this.client.reportToolSurface(e))}bufferTelemetry(e,t,n,r){this.telemetryBuffer.push({decision_id:crypto.randomUUID(),agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??e.operations.join("+"),...e.sessionId?{session_id:e.sessionId}:{},decision:r?Hn(t.decision):"permit",reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:{agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{}},...this.harnessKind||e.context?{context:{...this.harnessKind?{[$e]:this.harnessKind}:{},...e.context??{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Pn&&this.flushTelemetry()}pendingTelemetryCount(){return this.telemetryBuffer.length}hasBackend(){return this.client!==null}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0);try{await this.client.sendTelemetry(e)}catch(t){console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",t)}}enforceTelemetryCap(){let e=this.telemetryBuffer.length-ot;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${ot})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(xn(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Dn&&this.flushCognition())}async flushCognition(){if(this.cognitionBuffer.length===0||!this.client)return;let e=this.cognitionBuffer.splice(0);try{await this.client.sendCognition(void 0,e)}catch(t){console.error("[UnifiedRuntime] cognition flush failed (non-fatal):",t)}}enforceCognitionCap(){let e=this.cognitionBuffer.length-at;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${at})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.cognitionTimer&&(clearInterval(this.cognitionTimer),this.cognitionTimer=null),this.flushTelemetry(),this.flushCognition()}};function ye(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function Gn(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function E(e,...t){for(let n of t){let r=Gn(e[n]);if(r)return r}}var Qn=[{framework:"openai-agents",matches:e=>/^transfer_to_.+/.test(e),extract:(e,t)=>{let n=e.replace(/^transfer_to_/,"");return{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"teammate",task:E(t,"task","input","reason","message"),source:"structural"}}},{framework:"voltagent",matches:e=>e==="delegate_task",extract:(e,t)=>{let n=E(t,"targetAgent","agent","subAgent","agentName","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:E(t,"task","message","input"),description:E(t,"purpose"),source:"structural"}:null}},{framework:"crewai",matches:e=>/delegate work to (co-?worker|.+)/i.test(e),extract:(e,t)=>{let n=E(t,"coworker","agent","role");return n?{childAgentId:n,childName:n,kind:"teammate",agentType:n,task:E(t,"task","question"),description:E(t,"context"),source:"structural"}:null}},{framework:"llamaindex",matches:e=>e==="handoff"||/handoff/i.test(e),extract:(e,t)=>{let n=E(t,"to_agent","toAgent","agent_name","agentName","agent","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:E(t,"reason","task","message"),source:"structural"}:null}},{framework:"generic",matches:e=>/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)([_-].+)?$/i.test(e),extract:(e,t)=>{let n=E(t,"agent","agentName","agentId","target","targetAgent","to","to_agent","coworker","name")??(/[_-]/.test(e)?e.replace(/^(delegate|hand[_-]?off|route[_-]?to|call[_-]?agent)[_-]/i,""):void 0);return n?{childAgentId:n,childName:n.replace(/[_-]+/g," ").trim(),kind:"subagent",task:E(t,"task","message","input","reason","prompt"),source:"heuristic"}:null}}];function re(e,t){if(!e)return null;let n=t??{};for(let r of Qn)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function ie(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}var lt=new Map;function Zn(e){let t=(lt.get(e)??0)+1;return lt.set(e,t),t}function oe(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId:Yn(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:Zn(r),ts:Date.now(),kind:"spawn",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},spawn:{childAgentId:n.childAgentId,childName:n.childName,kind:n.kind,...n.model?{model:n.model}:{},...n.task?{prompt:n.task}:{}}})}function be(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 dt(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 T(e){let t=[],n=[],r,i=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let l={mode:a.mode};a.field&&(l.field=a.field),a.pattern&&(l.pattern=a.pattern),typeof a.keepFirst=="number"&&(l.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(l.keepLast=a.keepLast),a.maskChar&&(l.maskChar=a.maskChar),a.keepPattern&&(l.keepPattern=a.keepPattern),a.replacement!==void 0&&(l.replacement=a.replacement),i.push(l);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:s}=a;s&&r===void 0&&(r=s)}let o={};return t.length>0&&(o.fields=t),n.length>0&&(o.patterns=n),r!==void 0&&(o.replacement=r),i.length>0&&(o.directives=i),o}var Jn=[{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 b=Object.fromEntries(Jn.map(e=>[e.name,e.re.source])),Xn=["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"],er={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
2
2
|
MIIEv\u2026
|
|
3
|
-
-----END PRIVATE KEY-----`,template:{pattern:h.private_key,mode:"full"},defaultEnabled:!0},jwt:{id:"jwt",label:"JWT / bearer tokens",description:"JSON Web Tokens (base64url header.payload.signature).",category:"secret",example:"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.dBjftJeZ4CVP",template:{pattern:h.jwt,mode:"full"},defaultEnabled:!0},aws_access_key:{id:"aws_access_key",label:"AWS access key IDs",description:"AWS access / identity key ids (AKIA / ASIA / AROA \u2026).",category:"secret",example:"AKIAIOSFODNN7EXAMPLE",template:{pattern:h.aws_access_key,mode:"full"},defaultEnabled:!0},github_token:{id:"github_token",label:"GitHub tokens",description:"GitHub personal / OAuth tokens (classic ghp_\u2026 + fine-grained).",category:"secret",example:"ghp_0123456789abcdef0123456789abcdef0123",template:{pattern:h.github_token,mode:"full"},defaultEnabled:!0},slack_token:{id:"slack_token",label:"Slack tokens",description:"Slack bot / user / app tokens (xoxb- / xoxp- \u2026).",category:"secret",example:"xoxb-1234567890-abcdefghijkl",template:{pattern:h.slack_token,mode:"full"},defaultEnabled:!0},stripe_secret:{id:"stripe_secret",label:"Stripe secret keys",description:"Stripe live secret / restricted keys (sk_live_ / rk_live_).",category:"secret",example:"sk_live_0123456789abcdefABCDEF",template:{pattern:h.stripe_secret,mode:"full"},defaultEnabled:!0},google_api_key:{id:"google_api_key",label:"Google API keys",description:"Google API keys (AIza\u2026).",category:"secret",example:"AIzaSyA1234567890abcdefghijklmnopqrstuv",template:{pattern:h.google_api_key,mode:"full"},defaultEnabled:!0},llm_api_key:{id:"llm_api_key",label:"LLM provider API keys",description:"OpenAI / Anthropic secret keys (sk-\u2026, sk-proj-\u2026, sk-ant-\u2026).",category:"secret",example:"sk-ant-api03-AbCdEf0123456789AbCdEf01",template:{pattern:h.llm_api_key,mode:"full"},defaultEnabled:!0},bearer_token:{id:"bearer_token",label:"Authorization bearer tokens",description:"Credentials following an HTTP `Authorization: Bearer \u2026` header.",category:"secret",example:"Bearer abcdef0123456789abcdef0123456789",template:{pattern:h.bearer_token,mode:"full"},defaultEnabled:!0},connection_string:{id:"connection_string",label:"Connection strings (with password)",description:"Database / broker DSNs carrying an inline password (scheme://user:pass@host).",category:"secret",example:"postgres://app:s3cr3t@db.internal:5432/main",template:{pattern:h.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS).",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\b\\d{13,19}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){10,30}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:"\\b\\d{9}\\b",mode:"full"},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX).",category:"financial",example:"12-3456789",template:{pattern:h.us_ein,mode:"full"},defaultEnabled:!0},swift_bic:{id:"swift_bic",label:"SWIFT / BIC codes",description:"Bank SWIFT/BIC codes (8 or 11 chars). DEFAULT-OFF (matches uppercase tokens).",category:"financial",example:"DEUTDEFF500",template:{pattern:h.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789).",category:"pii",example:"123-45-6789",template:{pattern:h.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept).",category:"pii",example:"alice@acme.com",template:{pattern:h.email,mode:"email"},defaultEnabled:!0},us_phone:{id:"us_phone",label:"US phone numbers",description:"US phone numbers in common formats. DEFAULT-OFF (10-digit false-positive surface).",category:"pii",example:"(415) 555-0132",template:{pattern:h.us_phone,mode:"partial",keepLast:4},defaultEnabled:!1},ipv4:{id:"ipv4",label:"IPv4 addresses",description:"Dotted-quad IPv4 addresses. DEFAULT-OFF (common + usually benign).",category:"identifier",example:"203.0.113.42",template:{pattern:h.ipv4,mode:"full"},defaultEnabled:!1},mac_address:{id:"mac_address",label:"MAC addresses",description:"Hardware MAC addresses. DEFAULT-OFF.",category:"identifier",example:"3c:22:fb:1a:2b:3c",template:{pattern:h.mac_address,mode:"full"},defaultEnabled:!1}},Lr=new Set(Tn.filter(e=>!In[e].defaultEnabled));var fe="[REDACTED]",j="\u2022",X=e=>/[A-Za-z0-9]/.test(e);function Je(e,t,n,r){let i=Array.from(e),o=i.length,a=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:j,c=a+s>=o;return i.map((u,f)=>!c&&(f<a||f>=o-s)?u:X(u)?l:u).join("")}function Rn(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Je(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:j;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>X(a)?o:a).join(""))+i}function Sn(e,t,n){let r=n.length>0?n:j,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 o=!1,a=!0;for(let c=0;c<e.length;c++)if(X(e[c])&&(o=!0,!i[c])){a=!1;break}let s=o&&a,l="";for(let c=0;c<e.length;c++){let u=e[c];!s&&i[c]||!X(u)?l+=u:l+=r}return l}function Xe(e,t){let n=t.mode??"full";return n==="partial"?Je(e,t.keepFirst??0,t.keepLast??0,t.maskChar??j):n==="email"?Rn(e,t.maskChar??j):n==="custom"?Sn(e,t.keepPattern,t.maskChar??j):t.replacement??fe}function En(e,t){return typeof e=="string"?Xe(e,t):t.replacement??fe}function et(e){let t=[],n=e.replacement??fe;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:o=>Xe(o,r)})}return t}function tt(e,t){let n=e;for(let{source:r,replacer:i}of t){let o;try{o=new RegExp(r,"g")}catch(a){let s=a instanceof Error?a.message:String(a);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(o,a=>i(a))}return n}function k(e,t){return e==null?e:typeof e=="string"?xn(e,t):typeof e=="object"?Cn(e,t):e}function xn(e,t){if(typeof e!="string")return e;let n=et(t);return n.length===0?e:tt(e,n)}function Cn(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=et(t),i=n.size>0,o=r.length>0,a=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>a(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]=En(l[u],f);continue}c[u]=a(l[u])}return c}return typeof s=="string"&&o?tt(s,r):s};return a(e)}import{AsyncLocalStorage as On}from"node:async_hooks";var m=new On,Ln=5120,nt=50;function Nn(e,t){if(typeof e!="string")return"";let n=new TextEncoder,r=n.encode(e);if(r.length<=t)return e;let o=`\u2026[truncated ${Math.ceil(r.length/1024)}KB]`,a=n.encode(o).length,s=Math.max(0,t-a),l=r.subarray(0,s);return new TextDecoder("utf-8",{fatal:!1}).decode(l)+o}function L(e){if(!e)return;let t=r=>r.length<=nt?r.slice():r.slice(r.length-nt),n=r=>Nn(r,Ln);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 V(e,t){return e==="mask"&&(t?.length??0)>0}var Pn=new Set(["approved","resolved"]),Fn=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function Dn(e){return new Promise(t=>setTimeout(t,e))}function Mn(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 H(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=12e4,maskFallback:o=!1,fetchImpl:a=globalThis.fetch,sleep:s=Dn,log:l=g=>console.warn(g)}=e,c=g=>o?{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 I=Date.now()+Math.max(0,i),A=0;for(l(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=I)return l(`[VisIQ HITL] Decision ${r} timed out after ${i}ms \u2014 ${o?"masking":"blocking"} (G001)`),c("HITL approval timed out");let g=null;try{let _=new AbortController,C=setTimeout(()=>_.abort(),5e3),S;try{S=await a(u,{method:"GET",headers:f,signal:_.signal})}finally{clearTimeout(C)}if(!S.ok)throw new Error(`HTTP ${S.status} ${S.statusText}`);let v=await S.json();g=Mn(v),A=0}catch(_){A+=1;let C=_ instanceof Error?_.message:String(_);if(l(`[VisIQ HITL] Poll failed for decision ${r} (${A}/3): ${C}`),A>=3)return c(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${C}`);await s(2e3);continue}if(g!==null){let _=g.toLowerCase();return Pn.has(_)?(l(`[VisIQ HITL] Decision ${r} approved (${g}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${g})`}):Fn.has(_)?(l(`[VisIQ HITL] Decision ${r} resolved as ${g} \u2014 ${o?"masking":"blocking"}`),c(`Not approved by human reviewer (${g})`)):(l(`[VisIQ HITL] Decision ${r} returned unknown status '${g}' \u2014 ${o?"masking":"blocking"} (G001)`),c(`HITL returned unknown status '${g}' \u2014 fail-closed (G001)`))}await s(2e3)}}function F(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 it(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&V(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}async function te(e,t,n){let r=m.getStore(),i=L(r),o=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 it(o)}async function ne(e,t,n){return await e.awaitBundleReady(),te(e,t,n)}function ot(e,t){if(t.action==="deny")return null;if(t.action==="redact"&&t.redactionRules.length>0)try{return k(e,w(t.redactionRules))}catch{return null}return e}async function at(e,t,n,r){if(!Array.isArray(e)||e.length===0)return e;await r.awaitBundleReady();let i=[];for(let o of e){let a=o,s=String(a.pageContent??a.text??a.content??""),l=a.metadata??{},c=await te(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s.slice(0,500)}),u=ot(o,c);u!==null&&i.push(u)}return i}async function st(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await te(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 k(e,w(r.redactionRules))}catch{return"[RECALL] Retrieved context was blocked by policy."}}default:return e}}var lt=4,ct=1e3;function ee(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 ut(e,t,n){let r=[];for(let i of e){let o=i,a=String(o.pageContent??o.text??o.content??""),s={...o.metadata??{},content_preview:a.slice(0,500)},l;try{l=await te(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:a.slice(0,500)})}catch{continue}let c=ot(i,l);c!==null&&r.push(c)}return r}async function ge(e,t,n,r,i){if(r>lt||i.nodes++>ct)return e;if(Array.isArray(e)){if(ee(e))return i.matched=!0,ut(e,t,n);let o=[];for(let a of e)o.push(await ge(a,t,n,r+1,i));return o}if(e!==null&&typeof e=="object"){let o=e,a={...o};for(let s of Object.keys(o))a[s]=await ge(o[s],t,n,r+1,i);return a}return e}async function re(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&ee(e))return ut(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await ge(e,t,n,0,r);if(r.matched)return i}return e}var jn={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function me(e,t,n){if(t>lt||n.n++>ct)return e;if(Array.isArray(e))return ee(e)?[]:e.map(r=>me(r,t+1,n));if(e!==null&&typeof e=="object"){if(ee([e]))return{...jn};let r=e,i={};for(let o of Object.keys(r))i[o]=me(r[o],t+1,n);return i}return e}function rt(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?me(e,0,{n:0}):e}function dt(e,t){let n=it(t);if(n.action==="deny")return rt(e);if(n.action==="redact"&&n.redactionRules.length>0)try{return k(e,w(n.redactionRules))}catch{return rt(e)}return e}import{z as ie}from"zod";var qn=ie.object({decision:ie.enum(["permit","deny"]),reason:ie.string(),handoff_event_id:ie.string().nullable()}),D=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},q=class extends D{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},$n="https://api.visiqlabs.com",Un=1e4,$=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??$n,timeoutMs:e.timeoutMs??Un},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 o=await i.json();if(!i.ok){let a=o?.error??`HTTP ${i.status}`;throw new D(a,"API_ERROR",i.status)}return o}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=qn.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 pt=new Map;async function ft(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=pt.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,o=(await new $({agentId:e,apiKey:r,...i?{endpoint:i}:{}}).acceptGrant(t)).grantToken;if(!o||o.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: backend returned empty grant token");return pt.set(e,o),o}var W=Symbol.for("visiq.orchestrate.wrapped");function gt(e,t){if(!t.agentId||t.agentId.trim()==="")throw new D("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new D("grantToken is required","CONFIG_ERROR");if(e[W]===!0)return e;let n=new $(t),r=t.failBehavior??"deny",i=async(o,a)=>{let s;try{s=await n.evaluate({grantToken:t.grantToken,action:o,resourceType:a})}catch(l){if(r==="permit"){console.warn("[ORCHESTRATE] evaluate failed \u2014 failing open (failBehavior=permit)",l);return}throw new D(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new q(s.reason,s.handoffEventId)};return new Proxy(e,{get(o,a,s){let l=Reflect.get(o,a,s);return a===W?!0:a==="_call"&&typeof l=="function"?async function(c,...u){let f=o.name;return await i(f??"_call"),l.call(this??o,c,...u)}:(a==="call"||a==="execute"||a==="run")&&typeof l=="function"?async function(c,...u){let f=o.name;return await i(f??String(a)),l.call(this??o,c,...u)}:l}})}import{randomUUID as yt}from"node:crypto";var mt=Symbol.for("visiq.semantickernel.instrumented");function _t(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 _e=class{constructor(t){this.deps=t}deps;async onFunctionInvocation(t){let{agentId:n,unified:r}=this.deps,i=t.functionName??"unknown",o=t.arguments??{},a=t.pluginName;try{let u=F(await r.evaluate({operations:["action"],agentId:n,toolName:i,toolArgs:o,...a!==void 0?{targetResource:a}:{}}));if(!u.allowed){t.result=`[VisIQ ALLOW] Action blocked: ${u.reason??"policy denied"}.`;return}u.decision==="mask"&&u.argRedactionRules.length>0&&(t.arguments=k(o,w(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 ne(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 ne(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=k(t.result,w(c.redactionRules))}catch{t.result="[RECALL] Result withheld \u2014 redaction error (fail-closed)."}}},he=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 ne(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=k(n,w(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 ht(e,t){let n=e;return n[mt]===!0||(Array.isArray(n.functionInvocationFilters)||(n.functionInvocationFilters=[]),Array.isArray(n.promptRenderFilters)||(n.promptRenderFilters=[]),n.functionInvocationFilters.unshift(new _e(t)),n.promptRenderFilters.push(new he(t)),n[mt]=!0),e}function R(e,t){return`[VisIQ ${e}] Action blocked: ${t}. (VisIQ is a security harness installed by your developer.)`}var Bn=/https?:\/\/[^\s"'`,)}\]]+/;function ye(e){let t=e.match(Bn);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var U=Symbol.for("visiq.toolexec.instrumented");function Kn(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}function bt(e){if(e===null||typeof e!="object")return null;let t=e;if(Kn(t))return null;if(_t(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 Vn(e,t,n,r,i){let{agentId:o,unified:a}=e,s=L(i),l;try{await a.awaitBundleReady(),l=F(await a.evaluate({operations:["action"],agentId:o,toolName:t,toolArgs:n,...i?.session_id?{sessionId:i.session_id}:{},...r!==void 0?{targetResource:r}:{},...s?{telemetry:s}:{}}))}catch(c){return{block:R("EVAL-ERROR",`policy evaluation failed: ${c instanceof Error?c.message:String(c)}`)}}if(l.decision==="approval_required"&&l.decisionId){let c=a.getApiKey()??e.apiKey,u=await H({endpoint:a.getEndpoint()??e.endpoint??"",...c?{apiKey:c}:{},decisionId:l.decisionId,timeoutMs:e.hitlTimeoutMs});return u.resolution!=="proceed"?{block:R(l.ruleCode??"HITL-BLOCK",u.reason)}:{block:null}}if(!l.allowed){let c=l.ruleCode??"DENY",u=l.reason??"denied by policy";return{block:R(c,u)}}if(l.decision==="mask"&&l.argRedactionRules&&l.argRedactionRules.length>0)try{let c=w(l.argRedactionRules);return{block:null,maskedArgs:k(n,c)}}catch(c){return{block:R("MASK-ERROR",`argument masking failed: ${c instanceof Error?c.message:String(c)}`)}}return{block:null}}async function be(e,t,n,r,i){let o=m.getStore()??e.telemetry,a=await Vn(e,t,n,ye(r),o);if(a.block!==null)return a.block;let s=a.maskedArgs??n,l=await i(s);return re(l,e.agentId,e.unified)}function oe(e,t,n){let r=e;if(r[U]||typeof r.execute!="function")return;let i=r.execute;we(r,"execute",async function(...a){let s=pe(a[0]);return be(n,t,s,G(s),l=>Promise.resolve(i.apply(this,[l,...a.slice(1)])))}),r[U]=!0}function Hn(e,t,n){let r=e;if(r[U]||typeof r.invoke!="function")return;let i=r.invoke;we(r,"invoke",async function(...a){let s=a[1],l=Ze(s),c=typeof s=="string"?s:G(l);return be(n,t,l,c,u=>{let f=typeof s=="string"?JSON.stringify(u):u;return Promise.resolve(i.apply(this,[a[0],f,...a.slice(2)]))})}),r[U]=!0}function Wn(e,t){let n=e;if(n[U]||typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",o=n.call;we(n,"call",async function(...s){let l=pe(s[0]);return be(t,i,l,G(l),c=>Promise.resolve(o.apply(this,[c,...s.slice(1)])))}),n[U]=!0}function vt(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&oe(r,n,t);return e}function wt(e,t,n){switch(n){case"vercel":return zn(e,t);case"mastra":return Gn(e,t);case"openai":return Zn(e,t);case"llamaindex":return Yn(e,t);case"voltagent":return Qn(e,t);case"semantic-kernel":return ht(e,t);default:return e}}function zn(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"&&vt(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=ve(r.onStepFinish)),ae(e,["generate","stream"],async(o,a)=>(z(a,o[0]),o)),e}function Gn(e,t){let r=tr(e);return r&&vt(r,t),ae(e,["generate","stream","generateVNext","streamVNext"],async(i,o)=>{z(o,i[0]);let a=i[1]&&typeof i[1]=="object"?{...i[1]}:{};a.onStepFinish=ve(a.onStepFinish);let s=[...i];return s[1]=a,s}),e}function Qn(e,t){let n=Xn(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;oe(r,typeof i=="string"?i:"unknown",t)}}return ae(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{z(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=ve(o.onStepFinish);let a=[...r];return a[1]=o,a}),e}function Yn(e,t){let n=e,r=o=>{let a=o?.tools;if(Array.isArray(a))for(let s of a)s!==null&&typeof s=="object"&&Wn(s,t)},{agents:i}=n;if(i instanceof Map)for(let o of i.values())r(o);else Array.isArray(n.tools)&&r(n);return ae(e,["run"],async(o,a)=>(z(a,o[0]),o)),er(e,"runStream",(o,a,s)=>{s||z(a,o[0])}),e}function Zn(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:o}=i;Hn(i,typeof o=="string"?o:"unknown",t)}}return Jn(e,t),e}function Jn(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",(...o)=>{i.session_id=yt(),i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let a=o[2];a!=null&&i.llm_prompts.push(G(a).slice(0,5120))}),r.call(e,"agent_end",(...o)=>{let a=o[1];typeof a=="string"&&a&&i.llm_responses.push(a.slice(0,5120))}),n.__visiq_openai_hooks=!0}function Xn(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 ae(e,t,n){let r=e;for(let i of t){if(typeof r[i]!="function")continue;let o=`__visiq_wrapped_${i}`;if(r[o])continue;let a=r[i];r[i]=function(...s){let l=kt();return m.run(l,async()=>{let c=await n(s,l);return a.apply(e,c)})},r[o]=!0}}function er(e,t,n){let r=e;if(typeof r[t]!="function")return;let i=`__visiq_wrapped_${t}`;if(r[i])return;let o=r[t];r[t]=function(...a){let s=m.getStore(),l=s??kt();return n(a,l,s!==void 0),m.run(l,()=>o.apply(e,a))},r[i]=!0}function ve(e){return t=>{let n=m.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 z(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(G(n).slice(0,5120))}function tr(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 kt(){return{session_id:yt(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function we(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function G(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Et(e,t){let n=sr(t);if(e[W]===!0)return e;let r=ur(e);if(r==="langchain-executor"||r==="langchain-graph")return dr(e,n);let i=bt(e);if(i)return wt(e,Lt(n),i);if(fr(e)){let o=process.env.VISIQ_GRANT_ID;return o?gr(e,n,o):mr(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 or="\0",At=new Map;function Ae(e,t,n,r){let i=[e??"",t??"",n??"",r??""].join(or),o=At.get(i);return o||(o=new Ye(e,t,n,void 0,r),o.registerHostEnvironment(),At.set(i,o)),o}function ar(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 sr(e){return{agentId:e?.agentId??process.env.VISIQ_AGENT_ID??lr(),apiKey:e?.apiKey??process.env.VISIQ_API_KEY,endpoint:e?.endpoint??process.env.VISIQ_ENDPOINT,hitlTimeoutMs:cr(e?.hitlTimeoutMs),timeoutMs:ar(e?.timeoutMs)}}function lr(){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=ce.join(t,"package.json");if(le.existsSync(r)){let o=JSON.parse(le.readFileSync(r,"utf8"));if(typeof o.name=="string"&&o.name.trim()){let a=e(o.name);if(a)return a}break}let i=ce.dirname(t);if(i===t)break;t=i}}catch{}try{let t=e(St.hostname());if(t)return t}catch{}return"agent"}function cr(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 ur(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 dr(e,t){let n=e,r=Ae(t.apiKey,t.endpoint,t.agentId,t.timeoutMs);if(Array.isArray(n.tools))for(let o of n.tools)Te(o,t.agentId,r),pr(o,t.agentId,r,t),Ct(o,r,t);let i=n.invoke;if(n.invoke=function(o,a){let s=ke(),l=Rt(t.agentId,r),c=a?.callbacks??[];return m.run(s,()=>i.call(this,o,{...a,callbacks:[...c,l]}))},typeof n.stream=="function"){let o=n.stream;n.stream=function(a,s){let l=ke(),c=Rt(t.agentId,r),u=s?.callbacks??[];return m.run(l,()=>o.call(this,a,{...s,callbacks:[...u,c]}))}}return e}function ke(){return{session_id:rr(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Te(e,t,n){let r=e,i=Symbol.for("visiq.recall.instrumented");if(!r[i]){if(typeof r._getRelevantDocuments=="function"){let o=r._getRelevantDocuments;r._getRelevantDocuments=async function(a,s){let l=await o.call(this,a,s);return Tt(l,t,a,n)},r[i]=!0}if(typeof r.retrieve=="function"&&!r._getRelevantDocuments){let o=r.retrieve;r.retrieve=async function(a){let s=await o.call(this,a);return Tt(s,t,String(a),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&Te(r.retriever,t,n)}}function pr(e,t,n,r){let i=e,o=Symbol.for("visiq.recall.tool-instrumented");if(i[o]||typeof i.func!="function")return;let a=typeof i.name=="string"?i.name:"",s=typeof i.retriever=="object"&&i.retriever!==null,l=a.split(/[^a-zA-Z0-9]+|(?<=[a-z])(?=[A-Z])/).map(y=>y.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),f=l.some(y=>c.has(y)),I=u.has(l[0]??""),A=f||I,g=["update","delete","create","archive","insert","remove"],_=l.some(y=>g.some(b=>y.length>b.length&&y.endsWith(b))),S=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!A&&!_;if(!(s||S))return;let E=f||_;if(!E)if(s)Te(i.retriever,t,n);else{let y=globalThis,b=Symbol.for("visiq.recall.closureRetrieverWarned"),N=y[b]??=new Set;N.has(a)||(N.add(a),console.warn(`[VisIQ] Retriever tool "${a||"(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 O=i.func;E?(i[xt]=!0,i.func=async function(...y){await n.awaitBundleReady();let b=y[0],N=typeof b=="object"&&b!==null?b:{input:b},Ie=typeof N.query=="string"?N.query:void 0,ue=m.getStore(),Re=L(ue),Se=await n.evaluate({operations:["retrieval","action"],agentId:t,...ue?.session_id?{sessionId:ue.session_id}:{},toolName:a||"unknown",toolArgs:N,resourceType:"document",resourceMetadata:{},...Ie!==void 0?{query:Ie}:{},...Re?{telemetry:Re}:{}}),T=F(Se),Ft=V(T.hitlFallback,T.argRedactionRules),Ee=y,xe=()=>{try{return Ee=[k(N,w(T.argRedactionRules)),...y.slice(1)],null}catch{return R("MASK-ERROR","argument masking failed (fail-closed)")}};if(T.decision==="approval_required"&&T.decisionId&&r){let P=await H({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:T.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:Ft});if(P.resolution==="mask"){let Ce=xe();if(Ce)return Ce}else if(P.resolution!=="proceed")return R(T.ruleCode??"HITL-BLOCK",P.reason)}else if(!T.allowed)return R(T.ruleCode??"DENY",T.reason);if(T.decision==="mask"&&T.argRedactionRules.length>0){let P=xe();if(P)return P}let Dt=await O.apply(this,Ee);return dt(Dt,Se)}):i.func=async function(...y){let b=await O.apply(this,y);return typeof b=="string"?st(b,t,n):re(b,t,n)},i[o]=!0}var xt=Symbol.for("visiq.hybrid.instrumented");async function Tt(e,t,n,r){return at(e,t,n,r)}var It=["invoke","call","_call"],se=new ir;function Ct(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[xt]||!It.some(c=>typeof r[c]=="function"))return;let{agentId:o}=n,a=typeof r.name=="string"?r.name:"unknown",s=Symbol("visiq.gate"),l=async(c,u,f,I,A)=>{let g=se.getStore();if(g!==void 0&&g.gateKey===s&&!g.entered.has(A))return g.entered.add(A),c.call(u,f,...I);let _;if(typeof f=="string")_=f;else{let E=f?.input;_=E!=null?String(E):JSON.stringify(f)??""}let C=m.getStore(),S=L(C);await t.awaitBundleReady();let v=F(await t.evaluate({operations:["action"],agentId:o,...C?.session_id?{sessionId:C.session_id}:{},toolName:a,toolArgs:typeof f=="object"&&f!==null?f:{input:_},targetResource:ye(_),...S?{telemetry:S}:{}}));if(v.decision==="approval_required"&&v.decisionId){let E=V(v.hitlFallback,v.argRedactionRules),O=await H({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:v.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:E});if(O.resolution==="proceed")return se.run({gateKey:s,entered:new Set([A])},()=>c.call(u,f,...I));if(O.resolution==="mask")try{let b=k(f,w(v.argRedactionRules));return se.run({gateKey:s,entered:new Set([A])},()=>c.call(u,b,...I))}catch{return R("MASK-ERROR","argument masking failed (fail-closed)")}let y=v.ruleCode??"HITL-BLOCK";return R(y,O.reason)}if(!v.allowed){let E=v.ruleCode??"DENY",O=v.reason??"denied by policy";return R(E,O)}return se.run({gateKey:s,entered:new Set([A])},()=>c.call(u,f,...I))};for(let c of It){if(typeof r[c]!="function")continue;let u=r[c];r[c]=function(f,...I){return l(u,this,f,I,c)}}r[i]=!0}function Rt(e,t){return{name:"VisiqHandler",handleLLMStart:async(n,r)=>{let i=m.getStore();i&&i.llm_prompts.push(...r)},handleLLMEnd:async n=>{let r=m.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=m.getStore();if(!r)return;let i=typeof n.log=="string"?n.log:"";i&&r.agent_reasoning.push(i)},handleRetrieverStart:async(n,r,i)=>{let o=m.getStore();o&&o.retrieverQueries.set(i,r??"")},handleRetrieverEnd:async(n,r)=>{let i=m.getStore();if(!i)return;let o=i.retrieverQueries.get(r)??"";if(i.retrieverQueries.delete(r),!Array.isArray(n))return;let a=L(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:o,contentPreview:c.slice(0,500),...a?{telemetry:a}:{}})}},handleRetrieverError:async(n,r)=>{let i=m.getStore();i&&i.retrieverQueries.delete(r)}}}var Ot=["_call","execute","call","run","invoke"];function fr(e){let t=e;for(let n of Ot)if(typeof t[n]=="function")return!0;return!1}function gr(e,t,n){let r=null,i=null,o=async()=>{if(r)return r;if(i)throw new q(`Failed to bootstrap grant ${n}: ${i.message}`,null);let a;try{a=await ft(t.agentId,n)}catch(s){throw i=s instanceof Error?s:new Error(String(s)),new q(`Failed to bootstrap grant ${n}: ${i.message}`,null)}return r=gt(e,{agentId:t.agentId,grantToken:a,...t.apiKey?{apiKey:t.apiKey}:{},...t.endpoint?{endpoint:t.endpoint}:{}}),r};return new Proxy(e,{get(a,s,l){if(s===W)return!0;let c=Reflect.get(a,s,l);return typeof c!="function"||typeof s!="string"||!Ot.includes(s)?c:async function(...u){let f=await o();return f[s].call(f,...u)}}})}function mr(e,t){let n=Ae(t.apiKey,t.endpoint,t.agentId,t.timeoutMs);Ct(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";oe(e,i,Lt(t))}return e}function Lt(e){return{agentId:e.agentId,unified:Ae(e.apiKey,e.endpoint,e.agentId,e.timeoutMs),hitlTimeoutMs:e.hitlTimeoutMs,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:ke()}}async function Nt(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 $({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 Q=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),M(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return M(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return M(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return M(this.transport,"POST","/api/discovery/fleet/stop")}};var Y=class{constructor(t){this.transport=t}transport;connectAws(t){return M(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function _r(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 Q(r),integrations:new Y(r)}}async function M(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,o={};e.cookieHeader&&(o.Cookie=e.cookieHeader),e.accessToken&&(o.Authorization=`Bearer ${e.accessToken}`);let a;r!==void 0&&(o["Content-Type"]="application/json",a=JSON.stringify(r));let s=await e.fetchImpl(i,{method:t,headers:o,body:a});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 Pt=Et;Pt.delegate=Nt;var Oi=Pt;export{Q as FleetClient,Y as IntegrationsClient,_r as createVisiqClient,Nt as delegate,Oi as visiq};
|
|
3
|
+
-----END PRIVATE KEY-----`,template:{pattern:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.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:b.mac_address,mode:"full"},defaultEnabled:!1}},yi=new Set(Xn.filter(e=>!er[e].defaultEnabled));var we="[REDACTED]",q="\u2022",ae=e=>/[A-Za-z0-9]/.test(e);function pt(e,t,n,r){let i=Array.from(e),o=i.length,a=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:q,c=a+s>=o;return i.map((u,f)=>!c&&(f<a||f>=o-s)?u:ae(u)?l:u).join("")}function tr(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return pt(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:q;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>ae(a)?o:a).join(""))+i}function nr(e,t,n){let r=n.length>0?n:q,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 o=!1,a=!0;for(let c=0;c<e.length;c++)if(ae(e[c])&&(o=!0,!i[c])){a=!1;break}let s=o&&a,l="";for(let c=0;c<e.length;c++){let u=e[c];!s&&i[c]||!ae(u)?l+=u:l+=r}return l}function ft(e,t){let n=t.mode??"full";return n==="partial"?pt(e,t.keepFirst??0,t.keepLast??0,t.maskChar??q):n==="email"?tr(e,t.maskChar??q):n==="custom"?nr(e,t.keepPattern,t.maskChar??q):t.replacement??we}function rr(e,t){return typeof e=="string"?ft(e,t):t.replacement??we}function gt(e){let t=[],n=e.replacement??we;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:o=>ft(o,r)})}return t}function mt(e,t){let n=e;for(let{source:r,replacer:i}of t){let o;try{o=new RegExp(r,"g")}catch(a){let s=a instanceof Error?a.message:String(a);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(o,a=>i(a))}return n}function I(e,t){return e==null?e:typeof e=="string"?ir(e,t):typeof e=="object"?or(e,t):e}function ir(e,t){if(typeof e!="string")return e;let n=gt(t);return n.length===0?e:mt(e,n)}function or(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=gt(t),i=n.size>0,o=r.length>0,a=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>a(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]=rr(l[u],f);continue}c[u]=a(l[u])}return c}return typeof s=="string"&&o?mt(s,r):s};return a(e)}import{AsyncLocalStorage as ar}from"node:async_hooks";var h=new ar,sr=5120,ht=50;function lr(e,t){if(typeof e!="string")return"";let n=new TextEncoder,r=n.encode(e);if(r.length<=t)return e;let o=`\u2026[truncated ${Math.ceil(r.length/1024)}KB]`,a=n.encode(o).length,s=Math.max(0,t-a),l=r.subarray(0,s);return new TextDecoder("utf-8",{fatal:!1}).decode(l)+o}function F(e){if(!e)return;let t=r=>r.length<=ht?r.slice():r.slice(r.length-ht),n=r=>lr(r,sr);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 W(e,t){return e==="mask"&&(t?.length??0)>0}var cr=new Set(["approved","resolved"]),ur=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function dr(e){return new Promise(t=>setTimeout(t,e))}function pr(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 G(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=12e4,maskFallback:o=!1,fetchImpl:a=globalThis.fetch,sleep:s=dr,log:l=g=>console.warn(g)}=e,c=g=>o?{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 R=Date.now()+Math.max(0,i),S=0;for(l(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=R)return l(`[VisIQ HITL] Decision ${r} timed out after ${i}ms \u2014 ${o?"masking":"blocking"} (G001)`),c("HITL approval timed out");let g=null;try{let _=new AbortController,C=setTimeout(()=>_.abort(),5e3),x;try{x=await a(u,{method:"GET",headers:f,signal:_.signal})}finally{clearTimeout(C)}if(!x.ok)throw new Error(`HTTP ${x.status} ${x.statusText}`);let V=await x.json();g=pr(V),S=0}catch(_){S+=1;let C=_ instanceof Error?_.message:String(_);if(l(`[VisIQ HITL] Poll failed for decision ${r} (${S}/3): ${C}`),S>=3)return c(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${C}`);await s(2e3);continue}if(g!==null){let _=g.toLowerCase();return cr.has(_)?(l(`[VisIQ HITL] Decision ${r} approved (${g}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${g})`}):ur.has(_)?(l(`[VisIQ HITL] Decision ${r} resolved as ${g} \u2014 ${o?"masking":"blocking"}`),c(`Not approved by human reviewer (${g})`)):(l(`[VisIQ HITL] Decision ${r} returned unknown status '${g}' \u2014 ${o?"masking":"blocking"} (G001)`),c(`HITL returned unknown status '${g}' \u2014 fail-closed (G001)`))}await s(2e3)}}function M(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 yt(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&W(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}async function le(e,t,n){let r=h.getStore(),i=F(r),o=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 yt(o)}async function ce(e,t,n){return await e.awaitBundleReady(),le(e,t,n)}function bt(e,t){if(t.action==="deny")return null;if(t.action==="redact"&&t.redactionRules.length>0)try{return I(e,T(t.redactionRules))}catch{return null}return e}async function wt(e,t,n,r){if(!Array.isArray(e)||e.length===0)return e;await r.awaitBundleReady();let i=[];for(let o of e){let a=o,s=String(a.pageContent??a.text??a.content??""),l=a.metadata??{},c=await le(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s.slice(0,500)}),u=bt(o,c);u!==null&&i.push(u)}return i}async function vt(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await le(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 I(e,T(r.redactionRules))}catch{return"[RECALL] Retrieved context was blocked by policy."}}default:return e}}var kt=4,At=1e3;function se(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 Tt(e,t,n){let r=[];for(let i of e){let o=i,a=String(o.pageContent??o.text??o.content??""),s={...o.metadata??{},content_preview:a.slice(0,500)},l;try{l=await le(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:a.slice(0,500)})}catch{continue}let c=bt(i,l);c!==null&&r.push(c)}return r}async function ve(e,t,n,r,i){if(r>kt||i.nodes++>At)return e;if(Array.isArray(e)){if(se(e))return i.matched=!0,Tt(e,t,n);let o=[];for(let a of e)o.push(await ve(a,t,n,r+1,i));return o}if(e!==null&&typeof e=="object"){let o=e,a={...o};for(let s of Object.keys(o))a[s]=await ve(o[s],t,n,r+1,i);return a}return e}async function ue(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&se(e))return Tt(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await ve(e,t,n,0,r);if(r.matched)return i}return e}var fr={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function ke(e,t,n){if(t>kt||n.n++>At)return e;if(Array.isArray(e))return se(e)?[]:e.map(r=>ke(r,t+1,n));if(e!==null&&typeof e=="object"){if(se([e]))return{...fr};let r=e,i={};for(let o of Object.keys(r))i[o]=ke(r[o],t+1,n);return i}return e}function _t(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?ke(e,0,{n:0}):e}function It(e,t){let n=yt(t);if(n.action==="deny")return _t(e);if(n.action==="redact"&&n.redactionRules.length>0)try{return I(e,T(n.redactionRules))}catch{return _t(e)}return e}function w(e){return typeof e=="object"&&e!==null?e:null}function St(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}function gr(e,t){let n=w(e.metadata),r=n&&typeof n.name=="string"?n.name:void 0;return St(e.name,e.id,r,t)}function mr(e){let t=w(e.metadata),n=t&&typeof t.description=="string"?t.description:void 0,r=St(e.description,n);return r===void 0?void 0:r.slice(0,4e3)}function hr(e){let t=w(e);return t!==null&&("type"in t||"properties"in t||"$schema"in t)}function _r(e){let t=w(e);if(t===null||!("_def"in t))return;let{shape:n}=t;if(typeof n=="function")try{n=n.call(t)}catch{n=void 0}let r=w(n);if(r===null)return{type:"object"};let i={};for(let o of Object.keys(r))i[o]={};return{type:"object",properties:i}}var yr=new Set(["default","const","enum","examples","example"]);function Ae(e){if(Array.isArray(e))return e.map(Ae);let t=w(e);if(t===null)return e;let n={};for(let[r,i]of Object.entries(t))yr.has(r)||(n[r]=Ae(i));return n}function br(e){let t;if(hr(e))t=e;else{let n=_r(e);if(n===void 0)return;t=n}try{let n=JSON.stringify(t);if(n.length>2e4){let r=w(t),i=r&&w(r.properties);if(i){let o={};for(let a of Object.keys(i))o[a]={};return{type:"object",properties:o}}return{type:"object"}}return Ae(JSON.parse(n))}catch{return}}function wr(e){let t=w(e.metadata),n=e.input_schema??e.inputSchema??e.parameters??e.schema??e.args_schema??e.tool_call_schema??(t?t.parameters:void 0);return n===void 0?void 0:br(n)}function vr(e,t){let n=w(e);if(n===null)return null;let r=gr(n,t);if(r===void 0)return null;let i={name:r.slice(0,255)},o=mr(n);o!==void 0&&(i.description=o);let a=wr(n);return a!==void 0&&(i.input_schema=a),i}function Q(e){let t=[],n=new Set,r=(i,o)=>{try{let a=vr(i,o);a!==null&&!n.has(a.name)&&(n.add(a.name),t.push(a))}catch{}};if(Array.isArray(e)){for(let i of e)if(r(i),t.length>=200)break}else if(e instanceof Map){for(let[i,o]of e.entries())if(r(o,typeof i=="string"?i:void 0),t.length>=200)break}else{let i=w(e);if(i!==null){for(let o of Object.keys(i))if(r(i[o],o),t.length>=200)break}}return t}function Te(e){try{let t=w(e);if(t===null)return[];let n=[],r=new Set,i=l=>{for(let c of l)!r.has(c.name)&&n.length<200&&(r.add(c.name),n.push(c))};t.tools!==void 0&&i(Q(t.tools));let o=w(t.settings);o&&o.tools!==void 0&&i(Q(o.tools));for(let l of["getTools","listTools"]){let c=t[l];if(typeof c=="function")try{i(Q(c.call(t)))}catch{}}let a=w(t.nodes);if(a)for(let l of Object.keys(a)){let c=w(a[l]);c&&c.tools!==void 0&&i(Q(c.tools))}let{agents:s}=t;if(s instanceof Map)for(let l of s.values()){let c=w(l);c&&c.tools!==void 0&&i(Q(c.tools))}return n}catch{return[]}}import{z as de}from"zod";var kr=de.object({decision:de.enum(["permit","deny"]),reason:de.string(),handoff_event_id:de.string().nullable()}),D=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},$=class extends D{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},Ar="https://api.visiqlabs.com",Tr=1e4,U=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??Ar,timeoutMs:e.timeoutMs??Tr},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 o=await i.json();if(!i.ok){let a=o?.error??`HTTP ${i.status}`;throw new D(a,"API_ERROR",i.status)}return o}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=kr.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 Rt=new Map;async function Et(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=Rt.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,o=(await new U({agentId:e,apiKey:r,...i?{endpoint:i}:{}}).acceptGrant(t)).grantToken;if(!o||o.trim()==="")throw new Error("[ORCHESTRATE] bootstrapGrant: backend returned empty grant token");return Rt.set(e,o),o}var Y=Symbol.for("visiq.orchestrate.wrapped");function Ct(e,t){if(!t.agentId||t.agentId.trim()==="")throw new D("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new D("grantToken is required","CONFIG_ERROR");if(e[Y]===!0)return e;let n=new U(t),r=t.failBehavior??"deny",i=async(o,a)=>{let s;try{s=await n.evaluate({grantToken:t.grantToken,action:o,resourceType:a})}catch(l){if(r==="permit"){console.warn("[ORCHESTRATE] evaluate failed \u2014 failing open (failBehavior=permit)",l);return}throw new D(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new $(s.reason,s.handoffEventId)};return new Proxy(e,{get(o,a,s){let l=Reflect.get(o,a,s);return a===Y?!0:a==="_call"&&typeof l=="function"?async function(c,...u){let f=o.name;return await i(f??"_call"),l.call(this??o,c,...u)}:(a==="call"||a==="execute"||a==="run")&&typeof l=="function"?async function(c,...u){let f=o.name;return await i(f??String(a)),l.call(this??o,c,...u)}:l}})}import{randomUUID as Lt}from"node:crypto";var xt=Symbol.for("visiq.semantickernel.instrumented");function Ot(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 Ie=class{constructor(t){this.deps=t}deps;async onFunctionInvocation(t){let{agentId:n,unified:r}=this.deps,i=t.functionName??"unknown",o=t.arguments??{},a=t.pluginName;try{let u=M(await r.evaluate({operations:["action"],agentId:n,toolName:i,toolArgs:o,...a!==void 0?{targetResource:a}:{}}));if(!u.allowed){t.result=k({outcome:"deny",code:u.ruleCode??"DENY",reason:u.reason});return}u.decision==="mask"&&u.argRedactionRules.length>0&&(t.arguments=I(o,T(u.argRedactionRules)))}catch(u){t.result=k({outcome:"error",code:"EVAL-ERROR",mechanism:`evaluation error (fail-closed): ${u instanceof Error?u.message:String(u)}`});return}try{let u=await ce(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 ce(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=I(t.result,T(c.redactionRules))}catch{t.result="[RECALL] Result withheld \u2014 redaction error (fail-closed)."}}},Se=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 ce(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=I(n,T(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 Nt(e,t){let n=e;return n[xt]===!0||(Array.isArray(n.functionInvocationFilters)||(n.functionInvocationFilters=[]),Array.isArray(n.promptRenderFilters)||(n.promptRenderFilters=[]),n.functionInvocationFilters.unshift(new Ie(t)),n.promptRenderFilters.push(new Se(t)),n[xt]=!0),e}function k(e){let t=/^D-/.test(e.code),n;e.outcome==="approval_required"?n="requires human approval, which was not granted":e.outcome==="error"?n="was blocked (fail-closed) after a policy-evaluation error":n="was denied by policy";let r=e.reason?.trim(),i;r?i=r:t?i="no policy rule covers this action, so the organization default applied":e.outcome==="approval_required"?i="this action is routed to a human for approval":i="denied by policy";let o=e.mechanism?.trim()?` \u2014 ${e.mechanism.trim()}`:"";return`[VisIQ decision=${e.outcome} code=${e.code}] This tool call was NOT executed: it ${n} (${i})${o}. VisIQ is a security harness installed by your developer. Report this reason to the user verbatim; do not invent a different one.`}var Ir=/https?:\/\/[^\s"'`,)}\]]+/;function Re(e){let t=e.match(Ir);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 Sr(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}var Ee={vercel:"Vercel AI SDK agent",mastra:"Mastra Agent",openai:"OpenAI Agents SDK agent",llamaindex:"LlamaIndex.TS agent",voltagent:"VoltAgent agent","semantic-kernel":"Semantic Kernel"};function Ft(e){if(e===null||typeof e!="object")return null;let t=e;if(Sr(t))return null;if(Ot(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 Rr(e,t,n,r,i,o){let{agentId:a,unified:s}=e,l=F(i),c;try{await s.awaitBundleReady(),c=M(await s.evaluate({operations:o?["action","delegation"]:["action"],agentId:a,toolName:t,toolArgs:n,...o?{context:ie(o,a)}:{},...i?.session_id?{sessionId:i.session_id}:{},...r!==void 0?{targetResource:r}:{},...l?{telemetry:l}:{}}))}catch(u){return{block:k({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${u instanceof Error?u.message:String(u)}`})}}if(c.decision==="approval_required"&&c.decisionId){let u=s.getApiKey()??e.apiKey,f=await G({endpoint:s.getEndpoint()??e.endpoint??"",...u?{apiKey:u}:{},decisionId:c.decisionId,timeoutMs:e.hitlTimeoutMs});return f.resolution!=="proceed"?{block:k({outcome:"approval_required",code:c.ruleCode??"HITL-BLOCK",reason:c.reason,mechanism:f.reason})}:{block:null}}if(!c.allowed)return{block:k({outcome:"deny",code:c.ruleCode??"DENY",reason:c.reason})};if(c.decision==="mask"&&c.argRedactionRules&&c.argRedactionRules.length>0)try{let u=T(c.argRedactionRules);return{block:null,maskedArgs:I(n,u)}}catch(u){return{block:k({outcome:"error",code:"MASK-ERROR",mechanism:`argument masking failed: ${u instanceof Error?u.message:String(u)}`})}}return{block:null}}async function Ce(e,t,n,r,i){let o=h.getStore()??e.telemetry,a=re(t,n);a&&oe(e.unified,{agentId:e.agentId,sessionId:o?.session_id},a);let s=await Rr(e,t,n,Re(r),o,a);if(s.block!==null)return s.block;let l=s.maskedArgs??n,c=await i(l);return ue(c,e.agentId,e.unified)}function pe(e,t,n){let r=e;if(r[B]){n.onWrap?.();return}if(typeof r.execute!="function")return;let i=r.execute;Oe(r,"execute",async function(...a){let s=be(a[0]);return Ce(n,t,s,J(s),l=>Promise.resolve(i.apply(this,[l,...a.slice(1)])))}),r[B]=!0,n.onWrap?.()}function Er(e,t,n){let r=e;if(r[B]){n.onWrap?.();return}if(typeof r.invoke!="function")return;let i=r.invoke;Oe(r,"invoke",async function(...a){let s=a[1],l=dt(s),c=typeof s=="string"?s:J(l);return Ce(n,t,l,c,u=>{let f=typeof s=="string"?JSON.stringify(u):u;return Promise.resolve(i.apply(this,[a[0],f,...a.slice(2)]))})}),r[B]=!0,n.onWrap?.()}function Cr(e,t){let n=e;if(n[B]){t.onWrap?.();return}if(typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",o=n.call;Oe(n,"call",async function(...s){let l=be(s[0]);return Ce(t,i,l,J(l),c=>Promise.resolve(o.apply(this,[c,...s.slice(1)])))}),n[B]=!0,t.onWrap?.()}function Pt(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&pe(r,n,t);return e}function Mt(e,t,n){switch(n){case"vercel":return xr(e,t);case"mastra":return Or(e,t);case"openai":return Fr(e,t);case"llamaindex":return Lr(e,t);case"voltagent":return Nr(e,t);case"semantic-kernel":return Nt(e,t);default:return e}}function xr(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"&&Pt(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=xe(r.onStepFinish)),fe(e,["generate","stream"],async(o,a)=>(Z(a,o[0]),o)),e}function Or(e,t){let r=jr(e);return r&&Pt(r,t),fe(e,["generate","stream","generateVNext","streamVNext"],async(i,o)=>{Z(o,i[0]);let a=i[1]&&typeof i[1]=="object"?{...i[1]}:{};a.onStepFinish=xe(a.onStepFinish);let s=[...i];return s[1]=a,s}),e}function Nr(e,t){let n=Mr(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;pe(r,typeof i=="string"?i:"unknown",t)}}return fe(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{Z(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=xe(o.onStepFinish);let a=[...r];return a[1]=o,a}),e}function Lr(e,t){let n=e,r=o=>{let a=o?.tools;if(Array.isArray(a))for(let s of a)s!==null&&typeof s=="object"&&Cr(s,t)},{agents:i}=n;if(i instanceof Map)for(let o of i.values())r(o);else Array.isArray(n.tools)&&r(n);return fe(e,["run"],async(o,a)=>(Z(a,o[0]),o)),Dr(e,"runStream",(o,a,s)=>{s||Z(a,o[0])}),e}function Fr(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:o}=i;Er(i,typeof o=="string"?o:"unknown",t)}}return Pr(e,t),e}function Pr(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",(...o)=>{i.session_id=Lt(),i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let a=o[2];a!=null&&i.llm_prompts.push(J(a).slice(0,5120))}),r.call(e,"agent_end",(...o)=>{let a=o[1];typeof a=="string"&&a&&i.llm_responses.push(a.slice(0,5120))}),n.__visiq_openai_hooks=!0}function Mr(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 fe(e,t,n){let r=e;for(let i of t){if(typeof r[i]!="function")continue;let o=`__visiq_wrapped_${i}`;if(r[o])continue;let a=r[i];r[i]=function(...s){let l=Dt();return h.run(l,async()=>{let c=await n(s,l);return a.apply(e,c)})},r[o]=!0}}function Dr(e,t,n){let r=e;if(typeof r[t]!="function")return;let i=`__visiq_wrapped_${t}`;if(r[i])return;let o=r[t];r[t]=function(...a){let s=h.getStore(),l=s??Dt();return n(a,l,s!==void 0),h.run(l,()=>o.apply(e,a))},r[i]=!0}function xe(e){return t=>{let n=h.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 Z(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(J(n).slice(0,5120))}function jr(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 Dt(){return{session_id:Lt(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Oe(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function J(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function zt(e,t){let n=Vr(t);if(e[Y]===!0)return e;let r=Gr(e);if(r==="langchain-executor"||r==="langchain-graph")return K(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,qt(r,null)),$t(e,n),Qr(e,n);let i=Ft(e);if(i){K(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,qt("unknown",i)),$t(e,n);let o=0,a=Qt(n);a.onWrap=()=>{o+=1};let s=Mt(e,a,i);if(o===0){let l=0;try{l=Te(e).length}catch{l=0}if(l>0){let c=`[VisIQ] Detected a ${Ee[i]} that ADVERTISES ${String(l)} tool(s) but instrumented ZERO of them \u2014 its tool calls would run UN-GOVERNED while this SDK appears correctly wired. This is almost always a tool bag that moved/renamed on a framework version bump. Upgrade @visiq/harness, or pass the tools through visiq() directly (visiq(tools, \u2026)). Failing closed (G001). Set onInstrumentFailure:'warn' (or VISIQ_ON_INSTRUMENT_FAILURE=warn) to downgrade this to a warning and run UNGOVERNED \u2014 not recommended.`;if(n.onInstrumentFailure==="warn")console.warn(c);else throw new Error(c)}else{let c=`[VisIQ] Detected a ${Ee[i]} with no tools to instrument (the agent advertises none). If it is intentionally tool-less (LLM-only) this is safe to ignore; otherwise its tool bag is not where this SDK looks for it \u2014 upgrade @visiq/harness or pass the tools through visiq() (visiq(tools, \u2026)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw) to fail closed here.`;if(n.onInstrumentFailure==="throw")throw new Error(c);console.warn(c)}}return s}if(Zr(e)){let o=process.env.VISIQ_GRANT_ID;return o?Jr(e,n,o):Xr(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 Br="\0",jt=new Map;function qt(e,t){if(e==="langchain-executor"||e==="langchain-graph")return"langchain";switch(t){case"vercel":return"vercel_ai";case"mastra":return"mastra";case"openai":return"openai_agents";case"llamaindex":return"llamaindex";case"voltagent":return"voltagent";case"semantic-kernel":return"semantic_kernel";default:return}}function K(e,t,n,r,i){let o=[e??"",t??"",n??"",r??""].join(Br),a=jt.get(o);return a||(a=new ut(e,t,n,void 0,r),a.registerHostEnvironment(i),jt.set(o,a)),a}function $t(e,t){try{let n=Te(e);n.length>0&&K(t.apiKey,t.endpoint,t.agentId,t.timeoutMs).reportToolSurface(n)}catch{}}function Kr(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 Vr(e){return{agentId:e?.agentId??process.env.VISIQ_AGENT_ID??Hr(),apiKey:e?.apiKey??process.env.VISIQ_API_KEY,endpoint:e?.endpoint??process.env.VISIQ_ENDPOINT,hitlTimeoutMs:Wr(e?.hitlTimeoutMs),timeoutMs:Kr(e?.timeoutMs),onInstrumentFailure:e?.onInstrumentFailure??zr()}}function zr(){let e=process.env.VISIQ_ON_INSTRUMENT_FAILURE;if(e==="throw")return"throw";if(e==="warn")return"warn"}function Hr(){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=he.join(t,"package.json");if(me.existsSync(r)){let o=JSON.parse(me.readFileSync(r,"utf8"));if(typeof o.name=="string"&&o.name.trim()){let a=e(o.name);if(a)return a}break}let i=he.dirname(t);if(i===t)break;t=i}}catch{}try{let t=e(Vt.hostname());if(t)return t}catch{}return"agent"}function Wr(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 Gr(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 Qr(e,t){let n=e,r=K(t.apiKey,t.endpoint,t.agentId,t.timeoutMs);if(Array.isArray(n.tools))for(let o of n.tools)Le(o,t.agentId,r),Yr(o,t.agentId,r,t),Wt(o,r,t);let i=n.invoke;if(n.invoke=function(o,a){let s=Ne(),l=Kt(t.agentId,r),c=a?.callbacks??[];return h.run(s,()=>i.call(this,o,{...a,callbacks:[...c,l]}))},typeof n.stream=="function"){let o=n.stream;n.stream=function(a,s){let l=Ne(),c=Kt(t.agentId,r),u=s?.callbacks??[];return h.run(l,()=>o.call(this,a,{...s,callbacks:[...u,c]}))}}return e}function Ne(){return{session_id:$r(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Le(e,t,n){let r=e,i=Symbol.for("visiq.recall.instrumented");if(!r[i]){if(typeof r._getRelevantDocuments=="function"){let o=r._getRelevantDocuments;r._getRelevantDocuments=async function(a,s){let l=await o.call(this,a,s);return Ut(l,t,a,n)},r[i]=!0}if(typeof r.retrieve=="function"&&!r._getRelevantDocuments){let o=r.retrieve;r.retrieve=async function(a){let s=await o.call(this,a);return Ut(s,t,String(a),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&Le(r.retriever,t,n)}}function Yr(e,t,n,r){let i=e,o=Symbol.for("visiq.recall.tool-instrumented");if(i[o]||typeof i.func!="function")return;let a=typeof i.name=="string"?i.name:"",s=typeof i.retriever=="object"&&i.retriever!==null,l=a.split(/[^a-zA-Z0-9]+|(?<=[a-z])(?=[A-Z])/).map(m=>m.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),f=l.some(m=>c.has(m)),R=u.has(l[0]??""),S=f||R,g=["update","delete","create","archive","insert","remove"],_=l.some(m=>g.some(y=>m.length>y.length&&m.endsWith(y))),x=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!S&&!_;if(!(s||x))return;let L=f||_;if(!L)if(s)Le(i.retriever,t,n);else{let m=globalThis,y=Symbol.for("visiq.recall.closureRetrieverWarned"),N=m[y]??=new Set;N.has(a)||(N.add(a),console.warn(`[VisIQ] Retriever tool "${a||"(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 v=i.func;L?(i[Ht]=!0,i.func=async function(...m){await n.awaitBundleReady();let y=m[0],N=typeof y=="object"&&y!==null?y:{input:y},Fe=typeof N.query=="string"?N.query:void 0,_e=h.getStore(),Pe=F(_e),Me=await n.evaluate({operations:["retrieval","action"],agentId:t,..._e?.session_id?{sessionId:_e.session_id}:{},toolName:a||"unknown",toolArgs:N,resourceType:"document",resourceMetadata:{},...Fe!==void 0?{query:Fe}:{},...Pe?{telemetry:Pe}:{}}),A=M(Me),Jt=W(A.hitlFallback,A.argRedactionRules),De=m,je=()=>{try{return De=[I(N,T(A.argRedactionRules)),...m.slice(1)],null}catch{return k({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (fail-closed)"})}};if(A.decision==="approval_required"&&A.decisionId&&r){let P=await G({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:A.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:Jt});if(P.resolution==="mask"){let qe=je();if(qe)return qe}else if(P.resolution!=="proceed")return k({outcome:"approval_required",code:A.ruleCode??"HITL-BLOCK",reason:A.reason,mechanism:P.reason})}else if(!A.allowed)return k({outcome:"deny",code:A.ruleCode??"DENY",reason:A.reason});if(A.decision==="mask"&&A.argRedactionRules.length>0){let P=je();if(P)return P}let Xt=await v.apply(this,De);return It(Xt,Me)}):i.func=async function(...m){let y=await v.apply(this,m);return typeof y=="string"?vt(y,t,n):ue(y,t,n)},i[o]=!0}var Ht=Symbol.for("visiq.hybrid.instrumented");async function Ut(e,t,n,r){return wt(e,t,n,r)}var Bt=["invoke","call","_call"],ge=new Ur;function Wt(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[Ht]||!Bt.some(c=>typeof r[c]=="function"))return;let{agentId:o}=n,a=typeof r.name=="string"?r.name:"unknown",s=Symbol("visiq.gate"),l=async(c,u,f,R,S)=>{let g=ge.getStore();if(g!==void 0&&g.gateKey===s&&!g.entered.has(S))return g.entered.add(S),c.call(u,f,...R);let _;if(typeof f=="string")_=f;else{let m=f?.input;_=m!=null?String(m):JSON.stringify(f)??""}let C=h.getStore(),x=F(C),V=typeof f=="object"&&f!==null?f:{input:_},L=re(a,V);L&&oe(t,{agentId:o,sessionId:C?.session_id,framework:"langchain"},L),await t.awaitBundleReady();let v=M(await t.evaluate({operations:L?["action","delegation"]:["action"],agentId:o,...C?.session_id?{sessionId:C.session_id}:{},toolName:a,toolArgs:V,targetResource:Re(_),...x?{telemetry:x}:{},...L?{context:ie(L,o)}:{}}));if(v.decision==="approval_required"&&v.decisionId){let m=W(v.hitlFallback,v.argRedactionRules),y=await G({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:v.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:m});if(y.resolution==="proceed")return ge.run({gateKey:s,entered:new Set([S])},()=>c.call(u,f,...R));if(y.resolution==="mask")try{let N=I(f,T(v.argRedactionRules));return ge.run({gateKey:s,entered:new Set([S])},()=>c.call(u,N,...R))}catch{return k({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (fail-closed)"})}return k({outcome:"approval_required",code:v.ruleCode??"HITL-BLOCK",reason:v.reason,mechanism:y.reason})}return v.allowed?ge.run({gateKey:s,entered:new Set([S])},()=>c.call(u,f,...R)):k({outcome:"deny",code:v.ruleCode??"DENY",reason:v.reason})};for(let c of Bt){if(typeof r[c]!="function")continue;let u=r[c];r[c]=function(f,...R){return l(u,this,f,R,c)}}r[i]=!0}function Kt(e,t){return{name:"VisiqHandler",handleLLMStart:async(n,r)=>{let i=h.getStore();i&&i.llm_prompts.push(...r)},handleLLMEnd:async n=>{let r=h.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=h.getStore();if(!r)return;let i=typeof n.log=="string"?n.log:"";i&&r.agent_reasoning.push(i)},handleRetrieverStart:async(n,r,i)=>{let o=h.getStore();o&&o.retrieverQueries.set(i,r??"")},handleRetrieverEnd:async(n,r)=>{let i=h.getStore();if(!i)return;let o=i.retrieverQueries.get(r)??"";if(i.retrieverQueries.delete(r),!Array.isArray(n))return;let a=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:o,contentPreview:c.slice(0,500),...a?{telemetry:a}:{}})}},handleRetrieverError:async(n,r)=>{let i=h.getStore();i&&i.retrieverQueries.delete(r)}}}var Gt=["_call","execute","call","run","invoke"];function Zr(e){let t=e;for(let n of Gt)if(typeof t[n]=="function")return!0;return!1}function Jr(e,t,n){let r=null,i=null,o=async()=>{if(r)return r;if(i)throw new $(`Failed to bootstrap grant ${n}: ${i.message}`,null);let a;try{a=await Et(t.agentId,n)}catch(s){throw i=s instanceof Error?s:new Error(String(s)),new $(`Failed to bootstrap grant ${n}: ${i.message}`,null)}return r=Ct(e,{agentId:t.agentId,grantToken:a,...t.apiKey?{apiKey:t.apiKey}:{},...t.endpoint?{endpoint:t.endpoint}:{}}),r};return new Proxy(e,{get(a,s,l){if(s===Y)return!0;let c=Reflect.get(a,s,l);return typeof c!="function"||typeof s!="string"||!Gt.includes(s)?c:async function(...u){let f=await o();return f[s].call(f,...u)}}})}function Xr(e,t){let n=K(t.apiKey,t.endpoint,t.agentId,t.timeoutMs);Wt(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";pe(e,i,Qt(t))}return e}function Qt(e){return{agentId:e.agentId,unified:K(e.apiKey,e.endpoint,e.agentId,e.timeoutMs),hitlTimeoutMs:e.hitlTimeoutMs,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:Ne()}}async function Yt(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 U({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 X=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),j(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return j(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return j(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return j(this.transport,"POST","/api/discovery/fleet/stop")}};var ee=class{constructor(t){this.transport=t}transport;connectAws(t){return j(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function ei(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 X(r),integrations:new ee(r)}}async function j(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,o={};e.cookieHeader&&(o.Cookie=e.cookieHeader),e.accessToken&&(o.Authorization=`Bearer ${e.accessToken}`);let a;r!==void 0&&(o["Content-Type"]="application/json",a=JSON.stringify(r));let s=await e.fetchImpl(i,{method:t,headers:o,body:a});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 Zt=zt;Zt.delegate=Yt;var vo=Zt;export{X as FleetClient,ee as IntegrationsClient,ei as createVisiqClient,Yt as delegate,vo 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.5",
|
|
4
4
|
"description": "VisIQ SDK — AI agent governance harness",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
"license": "MIT",
|
|
25
25
|
"files": [
|
|
26
26
|
"dist",
|
|
27
|
-
"README.md"
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
28
29
|
],
|
|
29
30
|
"repository": {
|
|
30
31
|
"type": "git",
|