@visiq/harness 0.2.6 → 0.2.7

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/README.md CHANGED
@@ -55,7 +55,7 @@ variables (option takes precedence, then the env var):
55
55
  | Option | Env var | Purpose |
56
56
  |---|---|---|
57
57
  | `apiKey` | `VISIQ_API_KEY` | Backend API key. |
58
- | `endpoint` | `VISIQ_ENDPOINT` | Backend endpoint URL. |
58
+ | `endpoint` | `VISIQ_ENDPOINT` | Backend endpoint URL. Optional — defaults to the managed SaaS host `https://api.visiqlabs.com`; set it explicitly only for onprem / self-hosted deployments. |
59
59
  | `agentId` | `VISIQ_AGENT_ID` | Stable agent identity. If unset it is derived (package name → hostname) and auto-provisioned in monitor mode. |
60
60
  | `hitlTimeoutMs` | `VISIQ_HITL_TIMEOUT_MS` | Max wait (ms) for a human to resolve an `approval_required` decision before failing closed. Default `120000`. |
61
61
 
package/dist/index.d.ts CHANGED
@@ -1,3 +1,19 @@
1
+ /** The facets an event participates in (the unified `operations` tag). */
2
+ /**
3
+ * What the runtime does when IT (not policy) fails — no bundle for an
4
+ * enforcing agent, refused dialect, governance core unavailable/crashed.
5
+ * `open` (DEFAULT, owner decision 2026-07-15): permit + loud fail-open
6
+ * telemetry. `closed`: strict fail-closed deny/throw (opt-in via
7
+ * VISIQ_FAIL_MODE=closed or `setFailMode('closed')`).
8
+ */
9
+ export type FailMode = "open" | "closed";
10
+ export declare const DEFAULT_FAIL_MODE: FailMode;
11
+ /**
12
+ * Normalize a raw failMode value. Only (case-insensitive) `open`/`closed`
13
+ * count; anything else → undefined so the default applies — a typo'd value
14
+ * must degrade to the DEFAULT, never invent strictness.
15
+ */
16
+ export declare function normalizeFailMode(raw: unknown): FailMode | undefined;
1
17
  export interface VisiqOptions {
2
18
  /**
3
19
  * Agent identity. Optional — resolution order is this option →
@@ -39,6 +55,15 @@ export interface VisiqOptions {
39
55
  * failure is now LOUD; only the silent path is removed.
40
56
  */
41
57
  onInstrumentFailure?: "warn" | "throw";
58
+ /**
59
+ * Error posture for harness-internal failures (a thrown evaluation, a failed
60
+ * arg-mask, a failed grant bootstrap). `'open'` (DEFAULT, owner decision
61
+ * 2026-07-15): the call proceeds UNGOVERNED with a loud stderr report — a
62
+ * VisIQ bug must never disrupt the agent. `'closed'`: strict blocking.
63
+ * Env override: VISIQ_FAIL_MODE. Policy outcomes (rule deny, approvals,
64
+ * applied masks) are unaffected.
65
+ */
66
+ failMode?: FailMode;
42
67
  }
