@visiq/openclaw-plugin 0.1.5 → 0.1.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/LICENSE +21 -0
- package/dist/chunk-PS2DVYPN.js +8 -0
- package/dist/cli/configure.js +9 -9
- package/dist/index.d.ts +5 -2
- package/dist/index.js +1 -1
- package/dist/openclaw-entry.js +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +3 -2
- package/dist/chunk-2TT2F3AO.js +0 -8
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 VisIQ Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{readFile as Ue}from"node:fs/promises";import{homedir as W}from"node:os";import{join as G,isAbsolute as Ve,resolve as Ke}from"node:path";import{createInterface as ze}from"node:readline";import{parseArgs as We}from"node:util";var H="@visiq/openclaw-plugin",Ge='[VisIQ] OpenClaw plugin is installed but missing credentials. Provide them with one of (highest precedence first): (1) environment variables VISIQ_API_KEY=<key> VISIQ_AGENT_ID=<id> (set before `openclaw gateway run` / `openclaw start`) ; (2) a JSON file at the path in VISIQ_CONFIG_PATH ; (3) ~/.openclaw/openclaw.json -> plugins.entries["@visiq/openclaw-plugin"].config = { "apiKey": "<key>", "agentId": "<id>" } . Until credentials are provided the plugin loads but every tool call is BLOCKED (fail-closed, G001) \u2014 configure it to govern.';function He(e){return e==="~"||e.startsWith("~/")?G(W(),e.slice(1).replace(/^\//,"")):e}async function Q(e){try{let t=Ve(e)?e:Ke(e),n=await Ue(t,"utf-8");return JSON.parse(n)}catch{return null}}function D(e,...t){for(let n of t){let r=e[n];if(typeof r=="string")return r}}function F(e){if(!e||typeof e!="object")return{};let t=e,n=D(t,"apiKey","api_key"),r=D(t,"agentId","agent_id"),i=D(t,"baseUrl","base_url"),a={};return n&&(a.apiKey=n),r&&(a.agentId=r),i&&(a.baseUrl=i),a}async function Qe(e){if(!e)return{};let t=He(e),n=await Q(t);if(!n||typeof n!="object")return{};let r=n,i=r.plugins?.entries,a=i&&typeof i=="object"?i[H]:void 0;return a&&typeof a=="object"&&a.config?F(a.config):F(r)}async function Ye(){let e=G(W(),".openclaw","openclaw.json"),t=await Q(e);if(!t||typeof t!="object")return{};let a=t.plugins?.entries?.[H];return!a||typeof a!="object"?{}:F(a.config)}async function Ze(e){if(!process.stdout.isTTY)return{};let t=ze({input:process.stdin,output:process.stdout}),n=r=>new Promise(i=>t.question(r,a=>i(a)));try{let r={...e};if(!r.apiKey){let i=(await n("VisIQ API key: ")).trim();i&&(r.apiKey=i)}if(!r.agentId){let i=(await n("VisIQ agent ID: ")).trim();i&&(r.agentId=i)}if(!r.baseUrl){let i=(await n("VisIQ base URL (optional, press Enter for default): ")).trim();i&&(r.baseUrl=i)}return r}finally{t.close()}}function Je(){try{let{values:e}=We({args:process.argv.slice(2),options:{"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"}},strict:!1,allowPositionals:!0}),t={},n=e["api-key"],r=e["agent-id"],i=e["base-url"];return typeof n=="string"&&n&&(t.apiKey=n),typeof r=="string"&&r&&(t.agentId=r),typeof i=="string"&&i&&(t.baseUrl=i),t}catch{return{}}}async function Y(){let e=Je(),t={};process.env.VISIQ_API_KEY&&(t.apiKey=process.env.VISIQ_API_KEY),process.env.VISIQ_AGENT_ID&&(t.agentId=process.env.VISIQ_AGENT_ID),process.env.VISIQ_BASE_URL?t.baseUrl=process.env.VISIQ_BASE_URL:process.env.VISIQ_ENDPOINT&&(t.baseUrl=process.env.VISIQ_ENDPOINT);let n=await Qe(process.env.VISIQ_CONFIG_PATH),i={...await Ye(),...n,...t,...e};if((!i.apiKey||!i.agentId)&&process.stdout.isTTY&&process.stdin.isTTY&&(i=await Ze(i)),!i.apiKey||!i.agentId)return process.stderr.write(`${Ge}
|
|
2
|
+
`),null;let a={apiKey:i.apiKey,agentId:i.agentId};return i.baseUrl&&(a.baseUrl=i.baseUrl),a}var M=null,Z={ready:!1,config:null};function y(){return M||(M=Y().catch(e=>(process.stderr.write(`[VisIQ] Config resolution failed (treating as unconfigured): ${e instanceof Error?e.message:String(e)}
|
|
3
|
+
`),null)).then(e=>(Z={ready:!0,config:e},e))),M}function E(){return Z}function xn(){y()}import{z as o}from"zod";import*as h from"node:os";var J="X-VisIQ-SDK",X="X-VisIQ-Dialect",ee="unknown";function B(e,t=1){return{[J]:e&&e.length>0?e:ee,[X]:String(t)}}var te="interceptor_source",Xe=o.enum(["enforce","audit","off"]),et=o.enum(["closed","open"]),ne=o.enum(["enforce","monitor","off"]),tt=o.object({apiKey:o.string().min(1,"apiKey is required"),agentId:o.string().min(1,"agentId is required"),endpoint:o.string().url().optional(),mode:Xe.optional(),timeoutMs:o.number().int().positive().optional(),hitlTimeoutMs:o.number().int().positive().optional(),failBehavior:et.optional()}),Ln=o.object({agent_id:o.string().min(1),target_app:o.string().min(1),action:o.string().min(1),context:o.record(o.unknown()).optional(),session_id:o.string().min(1).max(255).optional(),telemetry:o.record(o.unknown()).optional()}),nt=o.object({field:o.string().optional(),pattern:o.string().optional(),replacement:o.string().optional(),mode:o.enum(["full","partial","email"]).optional(),keepFirst:o.number().optional(),keepLast:o.number().optional(),maskChar:o.string().optional()}),rt=o.object({decision_id:o.string().min(1),decision:o.enum(["permit","deny","approval_required","mask"]),reason:o.string().optional(),rule_code:o.string().nullable().optional(),enforced:o.boolean().optional(),agent_mode:ne.optional(),arg_redaction_rules:o.array(nt).optional(),plane:o.string().nullable().optional(),operation:o.string().nullable().optional(),is_retrieval:o.boolean().optional(),metadata:o.record(o.unknown()).optional()}),it=o.object({field:o.string().min(1),operator:o.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:o.union([o.string(),o.number(),o.array(o.string())])}),at=o.object({id:o.string().min(1),rule_code:o.string().default(""),name:o.string().min(1),description:o.string().nullable().default(null),effect:o.enum(["allow","deny","hitl","mask"]),resource_type:o.string().min(1),rego_source:o.string().default(""),target_app:o.string().nullable().default(null),action_pattern:o.string().nullable().default(null),conditions:o.array(it).default([]),priority:o.number().int().default(0)}),ot=o.object({version:o.string().min(1),agent_mode:ne.optional(),rules:o.array(at),no_coverage:o.object({no_coverage_defaults:o.record(o.string()),autopilot_enabled:o.boolean(),enduser_hitl_enabled:o.boolean(),hitl_timeout_seconds:o.number()}).optional()}),st=2e3,re=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}versionHeaders(){return B(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 rt.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 a=await i.json();return ot.parse(a)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...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 a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let c=a,s=c.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 c.reason=="string"?c.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await lt(st)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function lt(e){return new Promise(t=>setTimeout(t,e))}function ie(){let e={};try{let t=`${h.platform()} ${h.release()}`.trim();t&&(e.os=t)}catch{}try{let t=h.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=h.userInfo();t&&(e.username=t)}catch{}try{let t=ct();t&&(e.ip=t)}catch{}return e}function ct(){let e=h.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 u}from"zod";import{createHash as Mn}from"crypto";import{createHash as qn}from"crypto";var ut=["tier1","tier2","tier3"];function se(e){return typeof e=="string"&&ut.includes(e)}var dt=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],pt=["internal","customer_facing","experimental","third_party"],le=[...dt,...pt];function ft(e){return typeof e=="string"&&le.includes(e)}function ce(e){let t=new Set;for(let n of e)ft(n)&&t.add(n);return le.filter(n=>t.has(n))}var gt=["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 ue(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 mt={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 ht(e){let t=ue(e);return t===null?"other":mt[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 ae={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 _t(e){let t=ue(e);return t===null?"other":ae[t]??ae[t.replace(/_/g,"")]??"other"}function de(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=ht(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=_t(t.targetApp)),n.context=r}return n}var oe=64,yt=64,k={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function pe(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var bt=new Set(["deny","approval_required","escalate"]);function T(e,t){if(t.length===0)return[...e];let n=new Set(e);for(let i of t)n.add(i);let r=[...n].sort();return r.length>oe?r.slice(0,oe):r}function vt(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function R(e){return typeof e=="string"&&e.length>0?e:null}function fe(e,t){let n=vt(t.data_categories),r=R(t.classification),i=R(t.action_class),a=i&>.includes(i)?i:null,c=R(t.target_app),s=R(t.decision),l={...e.action_counts};if(a)if(a in l)l[a]=(l[a]??0)+1;else if(Object.keys(l).length<yt)l[a]=1;else{let d=Object.keys(l).sort(),p=d[d.length-1];p!==void 0&&a<p&&(delete l[p],l[a]=1)}return{retrieved_data_categories:T(e.retrieved_data_categories,n),retrieved_classifications:T(e.retrieved_classifications,r?[r]:[]),action_classes:T(e.action_classes,a?[a]:[]),action_counts:l,denied_count:e.denied_count+(s==="deny"?1:0),inhibited_count:e.inhibited_count+(s&&bt.has(s)?1:0),event_count:e.event_count+1,target_apps:T(e.target_apps,c?[c]:[])}}var wt="generic",ge=[{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:wt,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."}],At=ge.map(e=>e.id),Bn=new Map(ge.map(e=>[e.id,e])),$n=new Set(At);var It=/^[a-z][a-z0-9_]*$/;function me(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&It.test(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}var kt=["narrow","moderate","broad","unbounded","unknown"];function he(e){return typeof e=="string"&&kt.includes(e)}function _e(e){return e==="open"||e==="closed"?e:null}var St=["action","retrieval","delegation"];function Ct(e){return typeof e=="string"&&St.includes(e)}var Et=new Set(["rules"]);function ye(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!Et.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(Ct):[];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 x}from"zod";import{randomUUID as un}from"node:crypto";var be=e=>e!==void 0&&e.length>5120?e.slice(0,5120):e;function Tt(e){let t={...e};return t.content?.text!==void 0&&(t.content={...t.content,text:be(t.content.text)}),t.spawn?.prompt!==void 0&&(t.spawn={...t.spawn,prompt:be(t.spawn.prompt)}),t}function Rt(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 xt=1440*60*1e3,Nt="VISIQ_BUNDLE_GRACE_TTL_MS",Ot="VISIQ_BUNDLE_CACHE_DISABLED",Lt="VISIQ_CACHE_DIR",Pt=x.object({graceTtlMs:x.number().int().nonnegative().optional(),disabled:x.boolean().optional(),cacheDir:x.string().min(1).optional()}).strict();function Dt(e){return e==null?{}:Pt.parse(e)}function Ft(e,t=process.env){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;let n=t[Nt];if(n!==void 0){let r=Number(n);if(Number.isInteger(r)&&r>=0)return r}return xt}function Mt(e,t=process.env){if(typeof e=="boolean")return e;let n=(t[Ot]??"").trim().toLowerCase();return n==="1"||n==="true"||n==="yes"}var ve;function Bt(){if(ve!==void 0)return ve;try{return typeof process<"u"&&!!process.versions&&!!process.versions.node}catch{return!1}}function $t(e){return JSON.stringify(j(e))}function j(e){if(Array.isArray(e))return e.map(j);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=j(t[r]);return n}return e}function jt(e,t,n){let r=n-e.fetchedAt;return r<0?!1:r<=t}function qt(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 Ce(){if(!Bt())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 Ee(e,t){return e.createHash("sha256").update($t(t)).digest("hex")}function Ut(e,t){let n=t.cacheDir?.trim();if(n)return n;let r=process.env[Lt]?.trim();if(r)return r;let i=process.env.XDG_CACHE_HOME?.trim();if(i)return e.path.join(i,"visiq");let a="";try{a=e.os.homedir()}catch{a=""}return a?e.path.join(a,".cache","visiq"):e.path.join(e.os.tmpdir(),"visiq-cache")}function Vt(e,t){return e.crypto.createHash("sha256").update(`${t.endpoint}\0${t.agentId}\0${t.apiKey}`).digest("hex")}function Te(e,t,n){return e.path.join(Ut(e,n),"bundles",`${Vt(e,t)}.json`)}async function Kt(e,t,n,r={}){let i=await Ce();if(i)try{let a=Te(i,e,r),c=i.path.dirname(a);await i.fs.mkdir(c,{recursive:!0,mode:448});let s={fetchedAt:r.now??Date.now(),version:n,contentHash:Ee(i.crypto,t),body:t},l=`${a}.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,a)}catch(d){throw await i.fs.rm(l,{force:!0}).catch(()=>{}),d}}catch{}}async function zt(e,t={}){let n=await Ce();if(!n)return null;try{let r=await n.fs.readFile(Te(n,e,t),"utf-8"),i=qt(JSON.parse(r));return!i||Ee(n.crypto,i.body)!==i.contentHash?null:i}catch{return null}}var S;async function Wt(){if(S!==void 0)return S;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;S=typeof t=="function"?t:null}catch{S=null}return S}var Gt=5e3,Ht=1e4,Qt=25,we=1e3,Yt=5e3,Zt=100,Ae=2e3,Jt=512,Xt=1800*1e3,en="monitor",tn="Agent has been shut down by an operator \u2014 all actions are blocked (G001)",nn="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.",rn=u.object({operations:u.array(u.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:u.string().min(1,"agentId is required"),sessionId:u.string().min(1).max(255).optional(),toolName:u.string().optional(),toolArgs:u.record(u.unknown()).optional(),targetResource:u.string().optional(),resourceType:u.string().optional(),resourceMetadata:u.record(u.unknown()).optional(),normalized:u.record(u.unknown()).optional(),query:u.string().optional(),contentPreview:u.string().optional(),telemetry:u.record(u.unknown()).optional(),context:u.record(u.unknown()).optional()}),an=u.object({version:u.string().min(1),dialect_version:u.number().int().optional(),min_dialect:u.number().int().optional(),shutdown:u.boolean().optional(),agent_mode:u.enum(["enforce","monitor","off"]).optional(),cognition_capture:u.boolean().optional(),agent_mode_by_operation:u.object({action:u.string().optional(),retrieval:u.string().optional(),delegation:u.string().optional()}).partial().optional(),agent_attributes:u.object({trust_tier:u.string().nullable().optional(),categories:u.array(u.string()).optional(),business_function:u.string().nullable().optional(),business_functions:u.array(u.string()).nullable().optional(),blast_radius_tier:u.string().nullable().optional(),no_coverage:u.string().nullable().optional()}).optional(),rules:u.array(u.record(u.unknown())),no_coverage:u.object({no_coverage_defaults:u.record(u.string()),autopilot_enabled:u.boolean(),enduser_hitl_enabled:u.boolean(),hitl_timeout_seconds:u.number().optional()}).optional()});function on(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=me(n);return{trust_tier:se(t)?t:null,categories:ce(e.categories??[]),business_functions:r,business_function:r[0]??null,blast_radius_tier:typeof e.blast_radius_tier=="string"&&he(e.blast_radius_tier)?e.blast_radius_tier:null}}function sn(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 ln(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var q=new Set,Ie=!1;async function ke(e){let t=[];for(let n of q){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 cn(){if(!Ie&&!(typeof process>"u"||typeof process.once!="function")){Ie=!0,process.once("beforeExit",()=>{ke(!1)});for(let e of["SIGINT","SIGTERM"])process.once(e,()=>{(async()=>{try{await ke(!0)}finally{process.kill(process.pid,e)}})()})}}var Re=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=en;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,a,c,s){let l=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,d=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,p=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";this.resolvedApiKey=l,this.resolvedEndpoint=d,this.resolvedAgentId=p,this.harnessKind=r,this.sdkVersion=a,this.sdkDialect=c,this.originalFetch=globalThis.fetch.bind(globalThis);let f=Dt(s);if(this.bundleCacheDisabled=Mt(f.disabled),this.bundleGraceTtlMs=Ft(f.graceTtlMs),this.bundleCacheDirOverride=f.cacheDir,this.cacheIdentity=l&&d&&!this.bundleCacheDisabled?{endpoint:d,agentId:p,apiKey:l}:null,l&&d){let m={apiKey:l,agentId:p,endpoint:d,mode:"enforce",timeoutMs:Rt(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{},...a!==void 0?{sdkVersion:a}:{},...c!==void 0?{sdkDialect:c}:{}};this.client=new re(m,this.originalFetch),this.initialBundlePromise=this.initialBundleLoad(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},Gt),$(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},Ht),$(this.telemetryTimer),this.cognitionTimer=setInterval(()=>{this.flushCognition()},Yt),$(this.cognitionTimer),q.add(this),cn()}else this.client=null}async evaluate(e){let t=rn.parse(e),n=Date.now();if(this.operatorShutdown){let l=this.denyAll(t,tn);return this.applyAgentMode(l,"enforce",t,n)}if(this.dialectRefused){let l=this.denyAll(t,nn);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 d=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(d,l,t,n)}let r=this.readSession(t.sessionId),i=await Wt();if(!i||!this.rawBundle)throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)");let a={...t,session:r,at:Date.now()},c={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},s=i(a,c);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 k;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>Xt?(this.sessions.delete(e),k):t.state:k}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),c=e.operations.includes("action")||e.operations.includes("delegation"),s=c?de(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},l=fe(r===k?pe():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,action_class:c?s.action_class:void 0,target_app:c?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>Jt){let d=this.sessions.keys().next().value;d!==void 0&&this.sessions.delete(d)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let c={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,c,i,!0),c}let a={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,a,i,!1),a}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=an.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=>ye(r)).filter(r=>r!==null),this.agentAttributes=t.agent_attributes?on(t.agent_attributes):null,this.agentNoCoverage=_e(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=sn(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",...B(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 a=this.bundleLoaded&&!this.dialectRefused&&!this.bundleApplyFailed;r&&a?this.bundleEtag=r:a||(this.bundleEtag=null),a&&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 zt(this.cacheIdentity,{...this.bundleCacheDirOverride?{cacheDir:this.bundleCacheDirOverride}:{}})}catch{return}if(!e)return;let t=Date.now();if(jt(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 Kt(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({...ie(),...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?ln(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?{[te]:this.harnessKind}:{},...e.context??{}}}:{}}),this.enforceTelemetryCap(),this.telemetryBuffer.length>=Qt&&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-we;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${we})`))}isCognitionEnabled(){return this.cognitionEnabled}emitCognition(e){!this.cognitionEnabled||!this.client||(this.cognitionBuffer.push(Tt(e)),this.enforceCognitionCap(),this.cognitionBuffer.length>=Zt&&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-Ae;e>0&&(this.cognitionBuffer.splice(0,e),console.warn(`[UnifiedRuntime] cognition buffer full \u2014 dropped ${e} oldest beats (cap ${Ae})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry(),await this.flushCognition()}async shutdown(){await this.flush(),this.dispose(),q.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 $(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}function C(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function xe(e,t){if(e!=="sessions_spawn")return null;let n=C(t.agentId);return n?{childAgentId:n,childName:C(t.taskName)??C(t.label)??n,kind:"subagent",task:C(t.task),model:C(t.model),source:"structural"}:null}function Ne(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 Se=new Map;function dn(e){let t=(Se.get(e)??0)+1;return Se.set(e,t),t}function Oe(e,t,n){if(!e||typeof e.isCognitionEnabled!="function"||!e.isCognitionEnabled())return;let r=t.sessionId&&t.sessionId.length>0?t.sessionId:t.agentId;e.emitCognition({clientEventId:un(),agentId:t.agentId,sessionId:r,threadId:t.agentId,parentId:t.agentId,seq:dn(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}:{}}})}var v=null;function U(e){let t=`${e.apiKey}::${e.agentId}::${e.baseUrl??""}`;if(v&&v.key===t)return v.runtimes;let n=new Re(e.apiKey,e.baseUrl,e.agentId,"cli_harness");return n.registerHostEnvironment(),v={key:t,runtimes:{unified:n}},v.runtimes}async function Xn(){if(v)try{await v.runtimes.unified.flush()}catch{}}async function er(e){try{let t=await y();if(!t)return;let{unified:n}=U(t);await n.awaitBundleReady(e)}catch{}}function b(e,t){return e?.sessionKey??t?.sessionKey??t?.sessionId??"default"}var V=class{entries=new Map;set(t,n){this.entries.set(t,n)}get(t){return this.entries.get(t)}delete(t){this.entries.delete(t)}clear(){this.entries.clear()}size(){return this.entries.size}},K=new Map;function A(e){let t=K.get(e);return t||(t=new V,K.set(e,t)),t}function Le(e){K.delete(e)}var Pe=new Set(["web_search","x_search","web_fetch","tool_search","tool_describe","get_account","get_transactions","get_devices","check_watchlist","search_knowledge"]);function pn(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}function De(e){return Pe.has(pn(e))}function rr(){return Pe}var fn=[{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 g=Object.fromEntries(fn.map(e=>[e.name,e.re.source])),gn=["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"],mn={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
4
|
+
MIIEv\u2026
|
|
5
|
+
-----END PRIVATE KEY-----`,template:{pattern:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.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:g.mac_address,mode:"full"},defaultEnabled:!1}},ar=new Set(gn.filter(e=>!mn[e].defaultEnabled));var z="[REDACTED]",I="\u2022",N=e=>/[A-Za-z0-9]/.test(e);function Fe(e,t,n,r){let i=Array.from(e),a=i.length,c=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),l=r.length>0?r:I,d=c+s>=a;return i.map((p,f)=>!d&&(f<c||f>=a-s)?p:N(p)?l:p).join("")}function hn(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return Fe(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:I;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(c=>N(c)?a:c).join(""))+i}function _n(e,t,n){let r=n.length>0?n:I,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let d=new RegExp(t,"g"),p;for(;(p=d.exec(e))!==null;){if(p[0].length===0){d.lastIndex++;continue}for(let f=p.index;f<p.index+p[0].length;f++)i[f]=!0}}catch{}let a=!1,c=!0;for(let d=0;d<e.length;d++)if(N(e[d])&&(a=!0,!i[d])){c=!1;break}let s=a&&c,l="";for(let d=0;d<e.length;d++){let p=e[d];!s&&i[d]||!N(p)?l+=p:l+=r}return l}function Me(e,t){let n=t.mode??"full";return n==="partial"?Fe(e,t.keepFirst??0,t.keepLast??0,t.maskChar??I):n==="email"?hn(e,t.maskChar??I):n==="custom"?_n(e,t.keepPattern,t.maskChar??I):t.replacement??z}function yn(e,t){return typeof e=="string"?Me(e,t):t.replacement??z}function Be(e){let t=[],n=e.replacement??z;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:a=>Me(a,r)})}return t}function $e(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(c){let s=c instanceof Error?c.message:String(c);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(a,c=>i(c))}return n}function O(e,t){return e==null?e:typeof e=="string"?bn(e,t):typeof e=="object"?vn(e,t):e}function bn(e,t){if(typeof e!="string")return e;let n=Be(t);return n.length===0?e:$e(e,n)}function vn(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=Be(t),i=n.size>0,a=r.length>0,c=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(l=>c(l));if(typeof s=="object"){let l=s,d=Object.create(Object.getPrototypeOf(l));for(let p of Object.keys(l)){let f=i?n.get(p):void 0;if(f){d[p]=yn(l[p],f);continue}d[p]=c(l[p])}return d}return typeof s=="string"&&a?$e(s,r):s};return c(e)}var je="@visiq/openclaw-plugin";function qe(e){let t=[],n=[],r;for(let a of e){let{field:c,pattern:s,replacement:l}=a;c&&t.push(c),s&&n.push(s),l&&r===void 0&&(r=l)}let i={};return t.length>0&&(i.fields=t),n.length>0&&(i.patterns=n),r!==void 0&&(i.replacement=r),i}async function fr(e,t){let n=await y();if(!n)return{block:!0,blockReason:"[VisIQ] Plugin is loaded but NOT configured \u2014 VisIQ cannot govern this tool call, so it is blocked (fail-closed). Set VISIQ_API_KEY + VISIQ_ENDPOINT (or the plugin config) so VisIQ can evaluate the call, then retry."};let r=U(n),i=n.agentId??t.agentId,a=b(e,t),c=t.toolCallId??e.toolCallId,l=De(e.toolName)?["retrieval","action"]:["action"],d=wn(e.params),p=xe(e.toolName,e.params??{}),f;p&&i&&(Oe(r.unified,{agentId:i,sessionId:a,framework:"openclaw"},p),l.push("delegation"),f=Ne(p,i));let m;try{await r.unified.awaitBundleReady(),m=await r.unified.evaluate({operations:l,agentId:i,sessionId:a,toolName:e.toolName,toolArgs:e.params??{},resourceType:"tool_result",resourceMetadata:{toolName:e.toolName,runId:e.runId??t.runId},...d!==void 0?{query:d}:{},...f?{context:f}:{}})}catch(_){return{block:!0,blockReason:`[VisIQ] Evaluation error (fail-closed): ${_ instanceof Error?_.message:String(_)}`}}if(!m.enforced)return;let{action:w}=m;if(w.decision==="approval_required")return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:m.reason,severity:"critical",allowedDecisions:["allow-once","allow-always","deny"],pluginId:je}};if(!w.allowed)return{block:!0,blockReason:`[VisIQ ${m.ruleCode??"DENY"}] ${m.reason}`};let P;if(w.decision==="mask"&&w.argRedactionRules&&w.argRedactionRules.length>0&&(P=O(e.params??{},qe(w.argRedactionRules))),l.includes("retrieval"))switch(m.retrieval.action){case"allow":case null:break;case"deny":return{block:!0,blockReason:`[VisIQ RECALL] ${m.reason}`};case"redact":{if(!c)return{block:!0,blockReason:"[VisIQ RECALL] Redact decision but no toolCallId \u2014 fail-closed"};let _=m.retrieval.redactionRules??[];_.length>0&&A(a).set(c,qe(_));break}case"escalate":return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:m.reason,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:je}};default:{let _=m.retrieval.action;return{block:!0,blockReason:`[VisIQ RECALL] Unknown action "${String(_)}" \u2014 fail-closed`}}}if(P)return{params:P}}function wn(e){if(e)for(let t of["query","q","url","prompt"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}}function yr(e,t){let{ready:n,config:r}=E();if(!n||!r)return;let i=e.toolCallId??t.toolCallId;if(!i)return;let a=b(e,t),c=A(a),s=c.get(i);if(!s)return;let l={...e.message};return l.content!==void 0&&(l.content=O(l.content,s)),c.delete(i),{message:l}}function Ar(e,t){let{ready:n,config:r}=E();if(n&&!r)return;let i=b(e,t),a=A(i);if(a.size()>0)return a.clear(),{block:!0}}async function L(e,t){let r=`${(e.baseUrl??"https://api.visiqlabs.com").replace(/\/$/,"")}/v1/events`;try{let i=new AbortController,a=setTimeout(()=>i.abort(),5e3);try{let c=await fetch(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(t),signal:i.signal});c.ok||process.stderr.write(`[VisIQ] /v1/events POST failed: ${c.status} ${c.statusText}
|
|
6
|
+
`);try{await c.text()}catch{}}finally{clearTimeout(a)}}catch(i){if(i instanceof Error&&i.name==="AbortError"){process.stderr.write(`[VisIQ] /v1/events POST timed out (5s)
|
|
7
|
+
`);return}process.stderr.write(`[VisIQ] /v1/events POST error: ${i instanceof Error?i.message:String(i)}
|
|
8
|
+
`)}}async function Er(e,t){let n=await y();if(!n)return;let r=n.agentId??t.agentId;L(n,{type:"llm_input",agentId:r,sessionId:e.sessionId??t.sessionId??t.sessionKey,runId:e.runId??t.runId,timestamp:new Date().toISOString(),payload:{provider:e.provider,model:e.model,hasSystemPrompt:typeof e.systemPrompt=="string"&&e.systemPrompt.length>0,promptLength:typeof e.prompt=="string"?e.prompt.length:0,historyMessageCount:Array.isArray(e.historyMessages)?e.historyMessages.length:0,imagesCount:e.imagesCount??0,toolCount:Array.isArray(e.tools)?e.tools.length:0}})}function An(e){if(!Array.isArray(e))return 0;let t=0;for(let n of e)typeof n=="string"&&(t+=n.length);return t}async function Nr(e,t){let n=await y();if(!n)return;let r=n.agentId??t.agentId;L(n,{type:"llm_output",agentId:r,sessionId:e.sessionId??t.sessionId??t.sessionKey,runId:e.runId??t.runId,timestamp:new Date().toISOString(),payload:{provider:e.provider,model:e.model,resolvedRef:e.resolvedRef,harnessId:e.harnessId,assistantSegmentCount:Array.isArray(e.assistantTexts)?e.assistantTexts.length:0,assistantTotalChars:An(e.assistantTexts),usage:e.usage??null}})}function Pr(e,t){Le(b(e,t))}export{Y as a,xn as b,Xn as c,er as d,V as e,A as f,Le as g,pn as h,De as i,rr as j,fr as k,yr as l,Ar as m,Er as n,Nr as o,Pr as p};
|
package/dist/cli/configure.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFile as
|
|
3
|
-
`,{mode:384})}async function
|
|
4
|
-
`),process.stdout.write(`Writing to: ${
|
|
2
|
+
import{readFile as m,writeFile as R,mkdir as v}from"node:fs/promises";import{homedir as y}from"node:os";import{dirname as I,join as C,resolve as E}from"node:path";import{fileURLToPath as N}from"node:url";import{createInterface as k}from"node:readline";var l="@visiq/openclaw-plugin",p=C(y(),".openclaw","openclaw.json");function A(){return E(I(N(import.meta.url)),"..","..")}function u(e,r){return new Promise(s=>e.question(r,n=>s(n)))}function b(e=process.env){return e.VISIQ_CONFIGURE_NONINTERACTIVE&&e.VISIQ_CONFIGURE_NONINTERACTIVE!=="0"?!0:!process.stdin.isTTY}function _(e=process.env){let r=(e.VISIQ_API_KEY??"").trim(),s=(e.VISIQ_AGENT_ID??"").trim(),n=(e.VISIQ_BASE_URL??"").trim();if(!r)throw new Error("VISIQ_API_KEY is required in non-interactive mode");if(!s)throw new Error("VISIQ_AGENT_ID is required in non-interactive mode");let t={apiKey:r,agentId:s};return n.length>0&&(t.baseUrl=n),t}async function h(e,r=p,s=A()){let n;try{let d=await m(r,"utf-8"),i=JSON.parse(d);n=i&&typeof i=="object"&&!Array.isArray(i)?i:{}}catch{n={}}let t=n.plugins??{},o=t.load??{},a=Array.isArray(o.paths)?o.paths.filter(d=>typeof d=="string"):[];a.includes(s)||a.push(s),o.paths=a,t.load=o;let c=t.entries??{},g=c[l]??{},w=g.hooks??{},f={apiKey:e.apiKey,agentId:e.agentId};e.baseUrl&&(f.baseUrl=e.baseUrl),c[l]={...g,enabled:!0,hooks:{...w,allowConversationAccess:!0},config:f},t.entries=c,n.plugins=t,await v(I(r),{recursive:!0,mode:448}),await R(r,`${JSON.stringify(n,null,2)}
|
|
3
|
+
`,{mode:384})}async function P(){let e=k({input:process.stdin,output:process.stdout});try{process.stdout.write(`Configuring ${l}
|
|
4
|
+
`),process.stdout.write(`Writing to: ${p}
|
|
5
5
|
|
|
6
|
-
`);let
|
|
7
|
-
`),null;let
|
|
8
|
-
`),null;let
|
|
9
|
-
Wrote credentials to ${
|
|
6
|
+
`);let r=(await u(e,"VisIQ API key: ")).trim();if(!r)return process.stderr.write(`No API key provided. Aborting.
|
|
7
|
+
`),null;let s=(await u(e,"VisIQ agent ID: ")).trim();if(!s)return process.stderr.write(`No agent ID provided. Aborting.
|
|
8
|
+
`),null;let n=(await u(e,"VisIQ base URL (optional, press Enter for default): ")).trim(),t={apiKey:r,agentId:s};return n.length>0&&(t.baseUrl=n),t}finally{e.close()}}async function U(){let e;if(b()?e=_():e=await P(),!e){process.exitCode=1;return}await h(e),process.stdout.write(`
|
|
9
|
+
Wrote credentials to ${p}
|
|
10
10
|
`),process.stdout.write(`You can now start OpenClaw with the VisIQ plugin enabled.
|
|
11
|
-
`)}var
|
|
12
|
-
`),process.exit(1)});export{
|
|
11
|
+
`)}var V=(()=>{let e=process.argv[1];return e?import.meta.url.endsWith(e)||import.meta.url.includes(e):!1})();V&&U().catch(e=>{process.stderr.write(`[VisIQ configure] ${e instanceof Error?e.message:String(e)}
|
|
12
|
+
`),process.exit(1)});export{b as isNonInteractive,_ as resolveCredsFromEnv,A as resolvePluginPackageRoot,h as writeCreds};
|
package/dist/index.d.ts
CHANGED
|
@@ -14,8 +14,11 @@
|
|
|
14
14
|
* options and return null
|
|
15
15
|
*
|
|
16
16
|
* This function NEVER throws. The plugin must remain installable / loadable
|
|
17
|
-
* even when unconfigured; downstream hooks
|
|
18
|
-
* function returns null
|
|
17
|
+
* even when unconfigured; but downstream enforcement hooks FAIL-CLOSED (BLOCK)
|
|
18
|
+
* when this function returns null (reform Phase 3, owner decision #2) — a
|
|
19
|
+
* security harness that cannot reach its policy engine must never silently let
|
|
20
|
+
* tool calls through. loadConfig itself just returns null + warns; the block
|
|
21
|
+
* happens in the hooks (see before-tool-call.ts).
|
|
19
22
|
*
|
|
20
23
|
* G004: never logs the resolved apiKey value, only its presence/absence.
|
|
21
24
|
*/
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as w,c as g,d as _,e as d,f as k,g as f,h as e,i as t,j as h,k as i,l as s,m as l,n as a,o as u,p}from"./chunk-
|
|
1
|
+
import{a as w,c as g,d as _,e as d,f as k,g as f,h as e,i as t,j as h,k as i,l as s,m as l,n as a,o as u,p}from"./chunk-PS2DVYPN.js";var c=new Set(["place_hold","block_card","wire_transfer","create_case","send_notification","bank_account_lookup_tool","exec","write_file","http_post","http_put","http_delete"]),N=new Set(["sessions_list","sessions_history","sessions_send","sessions_get","sessions_create","sessions_delete","memory_search","memory_read","memory_write"]),T=["sessions_","memory_"];function I(o){let r=e(o);return N.has(r)?!0:T.some(m=>r.startsWith(m))}function x(o){return!(t(o)||I(o))}function R(o){return c.has(e(o))}function O(){return c}var n="@visiq/openclaw-plugin";function b(){return{id:n,name:"VisIQ OpenClaw Plugin",version:"0.1.7",hooks:[{pluginId:n,hookName:"before_tool_call",handler:i,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"tool_result_persist",handler:s,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"before_message_write",handler:l,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"llm_input",handler:a,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"llm_output",handler:u,source:"visiq-openclaw-plugin"},{pluginId:n,hookName:"session_end",handler:p,source:"visiq-openclaw-plugin"}]}}var S=b;export{d as RedactionLedger,_ as awaitRuntimesReady,e as bareToolName,f as clearLedger,b as createPlugin,S as default,O as getActionToolNames,k as getLedger,h as getRetrievalToolNames,x as isActionTool,R as isKnownActionTool,t as isRetrievalTool,w as loadConfig,g as shutdownRuntimes};
|
package/dist/openclaw-entry.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as w,k as b,l as S,m as k,n as L,o as v,p as O}from"./chunk-
|
|
1
|
+
import{b as w,k as b,l as S,m as k,n as L,o as v,p as O}from"./chunk-PS2DVYPN.js";import{Type as e}from"typebox";import{definePluginEntry as D}from"openclaw/plugin-sdk/plugin-entry";import{readFileSync as x,readdirSync as A,statSync as C,existsSync as R}from"node:fs";import{join as p,dirname as $}from"node:path";import{fileURLToPath as P}from"node:url";var U="@visiq/openclaw-plugin",h=process.env.BANK_API_URL??"http://localhost:4000/api",I=$(P(import.meta.url));function c(n,i={}){return{content:[{type:"text",text:n}],details:i}}async function m(n){let i=await fetch(`${h}${n}`);return i.ok?await i.text():`[Error ${i.status}]`}async function d(n,i){let t=await fetch(`${h}${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return t.ok?await t.text():`[Error ${t.status}]`}function j(){let n=[p(I,"..","..","..","examples","langchain-agent","docs"),p(I,"..","..","examples","langchain-agent","docs"),process.env.VISIQ_KNOWLEDGE_DIR??""].filter(i=>i.length>0);for(let i of n)if(R(i))return i;return null}function N(){let n=j();if(!n)return[];let i=[];function t(o){for(let s of A(o)){let r=p(o,s);if(C(r).isDirectory())t(r);else if(s.endsWith(".txt")){let l=x(r,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(l){let a={};for(let _ of l[1].split(`
|
|
2
2
|
`)){let[g,...y]=_.split(":");g&&y.length&&(a[g.trim()]=y.join(":").trim())}i.push({path:r,title:a.title?.replace(/"/g,"")??s,classification:a.classification??"public",source:a.source??"unknown",content:l[2].trim()})}}}}return t(n),i}var f=null;function B(){return f===null&&(f=N()),f}function T(n,i=5){let t=B(),o=n.toLowerCase().split(/\s+/).filter(r=>r.length>=3);return t.map(r=>{let u=`${r.title} ${r.content}`.toLowerCase(),l=0;for(let a of o)u.includes(a)&&(l+=a.length,r.title.toLowerCase().includes(a)&&(l+=a.length*2));return{doc:r,score:l}}).filter(r=>r.score>0).sort((r,u)=>u.score-r.score).slice(0,i).map(r=>r.doc)}function K(n){w(),n.on("before_tool_call",b,{priority:50}),n.on("tool_result_persist",S),n.on("before_message_write",k),n.on("llm_input",L),n.on("llm_output",v),n.on("session_end",O),n.registerTool({name:"get_account",label:"Get account",description:"Get account holder profile from core banking system. Input: account ID (e.g. '4821-7734'). Returns: holder name, balance, risk score, KYC status, linked cards, address.",parameters:e.Object({account_id:e.String({description:"Account ID (e.g. '4821-7734')."})}),async execute(i,t){return c(await m(`/accounts/${t.account_id}`))}}),n.registerTool({name:"get_devices",label:"Get devices",description:"Get device fingerprints and login sessions from BioCatch. Input: account ID. Returns: registered devices, recent sessions with IP/geolocation, anomaly alerts.",parameters:e.Object({account_id:e.String({description:"Account ID to fetch devices for."})}),async execute(i,t){return c(await m(`/accounts/${t.account_id}/devices`))}}),n.registerTool({name:"get_transactions",label:"Get transactions",description:"Get recent transactions from the card processor with filtering. Returns: transaction list with amounts, merchants, locations, and risk flags.",parameters:e.Object({account_id:e.String({description:"Account ID (e.g. '4821-7734')."}),lookback_hours:e.Optional(e.Integer({minimum:1,maximum:720,description:"How far back to look (1\u2013720h, default 72)."})),min_amount:e.Optional(e.Number({minimum:0,description:"Filter out transactions below this dollar amount."}))}),async execute(i,t){let o=new URLSearchParams;t.lookback_hours!==void 0&&o.set("lookback_hours",String(t.lookback_hours)),t.min_amount!==void 0&&o.set("min_amount",String(t.min_amount));let s=o.toString()?`?${o.toString()}`:"";return c(await m(`/accounts/${t.account_id}/transactions${s}`))}}),n.registerTool({name:"check_watchlist",label:"Check watchlist",description:"Screen a name or entity against OFAC SDN, EU, and UN sanctions lists. Returns: match scores and recommendation.",parameters:e.Object({name:e.String({description:"Name or entity to screen."}),country_code:e.Optional(e.String({description:"ISO 3166-1 alpha-2 country code to scope the screening (e.g. 'US')."}))}),async execute(i,t){return c(await d("/watchlists/check",{name:t.name,country_code:t.country_code}))}}),n.registerTool({name:"search_knowledge",label:"Search knowledge base",description:"Search the bank's internal knowledge base for compliance policies, prior fraud case files, triage procedures, and customer information. Input is a free-text search query.",parameters:e.Object({query:e.String({description:"Free-text knowledge base search query."})}),async execute(i,t){let o=T(t.query,5);if(o.length===0)return c("No matching knowledge base documents found.",{hitCount:0});let s=o.map(r=>`--- ${r.title} (classification=${r.classification}, source=${r.source}) ---
|
|
3
3
|
${r.content}`).join(`
|
|
4
4
|
|
package/openclaw.plugin.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@visiq/openclaw-plugin",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "OpenClaw plugin for VisIQ ALLOW + RECALL + RECORD",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"dependencies": {
|
|
31
31
|
"zod": "^3.23.8",
|
|
32
32
|
"typebox": "^1.1.38",
|
|
33
|
-
"@visiq/core-wasm": "^0.1.
|
|
33
|
+
"@visiq/core-wasm": "^0.1.3"
|
|
34
34
|
},
|
|
35
35
|
"peerDependencies": {
|
|
36
36
|
"@langchain/core": ">=0.3.0",
|
|
@@ -55,6 +55,7 @@
|
|
|
55
55
|
"files": [
|
|
56
56
|
"dist",
|
|
57
57
|
"README.md",
|
|
58
|
+
"LICENSE",
|
|
58
59
|
"openclaw.plugin.json",
|
|
59
60
|
"skills"
|
|
60
61
|
],
|
package/dist/chunk-2TT2F3AO.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{readFile as ve}from"node:fs/promises";import{homedir as $}from"node:os";import{join as q,isAbsolute as Ae,resolve as we}from"node:path";import{createInterface as Ie}from"node:readline";import{parseArgs as ke}from"node:util";var B="@visiq/openclaw-plugin",Se='[VisIQ] OpenClaw plugin is installed but missing credentials. Provide them with one of (highest precedence first): (1) environment variables VISIQ_API_KEY=<key> VISIQ_AGENT_ID=<id> (set before `openclaw gateway run` / `openclaw start`) ; (2) a JSON file at the path in VISIQ_CONFIG_PATH ; (3) ~/.openclaw/openclaw.json -> plugins.entries["@visiq/openclaw-plugin"].config = { "apiKey": "<key>", "agentId": "<id>" } . Plugin will load but all hooks will no-op until credentials are provided.';function Ce(e){return e==="~"||e.startsWith("~/")?q($(),e.slice(1).replace(/^\//,"")):e}async function U(e){try{let t=Ae(e)?e:we(e),n=await ve(t,"utf-8");return JSON.parse(n)}catch{return null}}function O(e,...t){for(let n of t){let r=e[n];if(typeof r=="string")return r}}function N(e){if(!e||typeof e!="object")return{};let t=e,n=O(t,"apiKey","api_key"),r=O(t,"agentId","agent_id"),i=O(t,"baseUrl","base_url"),a={};return n&&(a.apiKey=n),r&&(a.agentId=r),i&&(a.baseUrl=i),a}async function Ee(e){if(!e)return{};let t=Ce(e),n=await U(t);if(!n||typeof n!="object")return{};let r=n,i=r.plugins?.entries,a=i&&typeof i=="object"?i[B]:void 0;return a&&typeof a=="object"&&a.config?N(a.config):N(r)}async function Te(){let e=q($(),".openclaw","openclaw.json"),t=await U(e);if(!t||typeof t!="object")return{};let a=t.plugins?.entries?.[B];return!a||typeof a!="object"?{}:N(a.config)}async function xe(e){if(!process.stdout.isTTY)return{};let t=Ie({input:process.stdin,output:process.stdout}),n=r=>new Promise(i=>t.question(r,a=>i(a)));try{let r={...e};if(!r.apiKey){let i=(await n("VisIQ API key: ")).trim();i&&(r.apiKey=i)}if(!r.agentId){let i=(await n("VisIQ agent ID: ")).trim();i&&(r.agentId=i)}if(!r.baseUrl){let i=(await n("VisIQ base URL (optional, press Enter for default): ")).trim();i&&(r.baseUrl=i)}return r}finally{t.close()}}function Re(){try{let{values:e}=ke({args:process.argv.slice(2),options:{"api-key":{type:"string"},"agent-id":{type:"string"},"base-url":{type:"string"}},strict:!1,allowPositionals:!0}),t={},n=e["api-key"],r=e["agent-id"],i=e["base-url"];return typeof n=="string"&&n&&(t.apiKey=n),typeof r=="string"&&r&&(t.agentId=r),typeof i=="string"&&i&&(t.baseUrl=i),t}catch{return{}}}async function W(){let e=Re(),t={};process.env.VISIQ_API_KEY&&(t.apiKey=process.env.VISIQ_API_KEY),process.env.VISIQ_AGENT_ID&&(t.agentId=process.env.VISIQ_AGENT_ID),process.env.VISIQ_BASE_URL?t.baseUrl=process.env.VISIQ_BASE_URL:process.env.VISIQ_ENDPOINT&&(t.baseUrl=process.env.VISIQ_ENDPOINT);let n=await Ee(process.env.VISIQ_CONFIG_PATH),i={...await Te(),...n,...t,...e};if((!i.apiKey||!i.agentId)&&process.stdout.isTTY&&process.stdin.isTTY&&(i=await xe(i)),!i.apiKey||!i.agentId)return process.stderr.write(`${Se}
|
|
2
|
-
`),null;let a={apiKey:i.apiKey,agentId:i.agentId};return i.baseUrl&&(a.baseUrl=i.baseUrl),a}var P=null,z={ready:!1,config:null};function h(){return P||(P=W().catch(e=>(process.stderr.write(`[VisIQ] Config resolution failed (treating as unconfigured): ${e instanceof Error?e.message:String(e)}
|
|
3
|
-
`),null)).then(e=>(z={ready:!0,config:e},e))),P}function k(){return z}function Lt(){h()}import{z as o}from"zod";import*as m from"node:os";var K="interceptor_source",Oe=o.enum(["enforce","audit","off"]),Ne=o.enum(["closed","open"]),V=o.enum(["enforce","monitor","off"]),Pe=o.object({apiKey:o.string().min(1,"apiKey is required"),agentId:o.string().min(1,"agentId is required"),endpoint:o.string().url().optional(),mode:Oe.optional(),timeoutMs:o.number().int().positive().optional(),hitlTimeoutMs:o.number().int().positive().optional(),failBehavior:Ne.optional()}),jt=o.object({agent_id:o.string().min(1),target_app:o.string().min(1),action:o.string().min(1),context:o.record(o.unknown()).optional(),session_id:o.string().min(1).max(255).optional(),telemetry:o.record(o.unknown()).optional()}),Le=o.object({field:o.string().optional(),pattern:o.string().optional(),replacement:o.string().optional(),mode:o.enum(["full","partial","email"]).optional(),keepFirst:o.number().optional(),keepLast:o.number().optional(),maskChar:o.string().optional()}),Fe=o.object({decision_id:o.string().min(1),decision:o.enum(["permit","deny","approval_required","mask"]),reason:o.string().optional(),rule_code:o.string().nullable().optional(),enforced:o.boolean().optional(),agent_mode:V.optional(),arg_redaction_rules:o.array(Le).optional(),plane:o.string().nullable().optional(),operation:o.string().nullable().optional(),is_retrieval:o.boolean().optional(),metadata:o.record(o.unknown()).optional()}),Me=o.object({field:o.string().min(1),operator:o.enum(["equals","in","not_equals","not_in","glob","gt","lt","gte","lte","contains","not_contains"]),value:o.union([o.string(),o.number(),o.array(o.string())])}),je=o.object({id:o.string().min(1),rule_code:o.string().default(""),name:o.string().min(1),description:o.string().nullable().default(null),effect:o.enum(["allow","deny","hitl","mask"]),resource_type:o.string().min(1),rego_source:o.string().default(""),target_app:o.string().nullable().default(null),action_pattern:o.string().nullable().default(null),conditions:o.array(Me).default([]),priority:o.number().int().default(0)}),De=o.object({version:o.string().min(1),agent_mode:V.optional(),rules:o.array(je),no_coverage:o.object({no_coverage_defaults:o.record(o.string()),autopilot_enabled:o.boolean(),enduser_hitl_enabled:o.boolean(),hitl_timeout_seconds:o.number()}).optional()}),$e=2e3,G=class{config;originalFetch;constructor(e,t){this.config=e,this.originalFetch=t}async evaluate(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeoutMs),r;try{r=await this.originalFetch(`${this.config.endpoint}/allow/evaluate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(e),signal:t.signal})}finally{clearTimeout(n)}if(!r.ok)throw new Error(`ALLOW evaluate request failed: HTTP ${r.status} ${r.statusText}`);let i=await r.json();return Fe.parse(i)}async fetchBundle(){let e=this.config.agentId?`?agent_id=${encodeURIComponent(this.config.agentId)}`:"",t=`${this.config.endpoint}/allow/rules/bundle${e}`,n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/json"},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW rules/bundle fetch failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();return De.parse(a)}async sendTelemetry(e){if(e.length===0)return;let t=`${this.config.endpoint}/allow/telemetry`,n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decisions:e})});if(!n.ok)throw new Error(`ALLOW telemetry delivery failed: HTTP ${n.status} ${n.statusText}`)}async reportExecutionResult(e,t,n){let r=`${this.config.endpoint}/allow/execution-events`;try{let i=await this.originalFetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({decision_id:e,result:t,details:n})});i.ok||console.warn(`[ALLOW] Execution result report failed: HTTP ${i.status}`)}catch(i){console.warn("[ALLOW] Execution result report failed:",i)}}async registerEnvironment(e){if(!this.config.agentId)return;let t=`${this.config.endpoint}/allow/agents/register`;try{let n=await this.originalFetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({agent_id:this.config.agentId,os:e.os,hostname:e.hostname,ip:e.ip,username:e.username,...this.config.harnessKind?{kind:this.config.harnessKind}:{}})});n.ok||console.warn(`[ALLOW] Agent registration failed: HTTP ${n.status} ${n.statusText}`)}catch(n){console.warn("[ALLOW] Agent registration failed:",n)}}async waitForApproval(e){if(!e)throw new Error("waitForApproval: decisionId must be a non-empty string");let t=Date.now()+this.config.hitlTimeoutMs;for(;Date.now()<t;){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeoutMs),i;try{i=await this.originalFetch(`${this.config.endpoint}/v1/allow/decisions/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`},signal:n.signal})}finally{clearTimeout(r)}if(!i.ok)throw new Error(`ALLOW decisions poll failed: HTTP ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a!="object"||a===null)throw new Error("ALLOW decisions poll returned unexpected non-object response");let l=a,s=l.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 l.reason=="string"?l.reason:"Rejected by human reviewer"};if(s==="timeout"||s==="expired")return{decision_id:e,decision:"deny",reason:"HITL approval timed out"};await qe($e)}return{decision_id:e,decision:"deny",reason:"HITL approval timed out"}}};function qe(e){return new Promise(t=>setTimeout(t,e))}function H(){let e={};try{let t=`${m.platform()} ${m.release()}`.trim();t&&(e.os=t)}catch{}try{let t=m.hostname();t&&(e.hostname=t)}catch{}try{let{username:t}=m.userInfo();t&&(e.username=t)}catch{}try{let t=Be();t&&(e.ip=t)}catch{}return e}function Be(){let e=m.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 u}from"zod";import{createHash as Bt}from"crypto";import{createHash as zt}from"crypto";var Ue=["tier1","tier2","tier3"];function Z(e){return typeof e=="string"&&Ue.includes(e)}var We=["read_only","transactional","data_processor","external_comms","code_exec","privileged"],ze=["internal","customer_facing","experimental","third_party"],J=[...We,...ze];function Ke(e){return typeof e=="string"&&J.includes(e)}function X(e){let t=new Set;for(let n of e)Ke(n)&&t.add(n);return J.filter(n=>t.has(n))}var Ve=["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 ee(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 Ge={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 He(e){let t=ee(e);return t===null?"other":Ge[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 Q={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 Qe(e){let t=ee(e);return t===null?"other":Q[t]??Q[t.replace(/_/g,"")]??"other"}function te(e,t){let n={...e};if(t.action!==void 0&&t.action!==null&&n.action_class===void 0&&(n.action_class=He(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=Qe(t.targetApp)),n.context=r}return n}var Y=64,Ye=64,w={retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]};function ne(){return{retrieved_data_categories:[],retrieved_classifications:[],action_classes:[],action_counts:{},denied_count:0,inhibited_count:0,event_count:0,target_apps:[]}}var Ze=new Set(["deny","approval_required","escalate"]);function S(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>Y?r.slice(0,Y):r}function Je(e){return e?e.filter(t=>typeof t=="string"&&t.length>0):[]}function C(e){return typeof e=="string"&&e.length>0?e:null}function re(e,t){let n=Je(t.data_categories),r=C(t.classification),i=C(t.action_class),a=i&&Ve.includes(i)?i:null,l=C(t.target_app),s=C(t.decision),c={...e.action_counts};if(a)if(a in c)c[a]=(c[a]??0)+1;else if(Object.keys(c).length<Ye)c[a]=1;else{let p=Object.keys(c).sort(),d=p[p.length-1];d!==void 0&&a<d&&(delete c[d],c[a]=1)}return{retrieved_data_categories:S(e.retrieved_data_categories,n),retrieved_classifications:S(e.retrieved_classifications,r?[r]:[]),action_classes:S(e.action_classes,a?[a]:[]),action_counts:c,denied_count:e.denied_count+(s==="deny"?1:0),inhibited_count:e.inhibited_count+(s&&Ze.has(s)?1:0),event_count:e.event_count+1,target_apps:S(e.target_apps,l?[l]:[])}}var Xe="generic",ie=[{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:Xe,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."}],Ut=ie.map(e=>e.id),et=new Map(ie.map(e=>[e.id,e]));function L(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e)typeof r=="string"&&et.has(r)&&!n.has(r)&&(n.add(r),t.push(r));return t}function ae(e){return L(e)[0]??null}function oe(e){return e==="open"||e==="closed"?e:null}var tt=["action","retrieval","delegation"];function nt(e){return typeof e=="string"&&tt.includes(e)}var rt=new Set(["rules"]);function se(e){if(typeof e.id!="string"||typeof e.vendor_id!="string")return null;let t=typeof e.origin_table=="string"?e.origin_table:"";if(!rt.has(t))return null;let n=Array.isArray(e.applies_to)?e.applies_to.filter(nt):[];return n.length===0?null:{id:e.id,originTable:t,vendorId:e.vendor_id,name:typeof e.name=="string"?e.name:"",description:typeof e.description=="string"?e.description:null,regoSource:typeof e.rego_source=="string"?e.rego_source:null,priority:typeof e.priority=="number"?e.priority:0,enabled:e.enabled===!0,appliesTo:n,targetApp:typeof e.target_app=="string"?e.target_app:null,actionPattern:typeof e.action_pattern=="string"?e.action_pattern:null,trustTier:typeof e.trust_tier=="string"?e.trust_tier:null,surface:typeof e.surface=="string"?e.surface:null,principalExclusions:Array.isArray(e.principal_exclusions)?e.principal_exclusions.filter(r=>typeof r=="string"):null,bypassActive:e.bypass_active===!0,bypassReason:typeof e.bypass_reason=="string"?e.bypass_reason:null,bypassExpiresAt:typeof e.bypass_expires_at=="string"?e.bypass_expires_at:null,redactionSpec:e.redaction_spec??null,failClosedOnEmptySpec:e.fail_closed_on_empty_spec===!0,hitlFallback:e.hitl_fallback==="mask"?"mask":"deny",ruleCode:typeof e.rule_code=="string"?e.rule_code:null}}function it(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 I;async function at(){if(I!==void 0)return I;try{let e=await import("@visiq/core-wasm"),t=e.evaluate??e.default?.evaluate;I=typeof t=="function"?t:null}catch{I=null}return I}var ot=5e3,st=1e4,le=1e3,lt=512,ct=1800*1e3,ut="monitor",dt=u.object({operations:u.array(u.enum(["retrieval","action","delegation"])).min(1,"at least one operation is required"),agentId:u.string().min(1,"agentId is required"),sessionId:u.string().min(1).max(255).optional(),toolName:u.string().optional(),toolArgs:u.record(u.unknown()).optional(),targetResource:u.string().optional(),resourceType:u.string().optional(),resourceMetadata:u.record(u.unknown()).optional(),normalized:u.record(u.unknown()).optional(),query:u.string().optional(),contentPreview:u.string().optional(),telemetry:u.record(u.unknown()).optional()}),pt=u.object({version:u.string().min(1),agent_mode:u.enum(["enforce","monitor","off"]).optional(),agent_mode_by_operation:u.object({action:u.string().optional(),retrieval:u.string().optional(),delegation:u.string().optional()}).partial().optional(),agent_attributes:u.object({trust_tier:u.string().nullable().optional(),categories:u.array(u.string()).optional(),business_function:u.string().nullable().optional(),business_functions:u.array(u.string()).nullable().optional(),no_coverage:u.string().nullable().optional()}).optional(),rules:u.array(u.record(u.unknown())),no_coverage:u.object({no_coverage_defaults:u.record(u.string()),autopilot_enabled:u.boolean(),enduser_hitl_enabled:u.boolean(),hitl_timeout_seconds:u.number().optional()}).optional()});function ft(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=L(n);return{trust_tier:Z(t)?t:null,categories:X(e.categories??[]),business_functions:r,business_function:ae(r)}}function gt(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 mt(e){return e==="permit"?"permit":e==="mask"||e==="redact"?"mask":e==="approval_required"||e==="escalate"?"approval_required":"deny"}var ue=class{client;originalFetch;resolvedApiKey;resolvedEndpoint;resolvedAgentId;harnessKind;rules=[];agentAttributes=null;agentNoCoverage=null;sessions=new Map;noCoverage=null;bundleVersion=null;bundleEtag=null;bundleLoaded=!1;bundleFetchInProgress=!1;initialBundlePromise=null;refreshTimer=null;agentMode=ut;agentModeByOperation=null;rawBundle=null;agentModeConfirmed=!1;bundleApplyFailed=!1;telemetryBuffer=[];telemetryTimer=null;envRegistered=!1;registerPromise=null;constructor(e,t,n,r,i){let a=e??process.env.VISIQ_API_KEY??process.env.ALLOW_API_KEY??process.env.VISIQ_ALLOW_API_KEY,l=t??process.env.VISIQ_ENDPOINT??process.env.ALLOW_ENDPOINT,s=n??process.env.VISIQ_AGENT_ID??process.env.ALLOW_AGENT_ID??"";if(this.resolvedApiKey=a,this.resolvedEndpoint=l,this.resolvedAgentId=s,this.harnessKind=r,this.originalFetch=globalThis.fetch.bind(globalThis),a&&l){let c={apiKey:a,agentId:s,endpoint:l,mode:"enforce",timeoutMs:it(i),hitlTimeoutMs:12e4,failBehavior:"closed",...r?{harnessKind:r}:{}};this.client=new G(c,this.originalFetch),this.initialBundlePromise=this.fetchBundleBackground(),this.refreshTimer=setInterval(()=>{this.fetchBundleBackground()},ot),ce(this.refreshTimer),this.telemetryTimer=setInterval(()=>{this.flushTelemetry()},st),ce(this.telemetryTimer)}else this.client=null}async evaluate(e){let t=dt.parse(e),n=Date.now();if(t.operations.every(c=>this.modeFor(c)==="off"))return this.offDecision(t);if(!this.bundleLoaded){let c;this.agentModeConfirmed?c=this.agentMode:this.bundleApplyFailed?c="enforce":c="monitor";let p=this.denyAll(t,"No unified bundle loaded and no local rules \u2014 fail-closed (G001)");return this.applyAgentMode(p,c,t,n)}let r=this.readSession(t.sessionId),i=await at();if(!i||!this.rawBundle)throw new Error("governance core (@visiq/core-wasm) unavailable \u2014 failing closed (G001)");let a={...t,session:r,at:Date.now()},l={...this.rawBundle,agent_mode:this.agentMode,...this.agentModeByOperation?{agent_mode_by_operation:this.agentModeByOperation}:{}},s=i(a,l);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 w;let t=this.sessions.get(e);return t?Date.now()-t.touchedAt>ct?(this.sessions.delete(e),w):t.state:w}foldSession(e,t){let{sessionId:n}=e;if(!n)return;let r=this.readSession(n),i=e.resourceMetadata??{},a=e.operations.includes("retrieval"),l=e.operations.includes("action")||e.operations.includes("delegation"),s=l?te(e.normalized??{},{action:e.toolName??"",targetApp:e.targetResource??e.toolName??""}):e.normalized??{},c=re(r===w?ne():r,{data_categories:a&&Array.isArray(i.data_categories)?i.data_categories:void 0,classification:a?i.classification:void 0,action_class:l?s.action_class:void 0,target_app:l?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>lt){let p=this.sessions.keys().next().value;p!==void 0&&this.sessions.delete(p)}}applyAgentMode(e,t,n,r){let i=Date.now()-r;if(t==="enforce"){let l={...e,enforced:!0,agentMode:"enforce"};return this.bufferTelemetry(n,l,i,!0),l}let a={...e,allowed:!0,enforced:!1,agentMode:"monitor"};return this.bufferTelemetry(n,a,i,!1),a}offDecision(e){let t=e.operations.includes("action")||e.operations.includes("delegation"),n=e.operations.includes("retrieval");return{decision:"permit",allowed:!0,reason:"agent_mode=off \u2014 evaluation bypassed",ruleId:null,ruleCode:null,enforced:!1,agentMode:"off",action:t?{decision:"permit",allowed:!0}:{decision:null,allowed:!0},retrieval:n?{action:"allow"}:{action:null}}}denyAll(e,t){let n=e.operations.includes("action")||e.operations.includes("delegation"),r=e.operations.includes("retrieval");return{decision:"deny",allowed:!1,reason:t,ruleId:null,ruleCode:null,enforced:!0,agentMode:"enforce",action:n?{decision:"deny",allowed:!1}:{decision:null,allowed:!0},retrieval:r?{action:"deny"}:{action:null}}}async registerHitl(e,t){if(this.client)try{let n={agent_id:e.agentId,target_app:e.targetResource??e.toolName??"",action:e.toolName??"",context:e.toolName?{[e.toolName]:e.toolArgs??{}}:{},...e.sessionId?{session_id:e.sessionId}:{},...e.telemetry?{telemetry:e.telemetry}:{}},r=await this.client.evaluate(n);r.decision_id&&(t.action.decisionId=r.decision_id)}catch(n){console.warn("[UNIFIED] HITL registration failed \u2014 staying fail-closed (G001):",n)}}applyBundle(e){this.bundleApplyFailed=!0;let t=pt.parse(e);this.bundleApplyFailed=!1,!(this.bundleLoaded&&t.version===this.bundleVersion)&&(this.rules=t.rules.map(n=>se(n)).filter(n=>n!==null),this.agentAttributes=t.agent_attributes?ft(t.agent_attributes):null,this.agentNoCoverage=oe(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=gt(t.agent_mode_by_operation),this.rawBundle=e)}async awaitBundleReady(e=5e3){if(!this.initialBundlePromise||this.bundleLoaded)return;let t,n=new Promise(r=>{t=setTimeout(r,e)});try{await Promise.race([this.initialBundlePromise,n])}catch{}finally{t&&clearTimeout(t)}}async fetchBundleBackground(){if(!(this.bundleFetchInProgress||!this.resolvedEndpoint||!this.resolvedApiKey)){this.bundleFetchInProgress=!0;try{let e=this.resolvedAgentId?`?agent_id=${encodeURIComponent(this.resolvedAgentId)}`:"",t={Authorization:`Bearer ${this.resolvedApiKey}`,Accept:"application/json"};this.bundleEtag&&(t["If-None-Match"]=this.bundleEtag);let n=await this.originalFetch(`${this.resolvedEndpoint}/rules/bundle${e}`,{method:"GET",headers:t});if(n.status===304)return;if(!n.ok)throw new Error(`unified bundle fetch failed: HTTP ${n.status}`);let r=n.headers.get("ETag");r&&(this.bundleEtag=r);let i=await n.json();this.applyBundle(i)}catch(e){this.bundleLoaded?console.warn("[UNIFIED] Bundle refresh failed (using cached rules):",e):console.warn("[UNIFIED] Initial bundle fetch failed (fail-closed until loaded):",e)}finally{this.bundleFetchInProgress=!1}}}hasRules(){return this.bundleLoaded&&this.rules.length>0}hasClient(){return this.client!==null}getEndpoint(){return this.resolvedEndpoint}getApiKey(){return this.resolvedApiKey}getBundleVersion(){return this.bundleVersion}getAgentMode(){return this.agentMode}getAgentAttributes(){return this.agentAttributes}getSessionState(e){return this.readSession(e)}registerEnvironment(e){!this.client||this.envRegistered||!this.resolvedAgentId||(this.envRegistered=!0,this.registerPromise=this.client.registerEnvironment(e))}registerHostEnvironment(){this.registerEnvironment(H())}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:mt(t.decision),reason:t.reason,evaluated_at:new Date().toISOString(),rule_id:t.ruleId,rule_code:t.ruleCode,enforced:r,agent_mode:this.agentMode,latency_ms:n,evaluation_mode:"local",raw_event:{agent_id:e.agentId,operations:e.operations,...e.toolName?{tool_name:e.toolName}:{},...e.targetResource?{target_resource:e.targetResource}:{},...e.resourceType?{resource_type:e.resourceType}:{}},...this.harnessKind?{context:{[K]:this.harnessKind}}:{}}),this.enforceTelemetryCap()}async flushTelemetry(){if(this.telemetryBuffer.length===0||!this.client)return;let e=this.telemetryBuffer.splice(0);try{await this.client.sendTelemetry(e)}catch(t){console.error("[UnifiedRuntime] telemetry flush failed (non-fatal):",t)}}enforceTelemetryCap(){let e=this.telemetryBuffer.length-le;e>0&&(this.telemetryBuffer.splice(0,e),console.warn(`[UnifiedRuntime] telemetry buffer full \u2014 dropped ${e} oldest entries (cap ${le})`))}async flush(){if(this.registerPromise)try{await this.registerPromise}catch{}await this.flushTelemetry()}dispose(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.telemetryTimer&&(clearInterval(this.telemetryTimer),this.telemetryTimer=null),this.flushTelemetry()}};function ce(e){e&&typeof e=="object"&&"unref"in e&&e.unref()}var b=null;function F(e){let t=`${e.apiKey}::${e.agentId}::${e.baseUrl??""}`;if(b&&b.key===t)return b.runtimes;let n=new ue(e.apiKey,e.baseUrl,e.agentId,"cli_harness");return n.registerHostEnvironment(),b={key:t,runtimes:{unified:n}},b.runtimes}async function Xt(){if(b)try{await b.runtimes.unified.flush()}catch{}}async function en(e){try{let t=await h();if(!t)return;let{unified:n}=F(t);await n.awaitBundleReady(e)}catch{}}function y(e,t){return e?.sessionKey??t?.sessionKey??t?.sessionId??"default"}var M=class{entries=new Map;set(t,n){this.entries.set(t,n)}get(t){return this.entries.get(t)}delete(t){this.entries.delete(t)}clear(){this.entries.clear()}size(){return this.entries.size}},j=new Map;function v(e){let t=j.get(e);return t||(t=new M,j.set(e,t)),t}function de(e){j.delete(e)}var pe=new Set(["web_search","x_search","web_fetch","tool_search","tool_describe","get_account","get_transactions","get_devices","check_watchlist","search_knowledge"]);function _t(e){if(typeof e!="string"||e.length===0)return e;let t=e.lastIndexOf("__");return t<0?e:e.slice(t+2)}function fe(e){return pe.has(_t(e))}function rn(){return pe}var ht=[{name:"private_key",re:/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{name:"aws_access_key",re:/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g},{name:"github_token",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack_token",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"stripe_secret",re:/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g},{name:"google_api_key",re:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"llm_api_key",re:/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g},{name:"bearer_token",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g},{name:"connection_string",re:/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s/@:]+:[^\s/@:]+@[^\s'"]+/g},{name:"us_ein",re:/\b\d{2}-\d{7}\b/g},{name:"ssn",re:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g},{name:"email",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{name:"swift_bic",re:/\b[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g},{name:"us_phone",re:/\b(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b/g},{name:"ipv4",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{name:"mac_address",re:/\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g}];var f=Object.fromEntries(ht.map(e=>[e.name,e.re.source])),yt=["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"],bt={private_key:{id:"private_key",label:"Private keys (PEM)",description:"PEM-encoded private keys (RSA / EC / EdDSA / OpenSSH).",category:"secret",example:`-----BEGIN PRIVATE KEY-----
|
|
4
|
-
MIIEv\u2026
|
|
5
|
-
-----END PRIVATE KEY-----`,template:{pattern:f.private_key,mode:"full"},defaultEnabled:!0},jwt:{id:"jwt",label:"JWT / bearer tokens",description:"JSON Web Tokens (base64url header.payload.signature).",category:"secret",example:"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.dBjftJeZ4CVP",template:{pattern:f.jwt,mode:"full"},defaultEnabled:!0},aws_access_key:{id:"aws_access_key",label:"AWS access key IDs",description:"AWS access / identity key ids (AKIA / ASIA / AROA \u2026).",category:"secret",example:"AKIAIOSFODNN7EXAMPLE",template:{pattern:f.aws_access_key,mode:"full"},defaultEnabled:!0},github_token:{id:"github_token",label:"GitHub tokens",description:"GitHub personal / OAuth tokens (classic ghp_\u2026 + fine-grained).",category:"secret",example:"ghp_0123456789abcdef0123456789abcdef0123",template:{pattern:f.github_token,mode:"full"},defaultEnabled:!0},slack_token:{id:"slack_token",label:"Slack tokens",description:"Slack bot / user / app tokens (xoxb- / xoxp- \u2026).",category:"secret",example:"xoxb-1234567890-abcdefghijkl",template:{pattern:f.slack_token,mode:"full"},defaultEnabled:!0},stripe_secret:{id:"stripe_secret",label:"Stripe secret keys",description:"Stripe live secret / restricted keys (sk_live_ / rk_live_).",category:"secret",example:"sk_live_0123456789abcdefABCDEF",template:{pattern:f.stripe_secret,mode:"full"},defaultEnabled:!0},google_api_key:{id:"google_api_key",label:"Google API keys",description:"Google API keys (AIza\u2026).",category:"secret",example:"AIzaSyA1234567890abcdefghijklmnopqrstuv",template:{pattern:f.google_api_key,mode:"full"},defaultEnabled:!0},llm_api_key:{id:"llm_api_key",label:"LLM provider API keys",description:"OpenAI / Anthropic secret keys (sk-\u2026, sk-proj-\u2026, sk-ant-\u2026).",category:"secret",example:"sk-ant-api03-AbCdEf0123456789AbCdEf01",template:{pattern:f.llm_api_key,mode:"full"},defaultEnabled:!0},bearer_token:{id:"bearer_token",label:"Authorization bearer tokens",description:"Credentials following an HTTP `Authorization: Bearer \u2026` header.",category:"secret",example:"Bearer abcdef0123456789abcdef0123456789",template:{pattern:f.bearer_token,mode:"full"},defaultEnabled:!0},connection_string:{id:"connection_string",label:"Connection strings (with password)",description:"Database / broker DSNs carrying an inline password (scheme://user:pass@host).",category:"secret",example:"postgres://app:s3cr3t@db.internal:5432/main",template:{pattern:f.connection_string,mode:"full"},defaultEnabled:!0},pan:{id:"pan",label:"Payment card numbers (PAN)",description:"Luhn-valid 13\u201319 digit primary account numbers (PCI-DSS).",category:"financial",example:"4242 4242 4242 4242",template:{pattern:"\\b\\d{13,19}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},iban:{id:"iban",label:"IBAN bank account numbers",description:"ISO 13616 IBANs (mod-97 validated); keeps the last 4 visible.",category:"financial",example:"DE89 3704 0044 0532 0130 00",template:{pattern:"\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){10,30}\\b",mode:"partial",keepLast:4},defaultEnabled:!0},aba_routing:{id:"aba_routing",label:"ABA routing numbers",description:"US bank routing-transit numbers (9-digit, checksum-validated). DEFAULT-OFF (9-digit false-positive surface).",category:"financial",example:"021000021",template:{pattern:"\\b\\d{9}\\b",mode:"full"},defaultEnabled:!1},us_ein:{id:"us_ein",label:"US Employer ID (EIN)",description:"US tax Employer Identification Numbers (XX-XXXXXXX).",category:"financial",example:"12-3456789",template:{pattern:f.us_ein,mode:"full"},defaultEnabled:!0},swift_bic:{id:"swift_bic",label:"SWIFT / BIC codes",description:"Bank SWIFT/BIC codes (8 or 11 chars). DEFAULT-OFF (matches uppercase tokens).",category:"financial",example:"DEUTDEFF500",template:{pattern:f.swift_bic,mode:"full"},defaultEnabled:!1},ssn:{id:"ssn",label:"US Social Security numbers",description:"Dashed / spaced US SSNs (e.g. 123-45-6789).",category:"pii",example:"123-45-6789",template:{pattern:f.ssn,mode:"partial",keepLast:4},defaultEnabled:!0},email:{id:"email",label:"Email addresses",description:"Email addresses (the mailbox is masked, the domain kept).",category:"pii",example:"alice@acme.com",template:{pattern:f.email,mode:"email"},defaultEnabled:!0},us_phone:{id:"us_phone",label:"US phone numbers",description:"US phone numbers in common formats. DEFAULT-OFF (10-digit false-positive surface).",category:"pii",example:"(415) 555-0132",template:{pattern:f.us_phone,mode:"partial",keepLast:4},defaultEnabled:!1},ipv4:{id:"ipv4",label:"IPv4 addresses",description:"Dotted-quad IPv4 addresses. DEFAULT-OFF (common + usually benign).",category:"identifier",example:"203.0.113.42",template:{pattern:f.ipv4,mode:"full"},defaultEnabled:!1},mac_address:{id:"mac_address",label:"MAC addresses",description:"Hardware MAC addresses. DEFAULT-OFF.",category:"identifier",example:"3c:22:fb:1a:2b:3c",template:{pattern:f.mac_address,mode:"full"},defaultEnabled:!1}},on=new Set(yt.filter(e=>!bt[e].defaultEnabled));var D="[REDACTED]",A="\u2022",E=e=>/[A-Za-z0-9]/.test(e);function ge(e,t,n,r){let i=Array.from(e),a=i.length,l=Math.max(0,Math.floor(t)||0),s=Math.max(0,Math.floor(n)||0),c=r.length>0?r:A,p=l+s>=a;return i.map((d,g)=>!p&&(g<l||g>=a-s)?d:E(d)?c:d).join("")}function vt(e,t){let n=e.indexOf("@");if(n<=0||n>=e.length-1)return ge(e,0,0,t);let r=e.slice(0,n),i=e.slice(n),a=t.length>0?t:A;return(r.length<=1?a:r[0]+Array.from(r.slice(1)).map(l=>E(l)?a:l).join(""))+i}function At(e,t,n){let r=n.length>0?n:A,i=new Array(e.length).fill(!1);if(typeof t=="string"&&t.length>0)try{let p=new RegExp(t,"g"),d;for(;(d=p.exec(e))!==null;){if(d[0].length===0){p.lastIndex++;continue}for(let g=d.index;g<d.index+d[0].length;g++)i[g]=!0}}catch{}let a=!1,l=!0;for(let p=0;p<e.length;p++)if(E(e[p])&&(a=!0,!i[p])){l=!1;break}let s=a&&l,c="";for(let p=0;p<e.length;p++){let d=e[p];!s&&i[p]||!E(d)?c+=d:c+=r}return c}function me(e,t){let n=t.mode??"full";return n==="partial"?ge(e,t.keepFirst??0,t.keepLast??0,t.maskChar??A):n==="email"?vt(e,t.maskChar??A):n==="custom"?At(e,t.keepPattern,t.maskChar??A):t.replacement??D}function wt(e,t){return typeof e=="string"?me(e,t):t.replacement??D}function _e(e){let t=[],n=e.replacement??D;for(let r of e.patterns??[])typeof r!="string"||r.length===0||t.push({source:r,replacer:()=>n});for(let r of e.directives??[]){let{pattern:i}=r;typeof i!="string"||i.length===0||t.push({source:i,replacer:a=>me(a,r)})}return t}function he(e,t){let n=e;for(let{source:r,replacer:i}of t){let a;try{a=new RegExp(r,"g")}catch(l){let s=l instanceof Error?l.message:String(l);throw new Error(`[visiq-redact] Invalid redaction pattern "${r}": ${s}`)}n=n.replace(a,l=>i(l))}return n}function T(e,t){return e==null?e:typeof e=="string"?It(e,t):typeof e=="object"?kt(e,t):e}function It(e,t){if(typeof e!="string")return e;let n=_e(t);return n.length===0?e:he(e,n)}function kt(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=_e(t),i=n.size>0,a=r.length>0,l=s=>{if(s==null)return s;if(Array.isArray(s))return s.map(c=>l(c));if(typeof s=="object"){let c=s,p=Object.create(Object.getPrototypeOf(c));for(let d of Object.keys(c)){let g=i?n.get(d):void 0;if(g){p[d]=wt(c[d],g);continue}p[d]=l(c[d])}return p}return typeof s=="string"&&a?he(s,r):s};return l(e)}var ye="@visiq/openclaw-plugin";function be(e){let t=[],n=[],r;for(let a of e){let{field:l,pattern:s,replacement:c}=a;l&&t.push(l),s&&n.push(s),c&&r===void 0&&(r=c)}let i={};return t.length>0&&(i.fields=t),n.length>0&&(i.patterns=n),r!==void 0&&(i.replacement=r),i}async function fn(e,t){let n=await h();if(!n)return;let r=F(n),i=n.agentId??t.agentId,a=y(e,t),l=t.toolCallId??e.toolCallId,c=fe(e.toolName)?["retrieval","action"]:["action"],p=St(e.params),d;try{await r.unified.awaitBundleReady(),d=await r.unified.evaluate({operations:c,agentId:i,sessionId:a,toolName:e.toolName,toolArgs:e.params??{},resourceType:"tool_result",resourceMetadata:{toolName:e.toolName,runId:e.runId??t.runId},...p!==void 0?{query:p}:{}})}catch(_){return{block:!0,blockReason:`[VisIQ] Evaluation error (fail-closed): ${_ instanceof Error?_.message:String(_)}`}}if(!d.enforced)return;let{action:g}=d;if(g.decision==="approval_required")return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:d.reason,severity:"critical",allowedDecisions:["allow-once","allow-always","deny"],pluginId:ye}};if(!g.allowed)return{block:!0,blockReason:`[VisIQ ${d.ruleCode??"DENY"}] ${d.reason}`};let R;if(g.decision==="mask"&&g.argRedactionRules&&g.argRedactionRules.length>0&&(R=T(e.params??{},be(g.argRedactionRules))),c.includes("retrieval"))switch(d.retrieval.action){case"allow":case null:break;case"deny":return{block:!0,blockReason:`[VisIQ RECALL] ${d.reason}`};case"redact":{if(!l)return{block:!0,blockReason:"[VisIQ RECALL] Redact decision but no toolCallId \u2014 fail-closed"};let _=d.retrieval.redactionRules??[];_.length>0&&v(a).set(l,be(_));break}case"escalate":return{requireApproval:{title:`VisIQ approval required: ${e.toolName}`,description:d.reason,severity:"warning",allowedDecisions:["allow-once","allow-always","deny"],pluginId:ye}};default:{let _=d.retrieval.action;return{block:!0,blockReason:`[VisIQ RECALL] Unknown action "${String(_)}" \u2014 fail-closed`}}}if(R)return{params:R}}function St(e){if(e)for(let t of["query","q","url","prompt"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}}function yn(e,t){let{ready:n,config:r}=k();if(!n||!r)return;let i=e.toolCallId??t.toolCallId;if(!i)return;let a=y(e,t),l=v(a),s=l.get(i);if(!s)return;let c={...e.message};return c.content!==void 0&&(c.content=T(c.content,s)),l.delete(i),{message:c}}function wn(e,t){let{ready:n,config:r}=k();if(n&&!r)return;let i=y(e,t),a=v(i);if(a.size()>0)return a.clear(),{block:!0}}async function x(e,t){let r=`${(e.baseUrl??"https://api.visiqlabs.com").replace(/\/$/,"")}/v1/events`;try{let i=new AbortController,a=setTimeout(()=>i.abort(),5e3);try{let l=await fetch(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(t),signal:i.signal});l.ok||process.stderr.write(`[VisIQ] /v1/events POST failed: ${l.status} ${l.statusText}
|
|
6
|
-
`);try{await l.text()}catch{}}finally{clearTimeout(a)}}catch(i){if(i instanceof Error&&i.name==="AbortError"){process.stderr.write(`[VisIQ] /v1/events POST timed out (5s)
|
|
7
|
-
`);return}process.stderr.write(`[VisIQ] /v1/events POST error: ${i instanceof Error?i.message:String(i)}
|
|
8
|
-
`)}}async function En(e,t){let n=await h();if(!n)return;let r=n.agentId??t.agentId;x(n,{type:"llm_input",agentId:r,sessionId:e.sessionId??t.sessionId??t.sessionKey,runId:e.runId??t.runId,timestamp:new Date().toISOString(),payload:{provider:e.provider,model:e.model,hasSystemPrompt:typeof e.systemPrompt=="string"&&e.systemPrompt.length>0,promptLength:typeof e.prompt=="string"?e.prompt.length:0,historyMessageCount:Array.isArray(e.historyMessages)?e.historyMessages.length:0,imagesCount:e.imagesCount??0,toolCount:Array.isArray(e.tools)?e.tools.length:0}})}function Ct(e){if(!Array.isArray(e))return 0;let t=0;for(let n of e)typeof n=="string"&&(t+=n.length);return t}async function On(e,t){let n=await h();if(!n)return;let r=n.agentId??t.agentId;x(n,{type:"llm_output",agentId:r,sessionId:e.sessionId??t.sessionId??t.sessionKey,runId:e.runId??t.runId,timestamp:new Date().toISOString(),payload:{provider:e.provider,model:e.model,resolvedRef:e.resolvedRef,harnessId:e.harnessId,assistantSegmentCount:Array.isArray(e.assistantTexts)?e.assistantTexts.length:0,assistantTotalChars:Ct(e.assistantTexts),usage:e.usage??null}})}function Ln(e,t){de(y(e,t))}export{W as a,Lt as b,Xt as c,en as d,M as e,v as f,de as g,_t as h,fe as i,rn as j,fn as k,yn as l,wn as m,En as n,On as o,Ln as p};
|