43
68
  export interface DelegateOptions {
44
69
  /** Restrict the child's tool calls to this allow-list. `undefined` inherits parent's full scope. */
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
- import{randomUUID as vi}from"node:crypto";import*as ye from"node:fs";import*as be from"node:path";import*as cn from"node:os";import{AsyncLocalStorage as ki}from"node:async_hooks";import{z as d}from"zod";import*as x from"node:os";var ve=1,Qe="X-VisIQ-SDK",Ye="X-VisIQ-Dialect",Ze="unknown";function j(e,t=1){return{[Qe]:e&&e.length>0?e:Ze,[Ye]:String(t)}}var Je="interceptor_source",bn=d.enum(["enforce","audit","off"]),wn=d.enum(["closed","open"]),Xe=d.enum(["enforce","monitor","off"]),vn=d.object({apiKey:d.string().min(1,"apiKey is required"),agentId:d.string().min(1,"agentId is required"),endpoint:d.string().url().optional(),mode:bn.optional(),timeoutMs:d.number().int().positive().optional(),hitlTimeoutMs:d.number().int().positive().optional(),failBehavior:wn.optional()}),Mi=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()}),kn=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()}),An=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:Xe.optional(),arg_redaction_rules:d.array(kn).optional(),plane:d.string().nullable().optional(),operation:d.string().nullable().optional(),is_retrieval:d.boolean().optional(),metadata:d.record(d.unknown()).optional()}),Tn=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())])}),In=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(Tn).default([]),priority:d.number().int().default(0)}),Sn=d.object({version:d.string().min(1),agent_mode:Xe.optional(),rules:d.array(In),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()}),Rn=2e3,et=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return j(this.config.sdkVersion,this.config.sdkDialect)}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return An.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json",...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();return Sn.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}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let 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 En(Rn)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function En(e){return new Promise(t=>setTimeout(t,e))}function tt(){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=Cn();t&&(e.ip=t)}catch{}return e}function Cn(){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 Ui}from"crypto";import{createHash as Hi}from"crypto";var xn=["tier1","tier2","tier3"];function it(e){return typeof e=="string"&&xn.includes(e)}var On=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Nn=["internal","customer_facing","experimental","third_party"],ot=[...On,...Nn];function Ln(e){return typeof e=="string"&&ot.includes(e)}function at(e){let t=new Set;for(let n of e)Ln(n)&&t.add(n);return ot.filter(n=>t.has(n))}var Dn=["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 st(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 Fn={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 Pn(e){let t=st(e);return t===null?"other":Fn[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 nt={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 Mn(e){let t=st(e);return t===null?"other":nt[t]??nt[t.replace(/_/g,"")]??"other"}function lt(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=Pn(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=Mn(t.targetApp)),n.context=r}return n}var rt=64,jn=64,G={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function ct(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var $n=new Set(["deny","approval_required","escalate"]);function re(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>rt?r.slice(0,rt):r}function qn(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function ie(e){return typeof e=="string"&&e.length>0?e:null}function ut(e,t){let n=qn(t.data_categories),r=ie(t.classification),i=ie(t.action_class),o=i&&Dn.includes(i)?i:null,a=ie(t.target_app),s=ie(t.decision),l={...e.action_counts};if(o)if(o in l)l[o]=(l[o]??0)+1;else if(Object.keys(l).length<jn)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:re(e.retrieved_data_categories,n),retrieved_classifications:re(e.retrieved_classifications,r?[r]:[]),action_classes:re(e.action_classes,o?[o]:[]),action_counts:l,denied_count:e.denied_count+(s==="deny"?1:0),inhibited_count:e.inhibited_count+(s&&$n.has(s)?1:0),event_count:e.event_count+1,target_apps:re(e.target_apps,a?[a]:[])}}var Un="generic",dt=[{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:Un,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."}],Bn=dt.map(e=>e.id),Bi=new Map(dt.map(e=>[e.id,e])),Vi=new Set(Bn);var Vn=/^[a-z][a-z0-9_]*$/;function pt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Vn.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Kn=["narrow","moderate","broad","unbounded","unknown"];function ft(e){return typeof e=="string"&&Kn.includes(e)}function gt(e){return e==="open"||e==="closed"?e:null}var Hn=["action","retrieval","delegation"];function zn(e){return typeof e=="string"&&Hn.includes(e)}var Gn=new Set(["rules"]);function mt(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Gn.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(zn):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{z as oe}from"zod";import{randomUUID as Or}from"node:crypto";var ht=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Wn(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:ht(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:ht(t.spawn.prompt)}),t}function Qn(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 Yn=1440*60*1e3,Zn="VISIQ_BUNDLE_GRACE_TTL_MS",Jn="VISIQ_BUNDLE_CACHE_DISABLED",Xn="VISIQ_CACHE_DIR",er=oe.object({graceTtlMs:oe.number().int().nonnegative().optional(),disabled:oe.boolean().optional(),cacheDir:oe.string().min(1).optional()}).strict();function tr(e){return e==null?{}:er.parse(e)}function nr(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Zn];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return Yn}function rr(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Jn]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var _t;function ir(){if(_t!==void 0)return _t;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function or(e){return JSON.stringify(Ae(e))}function Ae(e){if(Array.isArray(e))return e.map(Ae);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Ae(t[r]);return n}return e}function ar(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function sr(e){if(e!==null&&typeof e=="object"&&typeof e.fetchedAt=="number"&&typeof e.contentHash=="string"&&"body"in e){let t=e;return{fetchedAt:t.fetchedAt,version:typeof t.version=="string"?t.version:null,contentHash:t.contentHash,body:t.body}}return null}async function At(){if(!ir())return null;try{let[e,t,n,r]=await Promise.all([import("node:fs/promises"),import("node:path"),import("node:os"),import("node:crypto")]);return{fs:e,path:t,os:n,crypto:r}}catch{return null}}function Tt(e,t){return e.createHash("sha256").update(or(t)).digest("hex")}function lr(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Xn]?.trim();if(r)return r;let i=process.env.XDG_CACHE_HOME?.trim();if(i)return e.path.join(i,"visiq");let o="";try{o=e.os.homedir()}catch{o=""}return o?e.path.join(o,".cache","visiq"):e.path.join(e.os.tmpdir(),"visiq-cache")}function cr(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function It(e,t,n){return e.path.join(lr(e,n),"bundles",`${cr(e,t)}.json`)}async function ur(e,t,n,r={}){let i=await At();if(i)try{let o=It(i,e,r),a=i.path.dirname(o);await i.fs.mkdir(a,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:Tt(i.crypto,t),body:t},l=`${o}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(l,JSON.stringify(s),{mode:384});try{await i.fs.rename(l,o)}catch(c){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),c}}catch{}}async function dr(e,t={}){let n=await At();if(!n)return null;try{let r=await n.fs.readFile(It(n,e,t),"utf-8"),i=sr(JSON.parse(r));return!i||Tt(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var W;async function pr(){if(W!==void 0)return W;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;W=typeof t=="function"?t:null}catch{W=null}return W}var fr=5e3,gr=1e4,mr=25,yt=1e3,hr=5e3,_r=100,bt=2e3,yr=512,br=1800*1e3,wr="monitor",vr="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",kr="Rules bundle requires a newer SDK wire-contract dialect than this SDK supports \u2014 refusing the bundle and blocking all actions (fail-closed, G001). Upgrade the VisIQ SDK.",Ar=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()}),Tr=p.object({version:p.string().min(1),dialect_version:p.number().int().optional(),min_dialect:p.number().int().optional(),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 Ir(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=pt(n);return{trust_tier:it(t)?t:null,categories:at(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&ft(e.blast_radius_tier)?e.blast_radius_tier:null}}function Sr(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 Rr(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var Te=new Set,wt=!1;async function vt(e){let t=[];for(let n of Te){if(n.pendingTelemetryCount()>0&&!n.hasBackend()){console.warn(`[UnifiedRuntime] exiting with ${n.pendingTelemetryCount()} un-sent decision(s) and no backend \u2014 telemetry lost.`);continue}let r=n.flush();e&&t.push(r)}t.length>0&&await Promise.allSettled(t)}function Er(){if(!wt&&!(typeof process>"u"||typeof process.once!="function")){wt=!0,process.once("beforeExit",()=>{vt(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await vt(!0)}finally{process.kill(process.pid,e)}})()})}}var St=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;cacheIdentity;bundleCacheDisabled;bundleGraceTtlMs;bundleCacheDirOverride;diskFallbackServed=!1;agentMode=wr;agentModeByOperation=null;rawBundle=null;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;telemetryBuffer=[];telemetryTimer=null;cognitionBuffer=[];cognitionTimer=null;cognitionEnabled=process.env.VISIQ_COGNITION_CAPTURE==="1";envRegistered=!1;registerPromise=null;lastToolSurfaceSig=null;constructor(e,t,n,r,i,o,a,s){let l=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,c=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,u=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=l,this.resolvedEndpoint=c,this.resolvedAgentId=u,this.harnessKind=r,this.sdkVersion=o,this.sdkDialect=a,this.originalFetch=globalThis.fetch.bind(globalThis);let f=tr(s);if(this.bundleCacheDisabled=rr(f.disabled),this.bundleGraceTtlMs=nr(f.graceTtlMs),this.bundleCacheDirOverride=f.cacheDir,this.cacheIdentity=l&&c&&!this.bundleCacheDisabled?{endpoint:c,agentId:u,apiKey:l}:null,l&&c){let A={apiKey:l,agentId:u,endpoint:c,mode:"enforce",timeoutMs:Qn(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...o!==void 0?{sdkVersion:o}:{},...a!==void 0?{sdkDialect:a}:{}};this.client=new et(A,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},fr),ke(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},gr),ke(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},hr),ke(this.cognitionTimer),Te.add(this),Er()}else this.client=null}async evaluate(e){let t=Ar.parse(e),n=Date.now();if(this.operatorShutdown){let l=this.denyAll(t,vr);return this.applyAgentMode(l,"enforce",t,n)}if(this.dialectRefused){let l=this.denyAll(t,kr);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 pr();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 G;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>br?(this.sessions.delete(e),G):t.state:G}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?lt(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},l=ut(r===G?ct():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>yr){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=Tr.parse(e);this.bundleApplyFailed=!1;let n=this.sdkDialect??1;if(t.min_dialect!==void 0&&t.min_dialect>n){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle requires dialect ${t.min_dialect} but this SDK speaks ${n} \u2014 refusing the bundle and failing closed (deny-all, G001). Upgrade the VisIQ SDK.`);return}this.dialectRefused=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(r=>mt(r)).filter(r=>r!==null),this.agentAttributes=t.agent_attributes?Ir(t.agent_attributes):null,this.agentNoCoverage=gt(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=Sr(t.agent_mode_by_operation),process.env.VISIQ_COGNITION_CAPTURE==="1"?this.cognitionEnabled=!0:typeof t.cognition_capture=="boolean"&&(this.cognitionEnabled=t.cognition_capture),this.operatorShutdown=t.shutdown===!0,this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json",...j(this.sdkVersion,this.sdkDialect)};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let o=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&o?this.bundleEtag=r:o||(this.bundleEtag=null),o&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await dr(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(ar(e,this.bundleGraceTtlMs,t)){try{this.applyBundle(e.body)}catch{return}if(this.bundleLoaded&&!this.dialectRefused&&!this.diskFallbackServed){this.diskFallbackServed=!0;let n=Math.max(0,Math.round((t-e.fetchedAt)/1e3)),r=Math.round(this.bundleGraceTtlMs/1e3);console.warn(`[UnifiedRuntime] serving cached rules bundle (age ${n}s) \u2014 control plane unreachable on cold start; will keep retrying and fail closed once the cache exceeds the ${r}s grace window.`)}}}async persistBundleToDisk(e){this.bundleCacheDisabled||!this.cacheIdentity||await ur(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(e){this.registerEnvironment({...tt(),...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?Rr(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?{[Je]:this.harnessKind}:{},...e.context??{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=mr&&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-yt;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${yt})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Wn(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=_r&&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-bt;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${bt})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),Te.delete(this)}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.cognitionTimer&&(clearInterval(this.cognitionTimer),this.cognitionTimer=null),this.flushTelemetry(),this.flushCognition()}};function ke(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function Cr(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function E(e,...t){for(let n of t){let r=Cr(e[n]);if(r)return r}}var xr=[{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 ae(e,t){if(!e)return null;let n=t??{};for(let r of xr)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function se(e,t){return{delegation:{is_delegated:!0,role:"parent",parent_agent_id:t,target_agent:e.childAgentId,source:e.source,spawn:{childAgentId:e.childAgentId,childName:e.childName,kind:e.kind,...e.model?{model:e.model}:{},...e.task?{prompt:e.task}:{},...e.description?{description:e.description}:{},...e.goal?{goal:e.goal}:{},...e.agentType?{agentType:e.agentType}:{}}}}}var kt=new Map;function Nr(e){let t=(kt.get(e)??0)+1;return kt.set(e,t),t}function le(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:Or(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:Nr(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 Ie(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 Rt(e){if(typeof e=="string"){try{let t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{input:e}}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{input:e===void 0?"":String(e)}}function I(e){let t=[],n=[],r,i=[];for(let 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 F="0.2.6";var Lr=[{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 y=Object.fromEntries(Lr.map(e=>[e.name,e.re.source])),Dr=["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"],Fr={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 sa}from"node:crypto";import*as Ge from"node:fs";import*as He from"node:path";import*as lr from"node:os";import{AsyncLocalStorage as la}from"node:async_hooks";import{z as p}from"zod";import*as P from"node:os";import{randomUUID as ue}from"node:crypto";var We=1,Tt="X-VisIQ-SDK",Et="X-VisIQ-Dialect",Rt="unknown";function H(e,t=1){return{[Tt]:e&&e.length>0?e:Rt,[Et]:String(t)}}var Ct="interceptor_source",_r=p.enum(["enforce","audit","off"]),yr=p.enum(["closed","open"]),xt=p.enum(["enforce","monitor","off"]),br=p.object({apiKey:p.string().min(1,"apiKey is required"),agentId:p.string().min(1,"agentId is required"),endpoint:p.string().url().optional(),mode:_r.optional(),timeoutMs:p.number().int().positive().optional(),hitlTimeoutMs:p.number().int().positive().optional(),failBehavior:yr.optional()}),Ra=p.object({agent_id:p.string().min(1),target_app:p.string().min(1),action:p.string().min(1),context:p.record(p.unknown()).optional(),session_id:p.string().min(1).max(255).optional(),telemetry:p.record(p.unknown()).optional()}),vr=p.object({field:p.string().optional(),pattern:p.string().optional(),replacement:p.string().optional(),mode:p.enum(["full","partial","email"]).optional(),keepFirst:p.number().optional(),keepLast:p.number().optional(),maskChar:p.string().optional()}),wr=p.object({decision_id:p.string().min(1),decision:p.enum(["permit","deny","approval_required","mask"]),reason:p.string().optional(),rule_code:p.string().nullable().optional(),enforced:p.boolean().optional(),agent_mode:xt.optional(),arg_redaction_rules:p.array(vr).optional(),plane:p.string().nullable().optional(),operation:p.string().nullable().optional(),is_retrieval:p.boolean().optional(),metadata:p.record(p.unknown()).optional()}),kr=p.object({field:p.string().min(1),operator:p.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:p.union([p.string(),p.number(),p.array(p.string())])}),Ar=p.object({id:p.string().min(1),rule_code:p.string().default(""),name:p.string().min(1),description:p.string().nullable().default(null),effect:p.enum(["allow","deny","hitl","mask"]),resource_type:p.string().min(1),rego_source:p.string().default(""),target_app:p.string().nullable().default(null),action_pattern:p.string().nullable().default(null),conditions:p.array(kr).default([]),priority:p.number().int().default(0)}),Ir=p.object({version:p.string().min(1),agent_mode:xt.optional(),rules:p.array(Ar),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()}),Sr=2e3,Qe=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return H(this.config.sdkVersion,this.config.sdkDialect)}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return wr.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json",...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();return Ir.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}`,...this.versionHeaders()},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async sendCognition(e,t){if(t.length===0)return;let n=`${this.config.endpoint}/allow/cognition`,r=await this.originalFetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({...e?{session:e}:{},beats:t})});if(!r.ok)throw new Error(`ALLOW cognition delivery failed: HTTP ${r.status} ${r.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{},...e.agent_type?{agent_type:e.agent_type}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async reportToolSurface(e){if(!this.config.agentId||e.length===0)return;let t=`${this.config.endpoint}/allow/agents/tools`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},body:JSON.stringify({agent_id:this.config.agentId,tools:e})});n.ok||console.warn(`[ALLOW] Tool-surface report failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Tool-surface report failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.versionHeaders()},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let o=await i.json();if(typeof o!="object"||o===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let a=o,l=a.hitl_result;if(l==="approved")return{decision_id:e,decision:"permit",reason:"Approved by human reviewer"};if(l==="rejected")return{decision_id:e,decision:"deny",reason:typeof a.reason=="string"?a.reason:"Rejected by human reviewer"};if(l==="timeout"||l==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await Tr(Sr)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function Tr(e){return new Promise(t=>setTimeout(t,e))}function Ye(){let e={};try{let t=`${P.platform()} ${P.release()}`.trim();t&&(e.os=t)}catch{}try{let t=P.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=P.userInfo();t&&(e.username=t)}catch{}try{let t=Er();t&&(e.ip=t)}catch{}return e}function Er(){let e=P.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}function Rr(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Ce(e,...t){for(let n of t){let r=Rr(e[n]);if(r)return r}}function xe(e){if(Ce(e,"run_id","runId","session_id","sessionId","thread_id","threadId"))return"session";if(Ce(e,"user_id","userId"))return"user";if(Ce(e,"agent_id","agentId"))return"agent";if(Ce(e,"org_id","orgId","namespace"))return"org"}var Cr=[{framework:"mem0",matches:e=>/^(mem0[_-])?(add|search|get|retrieve|update|delete)[_-]memor(y|ies)$/i.test(e),extract:(e,t)=>{let n=/^(?:mem0[_-])?([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"||n==="update"?r="write":r="read";let i=xe(t);return{op:r,store:"mem0",framework:"mem0",...i?{scope:i}:{}}}},{framework:"letta",matches:e=>/^(core_memory_(append|replace)|archival_memory_(insert|search)|conversation_search)$/i.test(e),extract:e=>{let t=e.toLowerCase();return t.startsWith("core_memory_")?{op:"write",store:"letta-core",scope:"agent",framework:"letta"}:t==="archival_memory_insert"?{op:"write",store:"letta-archival",scope:"agent",framework:"letta"}:t==="archival_memory_search"?{op:"search",store:"letta-archival",scope:"agent",framework:"letta"}:{op:"search",store:"letta-conversation",scope:"session",framework:"letta"}}},{framework:"langgraph",matches:e=>/^(upsert_memory|save_recall_memory|search_recall_memories)$/i.test(e),extract:(e,t)=>{let n=/^search_/i.test(e),r=xe(t);return{op:n?"search":"write",store:"langgraph-store",framework:"langgraph",...r?{scope:r}:{}}}},{framework:"zep",matches:e=>/^zep[_-](add|search|get|delete)[_-]memory$/i.test(e),extract:(e,t)=>{let n=/^zep[_-]([a-z]+)/i.exec(e)?.[1]?.toLowerCase(),r;n==="search"?r="search":n==="delete"?r="delete":n==="add"?r="write":r="read";let i=xe(t)??"session";return{op:r,store:"zep",scope:i,framework:"zep"}}},{framework:"mcp-memory",matches:e=>/^(create_entities|create_relations|add_observations|delete_entities|delete_relations|delete_observations|search_nodes|open_nodes|read_graph)$/i.test(e),extract:e=>{let t=e.toLowerCase(),n;return t.startsWith("delete_")?n="delete":t==="search_nodes"?n="search":t==="open_nodes"||t==="read_graph"?n="read":n="write",{op:n,store:"mcp-memory",scope:"agent",framework:"mcp-memory"}}},{framework:"generic",matches:e=>/(^|[_\-.])(memory|memories|mem0|recall)([_\-.]|$)/i.test(e),extract:(e,t)=>{let n=e.toLowerCase(),r;/(^|[_\-.])(search|query|find|lookup|retrieve)([_\-.]|$)/.test(n)?r="search":/(^|[_\-.])(delete|remove|forget|clear|purge)([_\-.]|$)/.test(n)?r="delete":/(^|[_\-.])(add|save|write|store|upsert|put|set|update|insert|append|remember)([_\-.]|$)/.test(n)?r="write":r="read";let i=xe(t);return{op:r,store:"memory",framework:"generic",...i?{scope:i}:{}}}}];function ce(e,t){if(!e)return null;let n=t??{};for(let r of Cr)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function Je(e,t){let n=typeof t?.itemCount=="number"&&Number.isFinite(t.itemCount)&&t.itemCount>=0?Math.round(t.itemCount):void 0,r=typeof t?.bytes=="number"&&Number.isFinite(t.bytes)&&t.bytes>=0?Math.round(t.bytes):void 0,i=e.op==="read"||e.op==="search";return{op:e.op,store:e.store,...e.scope?{scope:e.scope}:{},...n!==void 0?{itemCount:n}:{},...r!==void 0?{bytes:r}:{},...i&&n!==void 0?{hit:n>0}:{}}}var St=new Map;function de(e){let t=(St.get(e)??0)+1;return St.set(e,t),t}function Ot(e){if(!e||typeof e!="object")return;let t={};for(let n of["tokensIn","tokensOut","cacheRead","cacheWrite"]){let r=e[n];typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[n]=Math.round(r))}return Object.keys(t).length>0?t:void 0}function Ze(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=Array.isArray(n.texts)?n.texts.filter(a=>typeof a=="string"&&a.length>0).join(`
2
+
3
+ `):"",o=Ot(n.usage);e.emitCognition({clientEventId:ue(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:de(r),ts:Date.now(),kind:n.final?"speech":"thought",visibility:"shown",provenance:"narration",...i?{content:{text:i}}:{},...o?{cost:o}:{},...n.model?{model:n.model}:{},...typeof n.durationMs=="number"&&Number.isFinite(n.durationMs)?{durationMs:Math.max(0,Math.round(n.durationMs))}:{},...t.framework?{framework:t.framework}:{}})}function pe(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:ue(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:de(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 fe(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=n.memory?Je(n.memory):void 0;e.emitCognition({clientEventId:ue(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:de(r),ts:Date.now(),kind:i?"memory":"action",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},tool:{name:n.toolName,...n.verb?{verb:n.verb}:{},...n.argSummary?{argSummary:n.argSummary}:{}},...i?{memory:i}:{}})}function me(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId,i=s=>typeof s=="number"&&Number.isFinite(s)&&s>=0?Math.round(s):void 0,o=i(n.bytes),a=i(n.itemCount),l=i(n.durationMs),c;n.memory&&(c=Je(n.memory,{itemCount:a,bytes:o})),e.emitCognition({clientEventId:ue(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:de(r),ts:Date.now(),kind:"observation",visibility:"shown",provenance:"parsed",...l!==void 0?{durationMs:l}:{},...t.framework?{framework:t.framework}:{},tool:{name:n.toolName},result:{ok:n.ok,...o!==void 0?{bytes:o}:{},...a!==void 0?{itemCount:a}:{}},...c?{memory:c}:{}})}function te(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:ue(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:de(r),ts:Date.now(),kind:"intervention",visibility:"shown",provenance:"parsed",...t.framework?{framework:t.framework}:{},tool:{name:n.toolName},governance:{decision:n.decision,enforced:n.enforced,...n.ruleCode?{ruleCode:n.ruleCode}:{},...n.ruleLabel?{ruleLabel:n.ruleLabel}:{},...n.harnessMessage?{harnessMessage:n.harnessMessage}:{}}})}function W(e){try{let t=JSON.stringify(e);return typeof t=="string"?t.length:void 0}catch{return}}function Q(e){try{return Array.isArray(e)?e.length:void 0}catch{return}}import{z as m}from"zod";import{createHash as La}from"crypto";import{createHash as $a}from"crypto";var xr=["tier1","tier2","tier3"];function Mt(e){return typeof e=="string"&&xr.includes(e)}var Or=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],Nr=["internal","customer_facing","experimental","third_party"],Dt=[...Or,...Nr];function Lr(e){return typeof e=="string"&&Dt.includes(e)}function $t(e){let t=new Set;for(let n of e)Lr(n)&&t.add(n);return Dt.filter(n=>t.has(n))}var Fr=["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 Pt(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 Mr={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 Dr(e){let t=Pt(e);return t===null?"other":Mr[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 Nt={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 $r(e){let t=Pt(e);return t===null?"other":Nt[t]??Nt[t.replace(/_/g,"")]??"other"}function Xe(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=Dr(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=$r(t.targetApp)),n.context=r}return n}var Lt=64,Pr=64,he={retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function jt(){return{retrieved_data_categories:[],retrieved_classifications:[],taint:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var jr=new Set(["deny","approval_required","escalate"]);function ge(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>Lt?r.slice(0,Lt):r}function Ft(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Oe(e){return typeof e=="string"&&e.length>0?e:null}function qt(e,t){let n=Ft(t.data_categories),r=Oe(t.classification),i=Ft(t.taint),o=Oe(t.action_class),a=o&&Fr.includes(o)?o:null,l=Oe(t.target_app),c=Oe(t.decision),s={...e.action_counts};if(a)if(a in s)s[a]=(s[a]??0)+1;else if(Object.keys(s).length<Pr)s[a]=1;else{let u=Object.keys(s).sort(),d=u[u.length-1];d!==void 0&&a<d&&(delete s[d],s[a]=1)}return{retrieved_data_categories:ge(e.retrieved_data_categories,n),retrieved_classifications:ge(e.retrieved_classifications,r?[r]:[]),taint:ge(e.taint,i),action_classes:ge(e.action_classes,a?[a]:[]),action_counts:s,denied_count:e.denied_count+(c==="deny"?1:0),inhibited_count:e.inhibited_count+(c&&jr.has(c)?1:0),event_count:e.event_count+1,target_apps:ge(e.target_apps,l?[l]:[])}}var Ut="generic",Bt=[{id:"finance_accounting",name:"Finance & Accounting",icon:"Landmark",description:"Payments, invoicing, ledgers, transactions, refunds, financial reporting, SOX/AML/KYC controls."},{id:"hr",name:"Human Resources",icon:"Users",description:"Employee records, payroll, hiring/recruiting, benefits, personnel actions and PII of staff."},{id:"engineering",name:"Engineering",icon:"Code",description:"Source code, build/deploy pipelines, infrastructure changes, production systems and developer tooling."},{id:"it_security",name:"IT & Security",icon:"ShieldCheck",description:"Credentials, secrets, access control, configuration, threat/exfiltration prevention and security operations."},{id:"legal",name:"Legal",icon:"Scale",description:"Contracts, NDAs, litigation, counsel communications and legal-hold material."},{id:"privacy_compliance",name:"Privacy & Compliance",icon:"BadgeCheck",description:"GDPR/CCPA/HIPAA, consent, data-subject rights, special-category data and regulatory data handling."},{id:"sales",name:"Sales",icon:"TrendingUp",description:"CRM, leads, deals, quotes, pipeline and customer commercial relationships."},{id:"marketing",name:"Marketing",icon:"Megaphone",description:"Campaigns, content, brand, social channels and prospect/audience data."},{id:"operations",name:"Operations",icon:"Cog",description:"Business operations, logistics, internal workflows, vendor/ops tooling and process automation."},{id:"customer_support",name:"Customer Support",icon:"LifeBuoy",description:"Support tickets, customer communications, account servicing and help-desk actions."},{id:"procurement",name:"Procurement",icon:"ShoppingCart",description:"Purchasing, supplier management, purchase orders, sourcing and spend approvals."},{id:Ut,name:"Generic",icon:"Shapes",description:"Catch-all for cross-cutting rules or rules that do not fit a specific function. Assign when no specific function clearly applies."}],qr=Bt.map(e=>e.id),Fa=new Map(Bt.map(e=>[e.id,e])),Ma=new Set(qr);function Vt(e){return Array.isArray(e)&&e.length>0?[...e]:[Ut]}var Ur=/^[a-z][a-z0-9_]*$/;function Kt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&Ur.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var Br=["narrow","moderate","broad","unbounded","unknown"];function zt(e){return typeof e=="string"&&Br.includes(e)}function Gt(e){return e==="open"||e==="closed"?e:null}var Vr=["action","retrieval","delegation"];function Kr(e){return typeof e=="string"&&Vr.includes(e)}var zr=new Set(["rules"]);function Ht(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!zr.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Kr):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}import{z as Fe}from"zod";var Gr="[REDACTED]",nn=[{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}];function rn(e){if(!/^\d+$/.test(e))return!1;let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let i=e.charCodeAt(r)-48;n&&(i*=2,i>9&&(i-=9)),t+=i,n=!n}return t%10===0}function Hr(e){let t=e.replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let i=0;i<n.length;i++){let o=n[i],a=o>="A"&&o<="Z"?String(o.charCodeAt(0)-55):o;for(let l=0;l<a.length;l++)r=(r*10+(a.charCodeAt(l)-48))%97}return r===1}function Wr(e){if(!/^\d{9}$/.test(e))return!1;let t=[3,7,1,3,7,1,3,7,1],n=0;for(let r=0;r<9;r++)n+=(e.charCodeAt(r)-48)*t[r];return n%10===0}var Qr=[{name:"pan",re:/\d(?:[ -]?\d){12,18}/g,normalize:e=>e.replace(/[ -]/g,""),validate:e=>e.length>=13&&e.length<=19&&rn(e)},{name:"iban",re:/\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]){10,30}\b/g,normalize:e=>e.replace(/\s/g,"").toUpperCase(),validate:Hr},{name:"aba_routing",re:/\b\d{9}\b/g,normalize:e=>e,validate:Wr}],E=Object.fromEntries(nn.map(e=>[e.name,e.re.source])),on=["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"],rt={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
4
  MIIEv\u2026
3
- -----END PRIVATE KEY-----`,template:{pattern:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.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:y.mac_address,mode:"full"},defaultEnabled:!1}},to=new Set(Dr.filter(e=>!Fr[e].defaultEnabled));var Se="[REDACTED]",B="\u2022",ce=e=>/[A-Za-z0-9]/.test(e);function Et(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:B,c=a+s>=o;return i.map((u,f)=>!c&&(f<a||f>=o-s)?u:ce(u)?l:u).join("")}function Pr(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Et(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:B;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>ce(a)?o:a).join(""))+i}function Mr(e,t,n){let r=n.length>0?n:B,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(ce(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]||!ce(u)?l+=u:l+=r}return l}function Ct(e,t){let n=t.mode??"full";return n==="partial"?Et(e,t.keepFirst??0,t.keepLast??0,t.maskChar??B):n==="email"?Pr(e,t.maskChar??B):n==="custom"?Mr(e,t.keepPattern,t.maskChar??B):t.replacement??Se}function jr(e,t){return typeof e=="string"?Ct(e,t):t.replacement??Se}function xt(e){let t=[],n=e.replacement??Se;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:o=>Ct(o,r)})}return t}function Ot(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 S(e,t){return e==null?e:typeof e=="string"?$r(e,t):typeof e=="object"?qr(e,t):e}function $r(e,t){if(typeof e!="string")return e;let n=xt(t);return n.length===0?e:Ot(e,n)}function qr(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=xt(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]=jr(l[u],f);continue}c[u]=a(l[u])}return c}return typeof s=="string"&&o?Ot(s,r):s};return a(e)}import{AsyncLocalStorage as Ur}from"node:async_hooks";var h=new Ur,Br=5120,Nt=50;function Vr(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 P(e){if(!e)return;let t=r=>r.length<=Nt?r.slice():r.slice(r.length-Nt),n=r=>Vr(r,Br);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)}}var Re=12e4,Lt=2e3,Dt=3,Kr=5e3;function Q(e,t){return e==="mask"&&(t?.length??0)>0}var Hr=new Set(["approved","resolved"]),zr=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function Gr(e){return new Promise(t=>setTimeout(t,e))}function Wr(e){if(typeof e!="object"||e===null)return null;let t=e,n=t.hitl_result;if(typeof n=="string"&&n.length>0)return n;let{hitl:r}=t;if(r&&typeof r=="object"){let{status:i}=r;if(typeof i=="string"&&i.length>0)return i==="pending"?null:i}return null}async function Y(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=Re,maskFallback:o=!1,sdkVersion:a,fetchImpl:s=globalThis.fetch,sleep:l=Gr,log:c=m=>console.warn(m)}=e,u=m=>o?{resolution:"mask",reason:m}:{resolution:"block",reason:m};if(!t)return u("HITL approval cannot be confirmed (no backend endpoint) \u2014 fail-closed (G001)");if(!r)return u("HITL approval cannot be confirmed (no decision id) \u2014 fail-closed (G001)");let f=`${t.replace(/\/$/,"")}/v1/allow/decisions/${encodeURIComponent(r)}`,A={Accept:"application/json",...j(a)};n&&(A.Authorization=`Bearer ${n}`);let O=Date.now()+Math.max(0,i),R=0;for(c(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=O)return c(`[VisIQ HITL] Decision ${r} timed out after ${i}ms \u2014 ${o?"masking":"blocking"} (G001)`),u("HITL approval timed out");let m=null;try{let w=new AbortController,N=setTimeout(()=>w.abort(),Kr),L;try{L=await s(f,{method:"GET",headers:A,signal:w.signal})}finally{clearTimeout(N)}if(!L.ok)throw new Error(`HTTP ${L.status} ${L.statusText}`);let C=await L.json();m=Wr(C),R=0}catch(w){R+=1;let N=w instanceof Error?w.message:String(w);if(c(`[VisIQ HITL] Poll failed for decision ${r} (${R}/${Dt}): ${N}`),R>=Dt)return u(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${N}`);await l(Lt);continue}if(m!==null){let w=m.toLowerCase();return Hr.has(w)?(c(`[VisIQ HITL] Decision ${r} approved (${m}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${m})`}):zr.has(w)?(c(`[VisIQ HITL] Decision ${r} resolved as ${m} \u2014 ${o?"masking":"blocking"}`),u(`Not approved by human reviewer (${m})`)):(c(`[VisIQ HITL] Decision ${r} returned unknown status '${m}' \u2014 ${o?"masking":"blocking"} (G001)`),u(`HITL returned unknown status '${m}' \u2014 fail-closed (G001)`))}await l(Lt)}}function $(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 Pt(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&Q(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}var Ft=new Set;function Oe(e){Ft.has(e)||(Ft.add(e),console.warn(`[VisIQ] unrecognized retrieval outcome "${e}" \u2014 failing closed (withholding content). Upgrade @visiq/harness if a newer control plane introduced this outcome.`))}async function de(e,t,n){let r=h.getStore(),i=P(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 Pt(o)}async function pe(e,t,n){return await e.awaitBundleReady(),de(e,t,n)}function Mt(e,t){switch(t.action){case"allow":case"escalate":return e;case"deny":return null;case"redact":{if(t.redactionRules.length===0)return e;try{return S(e,I(t.redactionRules))}catch{return null}}default:return Oe(String(t.action)),null}}async function jt(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 de(r,t,{resourceType:"document",resourceMetadata:l,query:n,contentPreview:s.slice(0,500)}),u=Mt(o,c);u!==null&&i.push(u)}return i}async function $t(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await de(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"allow":case"escalate":return e;case"deny":return"[RECALL] Retrieved context was blocked by policy.";case"redact":{if(r.redactionRules.length===0)return e;try{return S(e,I(r.redactionRules))}catch{return"[RECALL] Retrieved context was blocked by policy."}}default:return Oe(String(r.action)),"[RECALL] Retrieved context was blocked by policy."}}var qt=4,Ut=1e3;function ue(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 Bt(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 de(n,t,{resourceType:"document",resourceMetadata:s,contentPreview:a.slice(0,500)})}catch{continue}let c=Mt(i,l);c!==null&&r.push(c)}return r}async function Ce(e,t,n,r,i){if(r>qt||i.nodes++>Ut)return e;if(Array.isArray(e)){if(ue(e))return i.matched=!0,Bt(e,t,n);let o=[];for(let a of e)o.push(await Ce(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 Ce(o[s],t,n,r+1,i);return a}return e}async function fe(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&ue(e))return Bt(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await Ce(e,t,n,0,r);if(r.matched)return i}return e}var Qr={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function xe(e,t,n){if(t>qt||n.n++>Ut)return e;if(Array.isArray(e))return ue(e)?[]:e.map(r=>xe(r,t+1,n));if(e!==null&&typeof e=="object"){if(ue([e]))return{...Qr};let r=e,i={};for(let o of Object.keys(r))i[o]=xe(r[o],t+1,n);return i}return e}function Ee(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?xe(e,0,{n:0}):e}function Vt(e,t){let n=Pt(t);switch(n.action){case"allow":case"escalate":return e;case"deny":return Ee(e);case"redact":{if(n.redactionRules.length===0)return e;try{return S(e,I(n.redactionRules))}catch{return Ee(e)}}default:return Oe(String(n.action)),Ee(e)}}function b(e){return typeof e=="object"&&e!==null?e:null}function Kt(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}function Yr(e,t){let n=b(e.metadata),r=n&&typeof n.name=="string"?n.name:void 0;return Kt(e.name,e.id,r,t)}function Zr(e){let t=b(e.metadata),n=t&&typeof t.description=="string"?t.description:void 0,r=Kt(e.description,n);return r===void 0?void 0:r.slice(0,4e3)}function Jr(e){let t=b(e);return t!==null&&("type"in t||"properties"in t||"$schema"in t)}function Xr(e){let t=b(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=b(n);if(r===null)return{type:"object"};let i={};for(let o of Object.keys(r))i[o]={};return{type:"object",properties:i}}var ei=new Set(["default","const","enum","examples","example"]);function Ne(e){if(Array.isArray(e))return e.map(Ne);let t=b(e);if(t===null)return e;let n={};for(let[r,i]of Object.entries(t))ei.has(r)||(n[r]=Ne(i));return n}function ti(e){let t;if(Jr(e))t=e;else{let n=Xr(e);if(n===void 0)return;t=n}try{let n=JSON.stringify(t);if(n.length>2e4){let r=b(t),i=r&&b(r.properties);if(i){let o={};for(let a of Object.keys(i))o[a]={};return{type:"object",properties:o}}return{type:"object"}}return Ne(JSON.parse(n))}catch{return}}function ni(e){let t=b(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:ti(n)}function ri(e,t){let n=b(e);if(n===null)return null;let r=Yr(n,t);if(r===void 0)return null;let i={name:r.slice(0,255)},o=Zr(n);o!==void 0&&(i.description=o);let a=ni(n);return a!==void 0&&(i.input_schema=a),i}function Z(e){let t=[],n=new Set,r=(i,o)=>{try{let a=ri(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=b(e);if(i!==null){for(let o of Object.keys(i))if(r(i[o],o),t.length>=200)break}}return t}function Le(e){try{let t=b(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(Z(t.tools));let o=b(t.settings);o&&o.tools!==void 0&&i(Z(o.tools));for(let l of["getTools","listTools"]){let c=t[l];if(typeof c=="function")try{i(Z(c.call(t)))}catch{}}let a=b(t.nodes);if(a)for(let l of Object.keys(a)){let c=b(a[l]);c&&c.tools!==void 0&&i(Z(c.tools))}let{agents:s}=t;if(s instanceof Map)for(let l of s.values()){let c=b(l);c&&c.tools!==void 0&&i(Z(c.tools))}return n}catch{return[]}}import{z as ge}from"zod";var ii=ge.object({decision:ge.enum(["permit","deny"]),reason:ge.string(),handoff_event_id:ge.string().nullable()}),q=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},V=class extends q{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},oi="https://api.visiqlabs.com",ai=1e4,K=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??oi,timeoutMs:e.timeoutMs??ai},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 q(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=ii.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 Ht=new Map;async function zt(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=Ht.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 K({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 Ht.set(e,o),o}var J=Symbol.for("visiq.orchestrate.wrapped");function Gt(e,t){if(!t.agentId||t.agentId.trim()==="")throw new q("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new q("grantToken is required","CONFIG_ERROR");if(e[J]===!0)return e;let n=new K(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 q(`ORCHESTRATE evaluate failed: ${l instanceof Error?l.message:String(l)}`,"EVALUATE_ERROR")}if(s.decision==="deny")throw new V(s.reason,s.handoffEventId)};return new Proxy(e,{get(o,a,s){let l=Reflect.get(o,a,s);return a===J?!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 Zt}from"node:crypto";var Wt=Symbol.for("visiq.semantickernel.instrumented");function Qt(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 De=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=$(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=S(o,I(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 pe(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 pe(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=S(t.result,I(c.redactionRules))}catch{t.result="[RECALL] Result withheld \u2014 redaction error (fail-closed)."}}},Fe=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 pe(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=S(n,I(r.redactionRules))}catch{t.renderedPrompt="[RECALL] Prompt withheld \u2014 redaction error (fail-closed)."}return}(r.action==="deny"||r.action==="escalate")&&(t.renderedPrompt=`[RECALL: prompt suppressed \u2014 ${r.reason}]`)}};function Yt(e,t){let n=e;return n[Wt]===!0||(Array.isArray(n.functionInvocationFilters)||(n.functionInvocationFilters=[]),Array.isArray(n.promptRenderFilters)||(n.promptRenderFilters=[]),n.functionInvocationFilters.unshift(new De(t)),n.promptRenderFilters.push(new Fe(t)),n[Wt]=!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 si=/https?:\/\/[^\s"'`,)}\]]+/;function Pe(e){let t=e.match(si);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var H=Symbol.for("visiq.toolexec.instrumented");function li(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}var Me={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 Jt(e){if(e===null||typeof e!="object")return null;let t=e;if(li(t))return null;if(Qt(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 ci(e,t,n,r,i,o){let{agentId:a,unified:s}=e,l=P(i),c;try{await s.awaitBundleReady(),c=$(await s.evaluate({operations:o?["action","delegation"]:["action"],agentId:a,toolName:t,toolArgs:n,...o?{context:se(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 Y({endpoint:s.getEndpoint()??e.endpoint??"",...u?{apiKey:u}:{},decisionId:c.decisionId,timeoutMs:e.hitlTimeoutMs,sdkVersion:F});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=I(c.argRedactionRules);return{block:null,maskedArgs:S(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 je(e,t,n,r,i){let o=h.getStore()??e.telemetry,a=ae(t,n);a&&le(e.unified,{agentId:e.agentId,sessionId:o?.session_id},a);let s=await ci(e,t,n,Pe(r),o,a);if(s.block!==null)return s.block;let l=s.maskedArgs??n,c=await i(l);return fe(c,e.agentId,e.unified)}function me(e,t,n){let r=e;if(r[H]){n.onWrap?.();return}if(typeof r.execute!="function")return;let i=r.execute;qe(r,"execute",async function(...a){let s=Ie(a[0]);return je(n,t,s,ee(s),l=>Promise.resolve(i.apply(this,[l,...a.slice(1)])))}),r[H]=!0,n.onWrap?.()}function ui(e,t,n){let r=e;if(r[H]){n.onWrap?.();return}if(typeof r.invoke!="function")return;let i=r.invoke;qe(r,"invoke",async function(...a){let s=a[1],l=Rt(s),c=typeof s=="string"?s:ee(l);return je(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[H]=!0,n.onWrap?.()}function di(e,t){let n=e;if(n[H]){t.onWrap?.();return}if(typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",o=n.call;qe(n,"call",async function(...s){let l=Ie(s[0]);return je(t,i,l,ee(l),c=>Promise.resolve(o.apply(this,[c,...s.slice(1)])))}),n[H]=!0,t.onWrap?.()}function Xt(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&me(r,n,t);return e}function en(e,t,n){switch(n){case"vercel":return pi(e,t);case"mastra":return fi(e,t);case"openai":return hi(e,t);case"llamaindex":return mi(e,t);case"voltagent":return gi(e,t);case"semantic-kernel":return Yt(e,t);default:return e}}function pi(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"&&Xt(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=$e(r.onStepFinish)),he(e,["generate","stream"],async(o,a)=>(X(a,o[0]),o)),e}function fi(e,t){let r=wi(e);return r&&Xt(r,t),he(e,["generate","stream","generateVNext","streamVNext"],async(i,o)=>{X(o,i[0]);let a=i[1]&&typeof i[1]=="object"?{...i[1]}:{};a.onStepFinish=$e(a.onStepFinish);let s=[...i];return s[1]=a,s}),e}function gi(e,t){let n=yi(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;me(r,typeof i=="string"?i:"unknown",t)}}return he(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{X(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=$e(o.onStepFinish);let a=[...r];return a[1]=o,a}),e}function mi(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"&&di(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 he(e,["run"],async(o,a)=>(X(a,o[0]),o)),bi(e,"runStream",(o,a,s)=>{s||X(a,o[0])}),e}function hi(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;ui(i,typeof o=="string"?o:"unknown",t)}}return _i(e,t),e}function _i(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=Zt(),i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let a=o[2];a!=null&&i.llm_prompts.push(ee(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 yi(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 he(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=tn();return h.run(l,async()=>{let c=await n(s,l);return a.apply(e,c)})},r[o]=!0}}function bi(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??tn();return n(a,l,s!==void 0),h.run(l,()=>o.apply(e,a))},r[i]=!0}function $e(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 X(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(ee(n).slice(0,5120))}function wi(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 tn(){return{session_id:Zt(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function qe(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function ee(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function un(e,t){let n=Ii(t);if(e[J]===!0)return e;let r=Ci(e);if(r==="langchain-executor"||r==="langchain-graph")return z(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,rn(r,null)),on(e,n),xi(e,n);let i=Jt(e);if(i){z(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,rn("unknown",i)),on(e,n);let o=0,a=gn(n);a.onWrap=()=>{o+=1};let s=en(e,a,i);if(o===0){let l=0;try{l=Le(e).length}catch{l=0}if(l>0){let c=`[VisIQ] Detected a ${Me[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 ${Me[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(Ni(e)){let o=process.env.VISIQ_GRANT_ID;return o?Li(e,n,o):Di(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 Ai="\0",nn=new Map;function rn(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 z(e,t,n,r,i){let o=[e??"",t??"",n??"",r??""].join(Ai),a=nn.get(o);return a||(a=new St(e,t,n,void 0,r,F,ve),a.registerHostEnvironment(i),nn.set(o,a)),a}function on(e,t){try{let n=Le(e);n.length>0&&z(t.apiKey,t.endpoint,t.agentId,t.timeoutMs).reportToolSurface(n)}catch{}}function Ti(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 Ii(e){return{agentId:e?.agentId??process.env.VISIQ_AGENT_ID??Ri(),apiKey:e?.apiKey??process.env.VISIQ_API_KEY,endpoint:e?.endpoint??process.env.VISIQ_ENDPOINT,hitlTimeoutMs:Ei(e?.hitlTimeoutMs),timeoutMs:Ti(e?.timeoutMs),onInstrumentFailure:e?.onInstrumentFailure??Si()}}function Si(){let e=process.env.VISIQ_ON_INSTRUMENT_FAILURE;if(e==="throw")return"throw";if(e==="warn")return"warn"}function Ri(){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=be.join(t,"package.json");if(ye.existsSync(r)){let o=JSON.parse(ye.readFileSync(r,"utf8"));if(typeof o.name=="string"&&o.name.trim()){let a=e(o.name);if(a)return a}break}let i=be.dirname(t);if(i===t)break;t=i}}catch{}try{let t=e(cn.hostname());if(t)return t}catch{}return"agent"}function Ei(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 Re}function Ci(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 xi(e,t){let n=e,r=z(t.apiKey,t.endpoint,t.agentId,t.timeoutMs);if(Array.isArray(n.tools))for(let o of n.tools)Be(o,t.agentId,r),Oi(o,t.agentId,r,t),pn(o,r,t);let i=n.invoke;if(n.invoke=function(o,a){let s=Ue(),l=ln(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=Ue(),c=ln(t.agentId,r),u=s?.callbacks??[];return h.run(l,()=>o.call(this,a,{...s,callbacks:[...u,c]}))}}return e}function Ue(){return{session_id:vi(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function Be(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 an(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 an(s,t,String(a),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&Be(r.retriever,t,n)}}function Oi(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(g=>g.toLowerCase()),c=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),f=l.some(g=>c.has(g)),A=u.has(l[0]??""),O=f||A,R=["update","delete","create","archive","insert","remove"],m=l.some(g=>R.some(_=>g.length>_.length&&g.endsWith(_))),N=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!O&&!m;if(!(s||N))return;let C=f||m;if(!C)if(s)Be(i.retriever,t,n);else{let g=globalThis,_=Symbol.for("visiq.recall.closureRetrieverWarned"),D=g[_]??=new Set;D.has(a)||(D.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;C?(i[dn]=!0,i.func=async function(...g){await n.awaitBundleReady();let _=g[0],D=typeof _=="object"&&_!==null?_:{input:_},Ve=typeof D.query=="string"?D.query:void 0,we=h.getStore(),Ke=P(we),He=await n.evaluate({operations:["retrieval","action"],agentId:t,...we?.session_id?{sessionId:we.session_id}:{},toolName:a||"unknown",toolArgs:D,resourceType:"document",resourceMetadata:{},...Ve!==void 0?{query:Ve}:{},...Ke?{telemetry:Ke}:{}}),T=$(He),_n=Q(T.hitlFallback,T.argRedactionRules),ze=g,Ge=()=>{try{return ze=[S(D,I(T.argRedactionRules)),...g.slice(1)],null}catch{return k({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (fail-closed)"})}};if(T.decision==="approval_required"&&T.decisionId&&r){let M=await Y({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:T.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:_n,sdkVersion:F});if(M.resolution==="mask"){let We=Ge();if(We)return We}else if(M.resolution!=="proceed")return k({outcome:"approval_required",code:T.ruleCode??"HITL-BLOCK",reason:T.reason,mechanism:M.reason})}else if(!T.allowed)return k({outcome:"deny",code:T.ruleCode??"DENY",reason:T.reason});if(T.decision==="mask"&&T.argRedactionRules.length>0){let M=Ge();if(M)return M}let yn=await v.apply(this,ze);return Vt(yn,He)}):i.func=async function(...g){let _=await v.apply(this,g);return typeof _=="string"?$t(_,t,n):fe(_,t,n)},i[o]=!0}var dn=Symbol.for("visiq.hybrid.instrumented");async function an(e,t,n,r){return jt(e,t,n,r)}var sn=["invoke","call","_call"],_e=new ki;function pn(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[dn]||!sn.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,A,O)=>{let R=_e.getStore();if(R!==void 0&&R.gateKey===s&&!R.entered.has(O))return R.entered.add(O),c.call(u,f,...A);let m;if(typeof f=="string")m=f;else{let g=f?.input;m=g!=null?String(g):JSON.stringify(f)??""}let w=h.getStore(),N=P(w),L=typeof f=="object"&&f!==null?f:{input:m},C=ae(a,L);C&&le(t,{agentId:o,sessionId:w?.session_id,framework:"langchain"},C),await t.awaitBundleReady();let v;try{v=$(await t.evaluate({operations:C?["action","delegation"]:["action"],agentId:o,...w?.session_id?{sessionId:w.session_id}:{},toolName:a,toolArgs:L,targetResource:Pe(m),...N?{telemetry:N}:{},...C?{context:se(C,o)}:{}}))}catch(g){return k({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${g instanceof Error?g.message:String(g)}`})}if(v.decision==="approval_required"&&v.decisionId){let g=Q(v.hitlFallback,v.argRedactionRules),_=await Y({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:v.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:g,sdkVersion:F});if(_.resolution==="proceed")return _e.run({gateKey:s,entered:new Set([O])},()=>c.call(u,f,...A));if(_.resolution==="mask")try{let D=S(f,I(v.argRedactionRules));return _e.run({gateKey:s,entered:new Set([O])},()=>c.call(u,D,...A))}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:_.reason})}return v.allowed?_e.run({gateKey:s,entered:new Set([O])},()=>c.call(u,f,...A)):k({outcome:"deny",code:v.ruleCode??"DENY",reason:v.reason})};for(let c of sn){if(typeof r[c]!="function")continue;let u=r[c];r[c]=function(f,...A){return l(u,this,f,A,c)}}r[i]=!0}function ln(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=P(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 fn=["_call","execute","call","run","invoke"];function Ni(e){let t=e;for(let n of fn)if(typeof t[n]=="function")return!0;return!1}function Li(e,t,n){let r=null,i=null,o=async()=>{if(r)return r;if(i)throw new V(`Failed to bootstrap grant ${n}: ${i.message}`,null);let a;try{a=await zt(t.agentId,n)}catch(s){throw i=s instanceof Error?s:new Error(String(s)),new V(`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===J)return!0;let c=Reflect.get(a,s,l);return typeof c!="function"||typeof s!="string"||!fn.includes(s)?c:async function(...u){let f=await o();return f[s].call(f,...u)}}})}function Di(e,t){let n=z(t.apiKey,t.endpoint,t.agentId,t.timeoutMs);pn(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";me(e,i,gn(t))}return e}function gn(e){return{agentId:e.agentId,unified:z(e.apiKey,e.endpoint,e.agentId,e.timeoutMs),hitlTimeoutMs:e.hitlTimeoutMs,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:Ue()}}async function mn(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 K({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 te=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),U(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return U(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return U(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return U(this.transport,"POST","/api/discovery/fleet/stop")}};var ne=class{constructor(t){this.transport=t}transport;connectAws(t){return U(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function Fi(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 te(r),integrations:new ne(r)}}async function U(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,o={...j(F)};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 hn=un;hn.delegate=mn;var ca=hn;export{te as FleetClient,ne as IntegrationsClient,Fi as createVisiqClient,mn as delegate,ca as visiq};
5
+ -----END PRIVATE KEY-----`,template:{pattern:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.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:E.mac_address,mode:"full"},defaultEnabled:!1}},ja=new Set(on.filter(e=>!rt[e].defaultEnabled));function Yr(e,t){let n=new Set;for(let r of on)(rt[r].defaultEnabled?!e?.has(r):t?.has(r))||n.add(r);return n}function Jr(e,t,n,r){if(typeof e!="string"||e.length===0)return e;let i=e;for(let{name:o,re:a}of nn){let l=o;n.has(l)||(i=i.replace(a,()=>(r?.(l),t)))}for(let{name:o,re:a,normalize:l,validate:c}of Qr)n.has(o)||(i=i.replace(a,s=>c(l(s))?(r?.(o),t):s));return i}function Zr(e,t=Gr,n,r){let i=new Set,o=Yr(n,r),a=!o.has("pan"),l=s=>{i.add(s)},c=s=>{if(typeof s=="string")return Jr(s,t,o,l);if(typeof s=="number"&&Number.isInteger(s)&&s>0){if(!a)return s;let u=String(s);return u.length>=13&&u.length<=19&&rn(u)?(i.add("pan"),t):s}if(Array.isArray(s))return s.map(u=>c(u));if(s!==null&&typeof s=="object"){let u=s,d={};for(let h of Object.keys(u))d[h]=c(u[h]);return d}return s};return{value:c(e),detectors:[...i].sort()}}var Xr=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g,an=Object.freeze({\u0430:"a",\u0435:"e",\u043E:"o",\u0440:"p",\u0441:"c",\u0443:"y",\u0445:"x",\u0456:"i",\u0455:"s",\u043A:"k",\u043C:"m",\u0442:"t",\u043D:"h",\u0432:"b",\u0433:"r",\u03BF:"o",\u03B1:"a",\u03C1:"p",\u03B9:"i",\u03C4:"t",\u03B5:"e",\u03BA:"k",\u03BD:"v",\u03C5:"u",\u03B7:"n",\u0131:"i","\u04CF":"l",\u0578:"n"}),ei=new RegExp(`[${Object.keys(an).join("")}]`,"gu"),ti=Object.freeze({4:"a","@":"a",3:"e",1:"i","!":"i",0:"o",5:"s",$:"s",7:"t",9:"g","(":"c",8:"b"}),sn="\u2801\u2803\u2809\u2819\u2811\u280B\u281B\u2813\u280A\u281A\u2805\u2807\u280D\u281D\u2815\u280F\u281F\u2817\u280E\u281E\u2825\u2827\u283A\u282D\u283D\u2835",ni=Object.freeze(Object.fromEntries([...sn].map((e,t)=>[e,String.fromCharCode(97+t)]))),ri=new RegExp(`[${sn}\u2800]`,"g"),ln=/[⠀-⣿]/;function ii(e){let t="";for(let n of e){let r=n.codePointAt(0);r!==void 0&&(r>=917536&&r<=917630?t+=String.fromCodePoint(r-917504):r>=917504&&r<=917631||(t+=n))}return t}function oi(e){return e.replace(Xr,"")}function cn(e){return e.replace(ei,t=>an[t]??t)}function ai(e){return e.replace(/[4@31!05$79(8]/g,t=>ti[t]??t)}function si(e){return e.replace(/[a-zA-Z]/g,t=>{let n=t<="Z"?65:97;return String.fromCharCode((t.charCodeAt(0)-n+13)%26+n)})}function li(e){return ln.test(e)?e.replace(ri,t=>t==="\u2800"?" ":ni[t]??t):e}function Wt(e){let t;try{t=ii(e)}catch{t=e}try{t=t.normalize("NFKC")}catch{}return t=oi(t),t=cn(t),t}var ci=/^[A-Za-z0-9+/]{16,}={0,2}$/,ui=/^(?:[0-9a-fA-F]{2}\s*){8,}$/,Qt=/[A-Za-z0-9+/]{20,}={0,2}/g;function nt(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);(r===9||r===10||r===13||r>=32&&r<=126||r>=160&&r!==65533)&&t++}return t/e.length}var un=new TextDecoder("utf-8",{fatal:!1});function dn(e){let t;try{t=atob(e)}catch{return[]}let n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i)&255;let r=un.decode(n);return t===r?[t]:[r,t]}function di(e){let t=e.replace(/\s+/g,"");if(t.length===0||t.length%2!==0)return[];let n=new Uint8Array(t.length/2);for(let o=0;o<n.length;o++){let a=Number.parseInt(t.slice(o*2,o*2+2),16);if(Number.isNaN(a))return[];n[o]=a}let r="";for(let o=0;o<n.length;o++)r+=String.fromCharCode(n[o]);let i=un.decode(n);return r===i?[r]:[i,r]}function Yt(e){let t=e.trim(),n=[];if(ui.test(t))for(let r of di(t))n.push({decoded:r,textiness:nt(r)});if(ci.test(t)&&t.length%4===0)for(let r of dn(t))n.push({decoded:r,textiness:nt(r)});return n}function Jt(e,t){let n=[],r;for(Qt.lastIndex=0;(r=Qt.exec(e))!==null&&n.length<t;){let i=r[0];if(i.length%4===0)for(let o of dn(i))n.push({decoded:o,textiness:nt(o)})}return n}var pi=Object.freeze({maxDepth:3,byteCap:262144,maxNodes:256,maxBlobsPerNode:8});function pn(e,t=pi){if(typeof e!="string"||e.length===0)return{views:[],anyDecoded:!1,truncated:!1,nodes:0,maxDepthSeen:0};let{maxDepth:n,byteCap:r,maxNodes:i,maxBlobsPerNode:o}=t,a=new Set,l=_=>{_.length>0&&_.length<=r&&a.add(_)},c=!1,s=!1,u=0,d=0,h=[{s:e,depth:0}];for(;h.length>0;){if(u>=i){s=!0;break}let _=h.pop();if(_===void 0)break;let{s:g,depth:f}=_;if(g.length>r){s=!0;continue}u++,f>d&&(d=f);let b=Wt(g);l(b);let L=ai(b);if(L!==b&&l(L),l(si(b)),ln.test(g)&&l(li(b)),f>=n){let I=Wt(g);(Yt(I).length>0||Jt(I,o).length>0)&&(s=!0);continue}let F=[...Yt(b),...Jt(b,o)];for(let I of F){if(c=!0,I.decoded.length>r){s=!0;continue}I.textiness>=.85&&I.decoded!==b?h.push({s:I.decoded,depth:f+1}):l(I.decoded)}}return{views:[...a],anyDecoded:c,truncated:s,nodes:u,maxDepthSeen:d}}var fn=["hidden_text_carrier","injected_turn_boundary","mixed_script_token","nested_encoding_payload"],fi=Object.freeze(["hidden_text_carrier","injected_turn_boundary","mixed_script_token"]),mi=8,gi=new Set([173,8203,8204,8205,8206,8207,8288,65279,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Zt=e=>e!==void 0&&(e>=65&&e<=90||e>=97&&e<=122);function hi(e){let t=[...e].map(r=>r.codePointAt(0)),n=0;for(let r=0;r<t.length;r++){let i=t[r];if(i>=917504&&i<=917631||gi.has(i)&&Zt(t[r-1])&&Zt(t[r+1])&&(n++,n>=mi))return!0}return!1}var _i=/^[ \t]*(?:system|assistant|developer|user)[ \t]*:/i;function yi(e){let t=e.split(/\r?\n/),n=!1;for(let r of t){if(_i.test(r)){if(n)return!0;continue}r.trim().length>0&&(n=!0)}return!1}var bi=[{name:"latin",lo:65,hi:591},{name:"greek",lo:880,hi:1023},{name:"cyrillic",lo:1024,hi:1279}];function vi(e){for(let t of bi)if(e>=t.lo&&e<=t.hi)return t.name;return null}function wi(e){for(let t of e.split(/\s+/)){if(t.length<4)continue;let n=0,r=0,i=!0;for(let o of t){let a=vi(o.codePointAt(0));if(a===null){i=!1;break}a==="latin"?n++:cn(o)!==o&&r++}if(i&&n>0&&r>0)return!0}return!1}var Xt=Object.freeze({signals:[],contributes:!1});function ki(e){if(typeof e!="string"||e.length===0)return{...Xt,signals:[]};let t=new Set;try{hi(e)&&t.add("hidden_text_carrier"),yi(e)&&t.add("injected_turn_boundary"),wi(e)&&t.add("mixed_script_token");let{anyDecoded:n,maxDepthSeen:r,truncated:i}=pn(e);n&&(r>=2||i)&&t.add("nested_encoding_payload")}catch{return{...Xt,signals:[]}}return{signals:[...fn.filter(n=>t.has(n))],contributes:fi.some(n=>t.has(n))}}var Le=[{name:"override_instructions",re:/\bignore (?:all |the )?(?:previous|above|prior) (?:instructions|prompts?)\b/i},{name:"disregard_instructions",re:/\bdisregard (?:the )?(?:above|previous|system)\b/i},{name:"role_tag",re:/<\/?(system|assistant|instructions|host_context)\b/i},{name:"privilege_override",re:/\b(grant|escalate|elevate) (admin|root|all|full) (access|privileges?)\b/i},{name:"tool_smuggle",re:/```[\s\S]*?(tool_call|function_call)/i}];function en(e){return typeof e!="string"||e.length===0?[]:Le.filter(({re:t})=>t.test(e)).map(({name:t})=>t)}function Ai(e){if(typeof e!="string"||e.length===0)return[];let t=new Set(en(e)),{views:n}=pn(e);for(let r of n)for(let i of en(r))t.add(i);return Le.filter(r=>t.has(r.name)).map(r=>r.name)}function Ii(e){let t=new Set,n=new Set,r=!1,i=o=>{if(o!=null){if(typeof o=="string"){for(let l of Ai(o))t.add(l);let a=ki(o);for(let l of a.signals)n.add(l);a.contributes&&(r=!0);return}if(Array.isArray(o)){for(let a of o)i(a);return}if(typeof o=="object")for(let a of Object.values(o))i(a)}};return i(e),{matched:t.size>0||r,signatures:Le.filter(o=>t.has(o.name)).map(o=>o.name),structural:fn.filter(o=>n.has(o))}}function Si(e){return Ii(e).matched}var qa=Le.map(e=>e.name);var Ti=new Set(["untrusted","external","public","public_internet","external_third_party","web"]);var Ei="i:injection";function mn(e){let t=new Set;if(e.content!==void 0&&e.content!==null){let{detectors:i}=Zr(e.content);for(let o of i){let a=rt[o]?.category;a&&t.add(`c:${a}`)}Si(e.content)&&t.add(Ei)}let n=e.resourceMetadata??{},r=n.source_trust;return(n.untrusted_source===!0||typeof r=="string"&&Ti.has(r.toLowerCase()))&&t.add("i:untrusted"),[...t].sort()}var et="(?:system\\s+prompt|initial\\s+(?:instructions|prompt)|system\\s+(?:instructions|message)|hidden\\s+(?:instructions|prompt)|your\\s+(?:system\\s+prompt|initial\\s+instructions|instructions|prompt)|the\\s+prompt\\s+(?:above|you\\s+were\\s+given))",Ua=[{name:"reveal_prompt",re:new RegExp(`\\b(?:reveal|show|print|repeat|output|echo|display|expose|dump|leak|reprint|divulge|disclose)\\b[\\s\\S]{0,40}?\\b${et}\\b`,"i")},{name:"what_is_prompt",re:new RegExp(`\\bwhat\\s+(?:is|are|were)\\b[\\s\\S]{0,20}?\\b${et}\\b`,"i")},{name:"tell_me_prompt",re:new RegExp(`\\b(?:tell|give|send|show)\\s+me\\b[\\s\\S]{0,30}?\\b${et}\\b`,"i")},{name:"repeat_above",re:/\b(?:repeat|print|output|echo|reproduce)\b[\s\S]{0,20}?\b(?:everything|all\s+(?:the\s+)?(?:text|words))\b[\s\S]{0,12}?\b(?:above|before|preceding|verbatim|word\s+for\s+word)\b/i}],tn="(?:instructions?|prompts?|rules?|directives?|guidelines?|constraints?|guardrails?)",Ri=`(?:(?:all\\s+|any\\s+|the\\s+|these\\s+|those\\s+)*(?:previous|prior|preceding|earlier|above|foregoing|initial|original|system|developer)\\s+${tn}|your\\s+(?:(?:system|initial|original|previous|prior|current)\\s+)?(?:${tn}|programming|training))`,Ci="(?:(?:all|any|every|the|of|and|now|please|completely|entirely|totally|immediately)\\s+){0,3}",tt="(?:\\b(?:unrestricted|unfiltered|uncensored|unbounded|unlimited|unchained|jailbroken|lawless|amoral)\\b|\\b(?:DAN|STAN|DUDE|AIM)\\b|\\bno\\s+(?:longer\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|boundaries|constraints?)\\b|\\bwithout\\s+(?:any\\s+)?(?:restrictions?|limits?|rules?|guidelines?|filters?|constraints?|censorship)\\b|\\b(?:free|freed|released)\\s+from\\s+(?:your\\s+)?(?:restrictions?|limits?|rules?|guidelines?|guardrails?|programming|constraints?)\\b|\\b(?:can|will|are\\s+able\\s+to)\\s+(?:do|say)\\s+anything\\b|\\bignore\\s+(?:all\\s+)?(?:your\\s+)?(?:previous\\s+|prior\\s+|system\\s+)?(?:instructions?|rules?|guidelines?)\\b)",xi="(?:ignore|disregard|forget|override|overrule|bypass|act|behave|respond|reply|answer|pretend|roleplay|role-play|assume|impersonate|only|always|never|no\\s+longer|instead|obey|comply\\s+with|follow\\s+(?:only|my|these))",Ba=[{name:"override_instructions",re:new RegExp(`\\b(?:ignore|disregard|forget|discard|override|overrule|bypass|delete|erase)\\s+${Ci}${Ri}\\b`,"i")},{name:"forget_everything_prior",re:/\b(?:forget|ignore|disregard|erase|discard)\s+(?:about\s+|all\s+|any\s+)?(?:everything|anything)\b[\s\S]{0,24}?\b(?:above|before|previously|prior|earlier|you\s+(?:were|have\s+been)\s+(?:told|instructed|given|programmed))\b/i},{name:"persona_reassignment_jailbreak",re:new RegExp(`\\byou\\s+are\\s+now\\s+(?:(?:a|an|the)\\s+)?[\\s\\S]{0,48}?${tt}`,"i")},{name:"constraint_release",re:/\byou\s+are\s+no\s+longer\s+(?:bound|restricted|limited|constrained|obligated|governed|subject\s+to|required\s+to)\b/i},{name:"from_now_on_reassignment",re:new RegExp(`\\bfrom\\s+now\\s+on\\s*,?\\s+you\\s+(?:are|will|must|shall)\\s+(?:${xi}|(?:a|an|the)\\b[\\s\\S]{0,40}?${tt}|${tt})`,"i")},{name:"new_instructions_header",re:/^\s*(?:[#*>-]+\s*)?(?:new|real|actual|true|secret|hidden|override)\s+(?:system\s+)?(?:instructions?|prompts?|directives?)\s*:/im}];var Va=Object.freeze({"\u2019":"'",\u02BC:"'","\uFF07":"'","\u02B9":"'","\u2032":"'"});var U=e=>`[^.!?;\\n]{0,${e}}?`,Oi=["\\bi\\s+(?:can'?t|cannot|can\\s+not|won'?t|will\\s+not)\\b","\\bi(?:'m|\\s+am)\\s+(?:not\\s+able\\s+to|unable\\s+to|not\\s+going\\s+to|not\\s+permitted\\s+to|not\\s+allowed\\s+to)\\b"].join("|"),gn="(?:help|assist|provide|create|generate|produce|write|compose|draft|comply|fulfil|fulfill|share|disclose|reveal|perform|execute|run|send|transmit|publish|export|approve|grant|carry\\s+out|do\\s+that|do\\s+this|do\\s+so|go\\s+ahead)",Ka=Object.freeze([{id:"capability_denial",class:"strong",re:new RegExp([`(?:${Oi})\\s${U(40)}\\b${gn}\\b`,"\\b(?:that|this|it)(?:'s|\\s+is)\\s+not\\s+something\\s+i\\s+(?:can|could|am\\s+able\\s+to|'m\\s+able\\s+to)\\b",`\\b(?:falls|sits|is)\\s+outside\\s+(?:of\\s+)?(?:what|the\\s+(?:scope|range|bounds))\\b${U(40)}\\bi\\s+(?:can|am|'m)\\b`,"\\bnot\\s+something\\s+i(?:'m|\\s+am)\\s+(?:able|willing|permitted|allowed)\\s+to\\b"].join("|"),"i")},{id:"explicit_decline",class:"strong",re:new RegExp(["\\bi\\s+(?:must|have\\s+to|need\\s+to|will\\s+have\\s+to|am\\s+going\\s+to|'m\\s+going\\s+to)\\s+(?:respectfully\\s+)?decline\\b","\\bi(?:'m|\\s+am)\\s+not\\s+(?:comfortable|willing|prepared)\\b","\\bi(?:'ll|\\s+will)\\s+(?:have\\s+to\\s+)?pass\\s+on\\b","\\bi\\s+(?:must|have\\s+to)\\s+refuse\\b"].join("|"),"i")},{id:"policy_citation",class:"strong",re:new RegExp([`\\b(?:against|contrary\\s+to|prohibited\\s+by|forbidden\\s+by|in\\s+violation\\s+of|violates)\\s${U(24)}\\b(?:polic(?:y|ies)|guidelines?|terms\\s+of\\s+(?:use|service)|rules\\s+of\\s+engagement|code\\s+of\\s+conduct)\\b`,`\\b(?:my|our|the|company|organi[sz]ation'?s?)\\s+(?:polic(?:y|ies)|guidelines?)\\s${U(24)}\\b(?:do(?:es)?\\s+not\\s+(?:allow|permit)|prohibit|forbid|prevent)\\b`,`\\bnot\\s+(?:permitted|allowed|authori[sz]ed)\\s+(?:under|by)\\s${U(24)}\\b(?:polic(?:y|ies)|guidelines?)\\b`].join("|"),"i")},{id:"guardrail_selfreference",class:"strong",re:new RegExp(["\\bi(?:'ve|\\s+have)\\s+been\\s+(?:instructed|configured|told|trained)\\s+not\\s+to\\b","\\bi(?:'m|\\s+am)\\s+(?:designed|configured|programmed|built|set\\s+up)\\s+not\\s+to\\b",`\\bmy\\s+(?:safety\\s+)?(?:instructions|configuration|guardrails?|constraints|training)\\s${U(24)}\\b(?:prevent|prohibit|forbid|do(?:es)?\\s+not\\s+(?:allow|permit)|preclude)\\b`,"\\b(?:outside|beyond)\\s+(?:my|the)\\s+(?:permitted|authori[sz]ed|configured|approved)\\s+(?:scope|remit|capabilities|actions|operations)\\b"].join("|"),"i")},{id:"ethical_objection",class:"strong",re:new RegExp(["\\b(?:that|this|doing\\s+(?:so|that)|what\\s+you(?:'re|\\s+are)\\s+asking|the\\s+request|such\\s+a\\s+request)\\s+(?:would\\s+be|is|are)\\s+(?:clearly\\s+|both\\s+|potentially\\s+)?(?:illegal|unethical|unlawful|harmful|fraudulent)\\b","\\bi\\s+(?:do\\s+not|don'?t)\\s+condone\\b","\\b(?:goes|would\\s+go|runs)\\s+against\\s+my\\s+(?:principles|values|ethics)\\b","\\bi\\s+(?:can'?t|cannot|won'?t)\\s+in\\s+good\\s+conscience\\b"].join("|"),"i")},{id:"apology_marker",class:"weak",re:new RegExp("\\b(?:i(?:'m|\\s+am)\\s+(?:really\\s+|very\\s+|terribly\\s+|so\\s+)?sorry|i\\s+apologi[sz]e|my\\s+apologies)\\b","i")}]),za=Object.freeze([/```/,/\b(?:here(?:'s|\s+is|\s+are)|below\s+(?:is|are|you(?:'ll|\s+will)\s+find)|the\s+following\s+(?:is|are))\b/i,new RegExp(`\\b(?:but|however|instead|although|that\\s+said)\\b${U(60)}\\b(?:i\\s+(?:can|could)(?!'t)\\s${U(30)}\\b${gn}\\b|i(?:'d|\\s+would)\\s+be\\s+happy\\s+to\\b|i(?:'m|\\s+am)\\s+able\\s+to\\b)`,"i"),/\bwhat\s+i\s+can\s+do\s+(?:instead|is|for\s+you)\b/i]);var _e=e=>`[^.!?;\\n]{0,${e}}?`,Ga=Object.freeze([{id:"vulnerability_scanning",objectPatterns:[/\b(?:vulnerability|vuln|security)\s+(?:scan|scans|scanning|assessment|audit|test|testing)\b/i,/\bpen(?:etration)?[\s-]?test(?:ing)?\b/i,/\bport\s+scan(?:ning)?\b/i,/\b(?:exploit|nmap|metasploit|nessus|burp\s+suite)\b/i,/\bCVE-\d{4}-\d{4,7}\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|vulnerability|incident\s+respon\w{0,4}|threat|soc|red\s+team|phishing|malware)\b/i]},{id:"credential_access",objectPatterns:[/\b(?:credential|password|passphrase|api\s+key|access\s+key|secret|token|private\s+key|ssh\s+key)s?\b/i,/\b(?:vault|secrets?\s+manager|keychain|keystore)\b/i,/\bservice\s+account\s+key\b/i],purposeFunctions:["it_security","engineering"],purposePatterns:[/\b(?:security|identity|iam|credential|secrets?\s+manage\w{0,4}|vault|platform|devops)\b/i]},{id:"financial_transaction",objectPatterns:[/\b(?:wire\s+transfer|bank\s+transfer|payout|disbursement|chargeback)\b/i,new RegExp(`\\b(?:approve|issue|initiate|process|release)\\s${_e(20)}\\b(?:payment|refund|invoice|transfer|purchase\\s+order)s?\\b`,"i"),new RegExp(`\\b(?:move|transfer)\\s${_e(20)}\\b(?:funds|money)\\b`,"i")],purposeFunctions:["finance_accounting","procurement"],purposePatterns:[/\b(?:finance|financial|accounting|invoice|invoicing|payment|payments|billing|refund|refunds|treasury|procurement|spend|purchasing|fraud|kyc)\b/i]},{id:"personnel_data",objectPatterns:[/\b(?:employee|personnel|payroll|hr|staff)\s+(?:record|records|data|file|files|information|details)\b/i,/\b(?:salary|salaries|compensation|performance\s+review|termination\s+letter)s?\b/i,/\b(?:home\s+address|social\s+security\s+number|national\s+insurance\s+number)e?s?\b/i],purposeFunctions:["hr","privacy_compliance"],purposePatterns:[/\b(?:hr|human\s+resources|people\s+ops|payroll|benefits|recruit\w{0,4}|onboarding|privacy|dsar|consent)\b/i]},{id:"regulated_advice",objectPatterns:[/\b(?:legal|medical|tax|investment|financial)\s+advice\b/i,/\bpractis\w{0,3}\s+law\b/i,/\b(?:diagnose|diagnosis|prescribe|prescription)\b/i,/\b(?:binding|enforceable)\s+(?:opinion|interpretation)\b/i],purposeFunctions:["legal","privacy_compliance"],purposePatterns:[/\b(?:legal|compliance|counsel|contract|contracts|litigation|nda|privacy|regulator\w{0,2}|audit\w{0,3})\b/i]},{id:"data_export",objectPatterns:[new RegExp(`\\b(?:export|download|dump|extract|exfiltrat\\w{0,3}|bulk\\s+copy)\\b\\s${_e(30)}\\b(?:data|database|dataset|records?|table|tables|customer\\s+list|contact\\s+list|report)\\b`,"i"),/\b(?:full|entire|whole)\s+(?:database|dataset|customer\s+table)\b/i],purposeFunctions:["operations","engineering","privacy_compliance"],purposePatterns:[/\b(?:data\s+(?:pipeline|engineering|platform)|etl|export|reporting|analytics|operations|document\s+extract\w{0,3}|forecast\w{0,3})\b/i]},{id:"code_execution",objectPatterns:[new RegExp(`\\b(?:run|execute|invoke)\\s${_e(24)}\\b(?:script|scripts|command|commands|shell|code|binary|query|migration)\\b`,"i"),/\b(?:shell|root|sudo|admin)\s+(?:access|command|session)\b/i,/\bagainst\s+(?:the\s+)?production\s+(?:system|server|database|environment)s?\b/i],purposeFunctions:["engineering","it_security"],purposePatterns:[/\b(?:engineering|developer|devops|platform|release|deploy\w{0,4}|build|pipeline|sandbox|test\s+data|change\s+window)\b/i]},{id:"external_communication",objectPatterns:[new RegExp(`\\b(?:send|post|publish|email|tweet|message|broadcast)\\b\\s${_e(30)}\\b(?:external|customer|customers|public|press|social\\s+media|third[\\s-]party|prospect|prospects)\\b`,"i"),/\b(?:cold\s+outreach|marketing\s+blast|phishing\s+email|press\s+release)\b/i],purposeFunctions:["marketing","sales","customer_support"],purposePatterns:[/\b(?:marketing|campaign|outreach|email\s+assistant|support|customer|sales|lead|leads|communication|communications)\b/i]}]);var it="[REDACTED]",ne="\u2022",Ne=e=>/[A-Za-z0-9]/.test(e);function hn(e,t,n,r){let i=Array.from(e),o=i.length,a=Math.max(0,Math.floor(t)||0),l=Math.max(0,Math.floor(n)||0),c=r.length>0?r:ne,s=a+l>=o;return i.map((u,d)=>!s&&(d<a||d>=o-l)?u:Ne(u)?c:u).join("")}function Ni(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return hn(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),o=t.length>0?t:ne;return(r.length<=1?o:r[0]+Array.from(r.slice(1)).map(a=>Ne(a)?o:a).join(""))+i}function Li(e,t,n){let r=n.length>0?n:ne,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let s=new RegExp(t,"g"),u;for(;(u=s.exec(e))!==null;){if(u[0].length===0){s.lastIndex++;continue}for(let d=u.index;d<u.index+u[0].length;d++)i[d]=!0}}catch{}let o=!1,a=!0;for(let s=0;s<e.length;s++)if(Ne(e[s])&&(o=!0,!i[s])){a=!1;break}let l=o&&a,c="";for(let s=0;s<e.length;s++){let u=e[s];!l&&i[s]||!Ne(u)?c+=u:c+=r}return c}function _n(e,t){let n=t.mode??"full";return n==="partial"?hn(e,t.keepFirst??0,t.keepLast??0,t.maskChar??ne):n==="email"?Ni(e,t.maskChar??ne):n==="custom"?Li(e,t.keepPattern,t.maskChar??ne):t.replacement??it}function Fi(e,t){return typeof e=="string"?_n(e,t):t.replacement??it}function yn(e){let t=[],n=e.replacement??it;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=>_n(o,r)})}return t}function bn(e,t){let n=e;for(let{source:r,replacer:i}of t){let o;try{o=new RegExp(r,"g")}catch(a){let l=a instanceof Error?a.message:String(a);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${l}`)}n=n.replace(o,a=>i(a))}return n}function O(e,t){return e==null?e:typeof e=="string"?Mi(e,t):typeof e=="object"?Di(e,t):e}function Mi(e,t){if(typeof e!="string")return e;let n=yn(t);return n.length===0?e:bn(e,n)}function Di(e,t){let n=new Map;for(let l of t.fields??[])typeof l=="string"&&l.length>0&&n.set(l,{field:l,mode:"full",replacement:t.replacement});for(let l of t.directives??[])typeof l.field=="string"&&l.field.length>0&&n.set(l.field,l);let r=yn(t),i=n.size>0,o=r.length>0,a=l=>{if(l==null)return l;if(Array.isArray(l))return l.map(c=>a(c));if(typeof l=="object"){let c=l,s=Object.create(Object.getPrototypeOf(c));for(let u of Object.keys(c)){let d=i?n.get(u):void 0;if(d){s[u]=Fi(c[u],d);continue}s[u]=a(c[u])}return s}return typeof l=="string"&&o?bn(l,r):l};return a(e)}var vn=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function $i(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:vn(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:vn(t.spawn.prompt)}),t}function Pi(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 ji=1440*60*1e3,qi="VISIQ_BUNDLE_GRACE_TTL_MS",Ui="VISIQ_BUNDLE_CACHE_DISABLED",Bi="VISIQ_CACHE_DIR",Vi=Fe.object({graceTtlMs:Fe.number().int().nonnegative().optional(),disabled:Fe.boolean().optional(),cacheDir:Fe.string().min(1).optional()}).strict();function Ki(e){return e==null?{}:Vi.parse(e)}function zi(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[qi];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return ji}function Gi(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Ui]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var wn;function Hi(){if(wn!==void 0)return wn;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function Wi(e){return JSON.stringify(at(e))}function at(e){if(Array.isArray(e))return e.map(at);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=at(t[r]);return n}return e}function Qi(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function Yi(e){if(e!==null&&typeof e=="object"&&typeof e.fetchedAt=="number"&&typeof e.contentHash=="string"&&"body"in e){let t=e;return{fetchedAt:t.fetchedAt,version:typeof t.version=="string"?t.version:null,contentHash:t.contentHash,body:t.body}}return null}async function En(){if(!Hi())return null;try{let[e,t,n,r]=await Promise.all([import("node:fs/promises"),import("node:path"),import("node:os"),import("node:crypto")]);return{fs:e,path:t,os:n,crypto:r}}catch{return null}}function Rn(e,t){return e.createHash("sha256").update(Wi(t)).digest("hex")}function Ji(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Bi]?.trim();if(r)return r;let i=process.env.XDG_CACHE_HOME?.trim();if(i)return e.path.join(i,"visiq");let o="";try{o=e.os.homedir()}catch{o=""}return o?e.path.join(o,".cache","visiq"):e.path.join(e.os.tmpdir(),"visiq-cache")}function Zi(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function Cn(e,t,n){return e.path.join(Ji(e,n),"bundles",`${Zi(e,t)}.json`)}async function Xi(e,t,n,r={}){let i=await En();if(i)try{let o=Cn(i,e,r),a=i.path.dirname(o);await i.fs.mkdir(a,{recursive:!0,mode:448});let l={fetchedAt:r.now??Date.now(),version:n,contentHash:Rn(i.crypto,t),body:t},c=`${o}.tmp-${process.pid}-${i.crypto.randomBytes(6).toString("hex")}`;await i.fs.writeFile(c,JSON.stringify(l),{mode:384});try{await i.fs.rename(c,o)}catch(s){throw await i.fs.rm(c,{force:!0}).catch(()=>{}),s}}catch{}}async function eo(e,t={}){let n=await En();if(!n)return null;try{let r=await n.fs.readFile(Cn(n,e,t),"utf-8"),i=Yi(JSON.parse(r));return!i||Rn(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var ye;async function to(){if(ye!==void 0)return ye;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;ye=typeof t=="function"?t:null}catch{ye=null}return ye}var no=5e3,ro=1e4,io=25,kn=1e3,oo=5e3,ao=100,An=2e3,so=512,lo=1800*1e3,co="monitor",uo="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",In="Rules bundle requires a newer SDK wire-contract dialect than this SDK supports \u2014 refusing the bundle and blocking all actions (fail-closed, G001). Upgrade the VisIQ SDK.",Me="open";function be(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="open"||t==="closed"?t:void 0}function po(e,t){return mn({content:e,resourceMetadata:t})}var fo=m.object({operations:m.array(m.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:m.string().min(1,"agentId is required"),sessionId:m.string().min(1).max(255).optional(),toolName:m.string().optional(),toolArgs:m.record(m.unknown()).optional(),targetResource:m.string().optional(),resourceType:m.string().optional(),resourceMetadata:m.record(m.unknown()).optional(),normalized:m.record(m.unknown()).optional(),query:m.string().optional(),contentPreview:m.string().optional(),telemetry:m.record(m.unknown()).optional(),context:m.record(m.unknown()).optional()}),mo=m.object({version:m.string().min(1),dialect_version:m.number().int().optional(),min_dialect:m.number().int().optional(),shutdown:m.boolean().optional(),agent_mode:m.enum(["enforce","monitor","off"]).optional(),cognition_capture:m.boolean().optional(),agent_mode_by_operation:m.object({action:m.string().optional(),retrieval:m.string().optional(),delegation:m.string().optional()}).partial().optional(),agent_attributes:m.object({trust_tier:m.string().nullable().optional(),categories:m.array(m.string()).optional(),business_function:m.string().nullable().optional(),business_functions:m.array(m.string()).nullable().optional(),blast_radius_tier:m.string().nullable().optional(),no_coverage:m.string().nullable().optional(),fail_mode:m.string().nullable().optional()}).optional(),rules:m.array(m.record(m.unknown())),no_coverage:m.object({no_coverage_defaults:m.record(m.string()),autopilot_enabled:m.boolean(),enduser_hitl_enabled:m.boolean(),hitl_timeout_seconds:m.number().optional()}).optional()});function go(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=Vt(Kt(n));return{trust_tier:Mt(t)?t:null,categories:$t(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&zt(e.blast_radius_tier)?e.blast_radius_tier:null}}function ho(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 _o(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var st=new Set,Sn=!1;async function Tn(e){let t=[];for(let n of st){if(n.pendingTelemetryCount()>0&&!n.hasBackend()){console.warn(`[UnifiedRuntime] exiting with ${n.pendingTelemetryCount()} un-sent decision(s) and no backend \u2014 telemetry lost.`);continue}let r=n.flush();e&&t.push(r)}t.length>0&&await Promise.allSettled(t)}function yo(){if(!Sn&&!(typeof process>"u"||typeof process.once!="function")){Sn=!0,process.once("beforeExit",()=>{Tn(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await Tn(!0)}finally{process.kill(process.pid,e)}})()})}}var xn=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;sdkVersion;sdkDialect;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;cacheIdentity;bundleCacheDisabled;bundleGraceTtlMs;bundleCacheDirOverride;diskFallbackServed=!1;agentMode=co;agentModeByOperation=null;rawBundle=null;agentModeConfirmed=!1;operatorShutdown=!1;bundleApplyFailed=!1;dialectRefused=!1;failMode=be(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Me;governedFailMode=null;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,o,a,l){let c=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,s=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,u=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=c,this.resolvedEndpoint=s,this.resolvedAgentId=u,this.harnessKind=r,this.sdkVersion=o,this.sdkDialect=a,this.originalFetch=globalThis.fetch.bind(globalThis);let d=Ki(l);if(this.bundleCacheDisabled=Gi(d.disabled),this.bundleGraceTtlMs=zi(d.graceTtlMs),this.bundleCacheDirOverride=d.cacheDir,this.cacheIdentity=c&&s&&!this.bundleCacheDisabled?{endpoint:s,agentId:u,apiKey:c}:null,c&&s){let h={apiKey:c,agentId:u,endpoint:s,mode:"enforce",timeoutMs:Pi(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...o!==void 0?{sdkVersion:o}:{},...a!==void 0?{sdkDialect:a}:{}};this.client=new Qe(h,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},no),ot(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},ro),ot(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},oo),ot(this.cognitionTimer),st.add(this),yo()}else this.client=null}async evaluate(e){let t=fo.parse(e),n=Date.now();if(this.operatorShutdown){let s=this.denyAll(t,uo);return this.applyAgentMode(s,"enforce",t,n)}if(this.dialectRefused){if(this.failMode==="open")return this.failOpen(t,In,n);let s=this.denyAll(t,In);return this.applyAgentMode(s,"enforce",t,n)}if(t.operations.every(s=>this.modeFor(s)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let s;if(this.agentModeConfirmed?s=this.agentMode:this.bundleApplyFailed?s="enforce":s="monitor",s==="enforce"&&this.failMode==="open")return this.failOpen(t,"no unified bundle loaded and no local rules",n);let u=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(u,s,t,n)}let r=this.readSession(t.sessionId),i=await to();if(!i||!this.rawBundle){if(this.failMode==="open")return this.failOpen(t,"governance core (@visiq/core-wasm) unavailable",n);throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)")}let o=t.operations.includes("action")||t.operations.includes("delegation")?Xe(t.normalized??{},{action:t.toolName??"",targetApp:t.targetResource??t.toolName??""}):t.normalized,a={...t,normalized:o,session:r,at:Date.now()},l={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},c;try{c=i(a,l)}catch(s){if(this.failMode==="open")return this.failOpen(t,`governance core evaluation threw: ${s instanceof Error?s.message:String(s)}`,n);throw s}return this.foldSession(t,c.enforced?c.decision:"permit"),c.enforced&&c.action.decision==="approval_required"&&await this.registerHitl(t,c),this.bufferTelemetry(t,c,Date.now()-n,c.enforced),c}modeFor(e){return this.agentModeByOperation?.[e]??this.agentMode}readSession(e){if(!e)return he;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>lo?(this.sessions.delete(e),he):t.state:he}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},o=e.operations.includes("retrieval"),a=e.operations.includes("action")||e.operations.includes("delegation"),l=a?Xe(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},c=qt(r===he?jt():r,{data_categories:o&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:o?i.classification:void 0,taint:o?po(e.contentPreview,i):void 0,action_class:a?l.action_class:void 0,target_app:a?e.targetResource??e.toolName:void 0,decision:t});if(this.sessions.delete(n),this.sessions.set(n,{state:c,touchedAt:Date.now()}),this.sessions.size>so){let s=this.sessions.keys().next().value;s!==void 0&&this.sessions.delete(s)}}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}setFailMode(e){this.failMode=e}getFailMode(){return this.failMode}getGovernedFailMode(){return this.governedFailMode}failOpen(e,t,n){let r=`fail-open: ${t} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`;console.error(`[VisIQ] FAIL-OPEN: ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`);let i=e.operations.includes("action")||e.operations.includes("delegation"),o=e.operations.includes("retrieval"),a={decision:"permit",allowed:!0,reason:r,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:i?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:o?{action:"allow"}:{action:null},failOpen:!0};return this.bufferTelemetry(e,a,Date.now()-n,!1,!0),a}reportFailOpen(e,t){try{let n={operations:["action"],agentId:this.resolvedAgentId,...t?.toolName?{toolName:t.toolName}:{},...t?.sessionId?{sessionId:t.sessionId}:{}},r={decision:"permit",allowed:!0,reason:`fail-open: ${e} \u2014 proceeding UNGOVERNED (set VISIQ_FAIL_MODE=closed to block instead)`,ruleId:null,ruleCode:null,enforced:!1,agentMode:this.agentMode,action:{decision:"permit",allowed:!0},retrieval:{action:null},failOpen:!0};this.bufferTelemetry(n,r,0,!1,!0)}catch{}}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=mo.parse(e);this.bundleApplyFailed=!1;let n=this.sdkDialect??1;if(t.min_dialect!==void 0&&t.min_dialect>n){this.dialectRefused=!0,this.bundleApplyFailed=!0,console.warn(`[UNIFIED] rules bundle requires dialect ${t.min_dialect} but this SDK speaks ${n} \u2014 refusing the bundle and failing closed (deny-all, G001). Upgrade the VisIQ SDK.`);return}this.dialectRefused=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(r=>Ht(r)).filter(r=>r!==null),this.agentAttributes=t.agent_attributes?go(t.agent_attributes):null,this.agentNoCoverage=Gt(t.agent_attributes?.no_coverage),this.governedFailMode=be(t.agent_attributes?.fail_mode)??null,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=ho(t.agent_mode_by_operation),process.env.VISIQ_COGNITION_CAPTURE==="1"?this.cognitionEnabled=!0:typeof t.cognition_capture=="boolean"&&(this.cognitionEnabled=t.cognition_capture),this.operatorShutdown=t.shutdown===!0,this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json",...H(this.sdkVersion,this.sdkDialect)};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag"),i=await n.json();this.applyBundle(i);let o=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&o?this.bundleEtag=r:o||(this.bundleEtag=null),o&&await this.persistBundleToDisk(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}async initialBundleLoad(){await this.fetchBundleBackground(),this.bundleLoaded||await this.tryLoadFromDiskCache()}async tryLoadFromDiskCache(){if(this.bundleLoaded||this.bundleCacheDisabled||!this.cacheIdentity||this.dialectRefused)return;let e;try{e=await eo(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(Qi(e,this.bundleGraceTtlMs,t)){try{this.applyBundle(e.body)}catch{return}if(this.bundleLoaded&&!this.dialectRefused&&!this.diskFallbackServed){this.diskFallbackServed=!0;let n=Math.max(0,Math.round((t-e.fetchedAt)/1e3)),r=Math.round(this.bundleGraceTtlMs/1e3);console.warn(`[UnifiedRuntime] serving cached rules bundle (age ${n}s) \u2014 control plane unreachable on cold start; will keep retrying and fail closed once the cache exceeds the ${r}s grace window.`)}}}async persistBundleToDisk(e){this.bundleCacheDisabled||!this.cacheIdentity||await Xi(this.cacheIdentity,e,this.bundleVersion,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}isBundleLoaded(){return this.bundleLoaded}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({...Ye(),...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,i=!1){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?_o(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||i?{context:{...this.harnessKind?{[Ct]:this.harnessKind}:{},...e.context??{},...i?{fail_open:!0}:{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=io&&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-kn;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${kn})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push($i(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=ao&&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-An;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${An})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),st.delete(this)}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.cognitionTimer&&(clearInterval(this.cognitionTimer),this.cognitionTimer=null),this.flushTelemetry(),this.flushCognition()}};function ot(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function bo(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function $(e,...t){for(let n of t){let r=bo(e[n]);if(r)return r}}var vo=[{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:$(t,"task","input","reason","message"),source:"structural"}}},{framework:"voltagent",matches:e=>e==="delegate_task",extract:(e,t)=>{let n=$(t,"targetAgent","agent","subAgent","agentName","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:$(t,"task","message","input"),description:$(t,"purpose"),source:"structural"}:null}},{framework:"crewai",matches:e=>/delegate work to (co-?worker|.+)/i.test(e),extract:(e,t)=>{let n=$(t,"coworker","agent","role");return n?{childAgentId:n,childName:n,kind:"teammate",agentType:n,task:$(t,"task","question"),description:$(t,"context"),source:"structural"}:null}},{framework:"llamaindex",matches:e=>e==="handoff"||/handoff/i.test(e),extract:(e,t)=>{let n=$(t,"to_agent","toAgent","agent_name","agentName","agent","name");return n?{childAgentId:n,childName:n,kind:"subagent",task:$(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=$(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:$(t,"task","message","input","reason","prompt"),source:"heuristic"}:null}}];function De(e,t){if(!e)return null;let n=t??{};for(let r of vo)try{if(r.matches(e)){let i=r.extract(e,n);if(i)return i}}catch{}return null}function $e(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}:{}}}}}function lt(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 On(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 N(e){let t=[],n=[],r,i=[];for(let a of e){if(a.mode==="partial"||a.mode==="email"||a.mode==="custom"){let c={mode:a.mode};a.field&&(c.field=a.field),a.pattern&&(c.pattern=a.pattern),typeof a.keepFirst=="number"&&(c.keepFirst=a.keepFirst),typeof a.keepLast=="number"&&(c.keepLast=a.keepLast),a.maskChar&&(c.maskChar=a.maskChar),a.keepPattern&&(c.keepPattern=a.keepPattern),a.replacement!==void 0&&(c.replacement=a.replacement),i.push(c);continue}a.field&&t.push(a.field),a.pattern&&n.push(a.pattern);let{replacement:l}=a;l&&r===void 0&&(r=l)}let o={};return t.length>0&&(o.fields=t),n.length>0&&(o.patterns=n),r!==void 0&&(o.replacement=r),i.length>0&&(o.directives=i),o}var B="0.2.7";import{AsyncLocalStorage as wo}from"node:async_hooks";var T=new wo,ko=5120,Nn=50;function Ao(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,l=Math.max(0,t-a),c=r.subarray(0,l);return new TextDecoder("utf-8",{fatal:!1}).decode(c)+o}function V(e){if(!e)return;let t=r=>r.length<=Nn?r.slice():r.slice(r.length-Nn),n=r=>Ao(r,ko);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)}}var ct=12e4,Ln=2e3,Fn=3,Io=5e3;function ve(e,t){return e==="mask"&&(t?.length??0)>0}var So=new Set(["approved","resolved"]),To=new Set(["rejected","dismissed","expired","timeout","bypassed_disabled"]);function Eo(e){return new Promise(t=>setTimeout(t,e))}function Ro(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 we(e){let{endpoint:t,apiKey:n,decisionId:r,timeoutMs:i=ct,maskFallback:o=!1,sdkVersion:a,fetchImpl:l=globalThis.fetch,sleep:c=Eo,log:s=f=>console.warn(f)}=e,u=f=>o?{resolution:"mask",reason:f}:{resolution:"block",reason:f};if(!t)return u("HITL approval cannot be confirmed (no backend endpoint) \u2014 fail-closed (G001)");if(!r)return u("HITL approval cannot be confirmed (no decision id) \u2014 fail-closed (G001)");let d=`${t.replace(/\/$/,"")}/v1/allow/decisions/${encodeURIComponent(r)}`,h={Accept:"application/json",...H(a)};n&&(h.Authorization=`Bearer ${n}`);let _=Date.now()+Math.max(0,i),g=0;for(s(`[VisIQ HITL] Awaiting human approval for decision ${r} (timeout ${i}ms)`);;){if(Date.now()>=_)return s(`[VisIQ HITL] Decision ${r} timed out after ${i}ms \u2014 ${o?"masking":"blocking"} (G001)`),u("HITL approval timed out");let f=null;try{let b=new AbortController,L=setTimeout(()=>b.abort(),Io),F;try{F=await l(d,{method:"GET",headers:h,signal:b.signal})}finally{clearTimeout(L)}if(!F.ok)throw new Error(`HTTP ${F.status} ${F.statusText}`);let I=await F.json();f=Ro(I),g=0}catch(b){g+=1;let L=b instanceof Error?b.message:String(b);if(s(`[VisIQ HITL] Poll failed for decision ${r} (${g}/${Fn}): ${L}`),g>=Fn)return u(`HITL approval poll failed repeatedly \u2014 fail-closed (G001): ${L}`);await c(Ln);continue}if(f!==null){let b=f.toLowerCase();return So.has(b)?(s(`[VisIQ HITL] Decision ${r} approved (${f}) \u2014 proceeding`),{resolution:"proceed",reason:`Approved by human reviewer (${f})`}):To.has(b)?(s(`[VisIQ HITL] Decision ${r} resolved as ${f} \u2014 ${o?"masking":"blocking"}`),u(`Not approved by human reviewer (${f})`)):(s(`[VisIQ HITL] Decision ${r} returned unknown status '${f}' \u2014 ${o?"masking":"blocking"} (G001)`),u(`HITL returned unknown status '${f}' \u2014 fail-closed (G001)`))}await c(Ln)}}function K(e){return e??be(typeof process<"u"?process.env?.VISIQ_FAIL_MODE:void 0)??Me}function y(e,t){try{console.error(`[VisIQ] FAIL-OPEN (${e}): ${t} \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed to block instead.`)}catch{}}function q(e,t){try{console.error(`[VisIQ] TRACE-DEGRADED (${e}): ${t} \u2014 the governance decision was still made and enforced; only the execution-trace beat was lost.`)}catch{}}function re(e){let t=e.getFailMode;return(typeof t=="function"?t.call(e):void 0)??K()}function Y(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 Dn(e){if(!e.enforced)return{action:"allow",reason:e.reason,redactionRules:[]};let t=e.retrieval.action??"deny",n=e.retrieval.redactionRules??[];return t==="escalate"&&ve(e.retrieval.hitlFallback,n)?{action:"redact",reason:e.reason,redactionRules:n}:{action:t,reason:e.reason,redactionRules:n}}var Mn=new Set;function ft(e){Mn.has(e)||(Mn.add(e),console.warn(`[VisIQ] unrecognized retrieval outcome "${e}" \u2014 failing closed (withholding content). Upgrade @visiq/harness if a newer control plane introduced this outcome.`))}async function je(e,t,n){let r=T.getStore(),i=V(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 Dn(o)}async function qe(e,t,n){return await e.awaitBundleReady(),je(e,t,n)}function $n(e,t,n=K()){switch(t.action){case"allow":case"escalate":return e;case"deny":return null;case"redact":{if(t.redactionRules.length===0)return e;try{return O(e,N(t.redactionRules))}catch{return n==="closed"?null:(y("redact-error","document redaction failed \u2014 document passed UNREDACTED"),e)}}default:return ft(String(t.action)),n==="closed"?null:(y("unknown-retrieval-verb",`unrecognized outcome "${String(t.action)}" \u2014 document passed through`),e)}}async function Pn(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,l=String(a.pageContent??a.text??a.content??""),c=a.metadata??{},s=await je(r,t,{resourceType:"document",resourceMetadata:c,query:n,contentPreview:l.slice(0,500)}),u=$n(o,s,re(r));u!==null&&i.push(u)}return i}async function jn(e,t,n){if(typeof e!="string")return e;await n.awaitBundleReady();let r;try{r=await je(n,t,{resourceType:"document",resourceMetadata:{content_preview:e.slice(0,500)},contentPreview:e.slice(0,500)})}catch(i){return re(n)==="closed"?"[RECALL] Retrieved context blocked \u2014 policy evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":(y("eval-error",`retrieval evaluation failed \u2014 text passed through: ${i instanceof Error?i.message:String(i)}`),e)}switch(r.action){case"allow":case"escalate":return e;case"deny":return"[RECALL] Retrieved context was blocked by policy.";case"redact":{if(r.redactionRules.length===0)return e;try{return O(e,N(r.redactionRules))}catch{return re(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(y("redact-error","text redaction failed \u2014 text passed UNREDACTED"),e)}}default:return ft(String(r.action)),re(n)==="closed"?"[RECALL] Retrieved context was blocked by policy.":(y("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 text passed through`),e)}}var qn=4,Un=1e3;function Pe(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 Bn(e,t,n){let r=[];for(let i of e){let o=i,a=String(o.pageContent??o.text??o.content??""),l={...o.metadata??{},content_preview:a.slice(0,500)},c;try{c=await je(n,t,{resourceType:"document",resourceMetadata:l,contentPreview:a.slice(0,500)})}catch(u){if(re(n)==="closed")continue;y("eval-error",`document retrieval evaluation failed \u2014 document passed through: ${u instanceof Error?u.message:String(u)}`),r.push(i);continue}let s=$n(i,c,re(n));s!==null&&r.push(s)}return r}async function dt(e,t,n,r,i){if(r>qn||i.nodes++>Un)return e;if(Array.isArray(e)){if(Pe(e))return i.matched=!0,Bn(e,t,n);let o=[];for(let a of e)o.push(await dt(a,t,n,r+1,i));return o}if(e!==null&&typeof e=="object"){let o=e,a={...o};for(let l of Object.keys(o))a[l]=await dt(o[l],t,n,r+1,i);return a}return e}async function Ue(e,t,n){if(await n.awaitBundleReady(),Array.isArray(e)&&Pe(e))return Bn(e,t,n);if(e!==null&&typeof e=="object"){let r={nodes:0,matched:!1},i=await dt(e,t,n,0,r);if(r.matched)return i}return e}var Co={blocked:!0,reason:"[RECALL] Retrieved context was blocked by policy."};function pt(e,t,n){if(t>qn||n.n++>Un)return e;if(Array.isArray(e))return Pe(e)?[]:e.map(r=>pt(r,t+1,n));if(e!==null&&typeof e=="object"){if(Pe([e]))return{...Co};let r=e,i={};for(let o of Object.keys(r))i[o]=pt(r[o],t+1,n);return i}return e}function ut(e){return typeof e=="string"?"[RECALL] Retrieved context was blocked by policy.":Array.isArray(e)?[]:e!==null&&typeof e=="object"?pt(e,0,{n:0}):e}function Vn(e,t,n=K()){let r=Dn(t);switch(r.action){case"allow":case"escalate":return e;case"deny":return ut(e);case"redact":{if(r.redactionRules.length===0)return e;try{return O(e,N(r.redactionRules))}catch{return n==="closed"?ut(e):(y("redact-error","result redaction failed \u2014 result passed UNREDACTED"),e)}}default:return ft(String(r.action)),n==="closed"?ut(e):(y("unknown-retrieval-verb",`unrecognized outcome "${String(r.action)}" \u2014 result passed through`),e)}}function R(e){return typeof e=="object"&&e!==null?e:null}function Kn(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}function xo(e,t){let n=R(e.metadata),r=n&&typeof n.name=="string"?n.name:void 0;return Kn(e.name,e.id,r,t)}function Oo(e){let t=R(e.metadata),n=t&&typeof t.description=="string"?t.description:void 0,r=Kn(e.description,n);return r===void 0?void 0:r.slice(0,4e3)}function No(e){let t=R(e);return t!==null&&("type"in t||"properties"in t||"$schema"in t)}function Lo(e){let t=R(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=R(n);if(r===null)return{type:"object"};let i={};for(let o of Object.keys(r))i[o]={};return{type:"object",properties:i}}var Fo=new Set(["default","const","enum","examples","example"]);function mt(e){if(Array.isArray(e))return e.map(mt);let t=R(e);if(t===null)return e;let n={};for(let[r,i]of Object.entries(t))Fo.has(r)||(n[r]=mt(i));return n}function Mo(e){let t;if(No(e))t=e;else{let n=Lo(e);if(n===void 0)return;t=n}try{let n=JSON.stringify(t);if(n.length>2e4){let r=R(t),i=r&&R(r.properties);if(i){let o={};for(let a of Object.keys(i))o[a]={};return{type:"object",properties:o}}return{type:"object"}}return mt(JSON.parse(n))}catch{return}}function Do(e){let t=R(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:Mo(n)}function $o(e,t){let n=R(e);if(n===null)return null;let r=xo(n,t);if(r===void 0)return null;let i={name:r.slice(0,255)},o=Oo(n);o!==void 0&&(i.description=o);let a=Do(n);return a!==void 0&&(i.input_schema=a),i}function ke(e){let t=[],n=new Set,r=(i,o)=>{try{let a=$o(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=R(e);if(i!==null){for(let o of Object.keys(i))if(r(i[o],o),t.length>=200)break}}return t}function gt(e){try{let t=R(e);if(t===null)return[];let n=[],r=new Set,i=c=>{for(let s of c)!r.has(s.name)&&n.length<200&&(r.add(s.name),n.push(s))};t.tools!==void 0&&i(ke(t.tools));let o=R(t.settings);o&&o.tools!==void 0&&i(ke(o.tools));for(let c of["getTools","listTools"]){let s=t[c];if(typeof s=="function")try{i(ke(s.call(t)))}catch{}}let a=R(t.nodes);if(a)for(let c of Object.keys(a)){let s=R(a[c]);s&&s.tools!==void 0&&i(ke(s.tools))}let{agents:l}=t;if(l instanceof Map)for(let c of l.values()){let s=R(c);s&&s.tools!==void 0&&i(ke(s.tools))}return n}catch{return[]}}import{z as Be}from"zod";var Po=Be.object({decision:Be.enum(["permit","deny"]),reason:Be.string(),handoff_event_id:Be.string().nullable()}),j=class extends Error{constructor(e,t,n){super(e),this.code=t,this.status=n,this.name="OrchestrateError"}code;status},J=class extends j{constructor(e,t){super(`Orchestrate grant denied: ${e}`,"GRANT_DENIED"),this.reason=e,this.handoffEventId=t,this.name="GrantDeniedError"}reason;handoffEventId},jo="https://api.visiqlabs.com",qo=1e4,ie=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??jo,timeoutMs:e.timeoutMs??qo},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 j(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=Po.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 zn=new Map;async function Gn(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=zn.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 ie({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 zn.set(e,o),o}var Ae=Symbol.for("visiq.orchestrate.wrapped");function Uo(e){return e instanceof j&&typeof e.status=="number"&&e.status>=400&&e.status<500}function Hn(e,t){if(!t.agentId||t.agentId.trim()==="")throw new j("agentId is required","CONFIG_ERROR");if(!t.grantToken||t.grantToken.trim()==="")throw new j("grantToken is required","CONFIG_ERROR");if(e[Ae]===!0)return e;let n=new ie(t),r=t.failBehavior??(process.env.VISIQ_FAIL_MODE?.trim().toLowerCase()==="closed"?"deny":"permit"),i=async(o,a)=>{let l;try{l=await n.evaluate({grantToken:t.grantToken,action:o,resourceType:a})}catch(c){if(Uo(c))throw c;if(r==="permit"){console.warn('[VisIQ] FAIL-OPEN (orchestrate-eval-error): evaluate failed \u2014 proceeding UNGOVERNED. Set VISIQ_FAIL_MODE=closed (or failBehavior:"deny") to block instead.',c);return}throw new j(`ORCHESTRATE evaluate failed: ${c instanceof Error?c.message:String(c)}`,"EVALUATE_ERROR")}if(l.decision==="deny")throw new J(l.reason,l.handoffEventId)};return new Proxy(e,{get(o,a,l){let c=Reflect.get(o,a,l);return a===Ae?!0:a==="_call"&&typeof c=="function"?async function(s,...u){let d=o.name;return await i(d??"_call"),c.call(this??o,s,...u)}:(a==="call"||a==="execute"||a==="run")&&typeof c=="function"?async function(s,...u){let d=o.name;return await i(d??String(a)),c.call(this??o,s,...u)}:c}})}import{randomUUID as Jn}from"node:crypto";var Wn=Symbol.for("visiq.semantickernel.instrumented");function Qn(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.useFunctionInvocation=="function"&&typeof t.usePromptRender=="function"&&typeof t.execute!="function"&&typeof t.generate!="function"&&typeof t.run!="function"}function Bo(e){let t=e.arguments;return t&&typeof t=="object"&&"arguments"in t&&t.arguments&&typeof t.arguments=="object"?t.arguments:t??{}}function Vo(e,t){let n=e.arguments;if(n&&typeof n=="object"&&"arguments"in n&&n.arguments&&typeof n.arguments=="object"){let r=n.arguments;for(let i of Object.keys(r))delete r[i];Object.assign(r,t);return}e.arguments=t}function z(e,t){e.result&&typeof e.result=="object"?e.result.value=t:e.result={value:t}}function Ko(e){return e.result?.value}function zo(e){let{agentId:t,unified:n,failMode:r}=e;return async function(o,a){let l=o.function?.metadata?.name??"unknown",c=o.function?.metadata?.pluginName,s=Bo(o),u=c;try{let f=Y(await n.evaluate({operations:["action"],agentId:t,toolName:l,toolArgs:s,...u!==void 0?{targetResource:u}:{}}));if(!f.allowed){z(o,C({outcome:"deny",code:f.ruleCode??"DENY",reason:f.reason}));return}f.decision==="mask"&&f.argRedactionRules.length>0&&Vo(o,O(s,N(f.argRedactionRules)))}catch(f){if(r==="closed"){z(o,C({outcome:"error",code:"EVAL-ERROR",mechanism:`evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${f instanceof Error?f.message:String(f)}`}));return}y("eval-error",`SK action pre-gate failed for "${l}": ${f instanceof Error?f.message:String(f)}`)}try{let f=await qe(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:l,plugin_name:c}});if(f.action==="deny"||f.action==="escalate"){z(o,`[RECALL: access denied \u2014 ${f.reason}]`);return}}catch(f){if(r==="closed"){z(o,`[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed): ${f instanceof Error?f.message:String(f)}.`);return}y("eval-error",`SK retrieval pre-gate failed for "${l}": ${f instanceof Error?f.message:String(f)}`)}await a(o);let d=Ko(o),_=(typeof d=="string"?d:(()=>{try{return JSON.stringify(d)??String(d)}catch{return String(d)}})()).slice(0,500),g;try{g=await qe(n,t,{resourceType:"tool_result",resourceMetadata:{function_name:l,plugin_name:c,content_preview:_},contentPreview:_})}catch(f){r==="closed"?z(o,"[RECALL] Result withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):y("eval-error",`SK post-result retrieval eval failed for "${l}": ${f instanceof Error?f.message:String(f)}`);return}if(g.action==="deny"||g.action==="escalate"){z(o,`[RECALL: access denied \u2014 ${g.reason}]`);return}if(g.action==="redact"&&g.redactionRules&&g.redactionRules.length>0&&d!==null&&d!==void 0)try{z(o,O(d,N(g.redactionRules)))}catch(f){r==="closed"?z(o,"[RECALL] Result withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed)."):y("redact-error",`SK result redaction failed for "${l}" \u2014 result passed UNREDACTED: ${f instanceof Error?f.message:String(f)}`)}}}function Go(e){return async function(n,r){await r(n);let i=n.renderedPrompt;if(typeof i!="string"||i.length===0)return;let o;try{o=await qe(e.unified,e.agentId,{resourceType:"prompt",resourceMetadata:{},contentPreview:i.slice(0,500)})}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 evaluation error (blocked \u2014 VISIQ_FAIL_MODE=closed).":y("eval-error",`SK prompt-render eval failed: ${a instanceof Error?a.message:String(a)}`);return}if(o.action==="redact"&&o.redactionRules&&o.redactionRules.length>0){try{n.renderedPrompt=O(i,N(o.redactionRules))}catch(a){e.failMode==="closed"?n.renderedPrompt="[RECALL] Prompt withheld \u2014 redaction error (blocked \u2014 VISIQ_FAIL_MODE=closed).":y("redact-error",`SK prompt redaction failed \u2014 prompt passed UNREDACTED: ${a instanceof Error?a.message:String(a)}`)}return}(o.action==="deny"||o.action==="escalate")&&(n.renderedPrompt=`[RECALL: prompt suppressed \u2014 ${o.reason}]`)}}function Yn(e,t){let n=e;if(n[Wn]===!0)return t.onWrap?.(),e;let r=zo(t),i=Go(t),o=!1;return Array.isArray(n._functionInvocationFilters)?(n._functionInvocationFilters.unshift(r),o=!0):typeof n.useFunctionInvocation=="function"&&(n.useFunctionInvocation(r),o=!0),typeof n.usePromptRender=="function"?n.usePromptRender(i):Array.isArray(n._promptRenderFilters)&&n._promptRenderFilters.push(i),o&&(n[Wn]=!0,t.onWrap?.()),e}function C(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.`}function Ve(e){return e instanceof Error?e.message:String(e)}var Ho=/https?:\/\/[^\s"'`,)}\]]+/;function ht(e){let t=e.match(Ho);if(t)try{let n=new URL(t[0]);return n.hostname+n.pathname}catch{return t[0]}}var oe=Symbol.for("visiq.toolexec.instrumented");function Wo(e){return e!==null&&typeof e=="object"&&typeof e.execute=="function"}var _t={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 Zn(e){if(e===null||typeof e!="object")return null;let t=e;if(Wo(t))return null;if(Qn(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 Qo(e,t,n,r,i,o){let{agentId:a,unified:l}=e,c=V(i),s;try{await l.awaitBundleReady(),s=Y(await l.evaluate({operations:o?["action","delegation"]:["action"],agentId:a,toolName:t,toolArgs:n,...o?{context:$e(o,a)}:{},...i?.session_id?{sessionId:i.session_id}:{},...r!==void 0?{targetResource:r}:{},...c?{telemetry:c}:{}}))}catch(u){let d=u instanceof Error?u.message:String(u);return e.failMode==="closed"?{block:C({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${d} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})}:(y("eval-error",`policy evaluation failed for tool "${t}": ${d}`),{block:null})}if(s.decision==="approval_required"&&s.decisionId){let u=l.getApiKey()??e.apiKey,d=await we({endpoint:l.getEndpoint()??e.endpoint??"",...u?{apiKey:u}:{},decisionId:s.decisionId,timeoutMs:e.hitlTimeoutMs,sdkVersion:B});return d.resolution!=="proceed"?{block:C({outcome:"approval_required",code:s.ruleCode??"HITL-BLOCK",reason:s.reason,mechanism:d.reason}),decision:s}:{block:null}}if(!s.allowed)return{block:C({outcome:"deny",code:s.ruleCode??"DENY",reason:s.reason}),decision:s};if(s.decision==="mask"&&s.argRedactionRules&&s.argRedactionRules.length>0)try{let u=N(s.argRedactionRules);return{block:null,maskedArgs:O(n,u),decision:s}}catch(u){let d=u instanceof Error?u.message:String(u);return e.failMode==="closed"?{block:C({outcome:"error",code:"MASK-ERROR",mechanism:`argument masking failed: ${d} (blocked \u2014 VISIQ_FAIL_MODE=closed)`})}:(y("mask-error",`argument masking failed for tool "${t}" \u2014 running with UNMASKED args: ${d}`),{block:null})}return{block:null}}async function yt(e,t,n,r,i){let o=T.getStore()??e.telemetry,a=De(t,n);a&&pe(e.unified,{agentId:e.agentId,sessionId:o?.session_id,...e.framework?{framework:e.framework}:{}},a);let l={agentId:e.agentId,sessionId:o?.session_id,...e.framework?{framework:e.framework}:{}},c=ce(t,n);try{fe(e.unified,l,{toolName:t,...c?{memory:c}:{},argSummary:r.slice(0,512)})}catch(g){q("step-beat",`emit failed for tool "${t}": ${Ve(g)}`)}let s=Date.now(),u=await Qo(e,t,n,ht(r),o,a);if(u.block!==null){try{u.decision&&te(e.unified,l,{toolName:t,decision:u.decision.decision??"deny",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0,harnessMessage:u.block})}catch(g){q("intervention-beat",`emit failed for tool "${t}": ${Ve(g)}`)}return u.block}if(u.maskedArgs!==void 0&&u.decision)try{te(e.unified,l,{toolName:t,decision:u.decision.decision??"mask",...u.decision.ruleCode?{ruleCode:u.decision.ruleCode}:{},...u.decision.reason?{ruleLabel:u.decision.reason}:{},enforced:!0})}catch(g){q("intervention-beat",`emit failed for tool "${t}": ${Ve(g)}`)}let d=u.maskedArgs??n,h=await i(d),_=await Ue(h,e.agentId,e.unified);try{me(e.unified,l,{toolName:t,ok:!0,durationMs:Date.now()-s,...W(_)!==void 0?{bytes:W(_)}:{},...Q(_)!==void 0?{itemCount:Q(_)}:{},...c?{memory:c}:{}})}catch(g){q("observation-beat",`emit failed for tool "${t}": ${Ve(g)}`)}return _}function Ke(e,t,n){let r=e;if(r[oe]){n.onWrap?.();return}if(typeof r.execute!="function")return;let i=r.execute;vt(r,"execute",async function(...a){let l=lt(a[0]);return yt(n,t,l,Se(l),c=>Promise.resolve(i.apply(this,[c,...a.slice(1)])))}),r[oe]=!0,n.onWrap?.()}function Yo(e,t,n){let r=e;if(r[oe]){n.onWrap?.();return}if(typeof r.invoke!="function")return;let i=r.invoke;vt(r,"invoke",async function(...a){let l=a[1],c=On(l),s=typeof l=="string"?l:Se(c);return yt(n,t,c,s,u=>{let d=typeof l=="string"?JSON.stringify(u):u;return Promise.resolve(i.apply(this,[a[0],d,...a.slice(2)]))})}),r[oe]=!0,n.onWrap?.()}function Jo(e,t){let n=e;if(n[oe]){t.onWrap?.();return}if(typeof n.call!="function")return;let r=n.metadata,i=typeof r?.name=="string"?r.name:"unknown",o=n.call;vt(n,"call",async function(...l){let c=lt(l[0]);return yt(t,i,c,Se(c),s=>Promise.resolve(o.apply(this,[s,...l.slice(1)])))}),n[oe]=!0,t.onWrap?.()}function Xn(e,t){for(let[n,r]of Object.entries(e))r!==null&&typeof r=="object"&&Ke(r,n,t);return e}function er(e,t,n){let r={...t,framework:n};switch(n){case"vercel":return Zo(e,r);case"mastra":return Xo(e,r);case"openai":return na(e,r);case"llamaindex":return ta(e,r);case"voltagent":return ea(e,r);case"semantic-kernel":return Yn(e,r);default:return e}}function Zo(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"&&Xn(i,t),r&&!r.__visiq_step&&(r.__visiq_step=!0,r.onStepFinish=bt(r.onStepFinish)),ze(e,["generate","stream"],async(o,a)=>(Ie(a,o[0]),o)),e}function Xo(e,t){let r=aa(e);return r&&Xn(r,t),ze(e,["generate","stream","generateVNext","streamVNext"],async(i,o)=>{Ie(o,i[0]);let a=i[1]&&typeof i[1]=="object"?{...i[1]}:{};a.onStepFinish=bt(a.onStepFinish);let l=[...i];return l[1]=a,l}),e}function ea(e,t){let n=ia(e);if(n){for(let r of n)if(r!==null&&typeof r=="object"){let{name:i}=r;Ke(r,typeof i=="string"?i:"unknown",t)}}return ze(e,["generateText","streamText","generateObject","streamObject"],async(r,i)=>{Ie(i,r[0]);let o=r[1]&&typeof r[1]=="object"?{...r[1]}:{};o.onStepFinish=bt(o.onStepFinish);let a=[...r];return a[1]=o,a}),e}function ta(e,t){let n=e,r=o=>{let a=o?.tools;if(Array.isArray(a))for(let l of a)l!==null&&typeof l=="object"&&Jo(l,t)},{agents:i}=n;if(i instanceof Map)for(let o of i.values())r(o);else Array.isArray(n.tools)&&r(n);return ze(e,["run"],async(o,a)=>(Ie(a,o[0]),o)),oa(e,"runStream",(o,a,l)=>{l||Ie(a,o[0])}),e}function na(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;Yo(i,typeof o=="string"?o:"unknown",t)}}return ra(e,t),e}function ra(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=Jn(),i.llm_prompts=[],i.llm_responses=[],i.agent_reasoning=[],i.retrieverQueries=new Map;let a=o[2];a!=null&&i.llm_prompts.push(Se(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 ia(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 ze(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(...l){let c=tr();return T.run(c,async()=>{let s=await n(l,c);return a.apply(e,s)})},r[o]=!0}}function oa(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 l=T.getStore(),c=l??tr();return n(a,c,l!==void 0),T.run(c,()=>o.apply(e,a))},r[i]=!0}function bt(e){return t=>{let n=T.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 Ie(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(Se(n).slice(0,5120))}function aa(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 tr(){return{session_id:Jn(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function vt(e,t,n){try{e[t]=n}catch{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}}function Se(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function cr(e,t){let n=pa(t);if(e[Ae]===!0)return e;let r=ha(e);if(r==="langchain-executor"||r==="langchain-graph")return se(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,rr(r,null),n.failMode),ir(e,n),_a(e,n);let i=Zn(e);if(i){se(n.apiKey,n.endpoint,n.agentId,n.timeoutMs,rr("unknown",i),n.failMode),ir(e,n);let o=0,a=fr(n);a.onWrap=()=>{o+=1};let l=er(e,a,i);if(o===0){let c=0;try{c=gt(e).length}catch{c=0}if(c>0){let s=`[VisIQ] Detected a ${_t[i]} that ADVERTISES ${String(c)} tool(s) but instrumented ZERO of them \u2014 its tool calls 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)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw / VISIQ_FAIL_MODE=closed) to refuse to run ungoverned.`;if(n.onInstrumentFailure!==void 0?n.onInstrumentFailure==="throw":n.failMode==="closed")throw new Error(s);y("zero-instrument",`advertised ${String(c)} tool(s), instrumented none`),console.warn(s)}else{let s=`[VisIQ] Detected a ${_t[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(s);console.warn(s)}}return l}if(ka(e)){let o=process.env.VISIQ_GRANT_ID;return o?Ia(e,n,o):Sa(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 ca="https://api.visiqlabs.com",ua="\0",nr=new Map;function rr(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 se(e,t,n,r,i,o){let a=[e??"",t??"",n??"",r??"",o??""].join(ua),l=nr.get(a);return l||(l=new xn(e,t,n,void 0,r,B,We),l.registerHostEnvironment(i),nr.set(a,l)),o!==void 0&&l.setFailMode(o),l}function ir(e,t){try{let n=gt(e);n.length>0&&se(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode).reportToolSurface(n)}catch{}}function da(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 pa(e){let t=e?.agentId??process.env.VISIQ_AGENT_ID??ma(),n=e?.apiKey??process.env.VISIQ_API_KEY,r=e?.endpoint??process.env.VISIQ_ENDPOINT??(n?ca:void 0);return{agentId:t,apiKey:n,endpoint:r,hitlTimeoutMs:ga(e?.hitlTimeoutMs),timeoutMs:da(e?.timeoutMs),onInstrumentFailure:e?.onInstrumentFailure??fa(),failMode:K(e?.failMode)}}function fa(){let e=process.env.VISIQ_ON_INSTRUMENT_FAILURE;if(e==="throw")return"throw";if(e==="warn")return"warn"}function ma(){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(Ge.existsSync(r)){let o=JSON.parse(Ge.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(lr.hostname());if(t)return t}catch{}return"agent"}function ga(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 ct}function ha(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 _a(e,t){let n=e,r=se(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode),i=ya(n);for(let c of i)At(c,t.agentId,r),ba(c,t.agentId,r,t),dr(c,r,t);let{nodes:o}=n;if(!!o&&typeof o=="object"&&"tools"in o&&i.length===0){let c="[VisIQ] Detected a LangGraph agent whose compiled graph carries a ToolNode, but resolved ZERO tools from it \u2014 its tool calls run UN-GOVERNED while this SDK appears correctly wired. This is almost always a compiled-graph tool bag that moved on a @langchain/langgraph version bump. Upgrade @visiq/harness, or pass the tools through visiq() directly (visiq(tools, \u2026)). Set onInstrumentFailure:'throw' (or VISIQ_ON_INSTRUMENT_FAILURE=throw / VISIQ_FAIL_MODE=closed) to refuse to run ungoverned.";if(t.onInstrumentFailure!==void 0?t.onInstrumentFailure==="throw":t.failMode==="closed")throw new Error(c);y("zero-instrument","langgraph compiled-graph ToolNode present, resolved no tools"),console.warn(c)}let l=n.invoke;if(n.invoke=function(c,s){let u=kt(),d=sr(t.agentId,r),h=s?.callbacks??[];return T.run(u,()=>l.call(this,c,{...s,callbacks:[...h,d]}))},typeof n.stream=="function"){let c=n.stream;n.stream=function(s,u){let d=kt(),h=sr(t.agentId,r),_=u?.callbacks??[];return T.run(d,()=>c.call(this,s,{...u,callbacks:[..._,h]}))}}return e}function ya(e){let t=[],n=new Set,r=o=>{if(Array.isArray(o))for(let a of o)a&&typeof a=="object"&&!n.has(a)&&(n.add(a),t.push(a))};r(e.tools);let{nodes:i}=e;if(i&&typeof i=="object"){for(let o of Object.values(i))if(o&&typeof o=="object"){let a=o;r(a.tools);let{bound:l}=a;l&&typeof l=="object"&&r(l.tools)}}return t}function kt(){return{session_id:sa(),llm_prompts:[],llm_responses:[],agent_reasoning:[],retrieverQueries:new Map}}function At(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,l){let c=await o.call(this,a,l);return or(c,t,a,n)},r[i]=!0}if(typeof r.retrieve=="function"&&!r._getRelevantDocuments){let o=r.retrieve;r.retrieve=async function(a){let l=await o.call(this,a);return or(l,t,String(a),n)},r[i]=!0}r.retriever&&typeof r.retriever=="object"&&At(r.retriever,t,n)}}function ba(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:"",l=typeof i.retriever=="object"&&i.retriever!==null,c=a.split(/[^a-zA-Z0-9]+|(?<=[a-z])(?=[A-Z])/).map(A=>A.toLowerCase()),s=new Set(["update","delete","create","write","archive","insert","remove","patch"]),u=new Set(["send","post","put"]),d=c.some(A=>s.has(A)),h=u.has(c[0]??""),_=d||h,g=["update","delete","create","archive","insert","remove"],f=c.some(A=>g.some(x=>A.length>x.length&&A.endsWith(x))),L=/retriev/i.test(a)||/search.*doc|knowledge/i.test(a)&&!_&&!f;if(!(l||L))return;let I=d||f;if(!I)if(l)At(i.retriever,t,n);else{let A=globalThis,x=Symbol.for("visiq.recall.closureRetrieverWarned"),M=A[x]??=new Set;M.has(a)||(M.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 G=i.func;I?(i[ur]=!0,i.func=async function(...A){await n.awaitBundleReady();let x=A[0],M=typeof x=="object"&&x!==null?x:{input:x},X=typeof M.query=="string"?M.query:void 0,v=T.getStore(),w=V(v),S;try{S=await n.evaluate({operations:["retrieval","action"],agentId:t,...v?.session_id?{sessionId:v.session_id}:{},toolName:a||"unknown",toolArgs:M,resourceType:"document",resourceMetadata:{},...X!==void 0?{query:X}:{},...w?{telemetry:w}:{}})}catch(D){let le=D instanceof Error?D.message:String(D);return K(r?.failMode)==="closed"?C({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${le} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(y("eval-error",`policy evaluation failed for hybrid tool "${a||"unknown"}": ${le}`),G.apply(this,A))}let k=Y(S),ee=ve(k.hitlFallback,k.argRedactionRules),Re=A,It=()=>{try{return Re=[O(M,N(k.argRedactionRules)),...A.slice(1)],null}catch{return K(r?.failMode)==="closed"?C({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(y("mask-error",`argument masking failed for tool "${a||"unknown"}" \u2014 running with UNMASKED args`),null)}};if(k.decision==="approval_required"&&k.decisionId&&r){let D=await we({endpoint:n.getEndpoint()??r.endpoint??"",apiKey:n.getApiKey()??r.apiKey,decisionId:k.decisionId,timeoutMs:r.hitlTimeoutMs,maskFallback:ee,sdkVersion:B});if(D.resolution==="mask"){let le=It();if(le)return le}else if(D.resolution!=="proceed")return C({outcome:"approval_required",code:k.ruleCode??"HITL-BLOCK",reason:k.reason,mechanism:D.reason})}else if(!k.allowed)return C({outcome:"deny",code:k.ruleCode??"DENY",reason:k.reason});if(k.decision==="mask"&&k.argRedactionRules.length>0){let D=It();if(D)return D}let hr=await G.apply(this,Re);return Vn(hr,S,r?.failMode)}):i.func=async function(...A){let x=await G.apply(this,A);return typeof x=="string"?jn(x,t,n):Ue(x,t,n)},i[o]=!0}var ur=Symbol.for("visiq.hybrid.instrumented");async function or(e,t,n,r){return Pn(e,t,n,r)}var ar=["invoke","call","_call"],ae=new la;function dr(e,t,n){let r=e,i=Symbol.for("visiq.allow.instrumented");if(r[i]||typeof r._getRelevantDocuments=="function"||r[ur]||!ar.some(s=>typeof r[s]=="function"))return;let{agentId:o}=n,a=typeof r.name=="string"?r.name:"unknown",l=Symbol("visiq.gate"),c=async(s,u,d,h,_)=>{let g=ae.getStore();if(g!==void 0&&g.gateKey===l&&!g.entered.has(_))return g.entered.add(_),s.call(u,d,...h);let f;if(typeof d=="string")f=d;else{let w=d?.input;f=w!=null?String(w):JSON.stringify(d)??""}let b=T.getStore(),L=V(b),F=typeof d=="object"&&d!==null?d:{input:f},I=De(a,F);I&&pe(t,{agentId:o,sessionId:b?.session_id,framework:"langchain"},I);let G={agentId:o,sessionId:b?.session_id,framework:"langchain"},A=ce(a,F);try{fe(t,G,{toolName:a,...A?{memory:A}:{},argSummary:f.slice(0,512)})}catch(w){q("step-beat",`emit failed for tool "${a}": ${wt(w)}`)}let x=Date.now(),M=async w=>{let S=await w();try{me(t,G,{toolName:a,ok:!0,durationMs:Date.now()-x,...W(S)!==void 0?{bytes:W(S)}:{},...Q(S)!==void 0?{itemCount:Q(S)}:{},...A?{memory:A}:{}})}catch(k){q("observation-beat",`emit failed for tool "${a}": ${wt(k)}`)}return S},X=(w,S,k,ee)=>{try{te(t,G,{toolName:a,decision:w,...S?{ruleCode:S}:{},...k?{ruleLabel:k}:{},enforced:!0,...ee?{harnessMessage:ee}:{}})}catch(Re){q("intervention-beat",`emit failed for tool "${a}": ${wt(Re)}`)}};await t.awaitBundleReady();let v;try{v=Y(await t.evaluate({operations:I?["action","delegation"]:["action"],agentId:o,...b?.session_id?{sessionId:b.session_id}:{},toolName:a,toolArgs:F,targetResource:ht(f),...L?{telemetry:L}:{},...I?{context:$e(I,o)}:{}}))}catch(w){let S=w instanceof Error?w.message:String(w);return n.failMode==="closed"?C({outcome:"error",code:"EVAL-ERROR",mechanism:`policy evaluation failed: ${S} (blocked \u2014 VISIQ_FAIL_MODE=closed)`}):(y("eval-error",`policy evaluation failed for tool "${a}": ${S}`),ae.run({gateKey:l,entered:new Set([_])},()=>s.call(u,d,...h)))}if(v.decision==="approval_required"&&v.decisionId){let w=ve(v.hitlFallback,v.argRedactionRules),S=await we({endpoint:t.getEndpoint()??n.endpoint??"",apiKey:t.getApiKey()??n.apiKey,decisionId:v.decisionId,timeoutMs:n.hitlTimeoutMs,maskFallback:w,sdkVersion:B});if(S.resolution==="proceed")return M(()=>ae.run({gateKey:l,entered:new Set([_])},()=>s.call(u,d,...h)));if(S.resolution==="mask")try{let ee=O(d,N(v.argRedactionRules));return X("mask",v.ruleCode,v.reason),M(()=>ae.run({gateKey:l,entered:new Set([_])},()=>s.call(u,ee,...h)))}catch{return n.failMode==="closed"?C({outcome:"error",code:"MASK-ERROR",mechanism:"argument masking failed (blocked \u2014 VISIQ_FAIL_MODE=closed)"}):(y("mask-error",`HITL mask fallback failed for tool "${a}" \u2014 running with UNMASKED args`),ae.run({gateKey:l,entered:new Set([_])},()=>s.call(u,d,...h)))}let k=C({outcome:"approval_required",code:v.ruleCode??"HITL-BLOCK",reason:v.reason,mechanism:S.reason});return X("approval_required",v.ruleCode,v.reason,k),k}if(!v.allowed){let w=C({outcome:"deny",code:v.ruleCode??"DENY",reason:v.reason});return X("deny",v.ruleCode,v.reason,w),w}return M(()=>ae.run({gateKey:l,entered:new Set([_])},()=>s.call(u,d,...h)))};for(let s of ar){if(typeof r[s]!="function")continue;let u=r[s];r[s]=function(d,...h){return c(u,this,d,h,s)}}r[i]=!0}function wt(e){return e instanceof Error?e.message:String(e)}function va(e,t,n){let r=(a,l)=>{if(!a||typeof a!="object")return;let c=a[l];return typeof c=="string"&&c.length>0?c:void 0},i=t?.invocation_params,o=e&&typeof e=="object"?e.kwargs:void 0;return r(i,"model")??r(i,"model_name")??r(n,"ls_model_name")??r(o,"model")??r(o,"model_name")}function wa(e,t){let n=(_,g)=>{if(!_||typeof _!="object")return;let f=_[g];return typeof f=="number"&&Number.isFinite(f)?f:void 0},r=e?.tokenUsage,i=n(r,"promptTokens"),o=n(r,"completionTokens");if(i!==void 0||o!==void 0)return{...i!==void 0?{tokensIn:i}:{},...o!==void 0?{tokensOut:o}:{}};let a=t?.usage_metadata,l=n(a,"input_tokens"),c=n(a,"output_tokens");if(l===void 0&&c===void 0)return;let s=a&&typeof a=="object"?a.input_token_details:void 0,u=n(s,"cache_read"),d=n(s,"cache_creation"),h=l!==void 0?Math.max(0,l-(u??0)-(d??0)):void 0;return{...h!==void 0?{tokensIn:h}:{},...c!==void 0?{tokensOut:c}:{},...u!==void 0?{cacheRead:u}:{},...d!==void 0?{cacheWrite:d}:{}}}function sr(e,t){return{name:"VisiqHandler",handleLLMStart:async(n,r,i,o,a,l,c)=>{let s=T.getStore();if(!s)return;s.llm_prompts.push(...r);let u=va(n,a,c);u&&(s.llm_model=u)},handleLLMEnd:async n=>{let r=T.getStore();if(!r)return;let o=n?.generations?.[0]?.[0],a=typeof o?.text=="string"?o.text:"";a&&r.llm_responses.push(a);try{let l=n?.llmOutput,c=o?.message&&typeof o.message=="object"?o.message:void 0,s=wa(l,c);if(!s&&!a)return;let u=c?.tool_calls,d=typeof l?.model=="string"?l.model:void 0,h=r.llm_model??d;await t.awaitBundleReady(),Ze(t,{agentId:e,sessionId:r.session_id,framework:"langchain"},{...a?{texts:[a]}:{},...s?{usage:s}:{},...h?{model:h}:{},final:!(Array.isArray(u)&&u.length>0)})}catch{}},handleAgentAction:async n=>{let r=T.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=T.getStore();o&&o.retrieverQueries.set(i,r??"")},handleRetrieverEnd:async(n,r)=>{let i=T.getStore();if(!i)return;let o=i.retrieverQueries.get(r)??"";if(i.retrieverQueries.delete(r),!Array.isArray(n))return;let a=V(i);for(let l of n){let c=l,s=String(c.pageContent??c.text??c.content??""),u=c.metadata??{};await t.evaluate({operations:["retrieval"],agentId:e,resourceType:"document",resourceMetadata:u,query:o,contentPreview:s.slice(0,500),...a?{telemetry:a}:{}})}},handleRetrieverError:async(n,r)=>{let i=T.getStore();i&&i.retrieverQueries.delete(r)}}}var pr=["_call","execute","call","run","invoke"];function ka(e){let t=e;for(let n of pr)if(typeof t[n]=="function")return!0;return!1}function Aa(e){return e instanceof J?!0:e instanceof j?typeof e.status=="number"&&e.status>=400&&e.status<500:!1}function Ia(e,t,n){let r=null,i=null,o=!1,a=async()=>{if(r)return r;if(i)throw new J(`Failed to bootstrap grant ${n}: ${i.message}`,null);let l;try{l=await Gn(t.agentId,n)}catch(c){throw o=Aa(c),o&&(i=c instanceof Error?c:new Error(String(c))),new J(`Failed to bootstrap grant ${n}: ${c instanceof Error?c.message:String(c)}`,null)}return r=Hn(e,{agentId:t.agentId,grantToken:l,failBehavior:t.failMode==="closed"?"deny":"permit",...t.apiKey?{apiKey:t.apiKey}:{},...t.endpoint?{endpoint:t.endpoint}:{}}),r};return new Proxy(e,{get(l,c,s){if(c===Ae)return!0;let u=Reflect.get(l,c,s);return typeof u!="function"||typeof c!="string"||!pr.includes(c)?u:async function(...d){let h;try{h=await a()}catch(g){if(o||t.failMode==="closed")throw g;return y("grant-bootstrap",`grant ${n} bootstrap failed: ${g instanceof Error?g.message:String(g)}`),u.call(this,...d)}return h[c].call(h,...d)}}})}function Sa(e,t){let n=se(t.apiKey,t.endpoint,t.agentId,t.timeoutMs,void 0,t.failMode);dr(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";Ke(e,i,fr(t))}return e}function fr(e){return{agentId:e.agentId,unified:se(e.apiKey,e.endpoint,e.agentId,e.timeoutMs,void 0,e.failMode),hitlTimeoutMs:e.hitlTimeoutMs,failMode:e.failMode,...e.apiKey?{apiKey:e.apiKey}:{},...e.endpoint?{endpoint:e.endpoint}:{},telemetry:kt()}}async function mr(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 ie({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 Te=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),Z(this.transport,"POST","/api/discovery/fleet/deploy",n)}status(){return Z(this.transport,"GET","/api/discovery/fleet/status")}heartbeat(t){return Z(this.transport,"POST","/api/discovery/fleet/heartbeat",{instance_id:t.instanceId,vendor:t.vendor})}stop(){return Z(this.transport,"POST","/api/discovery/fleet/stop")}};var Ee=class{constructor(t){this.transport=t}transport;connectAws(t){return Z(this.transport,"POST","/api/discovery/integrations/aws",{aws_account_id:t.awsAccountId,aws_region:t.awsRegion})}};function Ta(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 Te(r),integrations:new Ee(r)}}async function Z(e,t,n,r){let i=`${e.baseUrl}${n.startsWith("/")?n:`/${n}`}`,o={...H(B)};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 l=await e.fetchImpl(i,{method:t,headers:o,body:a});if(!l.ok){let c="";try{c=await l.text()}catch{}throw new Error(`[VisIQ] ${t} ${n} failed (${l.status}): ${c||l.statusText}`)}return await l.json()}var gr=cr;gr.delegate=mr;var _l=gr;export{Me as DEFAULT_FAIL_MODE,Te as FleetClient,Ee as IntegrationsClient,Ta as createVisiqClient,mr as delegate,be as normalizeFailMode,_l as visiq};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visiq/harness",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "description": "VisIQ SDK — AI agent governance harness",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",