@aicraftalchemy/aiaca 1.0.10 → 1.0.11

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.
Files changed (2) hide show
  1. package/dist/cli.js +222 -212
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -37,32 +37,32 @@ DO NOT use this tool to:
37
37
  `,{flag:"a"})}catch{}}}function Wz(){di.set("default",[{id:"fs-no-etc-write",type:"filesystem",description:"Never write to /etc",severity:"critical",action:"block",pattern:"/etc/**",patternType:"glob",direction:"write",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"fs-no-sudoers",type:"filesystem",description:"Never write to /etc/sudoers",severity:"critical",action:"block",pattern:"**/sudoers",patternType:"glob",direction:"write",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"fs-no-root-write",type:"filesystem",description:"Never write to /root",severity:"critical",action:"block",pattern:"/root/**",patternType:"glob",direction:"write",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"fs-no-pem-read",type:"filesystem",description:"Block read of *.pem files",severity:"high",action:"block",pattern:"**/*.pem",patternType:"glob",direction:"read",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"fs-no-key-read",type:"filesystem",description:"Block read of *.key files",severity:"high",action:"block",pattern:"**/*.key",patternType:"glob",direction:"read",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"fs-no-id-rsa",type:"filesystem",description:"Block read of id_rsa private keys",severity:"critical",action:"block",pattern:"**/id_rsa*",patternType:"glob",direction:"read",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"fs-no-aws-creds",type:"filesystem",description:"Block read of AWS credentials",severity:"critical",action:"block",pattern:"**/.aws/credentials",patternType:"glob",direction:"read",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"fs-no-ssh-private",type:"filesystem",description:"Block read of .ssh private keys",severity:"critical",action:"block",pattern:"**/.ssh/id_*",patternType:"glob",direction:"read",excludePatterns:["**/.ssh/id_*.pub"],enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"fs-no-env-write",type:"filesystem",description:"Block write to .env files (use a setting tool instead)",severity:"medium",action:"warn",pattern:"**/.env",patternType:"glob",direction:"write",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"net-no-private-ips",type:"network",description:"Block private IP ranges",severity:"high",action:"block",blockedHosts:["127.0.0.1","localhost","0.0.0.0","169.254.169.254"],enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"net-no-aws-metadata",type:"network",description:"Block AWS instance metadata service",severity:"critical",action:"block",blockedHosts:["169.254.169.254","metadata.google.internal","metadata.azure.com"],enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"cmd-no-shutdown",type:"command",description:"Block system shutdown commands",severity:"critical",action:"block",pattern:"\\b(shutdown|reboot|halt|poweroff)\\b",patternType:"regex",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"cmd-no-format",type:"command",description:"Block filesystem format commands",severity:"critical",action:"block",pattern:"\\b(mkfs|fdisk|format)\\b",patternType:"regex",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"cmd-no-fork-bomb",type:"command",description:"Block fork bomb patterns",severity:"critical",action:"block",pattern:":\\(\\)\\s*\\{\\s*:\\|:\\s*&\\s*\\}\\s*;\\s*:",patternType:"regex",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"},{id:"env-no-secret-display",type:"env",description:"Block displaying env vars with sensitive names",severity:"high",action:"sanitize",pattern:"(?i)\\b(PASSWORD|SECRET|TOKEN|API_KEY|PRIVATE_KEY|ACCESS_KEY)\\b",patternType:"regex",sanitizeReplacement:"[REDACTED]",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"default"}]),di.set("hipaa",[{id:"hipaa-no-phi-fs-write-public",type:"filesystem",description:"HIPAA: Block PHI writes to public paths",severity:"critical",action:"block",pattern:"/var/www/**",patternType:"glob",direction:"write",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"hipaa"},{id:"hipaa-encrypt-required",type:"filesystem",description:"HIPAA: PHI data must be encrypted at rest",severity:"high",action:"audit",pattern:"**/phi/**",patternType:"glob",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"hipaa"}]),di.set("pci",[{id:"pci-no-card-numbers",type:"secret",description:"PCI: Block credit card number patterns",severity:"critical",action:"sanitize",pattern:"\\b(?:\\d{4}[\\s-]?){3}\\d{4}\\b",patternType:"regex",sanitizeReplacement:"[CARD-REDACTED]",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"pci"},{id:"pci-no-cvv",type:"secret",description:"PCI: Block CVV/CVC patterns",severity:"high",action:"sanitize",pattern:"(?i)(?:CVV|CVC)[\\s:=]*\\d{3,4}",patternType:"regex",sanitizeReplacement:"[CVV-REDACTED]",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"pci"}]),di.set("soc2",[{id:"soc2-audit-config-changes",type:"filesystem",description:"SOC2: Audit all config file modifications",severity:"medium",action:"audit",pattern:"**/config/**",patternType:"glob",direction:"write",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"soc2"},{id:"soc2-audit-prod-deploys",type:"command",description:"SOC2: Audit production deployment commands",severity:"medium",action:"audit",pattern:"\\b(deploy|release)\\s+.*production",patternType:"regex",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"soc2"}]),di.set("gdpr",[{id:"gdpr-no-pii-export",type:"network",description:"GDPR: Block PII export to non-EU regions",severity:"critical",action:"block",pattern:"\\.(us-east|us-west|ap-)\\b",patternType:"regex",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"gdpr"},{id:"gdpr-redact-emails",type:"secret",description:"GDPR: Redact email addresses in logs",severity:"medium",action:"sanitize",pattern:"\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b",patternType:"regex",sanitizeReplacement:"[EMAIL-REDACTED]",enabled:!0,createdAt:Date.now(),hitCount:0,bundle:"gdpr"}])}function eI(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___DOUBLE_STAR___").replace(/\*/g,"[^/\\\\]*").replace(/___DOUBLE_STAR___/g,".*").replace(/\?/g,"[^/\\\\]");return new RegExp("^"+t+"$","i")}function tI(e,t){if(!t.pattern)return{matches:!1};let n=!1;try{switch(t.patternType){case"exact":n=e===t.pattern;break;case"prefix":n=e.startsWith(t.pattern);break;case"suffix":n=e.endsWith(t.pattern);break;case"glob":{n=eI(t.pattern).test(e);break}default:{n=new RegExp(t.pattern).test(e);break}}}catch{n=!1}if(n&&t.excludePatterns)for(let r of t.excludePatterns)try{if((t.patternType==="glob"?eI(r):new RegExp(r)).test(e))return{matches:!1}}catch{}return{matches:n,matched:t.pattern}}function Kz(e){return!!(e==="localhost"||e==="0.0.0.0"||/^127\./.test(e)||/^10\./.test(e)||/^192\.168\./.test(e)||/^172\.(?:1[6-9]|2\d|3[01])\./.test(e)||/^169\.254\./.test(e)||/^::1$|^fe80:|^fc00:|^fd00:/i.test(e))}function rI(){let e=[];for(let t of fi.values())t.enabled&&e.push(t);for(let t of on.enabledBundles){let n=di.get(t);n&&e.push(...n.filter(r=>r.enabled))}return e}function gf(e,t,n){if(!on.enabled)return[];gt.totalEvaluations++;let r=[],s=rI().filter(i=>i.type===e);for(let i of s){if(i.toolNames&&t.toolName&&!i.toolNames.includes(t.toolName)||i.argumentNames&&t.argumentName&&!i.argumentNames.includes(t.argumentName)||e==="filesystem"&&i.direction&&i.direction!=="both"&&n?.direction&&n.direction!==i.direction)continue;let o=!1,a,c;if(e==="network")try{let u=new zz(t.value).hostname.toLowerCase();if(i.blockedHosts&&i.blockedHosts.some(d=>u===d||u.endsWith("."+d))&&(o=!0,a=`blocked host: ${u}`),i.allowedHosts&&i.allowedHosts.length>0&&(i.allowedHosts.some(d=>u===d||u.endsWith("."+d))||(o=!0,a="not in allowed hosts")),i.allowPrivateIps===!1&&Kz(u)&&(o=!0,a=`private IP: ${u}`),i.pattern){let d=tI(u,i);d.matches&&(o=!0,a=d.matched)}}catch{}else{let l=tI(t.value,i);o=l.matches,a=l.matched}if(o){if(i.hitCount++,i.lastHitAt=Date.now(),gt.byRule[i.id]=(gt.byRule[i.id]||0)+1,gt.byType[i.type]=(gt.byType[i.type]||0)+1,gt.bySeverity[i.severity]=(gt.bySeverity[i.severity]||0)+1,i.action==="sanitize"&&i.sanitizeReplacement)try{if(i.patternType==="regex"){let d=new RegExp(i.pattern,"g");c=t.value.replace(d,i.sanitizeReplacement)}}catch{}let l=i.action==="block"&&(i.severity==="critical"&&on.blockOnCritical||i.severity==="high"&&on.blockOnHigh||i.severity==="medium"||i.severity==="low"||i.severity==="info"),u={ruleId:i.id,ruleType:i.type,severity:i.severity,action:i.action,description:i.description,context:t,matchedPattern:a,sanitizedValue:c,blocked:l};r.push(u),l?gt.totalBlocked++:i.action==="warn"?gt.totalWarned++:i.action==="audit"?gt.totalAudited++:i.action==="sanitize"&&gt.totalSanitized++,mf({event:"violation",...u}),pf.emit("violation",u),i.severity==="critical"&&pf.emit("critical_violation",u)}}return nI(),r}function Yz(e,t,n,r){return gf("filesystem",{toolName:n,value:e,sessionId:r},{direction:t})}function Qz(e,t,n){return gf("network",{toolName:t,value:e,sessionId:n})}function Zz(e,t,n){return gf("command",{toolName:t,value:e,sessionId:n})}function Xz(e,t){return gf("secret",{value:e,sessionId:t})}function e6(e){let t={...e,id:e.id||Hz(6).toString("hex"),createdAt:Date.now(),hitCount:0};return fi.set(t.id,t),lh(),mf({event:"rule_added",ruleId:t.id,type:t.type}),pf.emit("rule_added",{rule:t}),t}function t6(e){return fi.has(e)?(fi.delete(e),lh(),mf({event:"rule_removed",ruleId:e}),!0):!1}function n6(e){let t=fi.get(e);return t?(t.enabled=!0,lh(),!0):!1}function r6(e){let t=fi.get(e);return t?(t.enabled=!1,lh(),!0):!1}function s6(){return rI()}function sI(){let e=[];for(let t of fi.values())e.push(t);for(let[t,n]of di.entries())if(on.enabledBundles.includes(t))for(let r of n)e.push(r);return e}function iI(){return Array.from(di.entries()).map(([e,t])=>({id:e,ruleCount:t.length,enabled:on.enabledBundles.includes(e)}))}function i6(e){return di.has(e)?(on.enabledBundles.includes(e)||on.enabledBundles.push(e),mf({event:"bundle_enabled",bundleId:e}),!0):!1}function o6(e){return on.enabledBundles=on.enabledBundles.filter(t=>t!==e),mf({event:"bundle_disabled",bundleId:e}),!0}function a6(){return{...on}}function c6(e){on={...on,...e}}function l6(){return{...gt}}function u6(){gt={totalEvaluations:0,totalBlocked:0,totalWarned:0,totalAudited:0,totalSanitized:0,byRule:{},byType:{},bySeverity:{}},nI()}function d6(){return pf}function f6(e=100){if(!$S(_S))return[];try{return CS(_S,"utf-8").split(`
38
38
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function p6(){let e=[];e.push("# Compliance Policy Engine Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total evaluations: ${gt.totalEvaluations}`),e.push(`- \u{1F6AB} Blocked: ${gt.totalBlocked}`),e.push(`- \u26A0\uFE0F Warned: ${gt.totalWarned}`),e.push(`- \u{1F4CB} Audited: ${gt.totalAudited}`),e.push(`- \u{1F9F9} Sanitized: ${gt.totalSanitized}`),e.push(""),e.push("## Active Bundles");for(let n of iI()){let r=n.enabled?"\u2713":"\u2717";e.push(` ${r} ${n.id}: ${n.ruleCount} rules`)}e.push(""),e.push("## By Type");for(let[n,r]of Object.entries(gt.byType).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## By Severity");for(let[n,r]of Object.entries(gt.bySeverity).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## Top Triggered Rules");let t=sI().sort((n,r)=>r.hitCount-n.hitCount);for(let n of t.slice(0,15))n.hitCount!==0&&e.push(`- ${n.id}: ${n.hitCount} hits | ${n.severity} | ${n.description}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Declarative policy rules"),e.push("- \u2713 Hard block enforcement (not suggestions)"),e.push("- \u2713 Pre-canned bundles: default, hipaa, pci, soc2, gdpr"),e.push(`- ${on.blockOnCritical?"\u2713":"\u2717"} Block on critical`),e.push(`- ${on.blockOnHigh?"\u2713":"\u2717"} Block on high`),e.push(`- ${on.enableProjectInheritance?"\u2713":"\u2717"} Project policy inheritance`),e.push(`- ${on.enableAuditLog?"\u2713":"\u2717"} Audit log`),e.join(`
39
39
  `)}function m6(e){let t=e.severity==="critical"?"\u{1F6A8}":e.severity==="high"?"\u26A0\uFE0F ":e.severity==="medium"?"\u26A1":"\u2139\uFE0F ",n=e.action==="block"?"\u{1F6AB}":e.action==="warn"?"\u26A0\uFE0F":e.action==="sanitize"?"\u{1F9F9}":"\u{1F4CB}",r=[];return r.push(`${t} ${n} **${e.severity.toUpperCase()}** [${e.ruleType}] rule=${e.ruleId}`),r.push(` ${e.description}`),e.matchedPattern&&r.push(` Matched: ${e.matchedPattern}`),r.push(` Action: ${e.action.toUpperCase()}${e.blocked?" (BLOCKED)":""}`),e.sanitizedValue&&r.push(` Sanitized: ${e.sanitizedValue.slice(0,100)}`),e.context.toolName&&r.push(` Tool: ${e.context.toolName}`),r.join(`
40
- `)}var Vz,on,ah,AS,TS,_S,pf,fi,di,gt,ba=w(()=>{"use strict";Vz={enabled:!0,defaultAction:"audit",blockOnCritical:!0,blockOnHigh:!0,enabledBundles:["default"],customRulesPath:"",enableProjectInheritance:!0,enableDistributedSync:!1,enableAuditLog:!0},on={...Vz},ah=oh(Uz(),".aiaca","compliance-policy"),AS=oh(ah,"rules.json"),TS=oh(ah,"stats.json"),_S=oh(ah,"audit.jsonl"),pf=new Gz;pf.setMaxListeners(50);fi=new Map,di=new Map,gt={totalEvaluations:0,totalBlocked:0,totalWarned:0,totalAudited:0,totalSanitized:0,byRule:{},byType:{},bySeverity:{}};Jz()});var vf={};$(vf,{addRule:()=>FS,blockRule:()=>T6,checkRequest:()=>C6,configure:()=>I6,formatDecision:()=>B6,formatRule:()=>j6,generateComplianceReport:()=>O6,getAuditLog:()=>L6,getConfig:()=>P6,getEvents:()=>D6,getRecentRequests:()=>F6,getRule:()=>R6,getStats:()=>M6,listRules:()=>_6,removeRule:()=>A6,resetStats:()=>E6});import{existsSync as uh,mkdirSync as g6,readFileSync as dh,writeFileSync as fh}from"fs";import{join as hf}from"path";import{homedir as h6}from"os";import{URL as aI}from"url";import{EventEmitter as y6}from"events";import{randomBytes as PS}from"crypto";function bf(){g6(yf,{recursive:!0})}function v6(){if(bf(),uh(MS))try{D={...D,...JSON.parse(dh(MS,"utf-8"))}}catch{}if(uh(IS))try{let e=JSON.parse(dh(IS,"utf-8"));for(let t of e)Ps.set(t.id,t)}catch{}else S6()}function S6(){let e=[{domain:"api.openai.com",desc:"OpenAI API"},{domain:"api.anthropic.com",desc:"Anthropic API"},{domain:"*.googleapis.com",desc:"Google APIs"},{domain:"api.github.com",desc:"GitHub API"},{domain:"github.com",desc:"GitHub"},{domain:"raw.githubusercontent.com",desc:"GitHub raw"},{domain:"codeload.github.com",desc:"GitHub clone"},{domain:"registry.npmjs.org",desc:"npm registry"},{domain:"pypi.org",desc:"PyPI"},{domain:"crates.io",desc:"crates.io"},{domain:"api.osv.dev",desc:"OSV vulnerability database"},{domain:"*.docker.com",desc:"Docker registry"},{domain:"*.docker.io",desc:"Docker registry"},{domain:"registry-1.docker.io",desc:"Docker registry"},{domain:"rubygems.org",desc:"RubyGems"}];for(let t of e)FS({domain:t.domain,decision:"allow",description:t.desc})}function Rs(){bf();try{fh(MS,JSON.stringify(D,null,2),"utf-8")}catch{}}function cI(){bf();try{fh(IS,JSON.stringify(Array.from(Ps.values()),null,2),"utf-8")}catch{}}function Sl(e){if(ht.enableAuditLog){bf();try{fh(ES,JSON.stringify({...e,timestamp:Date.now()})+`
40
+ `)}var Vz,on,ah,AS,TS,_S,pf,fi,di,gt,ba=w(()=>{"use strict";Vz={enabled:!0,defaultAction:"audit",blockOnCritical:!0,blockOnHigh:!0,enabledBundles:["default"],customRulesPath:"",enableProjectInheritance:!0,enableDistributedSync:!1,enableAuditLog:!0},on={...Vz},ah=oh(Uz(),".aiaca","compliance-policy"),AS=oh(ah,"rules.json"),TS=oh(ah,"stats.json"),_S=oh(ah,"audit.jsonl"),pf=new Gz;pf.setMaxListeners(50);fi=new Map,di=new Map,gt={totalEvaluations:0,totalBlocked:0,totalWarned:0,totalAudited:0,totalSanitized:0,byRule:{},byType:{},bySeverity:{}};Jz()});var vf={};$(vf,{addRule:()=>FS,blockRule:()=>T6,checkRequest:()=>C6,configure:()=>I6,formatDecision:()=>B6,formatRule:()=>j6,generateComplianceReport:()=>O6,getAuditLog:()=>L6,getConfig:()=>P6,getEvents:()=>D6,getRecentRequests:()=>F6,getRule:()=>R6,getStats:()=>M6,listRules:()=>_6,removeRule:()=>A6,resetStats:()=>E6});import{existsSync as uh,mkdirSync as g6,readFileSync as dh,writeFileSync as fh}from"fs";import{join as hf}from"path";import{homedir as h6}from"os";import{URL as aI}from"url";import{EventEmitter as y6}from"events";import{randomBytes as PS}from"crypto";function bf(){g6(yf,{recursive:!0})}function v6(){if(bf(),uh(MS))try{F={...F,...JSON.parse(dh(MS,"utf-8"))}}catch{}if(uh(IS))try{let e=JSON.parse(dh(IS,"utf-8"));for(let t of e)Ps.set(t.id,t)}catch{}else S6()}function S6(){let e=[{domain:"api.openai.com",desc:"OpenAI API"},{domain:"api.anthropic.com",desc:"Anthropic API"},{domain:"*.googleapis.com",desc:"Google APIs"},{domain:"api.github.com",desc:"GitHub API"},{domain:"github.com",desc:"GitHub"},{domain:"raw.githubusercontent.com",desc:"GitHub raw"},{domain:"codeload.github.com",desc:"GitHub clone"},{domain:"registry.npmjs.org",desc:"npm registry"},{domain:"pypi.org",desc:"PyPI"},{domain:"crates.io",desc:"crates.io"},{domain:"api.osv.dev",desc:"OSV vulnerability database"},{domain:"*.docker.com",desc:"Docker registry"},{domain:"*.docker.io",desc:"Docker registry"},{domain:"registry-1.docker.io",desc:"Docker registry"},{domain:"rubygems.org",desc:"RubyGems"}];for(let t of e)FS({domain:t.domain,decision:"allow",description:t.desc})}function Rs(){bf();try{fh(MS,JSON.stringify(F,null,2),"utf-8")}catch{}}function cI(){bf();try{fh(IS,JSON.stringify(Array.from(Ps.values()),null,2),"utf-8")}catch{}}function Sl(e){if(ht.enableAuditLog){bf();try{fh(ES,JSON.stringify({...e,timestamp:Date.now()})+`
41
41
  `,{flag:"a"})}catch{}}}function oI(e){if(ht.enableRequestLog&&!(ht.logBlockedOnly&&e.decision!=="block")){bf();try{fh(DS,JSON.stringify(e)+`
42
- `,{flag:"a"})}catch{}}}function w6(e,t){if(e=e.toLowerCase(),t=t.toLowerCase(),e===t)return!0;if(t.startsWith("*.")){let n=t.slice(2);return e===n||e.endsWith("."+n)}return!1}function k6(e){return!!(e==="localhost"||e==="0.0.0.0"||/^127\./.test(e)||/^10\./.test(e)||/^192\.168\./.test(e)||/^172\.(?:1[6-9]|2\d|3[01])\./.test(e)||/^169\.254\./.test(e)||e==="::1"||/^fe80:|^fc00:|^fd00:/i.test(e))}function x6(e){return e==="169.254.169.254"||e==="metadata.google.internal"||e==="metadata.azure.com"||e==="100.100.100.200"}function $6(e){let t=(()=>{try{return new aI(e)}catch{return null}})();if(!t)return"unknown";let n=t.hostname.toLowerCase();return n.includes("webhook")||n.includes("hooks.")?"webhook":n.includes("api.")||n.startsWith("api-")||t.pathname.startsWith("/api/")||t.pathname.startsWith("/v1/")||t.pathname.startsWith("/v2/")?"api":n.includes("cdn.")||n.includes("static.")||n.endsWith(".cloudfront.net")||n.endsWith(".cloudflare.com")?"cdn":n.includes("telemetry.")||n.includes("analytics.")||n.includes("metrics.")||n.includes("sentry")?"telemetry":"unknown"}function C6(e){if(!ht.enabled)return{decision:"allow",reason:"Egress firewall disabled",classification:"unknown",riskScore:0};D.totalRequests++;let t;try{t=new aI(e.url)}catch{return D.totalBlocked++,D.byBlockReason.malformed_url=(D.byBlockReason.malformed_url||0)+1,Rs(),{decision:"block",reason:"Malformed URL",classification:"unknown",riskScore:.5}}let n=t.hostname.toLowerCase(),r=t.protocol.replace(":",""),s=t.port?parseInt(t.port,10):r==="https"?443:80,i=ht.enableAutoClassification?$6(e.url):"unknown";if(D.byDomain[n]||(D.byDomain[n]={requests:0,allowed:0,blocked:0}),D.byDomain[n].requests++,ht.blockPrivateIPs&&k6(n))return D.totalSSRFBlocked++,D.totalBlocked++,D.byBlockReason.private_ip=(D.byBlockReason.private_ip||0)+1,D.byDomain[n].blocked++,Rs(),Sl({event:"blocked_ssrf",url:e.url,reason:"private_ip"}),io.emit("ssrf_blocked",{url:e.url,hostname:n}),{decision:"block",reason:`Private IP blocked: ${n}`,classification:i,riskScore:.9};if(ht.blockMetadataServices&&x6(n))return D.totalSSRFBlocked++,D.totalBlocked++,D.byBlockReason.metadata_service=(D.byBlockReason.metadata_service||0)+1,D.byDomain[n].blocked++,Rs(),Sl({event:"blocked_metadata",url:e.url}),io.emit("metadata_blocked",{url:e.url,hostname:n}),{decision:"block",reason:`Cloud metadata service blocked: ${n}`,classification:i,riskScore:.99};let o;for(let a of Ps.values())if(w6(n,a.domain)){if(a.protocol&&a.protocol!=="any"&&a.protocol!==r||a.ports&&a.ports.length>0&&!a.ports.includes(s)||a.pathPrefix&&!t.pathname.startsWith(a.pathPrefix))continue;o=a;break}if(o){if(o.decision==="block")return D.totalBlocked++,D.byBlockReason.explicit_deny=(D.byBlockReason.explicit_deny||0)+1,D.byDomain[n].blocked++,Rs(),{decision:"block",reason:`Explicit deny: ${o.domain}`,matchedRule:o,classification:i,riskScore:.7};if(o.maxRequestsPerMinute){let a=Date.now();if((o.lastRequestAt&&a-o.lastRequestAt<6e4?o.totalRequests:0)>o.maxRequestsPerMinute)return D.totalBlocked++,D.byBlockReason.rate_limit=(D.byBlockReason.rate_limit||0)+1,Rs(),{decision:"block",reason:`Rate limit exceeded for ${o.domain}`,matchedRule:o,classification:i,riskScore:.5}}if(o.totalRequests++,o.lastRequestAt=Date.now(),e.bytesEstimated&&(o.totalBytes+=e.bytesEstimated),D.totalAllowed++,D.byDomain[n].allowed++,D.byClassification[i]=(D.byClassification[i]||0)+1,Rs(),ht.enableAnomalyDetection){let a=Date.now();for(vl.push({timestamp:a,hostname:n});vl.length>0&&a-vl[0].timestamp>6e4;)vl.shift();vl.length>ht.burstThreshold&&(D.totalAnomalies++,io.emit("burst_detected",{count:vl.length}))}return oI({id:PS(4).toString("hex"),timestamp:Date.now(),url:e.url,hostname:n,decision:"allow",toolName:e.toolName,agentId:e.agentId,classification:i,reason:"matched allow rule"}),io.emit("request_allowed",{url:e.url,hostname:n,classification:i}),{decision:"allow",reason:`Allowed: ${o.domain}`,matchedRule:o,classification:i,riskScore:.05}}return ht.defaultDecision==="allow"?(D.totalAllowed++,Rs(),{decision:"allow",reason:"No rule, default allow",classification:i,riskScore:.4}):ht.defaultDecision==="audit_only"?(D.totalAllowed++,Sl({event:"audit_only_request",url:e.url,hostname:n}),Rs(),{decision:"audit_only",reason:"No rule, audit-only mode",classification:i,riskScore:.4}):(D.totalBlocked++,D.byBlockReason.no_rule=(D.byBlockReason.no_rule||0)+1,D.byDomain[n].blocked++,Rs(),oI({id:PS(4).toString("hex"),timestamp:Date.now(),url:e.url,hostname:n,decision:"block",toolName:e.toolName,agentId:e.agentId,classification:i,reason:"no allow rule"}),Sl({event:"blocked_no_rule",url:e.url,hostname:n,classification:i}),io.emit("request_blocked",{url:e.url,hostname:n,reason:"no_rule"}),{decision:"block",reason:`No allow rule for ${n}. Add via /egress add ${n}`,classification:i,riskScore:.6})}function FS(e){let t={id:PS(6).toString("hex"),domain:e.domain,decision:e.decision||"allow",description:e.description,protocol:e.protocol,ports:e.ports,pathPrefix:e.pathPrefix,maxRequestsPerMinute:e.maxRequestsPerMinute,approvedAt:Date.now(),approvedBy:e.approvedBy||"system",totalRequests:0,totalBytes:0,classification:e.classification};return Ps.set(t.id,t),cI(),Sl({event:"rule_added",ruleId:t.id,domain:e.domain,decision:t.decision}),io.emit("rule_added",{rule:t}),t}function A6(e){return Ps.has(e)?(Ps.delete(e),cI(),Sl({event:"rule_removed",ruleId:e}),!0):!1}function T6(e,t){return FS({domain:e,decision:"block",description:t,approvedBy:"manual_block"})}function _6(){return Array.from(Ps.values())}function R6(e){return Ps.get(e)}function P6(){return{...ht}}function I6(e){ht={...ht,...e}}function M6(){return{...D}}function E6(){D={totalRequests:0,totalAllowed:0,totalBlocked:0,totalSSRFBlocked:0,totalAnomalies:0,totalBytesOut:0,totalBytesIn:0,byDomain:{},byClassification:{},byBlockReason:{}},Rs()}function D6(){return io}function F6(e=50){if(!uh(DS))return[];try{return dh(DS,"utf-8").split(`
42
+ `,{flag:"a"})}catch{}}}function w6(e,t){if(e=e.toLowerCase(),t=t.toLowerCase(),e===t)return!0;if(t.startsWith("*.")){let n=t.slice(2);return e===n||e.endsWith("."+n)}return!1}function k6(e){return!!(e==="localhost"||e==="0.0.0.0"||/^127\./.test(e)||/^10\./.test(e)||/^192\.168\./.test(e)||/^172\.(?:1[6-9]|2\d|3[01])\./.test(e)||/^169\.254\./.test(e)||e==="::1"||/^fe80:|^fc00:|^fd00:/i.test(e))}function x6(e){return e==="169.254.169.254"||e==="metadata.google.internal"||e==="metadata.azure.com"||e==="100.100.100.200"}function $6(e){let t=(()=>{try{return new aI(e)}catch{return null}})();if(!t)return"unknown";let n=t.hostname.toLowerCase();return n.includes("webhook")||n.includes("hooks.")?"webhook":n.includes("api.")||n.startsWith("api-")||t.pathname.startsWith("/api/")||t.pathname.startsWith("/v1/")||t.pathname.startsWith("/v2/")?"api":n.includes("cdn.")||n.includes("static.")||n.endsWith(".cloudfront.net")||n.endsWith(".cloudflare.com")?"cdn":n.includes("telemetry.")||n.includes("analytics.")||n.includes("metrics.")||n.includes("sentry")?"telemetry":"unknown"}function C6(e){if(!ht.enabled)return{decision:"allow",reason:"Egress firewall disabled",classification:"unknown",riskScore:0};F.totalRequests++;let t;try{t=new aI(e.url)}catch{return F.totalBlocked++,F.byBlockReason.malformed_url=(F.byBlockReason.malformed_url||0)+1,Rs(),{decision:"block",reason:"Malformed URL",classification:"unknown",riskScore:.5}}let n=t.hostname.toLowerCase(),r=t.protocol.replace(":",""),s=t.port?parseInt(t.port,10):r==="https"?443:80,i=ht.enableAutoClassification?$6(e.url):"unknown";if(F.byDomain[n]||(F.byDomain[n]={requests:0,allowed:0,blocked:0}),F.byDomain[n].requests++,ht.blockPrivateIPs&&k6(n))return F.totalSSRFBlocked++,F.totalBlocked++,F.byBlockReason.private_ip=(F.byBlockReason.private_ip||0)+1,F.byDomain[n].blocked++,Rs(),Sl({event:"blocked_ssrf",url:e.url,reason:"private_ip"}),io.emit("ssrf_blocked",{url:e.url,hostname:n}),{decision:"block",reason:`Private IP blocked: ${n}`,classification:i,riskScore:.9};if(ht.blockMetadataServices&&x6(n))return F.totalSSRFBlocked++,F.totalBlocked++,F.byBlockReason.metadata_service=(F.byBlockReason.metadata_service||0)+1,F.byDomain[n].blocked++,Rs(),Sl({event:"blocked_metadata",url:e.url}),io.emit("metadata_blocked",{url:e.url,hostname:n}),{decision:"block",reason:`Cloud metadata service blocked: ${n}`,classification:i,riskScore:.99};let o;for(let a of Ps.values())if(w6(n,a.domain)){if(a.protocol&&a.protocol!=="any"&&a.protocol!==r||a.ports&&a.ports.length>0&&!a.ports.includes(s)||a.pathPrefix&&!t.pathname.startsWith(a.pathPrefix))continue;o=a;break}if(o){if(o.decision==="block")return F.totalBlocked++,F.byBlockReason.explicit_deny=(F.byBlockReason.explicit_deny||0)+1,F.byDomain[n].blocked++,Rs(),{decision:"block",reason:`Explicit deny: ${o.domain}`,matchedRule:o,classification:i,riskScore:.7};if(o.maxRequestsPerMinute){let a=Date.now();if((o.lastRequestAt&&a-o.lastRequestAt<6e4?o.totalRequests:0)>o.maxRequestsPerMinute)return F.totalBlocked++,F.byBlockReason.rate_limit=(F.byBlockReason.rate_limit||0)+1,Rs(),{decision:"block",reason:`Rate limit exceeded for ${o.domain}`,matchedRule:o,classification:i,riskScore:.5}}if(o.totalRequests++,o.lastRequestAt=Date.now(),e.bytesEstimated&&(o.totalBytes+=e.bytesEstimated),F.totalAllowed++,F.byDomain[n].allowed++,F.byClassification[i]=(F.byClassification[i]||0)+1,Rs(),ht.enableAnomalyDetection){let a=Date.now();for(vl.push({timestamp:a,hostname:n});vl.length>0&&a-vl[0].timestamp>6e4;)vl.shift();vl.length>ht.burstThreshold&&(F.totalAnomalies++,io.emit("burst_detected",{count:vl.length}))}return oI({id:PS(4).toString("hex"),timestamp:Date.now(),url:e.url,hostname:n,decision:"allow",toolName:e.toolName,agentId:e.agentId,classification:i,reason:"matched allow rule"}),io.emit("request_allowed",{url:e.url,hostname:n,classification:i}),{decision:"allow",reason:`Allowed: ${o.domain}`,matchedRule:o,classification:i,riskScore:.05}}return ht.defaultDecision==="allow"?(F.totalAllowed++,Rs(),{decision:"allow",reason:"No rule, default allow",classification:i,riskScore:.4}):ht.defaultDecision==="audit_only"?(F.totalAllowed++,Sl({event:"audit_only_request",url:e.url,hostname:n}),Rs(),{decision:"audit_only",reason:"No rule, audit-only mode",classification:i,riskScore:.4}):(F.totalBlocked++,F.byBlockReason.no_rule=(F.byBlockReason.no_rule||0)+1,F.byDomain[n].blocked++,Rs(),oI({id:PS(4).toString("hex"),timestamp:Date.now(),url:e.url,hostname:n,decision:"block",toolName:e.toolName,agentId:e.agentId,classification:i,reason:"no allow rule"}),Sl({event:"blocked_no_rule",url:e.url,hostname:n,classification:i}),io.emit("request_blocked",{url:e.url,hostname:n,reason:"no_rule"}),{decision:"block",reason:`No allow rule for ${n}. Add via /egress add ${n}`,classification:i,riskScore:.6})}function FS(e){let t={id:PS(6).toString("hex"),domain:e.domain,decision:e.decision||"allow",description:e.description,protocol:e.protocol,ports:e.ports,pathPrefix:e.pathPrefix,maxRequestsPerMinute:e.maxRequestsPerMinute,approvedAt:Date.now(),approvedBy:e.approvedBy||"system",totalRequests:0,totalBytes:0,classification:e.classification};return Ps.set(t.id,t),cI(),Sl({event:"rule_added",ruleId:t.id,domain:e.domain,decision:t.decision}),io.emit("rule_added",{rule:t}),t}function A6(e){return Ps.has(e)?(Ps.delete(e),cI(),Sl({event:"rule_removed",ruleId:e}),!0):!1}function T6(e,t){return FS({domain:e,decision:"block",description:t,approvedBy:"manual_block"})}function _6(){return Array.from(Ps.values())}function R6(e){return Ps.get(e)}function P6(){return{...ht}}function I6(e){ht={...ht,...e}}function M6(){return{...F}}function E6(){F={totalRequests:0,totalAllowed:0,totalBlocked:0,totalSSRFBlocked:0,totalAnomalies:0,totalBytesOut:0,totalBytesIn:0,byDomain:{},byClassification:{},byBlockReason:{}},Rs()}function D6(){return io}function F6(e=50){if(!uh(DS))return[];try{return dh(DS,"utf-8").split(`
43
43
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function L6(e=100){if(!uh(ES))return[];try{return dh(ES,"utf-8").split(`
44
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function O6(){let e=[];e.push("# Egress Firewall Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total requests: ${D.totalRequests}`),e.push(`- \u2713 Allowed: ${D.totalAllowed}`),e.push(`- \u{1F6AB} Blocked: ${D.totalBlocked}`),e.push(`- \u{1F534} SSRF blocked: ${D.totalSSRFBlocked}`),e.push(`- \u26A0\uFE0F Anomalies: ${D.totalAnomalies}`),e.push(`- Rules: ${Ps.size}`),e.push(""),e.push("## By Block Reason");for(let[n,r]of Object.entries(D.byBlockReason).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## Top Domains");let t=Object.entries(D.byDomain).sort((n,r)=>r[1].requests-n[1].requests).slice(0,15);for(let[n,r]of t)e.push(`- ${n}: ${r.requests} requests (${r.allowed} \u2713 / ${r.blocked} \u{1F6AB})`);return e.push(""),e.push("## Compliance Properties"),e.push(`- \u2713 Per-project allowlist (${Ps.size} rules)`),e.push(`- \u2713 Default decision: ${ht.defaultDecision}`),e.push(`- ${ht.blockPrivateIPs?"\u2713":"\u2717"} SSRF private IP blocking`),e.push(`- ${ht.blockMetadataServices?"\u2713":"\u2717"} Cloud metadata blocking`),e.push(`- ${ht.enableAnomalyDetection?"\u2713":"\u2717"} Anomaly detection`),e.push(`- ${ht.enableAutoClassification?"\u2713":"\u2717"} Request classification`),e.push(`- ${ht.enableRequestLog?"\u2713":"\u2717"} Request logging`),e.push(`- ${ht.enableAuditLog?"\u2713":"\u2717"} Audit log`),e.push(`- Per-domain rate limit: ${ht.defaultPerDomainRpm} rpm`),e.push(`- Global rate limit: ${ht.globalRateLimitPerMin} rpm`),e.join(`
44
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function O6(){let e=[];e.push("# Egress Firewall Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total requests: ${F.totalRequests}`),e.push(`- \u2713 Allowed: ${F.totalAllowed}`),e.push(`- \u{1F6AB} Blocked: ${F.totalBlocked}`),e.push(`- \u{1F534} SSRF blocked: ${F.totalSSRFBlocked}`),e.push(`- \u26A0\uFE0F Anomalies: ${F.totalAnomalies}`),e.push(`- Rules: ${Ps.size}`),e.push(""),e.push("## By Block Reason");for(let[n,r]of Object.entries(F.byBlockReason).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## Top Domains");let t=Object.entries(F.byDomain).sort((n,r)=>r[1].requests-n[1].requests).slice(0,15);for(let[n,r]of t)e.push(`- ${n}: ${r.requests} requests (${r.allowed} \u2713 / ${r.blocked} \u{1F6AB})`);return e.push(""),e.push("## Compliance Properties"),e.push(`- \u2713 Per-project allowlist (${Ps.size} rules)`),e.push(`- \u2713 Default decision: ${ht.defaultDecision}`),e.push(`- ${ht.blockPrivateIPs?"\u2713":"\u2717"} SSRF private IP blocking`),e.push(`- ${ht.blockMetadataServices?"\u2713":"\u2717"} Cloud metadata blocking`),e.push(`- ${ht.enableAnomalyDetection?"\u2713":"\u2717"} Anomaly detection`),e.push(`- ${ht.enableAutoClassification?"\u2713":"\u2717"} Request classification`),e.push(`- ${ht.enableRequestLog?"\u2713":"\u2717"} Request logging`),e.push(`- ${ht.enableAuditLog?"\u2713":"\u2717"} Audit log`),e.push(`- Per-domain rate limit: ${ht.defaultPerDomainRpm} rpm`),e.push(`- Global rate limit: ${ht.globalRateLimitPerMin} rpm`),e.join(`
45
45
  `)}function j6(e){let t=[],n=e.decision==="allow"?"\u{1F7E2}":e.decision==="block"?"\u{1F534}":"\u{1F7E1}";return t.push(`${n} **${e.domain}** (${e.decision})`),t.push(` ID: ${e.id}`),e.description&&t.push(` Description: ${e.description}`),e.protocol&&t.push(` Protocol: ${e.protocol}`),e.ports?.length&&t.push(` Ports: ${e.ports.join(", ")}`),e.pathPrefix&&t.push(` Path: ${e.pathPrefix}`),e.maxRequestsPerMinute&&t.push(` Rate limit: ${e.maxRequestsPerMinute}/min`),t.push(` Stats: ${e.totalRequests} requests`),t.push(` Approved: ${new Date(e.approvedAt).toISOString()} by ${e.approvedBy}`),t.join(`
46
46
  `)}function B6(e,t){let n=e.decision==="allow"?"\u2713":e.decision==="block"?"\u{1F6AB}":"\u{1F4CB}",r=[];return r.push(`${n} **${e.decision.toUpperCase()}** ${t}`),r.push(` Reason: ${e.reason}`),r.push(` Classification: ${e.classification}`),r.push(` Risk: ${(e.riskScore*100).toFixed(0)}/100`),e.matchedRule&&r.push(` Matched rule: ${e.matchedRule.domain}`),r.join(`
47
- `)}var b6,ht,yf,IS,MS,ES,DS,io,Ps,vl,D,Sf=w(()=>{"use strict";b6={enabled:!0,defaultDecision:"block",blockPrivateIPs:!0,blockMetadataServices:!0,defaultPerDomainRpm:60,globalRateLimitPerMin:1e3,enableAnomalyDetection:!0,burstThreshold:100,resolveBeforeAllow:!1,cacheDnsResultsMs:300*1e3,enableAutoClassification:!0,enableRequestLog:!0,logBlockedOnly:!1,enableAuditLog:!0},ht={...b6},yf=hf(h6(),".aiaca","egress-firewall"),IS=hf(yf,"rules.json"),MS=hf(yf,"stats.json"),ES=hf(yf,"audit.jsonl"),DS=hf(yf,"requests.jsonl"),io=new y6;io.setMaxListeners(50);Ps=new Map,vl=[],D={totalRequests:0,totalAllowed:0,totalBlocked:0,totalSSRFBlocked:0,totalAnomalies:0,totalBytesOut:0,totalBytesIn:0,byDomain:{},byClassification:{},byBlockReason:{}};v6()});var $l={};$($l,{StreamingScanner:()=>HS,addCustomPattern:()=>X6,allowFingerprint:()=>Y6,configure:()=>n8,formatScanResult:()=>c8,getAuditLog:()=>a8,getConfig:()=>t8,getEvents:()=>i8,getStats:()=>r8,listAllowed:()=>Z6,listCustomPatterns:()=>e8,listPatterns:()=>o8,removeFingerprint:()=>Q6,resetStats:()=>s8,scanText:()=>US});import{existsSync as wf,mkdirSync as N6,readFileSync as kf,writeFileSync as xf}from"fs";import{join as wl}from"path";import{homedir as q6}from"os";import{createHash as mI}from"crypto";import{EventEmitter as U6}from"events";function xl(){N6(kl,{recursive:!0})}function z6(){if(xl(),wf(LS))try{yt={...yt,...JSON.parse(kf(LS,"utf-8"))}}catch{}if(wf(jS))try{let e=JSON.parse(kf(jS,"utf-8"));for(let t of e)Ve.allowedFingerprints.add(t)}catch{}if(wf(BS))try{let e=JSON.parse(kf(BS,"utf-8"));for(let t of e)try{va.push({...t,regex:new RegExp(t.regex.source||t.regex,t.regex.flags||"g")})}catch{}}catch{}if(wf(NS))try{let e=JSON.parse(kf(NS,"utf-8"));for(let t of e)mh.add(t)}catch{}}function gI(){xl();try{xf(LS,JSON.stringify(yt,null,2),"utf-8")}catch{}}function hI(){xl();try{xf(jS,JSON.stringify(Array.from(Ve.allowedFingerprints),null,2),"utf-8")}catch{}}function G6(){xl();try{let e=Array.from(mh).slice(-5e4);xf(NS,JSON.stringify(e,null,2),"utf-8")}catch{}}function V6(e){if(Ve.enableAuditLog){xl();try{xf(OS,JSON.stringify({...e,timestamp:Date.now()})+`
48
- `,{flag:"a"})}catch{}}}function lI(e){if(!e.length)return 0;let t={};for(let r of e)t[r]=(t[r]||0)+1;let n=0;for(let r of Object.values(t)){let s=r/e.length;n-=s*Math.log2(s)}return n}function uI(e,t,n,r=80){let s=Math.max(0,t-r),i=Math.min(e.length,n+r);return e.slice(s,i).replace(/\s+/g," ").trim()}function dI(e,t){return[/\btest\b/i,/\bexample\b/i,/\bsample\b/i,/\bplaceholder\b/i,/\bdummy\b/i,/\bfake\b/i,/\bmock\b/i,/\bfixture\b/i,/\bdocs?\b/i,/\bdocumentation\b/i,/\bxxxx+\b/i].some(r=>r.test(t))}function J6(e,t){let n=0,r=!0;if(e.contextHints){let s=e.contextHints.filter(i=>t.toLowerCase().includes(i.toLowerCase())).length;n+=s*.1,s===0&&e.type==="password"&&(r=!1)}if(e.contextAntiHints){for(let s of e.contextAntiHints)if(t.toLowerCase().includes(s.toLowerCase())){r=!1;break}}return{ok:r,confidenceBoost:Math.min(n,.3)}}function fI(e){if(!e)return"";switch(Ve.redactionStyle){case"asterisks":return"*".repeat(Math.min(e.length,16));case"brackets":return"[REDACTED]";case"partial":return e.length<8?"***":e.slice(0,3)+"*".repeat(Math.min(e.length-6,12))+e.slice(-3);case"fingerprint":return`[REDACTED:${mI("sha256").update(e).digest("hex").slice(0,8)}]`;default:return"[REDACTED]"}}function pI(e){return mI("sha256").update(e).digest("hex").slice(0,16)}function W6(e){switch(Ve.complianceMode){case"pci":return["pii_credit_card","pii_ssn"].includes(e)||e.startsWith("aws_")||e==="database_url";case"hipaa":return e.startsWith("pii_")||e==="database_url";case"gdpr":return e.startsWith("pii_");default:return!0}}function US(e,t="unknown"){let n=Date.now();if(!Ve.enabled||!e)return{matches:[],totalChecks:0,scanDurationMs:0,action:"allow",reason:"Scanner disabled or empty",riskScore:0};let r=e;e.length>Ve.maxScanBytes&&(e=e.slice(0,Ve.maxScanBytes));let s=[],i=new Set;if(Ve.enableRegex){let g=[...qS,...va];for(let h of g){if(!W6(h.type))continue;h.regex.lastIndex=0;let v;for(;(v=h.regex.exec(e))!==null;){let y=h.matchGroup??0,b=v[y]||v[0];if(!b)continue;let k=v.index+(y>0?v[0].indexOf(b):0),S=k+b.length,x=pI(b);if(Ve.allowedFingerprints.has(x)||i.has(x))continue;i.add(x);let A=uI(e,k,S),{ok:j,confidenceBoost:I}=J6(h,A);if(!j||Ve.suppressTestPatterns&&dI(e,A))continue;let ye=.85;if(h.minEntropy!==void 0){let De=lI(b);if(De<h.minEntropy)continue;ye=Math.min(.95,.6+(De-h.minEntropy)*.1)}ye=Math.min(1,ye+I);let Ne=e.slice(0,k).split(`
49
- `),mn=Ne.length,nn=Ne[Ne.length-1].length+1;s.push({id:`m_${s.length}_${x.slice(0,8)}`,type:h.type,severity:h.severity,startIndex:k,endIndex:S,line:mn,column:nn,match:b,redacted:fI(b),context:A.slice(0,200),detector:"regex",confidence:ye,provider:h.provider,fingerprint:x,remediation:h.remediation}),mh.has(x)||(mh.add(x),yt.uniqueLeaksDetected++),v.index===h.regex.lastIndex&&h.regex.lastIndex++}}}if(Ve.enableEntropy){let g=e.match(/[A-Za-z0-9+/=_\-]{20,}/g)||[];for(let h of g){if(h.length>200)continue;let v=pI(h);if(Ve.allowedFingerprints.has(v)||i.has(v))continue;let y=lI(h);if(y<4.5)continue;let b=e.indexOf(h);if(b<0)continue;let k=uI(e,b,b+h.length);if(Ve.suppressTestPatterns&&dI(e,k)||!/(?:key|token|secret|password|auth|credential|api)/i.test(k))continue;i.add(v);let S=e.slice(0,b).split(`
50
- `);s.push({id:`e_${s.length}_${v.slice(0,8)}`,type:"high_entropy",severity:"medium",startIndex:b,endIndex:b+h.length,line:S.length,column:S[S.length-1].length+1,match:h,redacted:fI(h),context:k.slice(0,200),detector:"entropy",confidence:Math.min(.85,.5+(y-4.5)*.1),fingerprint:v})}}let o={critical:5,high:4,medium:3,low:2,info:1};s.sort((g,h)=>o[h.severity]-o[g.severity]);let a=s.some(g=>g.severity==="critical"),c=s.some(g=>g.severity==="high"),l="allow",u="No secrets detected";s.length>0&&(a&&Ve.blockOnCritical?(l="block",u=`${s.filter(g=>g.severity==="critical").length} critical secret(s) detected`):c&&Ve.blockOnHigh?(l="block",u=`${s.filter(g=>g.severity==="high").length} high-severity secret(s) detected`):(l=Ve.defaultAction,u=`${s.length} secret(s) detected \u2014 ${l}`));let d;(l==="redact"||l==="block")&&(d=K6(r,s));let f={critical:1,high:.7,medium:.4,low:.2,info:.05},p=Math.min(1,s.reduce((g,h)=>g+f[h.severity]*h.confidence,0)*.25);yt.totalScans++,yt.totalBytesScanned+=e.length,yt.totalMatchesFound+=s.length,l==="redact"&&yt.totalRedactions++,l==="block"&&yt.totalBlocks++;for(let g of s)yt.byType[g.type]=(yt.byType[g.type]||0)+1,yt.bySeverity[g.severity]=(yt.bySeverity[g.severity]||0)+1,yt.byDetector[g.detector]=(yt.byDetector[g.detector]||0)+1,g.provider&&(yt.byProvider[g.provider]=(yt.byProvider[g.provider]||0)+1);let m=Date.now()-n;return yt.averageScanMs=(yt.averageScanMs*(yt.totalScans-1)+m)/yt.totalScans,gI(),s.length>0&&(G6(),V6({source:t,matchCount:s.length,action:l,riskScore:p,types:s.map(g=>g.type),severities:s.map(g=>g.severity)}),ph.emit("leak_detected",{source:t,matches:s,action:l}),a&&ph.emit("critical_leak",{source:t,matches:s})),{matches:s,totalChecks:qS.length+va.length,scanDurationMs:m,redactedText:d,action:l,reason:u,riskScore:p}}function K6(e,t){let n=[...t].sort((s,i)=>i.startIndex-s.startIndex),r=e;for(let s of n)r=r.slice(0,s.startIndex)+s.redacted+r.slice(s.endIndex);return r}function Y6(e){Ve.allowedFingerprints.add(e),hI()}function Q6(e){let t=Ve.allowedFingerprints.delete(e);return t&&hI(),t}function Z6(){return Array.from(Ve.allowedFingerprints)}function X6(e){va.push(e),xl();try{xf(BS,JSON.stringify(va.map(t=>({...t,regex:{source:t.regex.source,flags:t.regex.flags}})),null,2),"utf-8")}catch{}}function e8(){return[...va]}function t8(){return{...Ve,allowedFingerprints:new Set(Ve.allowedFingerprints)}}function n8(e){Ve={...Ve,...e}}function r8(){return{...yt}}function s8(){yt={totalScans:0,totalMatchesFound:0,totalRedactions:0,totalBlocks:0,byType:{},bySeverity:{},byProvider:{},byDetector:{},averageScanMs:0,totalBytesScanned:0,uniqueLeaksDetected:0},gI()}function i8(){return ph}function o8(){return[...qS,...va]}function a8(e=100){if(!wf(OS))return[];try{return kf(OS,"utf-8").split(`
51
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function c8(e){let t=[],n=e.action==="block"?"\u{1F6AB}":e.action==="redact"?"\u{1F9F9}":e.matches.length>0?"\u26A0\uFE0F":"\u2713";if(t.push(`${n} **Secret Scan Result**`),t.push(`Action: ${e.action.toUpperCase()}`),t.push(`Reason: ${e.reason}`),t.push(`Risk: ${(e.riskScore*100).toFixed(0)}/100`),t.push(`Duration: ${e.scanDurationMs}ms | Patterns checked: ${e.totalChecks}`),t.push(""),e.matches.length>0){t.push(`## Matches (${e.matches.length})`);for(let r of e.matches.slice(0,20)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="high"?"\u26A0\uFE0F ":r.severity==="medium"?"\u26A1":"\u2139\uFE0F ";t.push(`${s} [${r.type}] line ${r.line}:${r.column} | confidence ${(r.confidence*100).toFixed(0)}% | ${r.detector}`),t.push(` Match: ${r.redacted}`),r.provider&&t.push(` Provider: ${r.provider}`),r.remediation&&t.push(` Fix: ${r.remediation}`)}}return t.join(`
52
- `)}var H6,Ve,kl,LS,OS,jS,BS,NS,ph,mh,va,yt,qS,HS,Cl=w(()=>{"use strict";H6={enabled:!0,enableRegex:!0,enableEntropy:!0,enableContext:!0,enableML:!1,defaultAction:"redact",blockOnCritical:!0,blockOnHigh:!1,complianceMode:"standard",maxScanBytes:5*1024*1024,streamingChunkBytes:64*1024,allowedFingerprints:new Set,redactionStyle:"partial",enableAuditLog:!0,suppressTestPatterns:!0},Ve={...H6},kl=wl(q6(),".aiaca","secret-scanner"),LS=wl(kl,"stats.json"),OS=wl(kl,"audit.jsonl"),jS=wl(kl,"allowlist.json"),BS=wl(kl,"custom-patterns.json"),NS=wl(kl,"seen.json"),ph=new U6;ph.setMaxListeners(50);mh=new Set,va=[],yt={totalScans:0,totalMatchesFound:0,totalRedactions:0,totalBlocks:0,byType:{},bySeverity:{},byProvider:{},byDetector:{},averageScanMs:0,totalBytesScanned:0,uniqueLeaksDetected:0};z6();qS=[{type:"aws_credentials",name:"AWS Access Key ID",provider:"aws",regex:/\b((?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASCA)[A-Z0-9]{16})\b/g,severity:"critical",remediation:"Rotate AWS credentials immediately via IAM console"},{type:"aws_credentials",name:"AWS Secret Access Key",provider:"aws",regex:/\b(aws[_\-]?secret[_\-]?(?:access[_\-]?)?key[\s"':=]+)([A-Za-z0-9/+=]{40})\b/gi,severity:"critical",matchGroup:2,contextHints:["aws","secret","access"]},{type:"aws_credentials",name:"AWS Session Token",provider:"aws",regex:/\b(?:aws[_\-]?session[_\-]?token[\s"':=]+)([A-Za-z0-9/+=]{100,})\b/gi,severity:"critical",matchGroup:1},{type:"gcp_credentials",name:"GCP Service Account JSON",provider:"gcp",regex:/"type":\s*"service_account"[^}]+"private_key":\s*"-----BEGIN[^"]+"/g,severity:"critical"},{type:"gcp_credentials",name:"GCP API Key",provider:"gcp",regex:/\b(AIza[0-9A-Za-z\-_]{35})\b/g,severity:"high"},{type:"gcp_credentials",name:"GCP OAuth Token",provider:"gcp",regex:/\b(ya29\.[0-9A-Za-z\-_]+)\b/g,severity:"high"},{type:"azure_credentials",name:"Azure Storage Connection String",provider:"azure",regex:/DefaultEndpointsProtocol=https?;AccountName=[^;]+;AccountKey=[A-Za-z0-9+/=]+/g,severity:"critical"},{type:"azure_credentials",name:"Azure Client Secret",provider:"azure",regex:/\b(azure[_\-]?client[_\-]?secret[\s"':=]+)([A-Za-z0-9._~\-]{32,})\b/gi,severity:"high",matchGroup:2},{type:"github_token",name:"GitHub Personal Access Token",provider:"github",regex:/\b(ghp_[A-Za-z0-9]{36})\b/g,severity:"critical",remediation:"Revoke at github.com/settings/tokens"},{type:"github_token",name:"GitHub OAuth Token",provider:"github",regex:/\b(gho_[A-Za-z0-9]{36})\b/g,severity:"critical"},{type:"github_token",name:"GitHub User Token",provider:"github",regex:/\b(ghu_[A-Za-z0-9]{36})\b/g,severity:"critical"},{type:"github_token",name:"GitHub Server Token",provider:"github",regex:/\b(ghs_[A-Za-z0-9]{36})\b/g,severity:"critical"},{type:"github_token",name:"GitHub Refresh Token",provider:"github",regex:/\b(ghr_[A-Za-z0-9]{36,})\b/g,severity:"critical"},{type:"gitlab_token",name:"GitLab Personal Access Token",provider:"gitlab",regex:/\b(glpat-[A-Za-z0-9_\-]{20})\b/g,severity:"critical"},{type:"gitlab_token",name:"GitLab CI Token",provider:"gitlab",regex:/\b(glcbt-[A-Za-z0-9_\-]{20,})\b/g,severity:"high"},{type:"slack_token",name:"Slack Bot Token",provider:"slack",regex:/\b(xox[baprs]-[A-Za-z0-9\-]{10,})\b/g,severity:"critical"},{type:"slack_token",name:"Slack Webhook URL",provider:"slack",regex:/https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,severity:"high"},{type:"discord_token",name:"Discord Bot Token",provider:"discord",regex:/\b(?:discord[_\-]?(?:bot[_\-]?)?token[\s"':=]+)?([MN][A-Za-z\d]{23}\.[\w\-]{6}\.[\w\-]{27,})\b/g,severity:"critical",matchGroup:1},{type:"discord_token",name:"Discord Webhook",provider:"discord",regex:/https:\/\/discord(?:app)?\.com\/api\/webhooks\/\d+\/[A-Za-z0-9_\-]+/g,severity:"high"},{type:"stripe_key",name:"Stripe Live Secret Key",provider:"stripe",regex:/\b(sk_live_[A-Za-z0-9]{24,})\b/g,severity:"critical",remediation:"Roll key at dashboard.stripe.com/apikeys"},{type:"stripe_key",name:"Stripe Test Secret Key",provider:"stripe",regex:/\b(sk_test_[A-Za-z0-9]{24,})\b/g,severity:"high"},{type:"stripe_key",name:"Stripe Restricted Key",provider:"stripe",regex:/\b(rk_live_[A-Za-z0-9]{24,})\b/g,severity:"critical"},{type:"twilio_key",name:"Twilio Account SID",provider:"twilio",regex:/\b(AC[a-f0-9]{32})\b/g,severity:"high"},{type:"twilio_key",name:"Twilio Auth Token",provider:"twilio",regex:/\b(?:twilio[_\-]?(?:auth[_\-]?)?token[\s"':=]+)([a-f0-9]{32})\b/gi,severity:"critical",matchGroup:1},{type:"sendgrid_key",name:"SendGrid API Key",provider:"sendgrid",regex:/\b(SG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43})\b/g,severity:"critical"},{type:"mailgun_key",name:"Mailgun API Key",provider:"mailgun",regex:/\b(key-[a-f0-9]{32})\b/g,severity:"high"},{type:"npm_token",name:"npm Token",provider:"npm",regex:/\b(npm_[A-Za-z0-9]{36})\b/g,severity:"high"},{type:"pypi_token",name:"PyPI Token",provider:"pypi",regex:/\b(pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_\-]{50,})\b/g,severity:"high"},{type:"crates_token",name:"crates.io Token",provider:"crates.io",regex:/\b(cio[A-Za-z0-9]{32})\b/g,severity:"high"},{type:"jwt",name:"JSON Web Token (JWT)",regex:/\b(eyJ[A-Za-z0-9_=\-]+\.eyJ[A-Za-z0-9_=\-]+\.[A-Za-z0-9_\-+/=]+)\b/g,severity:"high"},{type:"oauth_token",name:"Bearer Token",regex:/\b(?:bearer\s+)([A-Za-z0-9_\-\.~+/]{30,}=*)\b/gi,severity:"high",matchGroup:1,contextHints:["authorization","bearer"]},{type:"api_key",name:"Generic API Key",regex:/\b(?:api[_\-]?key|apikey|api[_\-]?secret)[\s"':=]+([A-Za-z0-9_\-]{20,})\b/gi,severity:"high",matchGroup:1,contextHints:["api"]},{type:"session_cookie",name:"Session Cookie",regex:/\b(?:session|sessid|jsessionid|phpsessid)[\s"':=]+([A-Za-z0-9_\-]{20,})\b/gi,severity:"medium",matchGroup:1},{type:"private_key",name:"PEM Private Key",regex:/-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----[\s\S]+?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/g,severity:"critical",remediation:"Rotate the keypair immediately"},{type:"ssh_key",name:"SSH Private Key",regex:/-----BEGIN OPENSSH PRIVATE KEY-----[\s\S]+?-----END OPENSSH PRIVATE KEY-----/g,severity:"critical"},{type:"gpg_key",name:"GPG Private Key",regex:/-----BEGIN PGP PRIVATE KEY BLOCK-----[\s\S]+?-----END PGP PRIVATE KEY BLOCK-----/g,severity:"critical"},{type:"cert",name:"Certificate",regex:/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g,severity:"low"},{type:"database_url",name:"PostgreSQL URL",regex:/\b(postgres(?:ql)?:\/\/[^:\s]+:([^@\s]+)@[^\s]+)\b/g,severity:"critical",matchGroup:1,remediation:"Rotate DB password"},{type:"database_url",name:"MySQL URL",regex:/\b(mysql:\/\/[^:\s]+:([^@\s]+)@[^\s]+)\b/g,severity:"critical",matchGroup:1},{type:"database_url",name:"MongoDB URL",regex:/\b(mongodb(?:\+srv)?:\/\/[^:\s]+:([^@\s]+)@[^\s]+)\b/g,severity:"critical",matchGroup:1},{type:"database_url",name:"Redis URL with password",regex:/\b(redis(?:s)?:\/\/[^:\s]*:([^@\s]+)@[^\s]+)\b/g,severity:"high",matchGroup:1},{type:"connection_string",name:"Generic Connection String with password",regex:/\b((?:user|uid|username)[\s]*=[\s]*[^;\s]+;[\s]*(?:password|pwd)[\s]*=[\s]*[^;\s]+)\b/gi,severity:"high"},{type:"password",name:"Password Assignment",regex:/\b(?:password|passwd|pwd|secret)[\s"':=]+["']?([A-Za-z0-9!@#$%^&*\-_+=]{8,})["']?/gi,severity:"high",matchGroup:1,contextHints:["password"],contextAntiHints:["hash","bcrypt","salted","placeholder","example"]},{type:"pii_email",name:"Email Address",regex:/\b([A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,})\b/g,severity:"low"},{type:"pii_phone",name:"US Phone Number",regex:/\b((?:\+?1[\s\-.]?)?\(?[2-9][0-9]{2}\)?[\s\-.]?[0-9]{3}[\s\-.]?[0-9]{4})\b/g,severity:"medium"},{type:"pii_ssn",name:"US Social Security Number",regex:/\b((?:\d{3}-\d{2}-\d{4})|(?:\d{9}))\b/g,severity:"critical",contextHints:["ssn","social"]},{type:"pii_credit_card",name:"Credit Card Number",regex:/\b((?:\d{4}[\s\-]?){3}\d{4})\b/g,severity:"critical"},{type:"pii_ip",name:"IPv4 Address",regex:/\b((?:\d{1,3}\.){3}\d{1,3})\b/g,severity:"low"},{type:"pii_passport",name:"US Passport Number",regex:/\b([A-Z]{1,2}\d{6,9})\b/g,severity:"high",contextHints:["passport"]},{type:"crypto_seed",name:"Mnemonic Seed Phrase (12-word)",regex:/\b((?:\b[a-z]{3,8}\b[\s\-]+){11}\b[a-z]{3,8}\b)\b/gi,severity:"critical",contextHints:["mnemonic","seed","wallet","phrase"]},{type:"high_entropy",name:"High Entropy String",regex:/["'`]([A-Za-z0-9+/=_\-]{32,})["'`]/g,severity:"medium",minEntropy:4.5,matchGroup:1}];HS=class{buffer="";offset=0;allMatches=[];source;overlapSize=1024;constructor(t="stream"){this.source=t}ingest(t){if(this.buffer+=t,this.buffer.length<Ve.streamingChunkBytes)return{matches:[],redactedChunk:t};let n=this.buffer.slice(0,this.buffer.length-this.overlapSize),r=US(n,this.source);this.allMatches.push(...r.matches);let s=r.redactedText||n;return this.buffer=this.buffer.slice(n.length),{matches:r.matches,redactedChunk:s}}finalize(){if(this.buffer.length>0){let t=US(this.buffer,this.source);this.allMatches.push(...t.matches);let n=t.redactedText||this.buffer,r=this.allMatches;return this.buffer="",{matches:r,redactedText:n}}return{matches:this.allMatches,redactedText:""}}}});var hh={};$(hh,{clearCache:()=>j8,compareVersions:()=>Cf,configure:()=>F8,detectEcosystems:()=>VS,formatScanResult:()=>B8,generateSBOM:()=>R8,getConfig:()=>D8,getStats:()=>L8,isVersionVulnerable:()=>JS,listSuppressions:()=>_8,parseAllDependencies:()=>AI,parseCargoDependencies:()=>CI,parseGoDependencies:()=>$I,parseNpmDependencies:()=>kI,parsePypiDependencies:()=>xI,resetStats:()=>O8,scanProject:()=>$8,suppressVulnerability:()=>A8,unsuppressVulnerability:()=>T8});import{existsSync as Ft,mkdirSync as l8,readFileSync as pi,writeFileSync as Af}from"fs";import{join as At,resolve as u8}from"path";import{homedir as d8}from"os";import{execSync as SI}from"child_process";function _f(){l8(Tf,{recursive:!0})}function wI(e,t){return`${t}:${e}`}function m8(){if(_f(),!!Ft($f))try{let e=JSON.parse(pi($f,"utf-8"));for(let[t,n]of Object.entries(e))Al.set(t,n)}catch{}}function g8(){_f();try{let e={};for(let[t,n]of Al)e[t]=n;Af($f,JSON.stringify(e),"utf-8")}catch{}}function VS(e){let t=[];return Ft(At(e,"package.json"))&&t.push("npm"),(Ft(At(e,"requirements.txt"))||Ft(At(e,"pyproject.toml"))||Ft(At(e,"Pipfile")))&&t.push("pypi"),Ft(At(e,"go.mod"))&&t.push("go"),Ft(At(e,"Cargo.toml"))&&t.push("crates"),(Ft(At(e,"pom.xml"))||Ft(At(e,"build.gradle"))||Ft(At(e,"build.gradle.kts")))&&t.push("maven"),Ft(At(e,"Gemfile"))&&t.push("rubygems"),Ft(At(e,"composer.json"))&&t.push("packagist"),t}function kI(e){let t=At(e,"package.json");if(!Ft(t))return[];let n=[];try{let s=JSON.parse(pi(t,"utf-8"));for(let[i,o]of Object.entries(s.dependencies||{}))n.push({name:i,version:String(o).replace(/^[\^~]/,""),ecosystem:"npm",isDevDependency:!1,isDirect:!0});for(let[i,o]of Object.entries(s.devDependencies||{}))n.push({name:i,version:String(o).replace(/^[\^~]/,""),ecosystem:"npm",isDevDependency:!0,isDirect:!0})}catch{}let r=At(e,"package-lock.json");if(Ft(r))try{let s=JSON.parse(pi(r,"utf-8")),i=new Set(n.map(o=>o.name));for(let[o,a]of Object.entries(s.packages||{})){if(!o||o==="")continue;let c=o.replace(/^node_modules\//,"").split("/")[0];i.has(c)||(i.add(c),n.push({name:c,version:a.version||"",ecosystem:"npm",isDevDependency:!!a.dev,isDirect:!1}))}}catch{}return n}function xI(e){let t=[],n=At(e,"requirements.txt");if(Ft(n))try{for(let s of pi(n,"utf-8").split(`
47
+ `)}var b6,ht,yf,IS,MS,ES,DS,io,Ps,vl,F,Sf=w(()=>{"use strict";b6={enabled:!0,defaultDecision:"block",blockPrivateIPs:!0,blockMetadataServices:!0,defaultPerDomainRpm:60,globalRateLimitPerMin:1e3,enableAnomalyDetection:!0,burstThreshold:100,resolveBeforeAllow:!1,cacheDnsResultsMs:300*1e3,enableAutoClassification:!0,enableRequestLog:!0,logBlockedOnly:!1,enableAuditLog:!0},ht={...b6},yf=hf(h6(),".aiaca","egress-firewall"),IS=hf(yf,"rules.json"),MS=hf(yf,"stats.json"),ES=hf(yf,"audit.jsonl"),DS=hf(yf,"requests.jsonl"),io=new y6;io.setMaxListeners(50);Ps=new Map,vl=[],F={totalRequests:0,totalAllowed:0,totalBlocked:0,totalSSRFBlocked:0,totalAnomalies:0,totalBytesOut:0,totalBytesIn:0,byDomain:{},byClassification:{},byBlockReason:{}};v6()});var $l={};$($l,{StreamingScanner:()=>HS,addCustomPattern:()=>X6,allowFingerprint:()=>Y6,configure:()=>nG,formatScanResult:()=>cG,getAuditLog:()=>aG,getConfig:()=>tG,getEvents:()=>iG,getStats:()=>rG,listAllowed:()=>Z6,listCustomPatterns:()=>eG,listPatterns:()=>oG,removeFingerprint:()=>Q6,resetStats:()=>sG,scanText:()=>US});import{existsSync as wf,mkdirSync as N6,readFileSync as kf,writeFileSync as xf}from"fs";import{join as wl}from"path";import{homedir as q6}from"os";import{createHash as mI}from"crypto";import{EventEmitter as U6}from"events";function xl(){N6(kl,{recursive:!0})}function z6(){if(xl(),wf(LS))try{yt={...yt,...JSON.parse(kf(LS,"utf-8"))}}catch{}if(wf(jS))try{let e=JSON.parse(kf(jS,"utf-8"));for(let t of e)Ve.allowedFingerprints.add(t)}catch{}if(wf(BS))try{let e=JSON.parse(kf(BS,"utf-8"));for(let t of e)try{va.push({...t,regex:new RegExp(t.regex.source||t.regex,t.regex.flags||"g")})}catch{}}catch{}if(wf(NS))try{let e=JSON.parse(kf(NS,"utf-8"));for(let t of e)mh.add(t)}catch{}}function gI(){xl();try{xf(LS,JSON.stringify(yt,null,2),"utf-8")}catch{}}function hI(){xl();try{xf(jS,JSON.stringify(Array.from(Ve.allowedFingerprints),null,2),"utf-8")}catch{}}function G6(){xl();try{let e=Array.from(mh).slice(-5e4);xf(NS,JSON.stringify(e,null,2),"utf-8")}catch{}}function V6(e){if(Ve.enableAuditLog){xl();try{xf(OS,JSON.stringify({...e,timestamp:Date.now()})+`
48
+ `,{flag:"a"})}catch{}}}function lI(e){if(!e.length)return 0;let t={};for(let r of e)t[r]=(t[r]||0)+1;let n=0;for(let r of Object.values(t)){let s=r/e.length;n-=s*Math.log2(s)}return n}function uI(e,t,n,r=80){let s=Math.max(0,t-r),i=Math.min(e.length,n+r);return e.slice(s,i).replace(/\s+/g," ").trim()}function dI(e,t){return[/\btest\b/i,/\bexample\b/i,/\bsample\b/i,/\bplaceholder\b/i,/\bdummy\b/i,/\bfake\b/i,/\bmock\b/i,/\bfixture\b/i,/\bdocs?\b/i,/\bdocumentation\b/i,/\bxxxx+\b/i].some(r=>r.test(t))}function J6(e,t){let n=0,r=!0;if(e.contextHints){let s=e.contextHints.filter(i=>t.toLowerCase().includes(i.toLowerCase())).length;n+=s*.1,s===0&&e.type==="password"&&(r=!1)}if(e.contextAntiHints){for(let s of e.contextAntiHints)if(t.toLowerCase().includes(s.toLowerCase())){r=!1;break}}return{ok:r,confidenceBoost:Math.min(n,.3)}}function fI(e){if(!e)return"";switch(Ve.redactionStyle){case"asterisks":return"*".repeat(Math.min(e.length,16));case"brackets":return"[REDACTED]";case"partial":return e.length<8?"***":e.slice(0,3)+"*".repeat(Math.min(e.length-6,12))+e.slice(-3);case"fingerprint":return`[REDACTED:${mI("sha256").update(e).digest("hex").slice(0,8)}]`;default:return"[REDACTED]"}}function pI(e){return mI("sha256").update(e).digest("hex").slice(0,16)}function W6(e){switch(Ve.complianceMode){case"pci":return["pii_credit_card","pii_ssn"].includes(e)||e.startsWith("aws_")||e==="database_url";case"hipaa":return e.startsWith("pii_")||e==="database_url";case"gdpr":return e.startsWith("pii_");default:return!0}}function US(e,t="unknown"){let n=Date.now();if(!Ve.enabled||!e)return{matches:[],totalChecks:0,scanDurationMs:0,action:"allow",reason:"Scanner disabled or empty",riskScore:0};let r=e;e.length>Ve.maxScanBytes&&(e=e.slice(0,Ve.maxScanBytes));let s=[],i=new Set;if(Ve.enableRegex){let g=[...qS,...va];for(let h of g){if(!W6(h.type))continue;h.regex.lastIndex=0;let v;for(;(v=h.regex.exec(e))!==null;){let y=h.matchGroup??0,b=v[y]||v[0];if(!b)continue;let k=v.index+(y>0?v[0].indexOf(b):0),S=k+b.length,x=pI(b);if(Ve.allowedFingerprints.has(x)||i.has(x))continue;i.add(x);let A=uI(e,k,S),{ok:D,confidenceBoost:M}=J6(h,A);if(!D||Ve.suppressTestPatterns&&dI(e,A))continue;let ee=.85;if(h.minEntropy!==void 0){let De=lI(b);if(De<h.minEntropy)continue;ee=Math.min(.95,.6+(De-h.minEntropy)*.1)}ee=Math.min(1,ee+M);let Ne=e.slice(0,k).split(`
49
+ `),mn=Ne.length,nn=Ne[Ne.length-1].length+1;s.push({id:`m_${s.length}_${x.slice(0,8)}`,type:h.type,severity:h.severity,startIndex:k,endIndex:S,line:mn,column:nn,match:b,redacted:fI(b),context:A.slice(0,200),detector:"regex",confidence:ee,provider:h.provider,fingerprint:x,remediation:h.remediation}),mh.has(x)||(mh.add(x),yt.uniqueLeaksDetected++),v.index===h.regex.lastIndex&&h.regex.lastIndex++}}}if(Ve.enableEntropy){let g=e.match(/[A-Za-z0-9+/=_\-]{20,}/g)||[];for(let h of g){if(h.length>200)continue;let v=pI(h);if(Ve.allowedFingerprints.has(v)||i.has(v))continue;let y=lI(h);if(y<4.5)continue;let b=e.indexOf(h);if(b<0)continue;let k=uI(e,b,b+h.length);if(Ve.suppressTestPatterns&&dI(e,k)||!/(?:key|token|secret|password|auth|credential|api)/i.test(k))continue;i.add(v);let S=e.slice(0,b).split(`
50
+ `);s.push({id:`e_${s.length}_${v.slice(0,8)}`,type:"high_entropy",severity:"medium",startIndex:b,endIndex:b+h.length,line:S.length,column:S[S.length-1].length+1,match:h,redacted:fI(h),context:k.slice(0,200),detector:"entropy",confidence:Math.min(.85,.5+(y-4.5)*.1),fingerprint:v})}}let o={critical:5,high:4,medium:3,low:2,info:1};s.sort((g,h)=>o[h.severity]-o[g.severity]);let a=s.some(g=>g.severity==="critical"),c=s.some(g=>g.severity==="high"),l="allow",u="No secrets detected";s.length>0&&(a&&Ve.blockOnCritical?(l="block",u=`${s.filter(g=>g.severity==="critical").length} critical secret(s) detected`):c&&Ve.blockOnHigh?(l="block",u=`${s.filter(g=>g.severity==="high").length} high-severity secret(s) detected`):(l=Ve.defaultAction,u=`${s.length} secret(s) detected \u2014 ${l}`));let d;(l==="redact"||l==="block")&&(d=K6(r,s));let f={critical:1,high:.7,medium:.4,low:.2,info:.05},p=Math.min(1,s.reduce((g,h)=>g+f[h.severity]*h.confidence,0)*.25);yt.totalScans++,yt.totalBytesScanned+=e.length,yt.totalMatchesFound+=s.length,l==="redact"&&yt.totalRedactions++,l==="block"&&yt.totalBlocks++;for(let g of s)yt.byType[g.type]=(yt.byType[g.type]||0)+1,yt.bySeverity[g.severity]=(yt.bySeverity[g.severity]||0)+1,yt.byDetector[g.detector]=(yt.byDetector[g.detector]||0)+1,g.provider&&(yt.byProvider[g.provider]=(yt.byProvider[g.provider]||0)+1);let m=Date.now()-n;return yt.averageScanMs=(yt.averageScanMs*(yt.totalScans-1)+m)/yt.totalScans,gI(),s.length>0&&(G6(),V6({source:t,matchCount:s.length,action:l,riskScore:p,types:s.map(g=>g.type),severities:s.map(g=>g.severity)}),ph.emit("leak_detected",{source:t,matches:s,action:l}),a&&ph.emit("critical_leak",{source:t,matches:s})),{matches:s,totalChecks:qS.length+va.length,scanDurationMs:m,redactedText:d,action:l,reason:u,riskScore:p}}function K6(e,t){let n=[...t].sort((s,i)=>i.startIndex-s.startIndex),r=e;for(let s of n)r=r.slice(0,s.startIndex)+s.redacted+r.slice(s.endIndex);return r}function Y6(e){Ve.allowedFingerprints.add(e),hI()}function Q6(e){let t=Ve.allowedFingerprints.delete(e);return t&&hI(),t}function Z6(){return Array.from(Ve.allowedFingerprints)}function X6(e){va.push(e),xl();try{xf(BS,JSON.stringify(va.map(t=>({...t,regex:{source:t.regex.source,flags:t.regex.flags}})),null,2),"utf-8")}catch{}}function eG(){return[...va]}function tG(){return{...Ve,allowedFingerprints:new Set(Ve.allowedFingerprints)}}function nG(e){Ve={...Ve,...e}}function rG(){return{...yt}}function sG(){yt={totalScans:0,totalMatchesFound:0,totalRedactions:0,totalBlocks:0,byType:{},bySeverity:{},byProvider:{},byDetector:{},averageScanMs:0,totalBytesScanned:0,uniqueLeaksDetected:0},gI()}function iG(){return ph}function oG(){return[...qS,...va]}function aG(e=100){if(!wf(OS))return[];try{return kf(OS,"utf-8").split(`
51
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function cG(e){let t=[],n=e.action==="block"?"\u{1F6AB}":e.action==="redact"?"\u{1F9F9}":e.matches.length>0?"\u26A0\uFE0F":"\u2713";if(t.push(`${n} **Secret Scan Result**`),t.push(`Action: ${e.action.toUpperCase()}`),t.push(`Reason: ${e.reason}`),t.push(`Risk: ${(e.riskScore*100).toFixed(0)}/100`),t.push(`Duration: ${e.scanDurationMs}ms | Patterns checked: ${e.totalChecks}`),t.push(""),e.matches.length>0){t.push(`## Matches (${e.matches.length})`);for(let r of e.matches.slice(0,20)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="high"?"\u26A0\uFE0F ":r.severity==="medium"?"\u26A1":"\u2139\uFE0F ";t.push(`${s} [${r.type}] line ${r.line}:${r.column} | confidence ${(r.confidence*100).toFixed(0)}% | ${r.detector}`),t.push(` Match: ${r.redacted}`),r.provider&&t.push(` Provider: ${r.provider}`),r.remediation&&t.push(` Fix: ${r.remediation}`)}}return t.join(`
52
+ `)}var H6,Ve,kl,LS,OS,jS,BS,NS,ph,mh,va,yt,qS,HS,Cl=w(()=>{"use strict";H6={enabled:!0,enableRegex:!0,enableEntropy:!0,enableContext:!0,enableML:!1,defaultAction:"redact",blockOnCritical:!0,blockOnHigh:!1,complianceMode:"standard",maxScanBytes:5*1024*1024,streamingChunkBytes:64*1024,allowedFingerprints:new Set,redactionStyle:"partial",enableAuditLog:!0,suppressTestPatterns:!0},Ve={...H6},kl=wl(q6(),".aiaca","secret-scanner"),LS=wl(kl,"stats.json"),OS=wl(kl,"audit.jsonl"),jS=wl(kl,"allowlist.json"),BS=wl(kl,"custom-patterns.json"),NS=wl(kl,"seen.json"),ph=new U6;ph.setMaxListeners(50);mh=new Set,va=[],yt={totalScans:0,totalMatchesFound:0,totalRedactions:0,totalBlocks:0,byType:{},bySeverity:{},byProvider:{},byDetector:{},averageScanMs:0,totalBytesScanned:0,uniqueLeaksDetected:0};z6();qS=[{type:"aws_credentials",name:"AWS Access Key ID",provider:"aws",regex:/\b((?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASCA)[A-Z0-9]{16})\b/g,severity:"critical",remediation:"Rotate AWS credentials immediately via IAM console"},{type:"aws_credentials",name:"AWS Secret Access Key",provider:"aws",regex:/\b(aws[_\-]?secret[_\-]?(?:access[_\-]?)?key[\s"':=]+)([A-Za-z0-9/+=]{40})\b/gi,severity:"critical",matchGroup:2,contextHints:["aws","secret","access"]},{type:"aws_credentials",name:"AWS Session Token",provider:"aws",regex:/\b(?:aws[_\-]?session[_\-]?token[\s"':=]+)([A-Za-z0-9/+=]{100,})\b/gi,severity:"critical",matchGroup:1},{type:"gcp_credentials",name:"GCP Service Account JSON",provider:"gcp",regex:/"type":\s*"service_account"[^}]+"private_key":\s*"-----BEGIN[^"]+"/g,severity:"critical"},{type:"gcp_credentials",name:"GCP API Key",provider:"gcp",regex:/\b(AIza[0-9A-Za-z\-_]{35})\b/g,severity:"high"},{type:"gcp_credentials",name:"GCP OAuth Token",provider:"gcp",regex:/\b(ya29\.[0-9A-Za-z\-_]+)\b/g,severity:"high"},{type:"azure_credentials",name:"Azure Storage Connection String",provider:"azure",regex:/DefaultEndpointsProtocol=https?;AccountName=[^;]+;AccountKey=[A-Za-z0-9+/=]+/g,severity:"critical"},{type:"azure_credentials",name:"Azure Client Secret",provider:"azure",regex:/\b(azure[_\-]?client[_\-]?secret[\s"':=]+)([A-Za-z0-9._~\-]{32,})\b/gi,severity:"high",matchGroup:2},{type:"github_token",name:"GitHub Personal Access Token",provider:"github",regex:/\b(ghp_[A-Za-z0-9]{36})\b/g,severity:"critical",remediation:"Revoke at github.com/settings/tokens"},{type:"github_token",name:"GitHub OAuth Token",provider:"github",regex:/\b(gho_[A-Za-z0-9]{36})\b/g,severity:"critical"},{type:"github_token",name:"GitHub User Token",provider:"github",regex:/\b(ghu_[A-Za-z0-9]{36})\b/g,severity:"critical"},{type:"github_token",name:"GitHub Server Token",provider:"github",regex:/\b(ghs_[A-Za-z0-9]{36})\b/g,severity:"critical"},{type:"github_token",name:"GitHub Refresh Token",provider:"github",regex:/\b(ghr_[A-Za-z0-9]{36,})\b/g,severity:"critical"},{type:"gitlab_token",name:"GitLab Personal Access Token",provider:"gitlab",regex:/\b(glpat-[A-Za-z0-9_\-]{20})\b/g,severity:"critical"},{type:"gitlab_token",name:"GitLab CI Token",provider:"gitlab",regex:/\b(glcbt-[A-Za-z0-9_\-]{20,})\b/g,severity:"high"},{type:"slack_token",name:"Slack Bot Token",provider:"slack",regex:/\b(xox[baprs]-[A-Za-z0-9\-]{10,})\b/g,severity:"critical"},{type:"slack_token",name:"Slack Webhook URL",provider:"slack",regex:/https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,severity:"high"},{type:"discord_token",name:"Discord Bot Token",provider:"discord",regex:/\b(?:discord[_\-]?(?:bot[_\-]?)?token[\s"':=]+)?([MN][A-Za-z\d]{23}\.[\w\-]{6}\.[\w\-]{27,})\b/g,severity:"critical",matchGroup:1},{type:"discord_token",name:"Discord Webhook",provider:"discord",regex:/https:\/\/discord(?:app)?\.com\/api\/webhooks\/\d+\/[A-Za-z0-9_\-]+/g,severity:"high"},{type:"stripe_key",name:"Stripe Live Secret Key",provider:"stripe",regex:/\b(sk_live_[A-Za-z0-9]{24,})\b/g,severity:"critical",remediation:"Roll key at dashboard.stripe.com/apikeys"},{type:"stripe_key",name:"Stripe Test Secret Key",provider:"stripe",regex:/\b(sk_test_[A-Za-z0-9]{24,})\b/g,severity:"high"},{type:"stripe_key",name:"Stripe Restricted Key",provider:"stripe",regex:/\b(rk_live_[A-Za-z0-9]{24,})\b/g,severity:"critical"},{type:"twilio_key",name:"Twilio Account SID",provider:"twilio",regex:/\b(AC[a-f0-9]{32})\b/g,severity:"high"},{type:"twilio_key",name:"Twilio Auth Token",provider:"twilio",regex:/\b(?:twilio[_\-]?(?:auth[_\-]?)?token[\s"':=]+)([a-f0-9]{32})\b/gi,severity:"critical",matchGroup:1},{type:"sendgrid_key",name:"SendGrid API Key",provider:"sendgrid",regex:/\b(SG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43})\b/g,severity:"critical"},{type:"mailgun_key",name:"Mailgun API Key",provider:"mailgun",regex:/\b(key-[a-f0-9]{32})\b/g,severity:"high"},{type:"npm_token",name:"npm Token",provider:"npm",regex:/\b(npm_[A-Za-z0-9]{36})\b/g,severity:"high"},{type:"pypi_token",name:"PyPI Token",provider:"pypi",regex:/\b(pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_\-]{50,})\b/g,severity:"high"},{type:"crates_token",name:"crates.io Token",provider:"crates.io",regex:/\b(cio[A-Za-z0-9]{32})\b/g,severity:"high"},{type:"jwt",name:"JSON Web Token (JWT)",regex:/\b(eyJ[A-Za-z0-9_=\-]+\.eyJ[A-Za-z0-9_=\-]+\.[A-Za-z0-9_\-+/=]+)\b/g,severity:"high"},{type:"oauth_token",name:"Bearer Token",regex:/\b(?:bearer\s+)([A-Za-z0-9_\-\.~+/]{30,}=*)\b/gi,severity:"high",matchGroup:1,contextHints:["authorization","bearer"]},{type:"api_key",name:"Generic API Key",regex:/\b(?:api[_\-]?key|apikey|api[_\-]?secret)[\s"':=]+([A-Za-z0-9_\-]{20,})\b/gi,severity:"high",matchGroup:1,contextHints:["api"]},{type:"session_cookie",name:"Session Cookie",regex:/\b(?:session|sessid|jsessionid|phpsessid)[\s"':=]+([A-Za-z0-9_\-]{20,})\b/gi,severity:"medium",matchGroup:1},{type:"private_key",name:"PEM Private Key",regex:/-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----[\s\S]+?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/g,severity:"critical",remediation:"Rotate the keypair immediately"},{type:"ssh_key",name:"SSH Private Key",regex:/-----BEGIN OPENSSH PRIVATE KEY-----[\s\S]+?-----END OPENSSH PRIVATE KEY-----/g,severity:"critical"},{type:"gpg_key",name:"GPG Private Key",regex:/-----BEGIN PGP PRIVATE KEY BLOCK-----[\s\S]+?-----END PGP PRIVATE KEY BLOCK-----/g,severity:"critical"},{type:"cert",name:"Certificate",regex:/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g,severity:"low"},{type:"database_url",name:"PostgreSQL URL",regex:/\b(postgres(?:ql)?:\/\/[^:\s]+:([^@\s]+)@[^\s]+)\b/g,severity:"critical",matchGroup:1,remediation:"Rotate DB password"},{type:"database_url",name:"MySQL URL",regex:/\b(mysql:\/\/[^:\s]+:([^@\s]+)@[^\s]+)\b/g,severity:"critical",matchGroup:1},{type:"database_url",name:"MongoDB URL",regex:/\b(mongodb(?:\+srv)?:\/\/[^:\s]+:([^@\s]+)@[^\s]+)\b/g,severity:"critical",matchGroup:1},{type:"database_url",name:"Redis URL with password",regex:/\b(redis(?:s)?:\/\/[^:\s]*:([^@\s]+)@[^\s]+)\b/g,severity:"high",matchGroup:1},{type:"connection_string",name:"Generic Connection String with password",regex:/\b((?:user|uid|username)[\s]*=[\s]*[^;\s]+;[\s]*(?:password|pwd)[\s]*=[\s]*[^;\s]+)\b/gi,severity:"high"},{type:"password",name:"Password Assignment",regex:/\b(?:password|passwd|pwd|secret)[\s"':=]+["']?([A-Za-z0-9!@#$%^&*\-_+=]{8,})["']?/gi,severity:"high",matchGroup:1,contextHints:["password"],contextAntiHints:["hash","bcrypt","salted","placeholder","example"]},{type:"pii_email",name:"Email Address",regex:/\b([A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,})\b/g,severity:"low"},{type:"pii_phone",name:"US Phone Number",regex:/\b((?:\+?1[\s\-.]?)?\(?[2-9][0-9]{2}\)?[\s\-.]?[0-9]{3}[\s\-.]?[0-9]{4})\b/g,severity:"medium"},{type:"pii_ssn",name:"US Social Security Number",regex:/\b((?:\d{3}-\d{2}-\d{4})|(?:\d{9}))\b/g,severity:"critical",contextHints:["ssn","social"]},{type:"pii_credit_card",name:"Credit Card Number",regex:/\b((?:\d{4}[\s\-]?){3}\d{4})\b/g,severity:"critical"},{type:"pii_ip",name:"IPv4 Address",regex:/\b((?:\d{1,3}\.){3}\d{1,3})\b/g,severity:"low"},{type:"pii_passport",name:"US Passport Number",regex:/\b([A-Z]{1,2}\d{6,9})\b/g,severity:"high",contextHints:["passport"]},{type:"crypto_seed",name:"Mnemonic Seed Phrase (12-word)",regex:/\b((?:\b[a-z]{3,8}\b[\s\-]+){11}\b[a-z]{3,8}\b)\b/gi,severity:"critical",contextHints:["mnemonic","seed","wallet","phrase"]},{type:"high_entropy",name:"High Entropy String",regex:/["'`]([A-Za-z0-9+/=_\-]{32,})["'`]/g,severity:"medium",minEntropy:4.5,matchGroup:1}];HS=class{buffer="";offset=0;allMatches=[];source;overlapSize=1024;constructor(t="stream"){this.source=t}ingest(t){if(this.buffer+=t,this.buffer.length<Ve.streamingChunkBytes)return{matches:[],redactedChunk:t};let n=this.buffer.slice(0,this.buffer.length-this.overlapSize),r=US(n,this.source);this.allMatches.push(...r.matches);let s=r.redactedText||n;return this.buffer=this.buffer.slice(n.length),{matches:r.matches,redactedChunk:s}}finalize(){if(this.buffer.length>0){let t=US(this.buffer,this.source);this.allMatches.push(...t.matches);let n=t.redactedText||this.buffer,r=this.allMatches;return this.buffer="",{matches:r,redactedText:n}}return{matches:this.allMatches,redactedText:""}}}});var hh={};$(hh,{clearCache:()=>jG,compareVersions:()=>Cf,configure:()=>FG,detectEcosystems:()=>VS,formatScanResult:()=>BG,generateSBOM:()=>RG,getConfig:()=>DG,getStats:()=>LG,isVersionVulnerable:()=>JS,listSuppressions:()=>_G,parseAllDependencies:()=>AI,parseCargoDependencies:()=>CI,parseGoDependencies:()=>$I,parseNpmDependencies:()=>kI,parsePypiDependencies:()=>xI,resetStats:()=>OG,scanProject:()=>$G,suppressVulnerability:()=>AG,unsuppressVulnerability:()=>TG});import{existsSync as Ft,mkdirSync as lG,readFileSync as pi,writeFileSync as Af}from"fs";import{join as At,resolve as uG}from"path";import{homedir as dG}from"os";import{execSync as SI}from"child_process";function _f(){lG(Tf,{recursive:!0})}function wI(e,t){return`${t}:${e}`}function mG(){if(_f(),!!Ft($f))try{let e=JSON.parse(pi($f,"utf-8"));for(let[t,n]of Object.entries(e))Al.set(t,n)}catch{}}function gG(){_f();try{let e={};for(let[t,n]of Al)e[t]=n;Af($f,JSON.stringify(e),"utf-8")}catch{}}function VS(e){let t=[];return Ft(At(e,"package.json"))&&t.push("npm"),(Ft(At(e,"requirements.txt"))||Ft(At(e,"pyproject.toml"))||Ft(At(e,"Pipfile")))&&t.push("pypi"),Ft(At(e,"go.mod"))&&t.push("go"),Ft(At(e,"Cargo.toml"))&&t.push("crates"),(Ft(At(e,"pom.xml"))||Ft(At(e,"build.gradle"))||Ft(At(e,"build.gradle.kts")))&&t.push("maven"),Ft(At(e,"Gemfile"))&&t.push("rubygems"),Ft(At(e,"composer.json"))&&t.push("packagist"),t}function kI(e){let t=At(e,"package.json");if(!Ft(t))return[];let n=[];try{let s=JSON.parse(pi(t,"utf-8"));for(let[i,o]of Object.entries(s.dependencies||{}))n.push({name:i,version:String(o).replace(/^[\^~]/,""),ecosystem:"npm",isDevDependency:!1,isDirect:!0});for(let[i,o]of Object.entries(s.devDependencies||{}))n.push({name:i,version:String(o).replace(/^[\^~]/,""),ecosystem:"npm",isDevDependency:!0,isDirect:!0})}catch{}let r=At(e,"package-lock.json");if(Ft(r))try{let s=JSON.parse(pi(r,"utf-8")),i=new Set(n.map(o=>o.name));for(let[o,a]of Object.entries(s.packages||{})){if(!o||o==="")continue;let c=o.replace(/^node_modules\//,"").split("/")[0];i.has(c)||(i.add(c),n.push({name:c,version:a.version||"",ecosystem:"npm",isDevDependency:!!a.dev,isDirect:!1}))}}catch{}return n}function xI(e){let t=[],n=At(e,"requirements.txt");if(Ft(n))try{for(let s of pi(n,"utf-8").split(`
53
53
  `)){let i=s.trim().replace(/#.*/,"").trim();if(!i)continue;let o=i.match(/^([\w_.-]+)\s*([=<>!~]+)\s*([\d.]+)/);if(o)t.push({name:o[1],version:o[3],ecosystem:"pypi",isDevDependency:!1,isDirect:!0});else{let a=i.match(/^([\w_.-]+)/)?.[1];a&&t.push({name:a,version:"latest",ecosystem:"pypi",isDevDependency:!1,isDirect:!0})}}}catch{}let r=At(e,"pyproject.toml");if(Ft(r))try{let i=pi(r,"utf-8").match(/\[(?:tool\.poetry\.dependencies|project\.dependencies)\]([\s\S]*?)(?=\n\[|$)/)?.[1]||"";for(let o of i.split(`
54
54
  `)){let a=o.match(/^([\w_-]+)\s*=\s*["']?([^"'\n]+)/);a&&a[1]!=="python"&&t.push({name:a[1],version:a[2].replace(/[~^]/,"").trim(),ecosystem:"pypi",isDevDependency:!1,isDirect:!0})}}catch{}return t}function $I(e){let t=[],n=At(e,"go.mod");if(!Ft(n))return t;try{let r=pi(n,"utf-8"),s=r.match(/require\s*\(([\s\S]*?)\)/)?.[1]||"";for(let o of s.split(`
55
55
  `)){let a=o.trim().match(/^(\S+)\s+(\S+)(?:\s+\/\/\s*indirect)?/);a&&t.push({name:a[1],version:a[2],ecosystem:"go",isDevDependency:!1,isDirect:!o.includes("// indirect")})}let i=r.matchAll(/^require\s+(\S+)\s+(\S+)/gm);for(let o of i)t.push({name:o[1],version:o[2],ecosystem:"go",isDevDependency:!1,isDirect:!0})}catch{}return t}function CI(e){let t=[],n=At(e,"Cargo.toml");if(!Ft(n))return t;try{let r=pi(n,"utf-8"),s=r.match(/\[dependencies\]([\s\S]*?)(?=\n\[|$)/)?.[1]||"";for(let o of s.split(`
56
56
  `)){let a=o.match(/^\s*([\w_-]+)\s*=\s*["']?([^"'{\n]+)/);if(a){let c=a[2].trim().replace(/[~^]/,"");t.push({name:a[1],version:c,ecosystem:"crates",isDevDependency:!1,isDirect:!0})}}let i=r.match(/\[dev-dependencies\]([\s\S]*?)(?=\n\[|$)/)?.[1]||"";for(let o of i.split(`
57
- `)){let a=o.match(/^\s*([\w_-]+)\s*=\s*["']?([^"'{\n]+)/);a&&t.push({name:a[1],version:a[2].trim().replace(/[~^]/,""),ecosystem:"crates",isDevDependency:!0,isDirect:!0})}}catch{}return t}function AI(e){let t=[],n=VS(e);return n.includes("npm")&&t.push(...kI(e)),n.includes("pypi")&&t.push(...xI(e)),n.includes("go")&&t.push(...$I(e)),n.includes("crates")&&t.push(...CI(e)),t}async function y8(e,t,n){if(vn.offlineMode)return[];let r=wI(e,n),s=Al.get(r);if(s&&Date.now()-s.cachedAt<vn.cacheTTLMs)return s.vulnerabilities.filter(i=>JS(t,i.vulnerableRanges));try{let i=await fetch("https://api.osv.dev/v1/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:{name:e,ecosystem:h8[n]},version:t}),signal:AbortSignal.timeout(vn.scanTimeout)});if(!i.ok)return[];let a=((await i.json()).vulns||[]).map(c=>{let l=(c.affected||[]).find(m=>m.package?.name===e)||c.affected?.[0],u=[],d;for(let m of l?.ranges||[])for(let g of m.events||[])g.introduced&&u.push(`>=${g.introduced}`),g.fixed&&(u.push(`<${g.fixed}`),(!d||Cf(g.fixed,d)<0)&&(d=g.fixed));let f=b8(c.severity,c.database_specific),p=(c.severity||[]).find(m=>m.type?.startsWith("CVSS"))?.score;return{id:c.id,package:e,ecosystem:n,installedVersion:t,vulnerableRanges:u,fixedVersion:d,severity:f,cvssScore:TI(p),cvssVector:p,cwe:c.database_specific?.cwe_ids||[],summary:c.summary||c.id,details:c.details?.slice(0,1e3),publishedAt:new Date(c.published||Date.now()).getTime(),references:(c.references||[]).map(m=>m.url).slice(0,5),source:"osv"}});return Al.set(r,{package:e,ecosystem:n,vulnerabilities:a,cachedAt:Date.now()}),queueMicrotask(()=>g8()),a}catch{return[]}}function b8(e,t){if(t?.severity){let r=t.severity.toLowerCase();if(r==="critical")return"critical";if(r==="high")return"high";if(r==="medium"||r==="moderate")return"medium";if(r==="low")return"low"}let n=(e||[]).find(r=>r.type?.startsWith("CVSS"));if(n?.score){let r=TI(n.score);if(r)return r>=9?"critical":r>=7?"high":r>=4?"medium":"low"}return"medium"}function TI(e){if(!e)return;let t=e.match(/(\d+\.\d+)/);return t?parseFloat(t[1]):void 0}async function v8(e){if(!vn.enableNpmAudit)return[];try{let t=SI("npm audit --json",{cwd:e,stdio:"pipe",timeout:vn.scanTimeout,encoding:"utf-8"});return yI(t)}catch(t){if(t.stdout)try{return yI(t.stdout.toString())}catch{}return[]}}function yI(e){let t=[];try{let n=JSON.parse(e),r=n.advisories||n.vulnerabilities;if(!r)return[];for(let[s,i]of Object.entries(r)){let o=i,a=o.via?.[0]||o;if(typeof a=="string")continue;let c=S8(o.severity||a.severity);t.push({id:a.cve||a.id?.toString()||a.url||`npm-${s}`,package:s,ecosystem:"npm",installedVersion:o.range||"unknown",vulnerableRanges:[o.range||""],fixedVersion:o.fixAvailable?.version||a.patched_versions,severity:c,cvssScore:a.cvss?.score,cvssVector:a.cvss?.vectorString,cwe:a.cwe||[],summary:a.title||a.url||"npm audit finding",details:a.overview?.slice(0,1e3),publishedAt:a.created?new Date(a.created).getTime():Date.now(),references:[a.url].filter(Boolean),source:"npm-audit"})}}catch{}return t}function S8(e){let t=e?.toLowerCase();return t==="critical"?"critical":t==="high"?"high":t==="moderate"?"medium":t==="low"?"low":"none"}function Tl(e){let t=e.replace(/^[v=]+/,"").split("+")[0],[n,r]=t.split("-"),s=n.split(".").map(i=>parseInt(i,10)||0);for(;s.length<3;)s.push(0);return{parts:s,pre:r}}function Cf(e,t){let n=Tl(e),r=Tl(t);for(let s=0;s<Math.max(n.parts.length,r.parts.length);s++){let i=(n.parts[s]||0)-(r.parts[s]||0);if(i!==0)return i}return n.pre&&!r.pre?-1:!n.pre&&r.pre?1:n.pre&&r.pre?n.pre.localeCompare(r.pre):0}function JS(e,t){if(t.length===0||e==="latest"||e==="*")return!0;let n=!1,r=!0;for(let s of t){let i=s.match(/^([<>=]+)(.+)$/);if(!i)continue;let o=i[1],a=i[2].trim(),c=Cf(e,a),l=!1;o===">="?l=c>=0:o===">"?l=c>0:o==="<="?l=c<=0:o==="<"?l=c<0:(o==="="||o==="==")&&(l=c===0),o.startsWith("<")?(l&&(n=n||r),r=!0):o.startsWith(">")&&(r=l)}if(t.length===1){let s=t[0].match(/^([<>=]+)(.+)$/);if(s){let i=Cf(e,s[2].trim());if(s[1]===">=")return i>=0;if(s[1]===">")return i>0;if(s[1]==="<=")return i<=0;if(s[1]==="<")return i<0;if(s[1]==="="||s[1]==="==")return i===0}}return n}function w8(e,t){let n=[],r=new Map;for(let a of t){let c=`${a.ecosystem}:${a.package}`;r.has(c)||r.set(c,[]),r.get(c).push(a)}for(let[a,c]of r){let l=e.find(f=>`${f.ecosystem}:${f.name}`===a);if(!l)continue;let u;for(let f of c)f.fixedVersion&&(!u||Cf(f.fixedVersion,u)>0)&&(u=f.fixedVersion);if(!u)continue;let d=k8(l.version,u);n.push({package:l.name,ecosystem:l.ecosystem,from:l.version,to:u,fixesVulns:c.map(f=>f.id),isBreaking:d,confidence:c.every(f=>f.fixedVersion)?.95:.6})}let s=n.length,i=n.filter(a=>a.isBreaking).length,o="trivial";return i>5||s>20?o="significant":i>2||s>10?o="moderate":(i>0||s>3)&&(o="minor"),{patches:n,totalFixable:s,breakingChanges:i,estimatedEffort:o}}function k8(e,t){try{let n=Tl(e),r=Tl(t);return n.parts[0]!==r.parts[0]}catch{return!1}}async function x8(e,t){if(!vn.enableOutdatedCheck)return[];let n=[];if(t.includes("npm"))try{let r=SI("npm outdated --json",{cwd:e,stdio:"pipe",timeout:vn.scanTimeout,encoding:"utf-8"});try{let s=JSON.parse(r||"{}");for(let[i,o]of Object.entries(s)){let a=o,c=bI(a.current,a.latest);n.push({name:i,ecosystem:"npm",current:a.current,wanted:a.wanted,latest:a.latest,type:c})}}catch{}}catch(r){if(r.stdout)try{let s=JSON.parse(r.stdout.toString()||"{}");for(let[i,o]of Object.entries(s)){let a=o;n.push({name:i,ecosystem:"npm",current:a.current,wanted:a.wanted,latest:a.latest,type:bI(a.current,a.latest)})}}catch{}}return n}function bI(e,t){try{let n=Tl(e),r=Tl(t);return n.parts[0]!==r.parts[0]?"major":n.parts[1]!==r.parts[1]?"minor":n.parts[2]!==r.parts[2]?"patch":"unknown"}catch{return"unknown"}}async function $8(e){let t=Date.now(),n=u8(e);if(!vn.enabled)return vI(n,["Scanner disabled"]);let r=VS(n);if(r.length===0)return vI(n,["No supported package files found"]);let s=gh(),i=AI(n),o=vn.excludeDevDependencies?i.filter(k=>!k.isDevDependency):i,a=[],c=0,l=[],u=o.map(async k=>{try{let S=wI(k.name,k.ecosystem),x=Al.get(S);return x&&Date.now()-x.cachedAt<vn.cacheTTLMs?(c++,x.vulnerabilities.filter(A=>JS(k.version,A.vulnerableRanges))):await y8(k.name,k.version,k.ecosystem)}catch(S){return l.push(`${k.name}: ${S.message}`),[]}}),d=await Promise.allSettled(u);for(let k of d)k.status==="fulfilled"&&a.push(...k.value);let f=new Set;if(a=a.filter(k=>f.has(k.id)?!1:(f.add(k.id),!0)),vn.enableNpmAudit&&r.includes("npm")){let k=await v8(n);for(let S of k)f.has(S.id)||(f.add(S.id),a.push(S))}a=a.filter(k=>!s.includes(k.id)&&!vn.suppressedVulns.includes(k.id));let p=["critical","high","medium","low","none"],m=p.indexOf(vn.severityThreshold);a=a.filter(k=>p.indexOf(k.severity)<=m);let g={critical:0,high:0,medium:0,low:0,none:0};for(let k of a)g[k.severity]++;let h=w8(o,a),v=await x8(n,r),y=C8(g,o.length),b={projectPath:n,ecosystems:r,totalDependencies:o.length,vulnerableCount:a.length,bySeverity:g,vulnerabilities:a,upgradePlan:h,outdatedPackages:v,riskScore:y,duration:Date.now()-t,scannedAt:Date.now(),cacheHits:c,errors:l};return E8(b),M8(b),b}function vI(e,t){return{projectPath:e,ecosystems:[],totalDependencies:0,vulnerableCount:0,bySeverity:{critical:0,high:0,medium:0,low:0,none:0},vulnerabilities:[],upgradePlan:{patches:[],totalFixable:0,breakingChanges:0,estimatedEffort:"trivial"},outdatedPackages:[],riskScore:0,duration:0,scannedAt:Date.now(),cacheHits:0,errors:t}}function C8(e,t){let n=e.critical*25+e.high*10+e.medium*3+e.low*1,r=Math.min(1,n/Math.max(1,t*5));return Math.round(r*100)}function gh(){if(!Ft(GS))return[];try{return JSON.parse(pi(GS,"utf-8"))}catch{return[]}}function _I(e){_f();try{Af(GS,JSON.stringify(e,null,2),"utf-8")}catch{}}function A8(e){let t=gh();t.includes(e)||(t.push(e),_I(t))}function T8(e){let t=gh().filter(n=>n!==e);_I(t)}function _8(){return gh()}function R8(e,t){return{bomFormat:"CycloneDX",specVersion:"1.5",version:1,metadata:{timestamp:new Date().toISOString(),tools:[{vendor:"AIACA",name:"vulnScan",version:"1.0"}],component:{type:"application",name:t.split(/[/\\]/).pop()}},components:e.map(n=>({type:"library",name:n.name,version:n.version,purl:P8(n),scope:n.isDevDependency?"optional":"required"}))}}function P8(e){return`pkg:${{npm:"npm",pypi:"pypi",go:"golang",crates:"cargo",maven:"maven",rubygems:"gem",packagist:"composer",nuget:"nuget"}[e.ecosystem]}/${e.name}@${e.version}`}function I8(){if(Ft(zS))try{an={...an,...JSON.parse(pi(zS,"utf-8"))}}catch{}}function RI(){_f();try{Af(zS,JSON.stringify(an,null,2),"utf-8")}catch{}}function M8(e){an.totalScans++,an.totalVulnsFound+=e.vulnerableCount,an.totalCriticalsFound+=e.bySeverity.critical,an.cacheHitRate=(an.cacheHitRate*(an.totalScans-1)+e.cacheHits/Math.max(1,e.totalDependencies))/an.totalScans,an.averageDurationMs=(an.averageDurationMs*(an.totalScans-1)+e.duration)/an.totalScans;for(let t of e.vulnerabilities)an.topVulnerablePackages[t.package]=(an.topVulnerablePackages[t.package]||0)+1;RI()}function E8(e){_f();try{let t=JSON.stringify({projectPath:e.projectPath,timestamp:e.scannedAt,vulnerableCount:e.vulnerableCount,riskScore:e.riskScore,bySeverity:e.bySeverity})+`
58
- `;Af(p8,t,{flag:"a"})}catch{}}function D8(){return{...vn}}function F8(e){vn={...vn,...e}}function L8(){return JSON.parse(JSON.stringify(an))}function O8(){an={totalScans:0,totalVulnsFound:0,totalCriticalsFound:0,totalSuppressed:0,cacheHitRate:0,averageDurationMs:0,topVulnerablePackages:{}},RI()}function j8(){if(Al.clear(),Ft($f))try{Af($f,"{}","utf-8")}catch{}}function B8(e){let t=[];if(t.push("# Dependency Vulnerability Scan"),t.push(""),t.push(`**Risk Score:** ${e.riskScore}/100`),t.push(`**Total Dependencies:** ${e.totalDependencies}`),t.push(`**Vulnerabilities Found:** ${e.vulnerableCount}`),t.push(`**Ecosystems:** ${e.ecosystems.join(", ")}`),t.push(""),e.vulnerableCount===0)t.push(`\u2713 No vulnerabilities found above ${vn.severityThreshold} severity.`);else{t.push("## Severity Breakdown"),e.bySeverity.critical>0&&t.push(` \u{1F6A8} Critical: ${e.bySeverity.critical}`),e.bySeverity.high>0&&t.push(` \u26A0\uFE0F High: ${e.bySeverity.high}`),e.bySeverity.medium>0&&t.push(` \u26A1 Medium: ${e.bySeverity.medium}`),e.bySeverity.low>0&&t.push(` \u2139\uFE0F Low: ${e.bySeverity.low}`),t.push(""),t.push("## Vulnerabilities (top 15)");let n=[...e.vulnerabilities].sort((r,s)=>{let i=["critical","high","medium","low","none"];return i.indexOf(r.severity)-i.indexOf(s.severity)});for(let r of n.slice(0,15)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="high"?"\u26A0\uFE0F ":r.severity==="medium"?"\u26A1":"\u2139\uFE0F ";t.push(`${s} **${r.id}** ${r.package}@${r.installedVersion} (${r.severity})`),t.push(` ${r.summary}`),r.fixedVersion&&t.push(` Fix: upgrade to ${r.fixedVersion}`),r.cvssScore&&t.push(` CVSS: ${r.cvssScore}`),t.push("")}if(e.upgradePlan.totalFixable>0){t.push("## Upgrade Plan"),t.push(`Effort: ${e.upgradePlan.estimatedEffort}`),t.push(`Fixable: ${e.upgradePlan.totalFixable} | Breaking: ${e.upgradePlan.breakingChanges}`),t.push("");for(let r of e.upgradePlan.patches.slice(0,10)){let s=r.isBreaking?" \u26A0\uFE0F BREAKING":"";t.push(` ${r.package}: ${r.from} \u2192 ${r.to}${s}`),t.push(` Fixes: ${r.fixesVulns.slice(0,3).join(", ")}${r.fixesVulns.length>3?"...":""}`)}}}if(e.outdatedPackages.length>0){t.push(""),t.push("## Outdated (top 10)");for(let n of e.outdatedPackages.slice(0,10))t.push(` ${n.name}: ${n.current} \u2192 ${n.latest} (${n.type})`)}return t.join(`
59
- `)}var f8,vn,Tf,$f,zS,p8,GS,Al,h8,an,yh=w(()=>{"use strict";f8={enabled:!0,primarySource:"osv",enableNpmAudit:!0,enablePipAudit:!0,enableLicenseCheck:!0,enableOutdatedCheck:!0,cacheTTLMs:1440*60*1e3,scanTimeout:6e4,blockOnCritical:!0,excludeDevDependencies:!1,severityThreshold:"medium",suppressedVulns:[],offlineMode:!1,scanOnInstall:!0},vn={...f8},Tf=At(d8(),".aiaca","vuln-scan"),$f=At(Tf,"vuln-cache.json"),zS=At(Tf,"stats.json"),p8=At(Tf,"history.jsonl"),GS=At(Tf,"suppressions.json"),Al=new Map;m8();h8={npm:"npm",pypi:"PyPI",go:"Go",crates:"crates.io",maven:"Maven",rubygems:"RubyGems",packagist:"Packagist",nuget:"NuGet"};an={totalScans:0,totalVulnsFound:0,totalCriticalsFound:0,totalSuppressed:0,cacheHitRate:0,averageDurationMs:0,topVulnerablePackages:{}};I8()});var kh={};$(kh,{addMalicious:()=>lG,auditDependencies:()=>LI,configure:()=>iG,detectEcosystem:()=>tw,formatAuditResult:()=>fG,generateComplianceReport:()=>dG,generateLockfile:()=>EI,getAuditLog:()=>uG,getConfig:()=>sG,getEvents:()=>cG,getStats:()=>oG,loadLockfile:()=>wh,resetStats:()=>aG,startAutoAudit:()=>nG,stopAutoAudit:()=>rG,verifyLockfileMatchesInstall:()=>FI});import{existsSync as Je,mkdirSync as WS,readFileSync as Is,writeFileSync as oo}from"fs";import{join as Ae,basename as PI,dirname as N8}from"path";import{homedir as q8}from"os";import{createHash as U8}from"crypto";import{EventEmitter as H8}from"events";function wa(){WS(Pl,{recursive:!0}),WS(II,{recursive:!0})}function G8(){if(wa(),Je(KS))try{We={...We,...JSON.parse(Is(KS,"utf-8"))}}catch{}if(Je(bh))try{let e=JSON.parse(Is(bh,"utf-8"));for(let t of e)Rl.add(t)}catch{}else V8();if(Je(QS))try{let e=JSON.parse(Is(QS,"utf-8"));for(let[t,n]of Object.entries(e))_l.set(t,new Set(n))}catch{}else J8()}function ew(){wa();try{oo(KS,JSON.stringify(We,null,2),"utf-8")}catch{}}function MI(e){wa();try{oo(YS,JSON.stringify({...e,timestamp:Date.now()})+`
60
- `,{flag:"a"})}catch{}}function V8(){let e=["cross-env@7.0.4","colors@1.4.44","faker@6.6.6","event-stream@3.3.6","flatmap-stream@0.1.1","noblox.js-proxy@1.0.0","electorn@1.4.16","opencv.js@1.0.0","ua-parser-js@0.7.29"];for(let t of e)Rl.add(t);wa();try{oo(bh,JSON.stringify(e,null,2),"utf-8")}catch{}}function J8(){_l.set("npm",new Set(["react","lodash","express","axios","webpack","typescript","eslint","next","vue","angular","jest","mocha","chai","commander","chalk","rxjs","tslib","electron","jquery","moment","underscore","request","async","bluebird","classnames","redux","react-dom","styled-components","fs-extra","glob","minimist","yargs","inquirer","dotenv","cross-env"])),_l.set("pypi",new Set(["requests","numpy","pandas","flask","django","pytest","tensorflow","torch","scipy","matplotlib","pillow","beautifulsoup4","lxml","pyyaml","click","sqlalchemy","fastapi","uvicorn","pydantic"])),_l.set("cargo",new Set(["serde","tokio","reqwest","clap","log","rand","chrono","thiserror"])),wa();try{let e={};for(let[t,n]of _l.entries())e[t]=Array.from(n);oo(QS,JSON.stringify(e,null,2),"utf-8")}catch{}}function vh(e){return U8("sha256").update(e).digest("hex")}function XS(e){let t=Object.keys(e).sort(),n={};for(let r of t){let s=e[r];n[r]={name:s.name,version:s.version,ecosystem:s.ecosystem,sha256:s.sha256,resolvedUrl:s.resolvedUrl,parents:[...s.parents].sort()}}return JSON.stringify(n)}function tw(e){return Je(Ae(e,"package.json"))||Je(Ae(e,"package-lock.json"))||Je(Ae(e,"yarn.lock"))||Je(Ae(e,"pnpm-lock.yaml"))?"npm":Je(Ae(e,"requirements.txt"))||Je(Ae(e,"pyproject.toml"))||Je(Ae(e,"Pipfile"))?"pypi":Je(Ae(e,"Cargo.toml"))?"cargo":Je(Ae(e,"Gemfile"))||Je(Ae(e,"Gemfile.lock"))?"gem":Je(Ae(e,"composer.json"))?"composer":Je(Ae(e,"pom.xml"))||Je(Ae(e,"build.gradle"))?"maven":Je(Ae(e,"go.mod"))?"go":Je(Ae(e,"packages.config"))?"nuget":"unknown"}async function EI(e){let t=tw(e);if(t==="unknown")return null;let n={};t==="npm"?await DI(e,n):t==="pypi"?await W8(e,n):t==="cargo"&&await K8(e,n);let r=PI(e),s=vh(XS(n)),i={version:1,generatedAt:Date.now(),generatedBy:"aiaca",ecosystem:t,projectName:r,projectPath:e,dependencies:n,lockfileHash:s,auditHistory:[]},o=Ae(e,".aiaca","deps.lock.json");return wa(),WS(N8(o),{recursive:!0}),oo(o,JSON.stringify(i,null,2),"utf-8"),ZS.set(e,i),We.totalLockfilesGenerated++,We.byEcosystem[t]=(We.byEcosystem[t]||0)+1,ew(),MI({event:"lockfile_generated",projectName:r,ecosystem:t,dependencyCount:Object.keys(n).length}),Sh.emit("lockfile_generated",{lockfile:i}),i}async function DI(e,t){let n=Ae(e,"package-lock.json");if(Je(n))try{let s=JSON.parse(Is(n,"utf-8")),i=s.packages||s.dependencies||{};for(let[o,a]of Object.entries(i)){if(!o||o==="")continue;let c=a.name||PI(o).replace(/^node_modules\//,"");if(!c||!a.version)continue;let l=`${c}@${a.version}`,u=a.integrity?a.integrity.replace(/^sha256-/,"").replace(/^sha512-/,""):a._shasum||"";t[l]={name:c,version:a.version,ecosystem:"npm",sha256:u,resolvedUrl:a.resolved,parents:[],status:"locked",vulnerabilities:[],lastAuditedAt:0}}return}catch{}let r=Ae(e,"package.json");if(Je(r))try{let s=JSON.parse(Is(r,"utf-8")),i={...s.dependencies,...s.devDependencies};for(let[o,a]of Object.entries(i)){let c=a.replace(/^[\^~>=<]+/,""),l=`${o}@${c}`;t[l]={name:o,version:c,ecosystem:"npm",sha256:"",parents:[],status:"unlocked",vulnerabilities:[],lastAuditedAt:0}}}catch{}}async function W8(e,t){let n=Ae(e,"requirements.txt");if(Je(n))try{let r=Is(n,"utf-8").split(`
61
- `).filter(s=>s.trim()&&!s.startsWith("#"));for(let s of r){let i=s.match(/^([\w\-_.]+)\s*(?:==|===)\s*([\w.\-+]+)(?:\s*--hash=sha256:([a-f0-9]+))?/i);if(i){let[,o,a,c]=i,l=`${o}@${a}`;t[l]={name:o,version:a,ecosystem:"pypi",sha256:c||"",parents:[],status:c?"locked":"unlocked",vulnerabilities:[],lastAuditedAt:0}}}}catch{}}async function K8(e,t){let n=Ae(e,"Cargo.lock");if(Je(n))try{let s=Is(n,"utf-8").split(/\n\[\[package\]\]\n/);for(let i of s.slice(1)){let o=i.match(/name\s*=\s*"([^"]+)"/),a=i.match(/version\s*=\s*"([^"]+)"/),c=i.match(/checksum\s*=\s*"([^"]+)"/);if(o&&a){let l=o[1],u=a[1],d=`${l}@${u}`;t[d]={name:l,version:u,ecosystem:"cargo",sha256:c?c[1]:"",parents:[],status:c?"locked":"unlocked",vulnerabilities:[],lastAuditedAt:0}}}}catch{}}function wh(e){let t=ZS.get(e);if(t)return t;let n=Ae(e,".aiaca","deps.lock.json");if(!Je(n))return null;try{let r=JSON.parse(Is(n,"utf-8"));return ZS.set(e,r),r}catch{return null}}function FI(e){let t=wh(e);if(!t)return{matches:!1,missingFromLock:[],extraInLock:[]};let n={};DI(e,n).catch(()=>{});let r=XS(t.dependencies),s=vh(r),i=XS(n),o=vh(i),a=new Set(Object.keys(t.dependencies)),c=new Set(Object.keys(n)),l=Array.from(c).filter(d=>!a.has(d)),u=Array.from(a).filter(d=>!c.has(d));return{matches:s===o,expectedHash:s,actualHash:o,missingFromLock:l,extraInLock:u}}async function LI(e){let t=Date.now(),n=tw(e),r=wh(e);if(r||(r=await EI(e)),!r)return{ecosystem:n,totalPackages:0,scannedPackages:0,findings:[],byType:{},bySeverity:{},blockers:0,durationMs:Date.now()-t,lockfileMatches:!1};let s=[],i={},o={},a=FI(e),c=Object.values(r.dependencies);for(let u of c){let d=`${u.name}@${u.version}`;if((Rl.has(d)||Rl.has(u.name))&&(s.push({packageName:u.name,packageVersion:u.version,type:"malicious",severity:"critical",description:`Known-malicious package: ${d}`,remediation:"Remove this package immediately and rotate any credentials"}),u.status="malicious",We.totalMalicious++),Sn.enableTyposquatDetection){let f=X8(u.name,n);f&&(s.push({packageName:u.name,packageVersion:u.version,type:"typosquat",severity:"high",description:`Possible typosquat of "${f}"`,remediation:`Verify package; consider switching to ${f}`}),u.status="typosquat",We.totalTyposquats++)}(u.status==="unlocked"||!u.sha256)&&(s.push({packageName:u.name,packageVersion:u.version,type:"unsigned",severity:"medium",description:"Package not pinned with SHA-256 hash",remediation:"Run package manager lock command (npm ci, cargo build, etc.)"}),We.totalUnlocked++),u.lastAuditedAt=Date.now()}if(Sn.enableOsvCheck)for(let u of c)try{let d=await Y8(u.name,u.version,n);for(let f of d)u.vulnerabilities.push(f),s.push({packageName:u.name,packageVersion:u.version,type:"cve",severity:f.severity,description:`${f.id}: ${f.summary}`,remediation:f.fixedIn?`Upgrade to ${f.fixedIn}`:"No fix available yet"}),We.totalVulnerabilities++}catch{}for(let u of s)i[u.type]=(i[u.type]||0)+1,o[u.severity]=(o[u.severity]||0)+1,We.bySeverity[u.severity]=(We.bySeverity[u.severity]||0)+1;let l=s.filter(u=>u.severity==="critical"||u.type==="malicious").length;r.auditHistory.push({timestamp:Date.now(),vulnerabilitiesFound:s.filter(u=>u.type==="cve").length,maliciousFound:s.filter(u=>u.type==="malicious").length}),r.auditHistory.length>50&&(r.auditHistory=r.auditHistory.slice(-50));try{let u=Ae(e,".aiaca","deps.lock.json");oo(u,JSON.stringify(r,null,2),"utf-8")}catch{}return We.totalAudits++,We.totalPackagesScanned+=c.length,ew(),MI({event:"audit_complete",project:r.projectName,ecosystem:n,packageCount:c.length,findingsCount:s.length,blockers:l,durationMs:Date.now()-t}),Sh.emit("audit_complete",{lockfile:r,findings:s,blockers:l}),{ecosystem:n,totalPackages:c.length,scannedPackages:c.length,findings:s,byType:i,bySeverity:o,blockers:l,durationMs:Date.now()-t,lockfileMatches:a.matches}}async function Y8(e,t,n){let r=`${n}:${e}@${t}`,s=Ae(II,vh(r).slice(0,16)+".json");if(Je(s))try{let a=JSON.parse(Is(s,"utf-8"));if(Date.now()-a.cachedAt<1440*60*1e3)return a.vulns}catch{}if(typeof fetch>"u")return[];let o={npm:"npm",pypi:"PyPI",cargo:"crates.io",gem:"RubyGems",composer:"Packagist",maven:"Maven",go:"Go",nuget:"NuGet",unknown:""}[n];if(!o)return[];try{let a=await fetch(Sn.osvApiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:{name:e,ecosystem:o},version:t})});if(!a.ok)return[];let c=await a.json(),l=[];for(let u of c.vulns||[]){let d=Q8(u);l.push({id:u.id,severity:d,summary:u.summary||u.details?.slice(0,200)||"No summary",affectedRanges:u.affected?.map(f=>f.ranges?.map(p=>p.events).flat()).flat().filter(Boolean),fixedIn:Z8(u)})}try{oo(s,JSON.stringify({cachedAt:Date.now(),vulns:l},null,2),"utf-8")}catch{}return l}catch{return[]}}function Q8(e){let t=e.severity?.find(n=>n.type?.includes("CVSS"));if(t?.score){let n=typeof t.score=="string"?parseFloat(t.score.match(/[\d.]+/)?.[0]||"0"):t.score;return n>=9?"critical":n>=7?"high":n>=4?"medium":"low"}return"medium"}function Z8(e){for(let t of e.affected||[])for(let n of t.ranges||[])for(let r of n.events||[])if(r.fixed)return r.fixed}function X8(e,t){let n=_l.get(t);if(!n)return null;let r=e.toLowerCase();if(n.has(r))return null;for(let s of n){let i=eG(r,s);if(i>Sn.typosquatThreshold&&i<1)return s}return null}function eG(e,t){return 1-tG(e,t)/Math.max(e.length,t.length)}function tG(e,t){let n=[];for(let r=0;r<=e.length;r++){n[r]=[r];for(let s=1;s<=t.length;s++)if(r===0)n[r][s]=s;else{let i=e[r-1]===t[s-1]?0:1;n[r][s]=Math.min(n[r-1][s]+1,n[r][s-1]+1,n[r-1][s-1]+i)}}return n[e.length][t.length]}function nG(e){Sa||!Sn.enableAutoAudit||(Sa=setInterval(()=>{LI(e).catch(()=>{})},Sn.auditIntervalMs),Sa.unref&&Sa.unref())}function rG(){Sa&&(clearInterval(Sa),Sa=null)}function sG(){return{...Sn}}function iG(e){Sn={...Sn,...e}}function oG(){return{...We}}function aG(){We={totalAudits:0,totalPackagesScanned:0,totalVulnerabilities:0,totalMalicious:0,totalTyposquats:0,totalUnlocked:0,totalRejected:0,totalLockfilesGenerated:0,byEcosystem:{},bySeverity:{}},ew()}function cG(){return Sh}function lG(e,t){let n=t?`${e}@${t}`:e;Rl.add(n),wa();try{oo(bh,JSON.stringify(Array.from(Rl),null,2),"utf-8")}catch{}}function uG(e=100){if(!Je(YS))return[];try{return Is(YS,"utf-8").split(`
62
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function dG(e){let t=[];t.push("# Dependency Lock & Audit Compliance Report"),t.push(`Generated: ${new Date().toISOString()}`),t.push(""),t.push("## Summary"),t.push(`- Total audits: ${We.totalAudits}`),t.push(`- Packages scanned: ${We.totalPackagesScanned}`),t.push(`- \u{1F6A8} Malicious: ${We.totalMalicious}`),t.push(`- \u{1F50D} Vulnerabilities: ${We.totalVulnerabilities}`),t.push(`- \u26A0\uFE0F Typosquats: ${We.totalTyposquats}`),t.push(`- \u{1F513} Unlocked: ${We.totalUnlocked}`),t.push(`- \u{1F527} Lockfiles generated: ${We.totalLockfilesGenerated}`),t.push(""),t.push("## By Ecosystem");for(let[n,r]of Object.entries(We.byEcosystem))t.push(`- ${n}: ${r}`);t.push(""),t.push("## By Severity");for(let[n,r]of Object.entries(We.bySeverity))t.push(`- ${n}: ${r}`);if(t.push(""),e){let n=wh(e);n&&(t.push(`## Project: ${n.projectName}`),t.push(`- Ecosystem: ${n.ecosystem}`),t.push(`- Dependencies: ${Object.keys(n.dependencies).length}`),t.push(`- Lockfile hash: ${n.lockfileHash.slice(0,16)}...`),t.push(`- Audit history entries: ${n.auditHistory.length}`))}return t.push(""),t.push("## Compliance Properties"),t.push("- \u2713 Cryptographic SHA-256 package hashes"),t.push("- \u2713 Exact version pinning"),t.push(`- ${Sn.rejectMalicious?"\u2713":"\u2717"} Reject known-malicious`),t.push(`- ${Sn.rejectVulnerable?"\u2713":"\u2717"} Reject vulnerable packages`),t.push(`- ${Sn.rejectUnlocked?"\u2713":"\u2717"} Reject unlocked packages`),t.push(`- ${Sn.enableOsvCheck?"\u2713":"\u2717"} OSV.dev vulnerability checks`),t.push(`- ${Sn.enableTyposquatDetection?"\u2713":"\u2717"} Typosquat detection`),t.push(`- ${Sn.enableAutoAudit?"\u2713":"\u2717"} Continuous auto-audit (${Sn.auditIntervalMs/864e5}d)`),t.push(`- ${Sn.enableLicenseCheck?"\u2713":"\u2717"} License compliance scan`),t.join(`
63
- `)}function fG(e){let t=[],n=e.blockers>0?"\u{1F6A8}":e.findings.length>0?"\u26A0\uFE0F":"\u2713";if(t.push(`${n} **Audit Result** (${e.ecosystem})`),t.push(`Packages: ${e.totalPackages} | Findings: ${e.findings.length} | Blockers: ${e.blockers}`),t.push(`Lockfile reproducible: ${e.lockfileMatches?"\u2713":"\u26A0\uFE0F MISMATCH"}`),t.push(`Duration: ${e.durationMs}ms`),t.push(""),e.findings.length>0){t.push("## Findings");for(let r of e.findings.slice(0,30)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="high"?"\u26A0\uFE0F ":r.severity==="medium"?"\u26A1":"\u2139\uFE0F ";t.push(`${s} [${r.type}] ${r.packageName}@${r.packageVersion}: ${r.description}`),r.remediation&&t.push(` \u2192 ${r.remediation}`)}}return t.join(`
64
- `)}var z8,Sn,Pl,KS,YS,bh,QS,II,Sh,Rl,_l,ZS,We,Sa,xh=w(()=>{"use strict";z8={enabled:!0,rejectUnlocked:!0,rejectVulnerable:!1,rejectMalicious:!0,blockOnCritical:!0,blockOnHigh:!1,enableAutoAudit:!0,auditIntervalMs:1440*60*1e3,enableOsvCheck:!0,osvApiUrl:"https://api.osv.dev/v1/query",enableTyposquatDetection:!0,typosquatThreshold:.85,enableSignatureVerification:!1,enablePackageCache:!0,enableLicenseCheck:!1,forbiddenLicenses:["GPL-3.0","AGPL-3.0","SSPL-1.0"]},Sn={...z8},Pl=Ae(q8(),".aiaca","dep-audit"),KS=Ae(Pl,"stats.json"),YS=Ae(Pl,"audit.jsonl"),bh=Ae(Pl,"known-malicious.json"),QS=Ae(Pl,"popular-packages.json"),II=Ae(Pl,"vuln-cache"),Sh=new H8;Sh.setMaxListeners(50);Rl=new Set,_l=new Map,ZS=new Map,We={totalAudits:0,totalPackagesScanned:0,totalVulnerabilities:0,totalMalicious:0,totalTyposquats:0,totalUnlocked:0,totalRejected:0,totalLockfilesGenerated:0,byEcosystem:{},bySeverity:{}};G8();Sa=null});import{execSync as hG}from"child_process";function yG(e){return/\b(npm install|npm i\b|yarn add|pnpm add|pnpm install|pip install|pip3 install|go get|go mod tidy|cargo add|cargo install|gem install|composer install|composer require)\b/.test(e)}async function bG(e,t,n,r){let s=Date.now(),i={cwd:t,timeout:n,encoding:"utf-8",maxBuffer:1048576,stdio:["ignore","pipe","pipe"],signal:r};try{return{output:hG(e,i)||"(no output)",exitCode:0,durationMs:Date.now()-s,truncated:!1}}catch(o){let a=o.stdout?.toString?.()||"",c=o.stderr?.toString?.()||"";return{output:[a,c].filter(Boolean).join(`
65
- `)||o.message||"Command failed",exitCode:o.status||1,durationMs:Date.now()-s,truncated:!!o.message?.includes("maxBuffer")}}}function vG(e,t){let n=e.output,r=n.split(`
57
+ `)){let a=o.match(/^\s*([\w_-]+)\s*=\s*["']?([^"'{\n]+)/);a&&t.push({name:a[1],version:a[2].trim().replace(/[~^]/,""),ecosystem:"crates",isDevDependency:!0,isDirect:!0})}}catch{}return t}function AI(e){let t=[],n=VS(e);return n.includes("npm")&&t.push(...kI(e)),n.includes("pypi")&&t.push(...xI(e)),n.includes("go")&&t.push(...$I(e)),n.includes("crates")&&t.push(...CI(e)),t}async function yG(e,t,n){if(vn.offlineMode)return[];let r=wI(e,n),s=Al.get(r);if(s&&Date.now()-s.cachedAt<vn.cacheTTLMs)return s.vulnerabilities.filter(i=>JS(t,i.vulnerableRanges));try{let i=await fetch("https://api.osv.dev/v1/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:{name:e,ecosystem:hG[n]},version:t}),signal:AbortSignal.timeout(vn.scanTimeout)});if(!i.ok)return[];let a=((await i.json()).vulns||[]).map(c=>{let l=(c.affected||[]).find(m=>m.package?.name===e)||c.affected?.[0],u=[],d;for(let m of l?.ranges||[])for(let g of m.events||[])g.introduced&&u.push(`>=${g.introduced}`),g.fixed&&(u.push(`<${g.fixed}`),(!d||Cf(g.fixed,d)<0)&&(d=g.fixed));let f=bG(c.severity,c.database_specific),p=(c.severity||[]).find(m=>m.type?.startsWith("CVSS"))?.score;return{id:c.id,package:e,ecosystem:n,installedVersion:t,vulnerableRanges:u,fixedVersion:d,severity:f,cvssScore:TI(p),cvssVector:p,cwe:c.database_specific?.cwe_ids||[],summary:c.summary||c.id,details:c.details?.slice(0,1e3),publishedAt:new Date(c.published||Date.now()).getTime(),references:(c.references||[]).map(m=>m.url).slice(0,5),source:"osv"}});return Al.set(r,{package:e,ecosystem:n,vulnerabilities:a,cachedAt:Date.now()}),queueMicrotask(()=>gG()),a}catch{return[]}}function bG(e,t){if(t?.severity){let r=t.severity.toLowerCase();if(r==="critical")return"critical";if(r==="high")return"high";if(r==="medium"||r==="moderate")return"medium";if(r==="low")return"low"}let n=(e||[]).find(r=>r.type?.startsWith("CVSS"));if(n?.score){let r=TI(n.score);if(r)return r>=9?"critical":r>=7?"high":r>=4?"medium":"low"}return"medium"}function TI(e){if(!e)return;let t=e.match(/(\d+\.\d+)/);return t?parseFloat(t[1]):void 0}async function vG(e){if(!vn.enableNpmAudit)return[];try{let t=SI("npm audit --json",{cwd:e,stdio:"pipe",timeout:vn.scanTimeout,encoding:"utf-8"});return yI(t)}catch(t){if(t.stdout)try{return yI(t.stdout.toString())}catch{}return[]}}function yI(e){let t=[];try{let n=JSON.parse(e),r=n.advisories||n.vulnerabilities;if(!r)return[];for(let[s,i]of Object.entries(r)){let o=i,a=o.via?.[0]||o;if(typeof a=="string")continue;let c=SG(o.severity||a.severity);t.push({id:a.cve||a.id?.toString()||a.url||`npm-${s}`,package:s,ecosystem:"npm",installedVersion:o.range||"unknown",vulnerableRanges:[o.range||""],fixedVersion:o.fixAvailable?.version||a.patched_versions,severity:c,cvssScore:a.cvss?.score,cvssVector:a.cvss?.vectorString,cwe:a.cwe||[],summary:a.title||a.url||"npm audit finding",details:a.overview?.slice(0,1e3),publishedAt:a.created?new Date(a.created).getTime():Date.now(),references:[a.url].filter(Boolean),source:"npm-audit"})}}catch{}return t}function SG(e){let t=e?.toLowerCase();return t==="critical"?"critical":t==="high"?"high":t==="moderate"?"medium":t==="low"?"low":"none"}function Tl(e){let t=e.replace(/^[v=]+/,"").split("+")[0],[n,r]=t.split("-"),s=n.split(".").map(i=>parseInt(i,10)||0);for(;s.length<3;)s.push(0);return{parts:s,pre:r}}function Cf(e,t){let n=Tl(e),r=Tl(t);for(let s=0;s<Math.max(n.parts.length,r.parts.length);s++){let i=(n.parts[s]||0)-(r.parts[s]||0);if(i!==0)return i}return n.pre&&!r.pre?-1:!n.pre&&r.pre?1:n.pre&&r.pre?n.pre.localeCompare(r.pre):0}function JS(e,t){if(t.length===0||e==="latest"||e==="*")return!0;let n=!1,r=!0;for(let s of t){let i=s.match(/^([<>=]+)(.+)$/);if(!i)continue;let o=i[1],a=i[2].trim(),c=Cf(e,a),l=!1;o===">="?l=c>=0:o===">"?l=c>0:o==="<="?l=c<=0:o==="<"?l=c<0:(o==="="||o==="==")&&(l=c===0),o.startsWith("<")?(l&&(n=n||r),r=!0):o.startsWith(">")&&(r=l)}if(t.length===1){let s=t[0].match(/^([<>=]+)(.+)$/);if(s){let i=Cf(e,s[2].trim());if(s[1]===">=")return i>=0;if(s[1]===">")return i>0;if(s[1]==="<=")return i<=0;if(s[1]==="<")return i<0;if(s[1]==="="||s[1]==="==")return i===0}}return n}function wG(e,t){let n=[],r=new Map;for(let a of t){let c=`${a.ecosystem}:${a.package}`;r.has(c)||r.set(c,[]),r.get(c).push(a)}for(let[a,c]of r){let l=e.find(f=>`${f.ecosystem}:${f.name}`===a);if(!l)continue;let u;for(let f of c)f.fixedVersion&&(!u||Cf(f.fixedVersion,u)>0)&&(u=f.fixedVersion);if(!u)continue;let d=kG(l.version,u);n.push({package:l.name,ecosystem:l.ecosystem,from:l.version,to:u,fixesVulns:c.map(f=>f.id),isBreaking:d,confidence:c.every(f=>f.fixedVersion)?.95:.6})}let s=n.length,i=n.filter(a=>a.isBreaking).length,o="trivial";return i>5||s>20?o="significant":i>2||s>10?o="moderate":(i>0||s>3)&&(o="minor"),{patches:n,totalFixable:s,breakingChanges:i,estimatedEffort:o}}function kG(e,t){try{let n=Tl(e),r=Tl(t);return n.parts[0]!==r.parts[0]}catch{return!1}}async function xG(e,t){if(!vn.enableOutdatedCheck)return[];let n=[];if(t.includes("npm"))try{let r=SI("npm outdated --json",{cwd:e,stdio:"pipe",timeout:vn.scanTimeout,encoding:"utf-8"});try{let s=JSON.parse(r||"{}");for(let[i,o]of Object.entries(s)){let a=o,c=bI(a.current,a.latest);n.push({name:i,ecosystem:"npm",current:a.current,wanted:a.wanted,latest:a.latest,type:c})}}catch{}}catch(r){if(r.stdout)try{let s=JSON.parse(r.stdout.toString()||"{}");for(let[i,o]of Object.entries(s)){let a=o;n.push({name:i,ecosystem:"npm",current:a.current,wanted:a.wanted,latest:a.latest,type:bI(a.current,a.latest)})}}catch{}}return n}function bI(e,t){try{let n=Tl(e),r=Tl(t);return n.parts[0]!==r.parts[0]?"major":n.parts[1]!==r.parts[1]?"minor":n.parts[2]!==r.parts[2]?"patch":"unknown"}catch{return"unknown"}}async function $G(e){let t=Date.now(),n=uG(e);if(!vn.enabled)return vI(n,["Scanner disabled"]);let r=VS(n);if(r.length===0)return vI(n,["No supported package files found"]);let s=gh(),i=AI(n),o=vn.excludeDevDependencies?i.filter(k=>!k.isDevDependency):i,a=[],c=0,l=[],u=o.map(async k=>{try{let S=wI(k.name,k.ecosystem),x=Al.get(S);return x&&Date.now()-x.cachedAt<vn.cacheTTLMs?(c++,x.vulnerabilities.filter(A=>JS(k.version,A.vulnerableRanges))):await yG(k.name,k.version,k.ecosystem)}catch(S){return l.push(`${k.name}: ${S.message}`),[]}}),d=await Promise.allSettled(u);for(let k of d)k.status==="fulfilled"&&a.push(...k.value);let f=new Set;if(a=a.filter(k=>f.has(k.id)?!1:(f.add(k.id),!0)),vn.enableNpmAudit&&r.includes("npm")){let k=await vG(n);for(let S of k)f.has(S.id)||(f.add(S.id),a.push(S))}a=a.filter(k=>!s.includes(k.id)&&!vn.suppressedVulns.includes(k.id));let p=["critical","high","medium","low","none"],m=p.indexOf(vn.severityThreshold);a=a.filter(k=>p.indexOf(k.severity)<=m);let g={critical:0,high:0,medium:0,low:0,none:0};for(let k of a)g[k.severity]++;let h=wG(o,a),v=await xG(n,r),y=CG(g,o.length),b={projectPath:n,ecosystems:r,totalDependencies:o.length,vulnerableCount:a.length,bySeverity:g,vulnerabilities:a,upgradePlan:h,outdatedPackages:v,riskScore:y,duration:Date.now()-t,scannedAt:Date.now(),cacheHits:c,errors:l};return EG(b),MG(b),b}function vI(e,t){return{projectPath:e,ecosystems:[],totalDependencies:0,vulnerableCount:0,bySeverity:{critical:0,high:0,medium:0,low:0,none:0},vulnerabilities:[],upgradePlan:{patches:[],totalFixable:0,breakingChanges:0,estimatedEffort:"trivial"},outdatedPackages:[],riskScore:0,duration:0,scannedAt:Date.now(),cacheHits:0,errors:t}}function CG(e,t){let n=e.critical*25+e.high*10+e.medium*3+e.low*1,r=Math.min(1,n/Math.max(1,t*5));return Math.round(r*100)}function gh(){if(!Ft(GS))return[];try{return JSON.parse(pi(GS,"utf-8"))}catch{return[]}}function _I(e){_f();try{Af(GS,JSON.stringify(e,null,2),"utf-8")}catch{}}function AG(e){let t=gh();t.includes(e)||(t.push(e),_I(t))}function TG(e){let t=gh().filter(n=>n!==e);_I(t)}function _G(){return gh()}function RG(e,t){return{bomFormat:"CycloneDX",specVersion:"1.5",version:1,metadata:{timestamp:new Date().toISOString(),tools:[{vendor:"AIACA",name:"vulnScan",version:"1.0"}],component:{type:"application",name:t.split(/[/\\]/).pop()}},components:e.map(n=>({type:"library",name:n.name,version:n.version,purl:PG(n),scope:n.isDevDependency?"optional":"required"}))}}function PG(e){return`pkg:${{npm:"npm",pypi:"pypi",go:"golang",crates:"cargo",maven:"maven",rubygems:"gem",packagist:"composer",nuget:"nuget"}[e.ecosystem]}/${e.name}@${e.version}`}function IG(){if(Ft(zS))try{an={...an,...JSON.parse(pi(zS,"utf-8"))}}catch{}}function RI(){_f();try{Af(zS,JSON.stringify(an,null,2),"utf-8")}catch{}}function MG(e){an.totalScans++,an.totalVulnsFound+=e.vulnerableCount,an.totalCriticalsFound+=e.bySeverity.critical,an.cacheHitRate=(an.cacheHitRate*(an.totalScans-1)+e.cacheHits/Math.max(1,e.totalDependencies))/an.totalScans,an.averageDurationMs=(an.averageDurationMs*(an.totalScans-1)+e.duration)/an.totalScans;for(let t of e.vulnerabilities)an.topVulnerablePackages[t.package]=(an.topVulnerablePackages[t.package]||0)+1;RI()}function EG(e){_f();try{let t=JSON.stringify({projectPath:e.projectPath,timestamp:e.scannedAt,vulnerableCount:e.vulnerableCount,riskScore:e.riskScore,bySeverity:e.bySeverity})+`
58
+ `;Af(pG,t,{flag:"a"})}catch{}}function DG(){return{...vn}}function FG(e){vn={...vn,...e}}function LG(){return JSON.parse(JSON.stringify(an))}function OG(){an={totalScans:0,totalVulnsFound:0,totalCriticalsFound:0,totalSuppressed:0,cacheHitRate:0,averageDurationMs:0,topVulnerablePackages:{}},RI()}function jG(){if(Al.clear(),Ft($f))try{Af($f,"{}","utf-8")}catch{}}function BG(e){let t=[];if(t.push("# Dependency Vulnerability Scan"),t.push(""),t.push(`**Risk Score:** ${e.riskScore}/100`),t.push(`**Total Dependencies:** ${e.totalDependencies}`),t.push(`**Vulnerabilities Found:** ${e.vulnerableCount}`),t.push(`**Ecosystems:** ${e.ecosystems.join(", ")}`),t.push(""),e.vulnerableCount===0)t.push(`\u2713 No vulnerabilities found above ${vn.severityThreshold} severity.`);else{t.push("## Severity Breakdown"),e.bySeverity.critical>0&&t.push(` \u{1F6A8} Critical: ${e.bySeverity.critical}`),e.bySeverity.high>0&&t.push(` \u26A0\uFE0F High: ${e.bySeverity.high}`),e.bySeverity.medium>0&&t.push(` \u26A1 Medium: ${e.bySeverity.medium}`),e.bySeverity.low>0&&t.push(` \u2139\uFE0F Low: ${e.bySeverity.low}`),t.push(""),t.push("## Vulnerabilities (top 15)");let n=[...e.vulnerabilities].sort((r,s)=>{let i=["critical","high","medium","low","none"];return i.indexOf(r.severity)-i.indexOf(s.severity)});for(let r of n.slice(0,15)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="high"?"\u26A0\uFE0F ":r.severity==="medium"?"\u26A1":"\u2139\uFE0F ";t.push(`${s} **${r.id}** ${r.package}@${r.installedVersion} (${r.severity})`),t.push(` ${r.summary}`),r.fixedVersion&&t.push(` Fix: upgrade to ${r.fixedVersion}`),r.cvssScore&&t.push(` CVSS: ${r.cvssScore}`),t.push("")}if(e.upgradePlan.totalFixable>0){t.push("## Upgrade Plan"),t.push(`Effort: ${e.upgradePlan.estimatedEffort}`),t.push(`Fixable: ${e.upgradePlan.totalFixable} | Breaking: ${e.upgradePlan.breakingChanges}`),t.push("");for(let r of e.upgradePlan.patches.slice(0,10)){let s=r.isBreaking?" \u26A0\uFE0F BREAKING":"";t.push(` ${r.package}: ${r.from} \u2192 ${r.to}${s}`),t.push(` Fixes: ${r.fixesVulns.slice(0,3).join(", ")}${r.fixesVulns.length>3?"...":""}`)}}}if(e.outdatedPackages.length>0){t.push(""),t.push("## Outdated (top 10)");for(let n of e.outdatedPackages.slice(0,10))t.push(` ${n.name}: ${n.current} \u2192 ${n.latest} (${n.type})`)}return t.join(`
59
+ `)}var fG,vn,Tf,$f,zS,pG,GS,Al,hG,an,yh=w(()=>{"use strict";fG={enabled:!0,primarySource:"osv",enableNpmAudit:!0,enablePipAudit:!0,enableLicenseCheck:!0,enableOutdatedCheck:!0,cacheTTLMs:1440*60*1e3,scanTimeout:6e4,blockOnCritical:!0,excludeDevDependencies:!1,severityThreshold:"medium",suppressedVulns:[],offlineMode:!1,scanOnInstall:!0},vn={...fG},Tf=At(dG(),".aiaca","vuln-scan"),$f=At(Tf,"vuln-cache.json"),zS=At(Tf,"stats.json"),pG=At(Tf,"history.jsonl"),GS=At(Tf,"suppressions.json"),Al=new Map;mG();hG={npm:"npm",pypi:"PyPI",go:"Go",crates:"crates.io",maven:"Maven",rubygems:"RubyGems",packagist:"Packagist",nuget:"NuGet"};an={totalScans:0,totalVulnsFound:0,totalCriticalsFound:0,totalSuppressed:0,cacheHitRate:0,averageDurationMs:0,topVulnerablePackages:{}};IG()});var kh={};$(kh,{addMalicious:()=>l8,auditDependencies:()=>LI,configure:()=>i8,detectEcosystem:()=>tw,formatAuditResult:()=>f8,generateComplianceReport:()=>d8,generateLockfile:()=>EI,getAuditLog:()=>u8,getConfig:()=>s8,getEvents:()=>c8,getStats:()=>o8,loadLockfile:()=>wh,resetStats:()=>a8,startAutoAudit:()=>n8,stopAutoAudit:()=>r8,verifyLockfileMatchesInstall:()=>FI});import{existsSync as Je,mkdirSync as WS,readFileSync as Is,writeFileSync as oo}from"fs";import{join as Ae,basename as PI,dirname as NG}from"path";import{homedir as qG}from"os";import{createHash as UG}from"crypto";import{EventEmitter as HG}from"events";function wa(){WS(Pl,{recursive:!0}),WS(II,{recursive:!0})}function GG(){if(wa(),Je(KS))try{We={...We,...JSON.parse(Is(KS,"utf-8"))}}catch{}if(Je(bh))try{let e=JSON.parse(Is(bh,"utf-8"));for(let t of e)Rl.add(t)}catch{}else VG();if(Je(QS))try{let e=JSON.parse(Is(QS,"utf-8"));for(let[t,n]of Object.entries(e))_l.set(t,new Set(n))}catch{}else JG()}function ew(){wa();try{oo(KS,JSON.stringify(We,null,2),"utf-8")}catch{}}function MI(e){wa();try{oo(YS,JSON.stringify({...e,timestamp:Date.now()})+`
60
+ `,{flag:"a"})}catch{}}function VG(){let e=["cross-env@7.0.4","colors@1.4.44","faker@6.6.6","event-stream@3.3.6","flatmap-stream@0.1.1","noblox.js-proxy@1.0.0","electorn@1.4.16","opencv.js@1.0.0","ua-parser-js@0.7.29"];for(let t of e)Rl.add(t);wa();try{oo(bh,JSON.stringify(e,null,2),"utf-8")}catch{}}function JG(){_l.set("npm",new Set(["react","lodash","express","axios","webpack","typescript","eslint","next","vue","angular","jest","mocha","chai","commander","chalk","rxjs","tslib","electron","jquery","moment","underscore","request","async","bluebird","classnames","redux","react-dom","styled-components","fs-extra","glob","minimist","yargs","inquirer","dotenv","cross-env"])),_l.set("pypi",new Set(["requests","numpy","pandas","flask","django","pytest","tensorflow","torch","scipy","matplotlib","pillow","beautifulsoup4","lxml","pyyaml","click","sqlalchemy","fastapi","uvicorn","pydantic"])),_l.set("cargo",new Set(["serde","tokio","reqwest","clap","log","rand","chrono","thiserror"])),wa();try{let e={};for(let[t,n]of _l.entries())e[t]=Array.from(n);oo(QS,JSON.stringify(e,null,2),"utf-8")}catch{}}function vh(e){return UG("sha256").update(e).digest("hex")}function XS(e){let t=Object.keys(e).sort(),n={};for(let r of t){let s=e[r];n[r]={name:s.name,version:s.version,ecosystem:s.ecosystem,sha256:s.sha256,resolvedUrl:s.resolvedUrl,parents:[...s.parents].sort()}}return JSON.stringify(n)}function tw(e){return Je(Ae(e,"package.json"))||Je(Ae(e,"package-lock.json"))||Je(Ae(e,"yarn.lock"))||Je(Ae(e,"pnpm-lock.yaml"))?"npm":Je(Ae(e,"requirements.txt"))||Je(Ae(e,"pyproject.toml"))||Je(Ae(e,"Pipfile"))?"pypi":Je(Ae(e,"Cargo.toml"))?"cargo":Je(Ae(e,"Gemfile"))||Je(Ae(e,"Gemfile.lock"))?"gem":Je(Ae(e,"composer.json"))?"composer":Je(Ae(e,"pom.xml"))||Je(Ae(e,"build.gradle"))?"maven":Je(Ae(e,"go.mod"))?"go":Je(Ae(e,"packages.config"))?"nuget":"unknown"}async function EI(e){let t=tw(e);if(t==="unknown")return null;let n={};t==="npm"?await DI(e,n):t==="pypi"?await WG(e,n):t==="cargo"&&await KG(e,n);let r=PI(e),s=vh(XS(n)),i={version:1,generatedAt:Date.now(),generatedBy:"aiaca",ecosystem:t,projectName:r,projectPath:e,dependencies:n,lockfileHash:s,auditHistory:[]},o=Ae(e,".aiaca","deps.lock.json");return wa(),WS(NG(o),{recursive:!0}),oo(o,JSON.stringify(i,null,2),"utf-8"),ZS.set(e,i),We.totalLockfilesGenerated++,We.byEcosystem[t]=(We.byEcosystem[t]||0)+1,ew(),MI({event:"lockfile_generated",projectName:r,ecosystem:t,dependencyCount:Object.keys(n).length}),Sh.emit("lockfile_generated",{lockfile:i}),i}async function DI(e,t){let n=Ae(e,"package-lock.json");if(Je(n))try{let s=JSON.parse(Is(n,"utf-8")),i=s.packages||s.dependencies||{};for(let[o,a]of Object.entries(i)){if(!o||o==="")continue;let c=a.name||PI(o).replace(/^node_modules\//,"");if(!c||!a.version)continue;let l=`${c}@${a.version}`,u=a.integrity?a.integrity.replace(/^sha256-/,"").replace(/^sha512-/,""):a._shasum||"";t[l]={name:c,version:a.version,ecosystem:"npm",sha256:u,resolvedUrl:a.resolved,parents:[],status:"locked",vulnerabilities:[],lastAuditedAt:0}}return}catch{}let r=Ae(e,"package.json");if(Je(r))try{let s=JSON.parse(Is(r,"utf-8")),i={...s.dependencies,...s.devDependencies};for(let[o,a]of Object.entries(i)){let c=a.replace(/^[\^~>=<]+/,""),l=`${o}@${c}`;t[l]={name:o,version:c,ecosystem:"npm",sha256:"",parents:[],status:"unlocked",vulnerabilities:[],lastAuditedAt:0}}}catch{}}async function WG(e,t){let n=Ae(e,"requirements.txt");if(Je(n))try{let r=Is(n,"utf-8").split(`
61
+ `).filter(s=>s.trim()&&!s.startsWith("#"));for(let s of r){let i=s.match(/^([\w\-_.]+)\s*(?:==|===)\s*([\w.\-+]+)(?:\s*--hash=sha256:([a-f0-9]+))?/i);if(i){let[,o,a,c]=i,l=`${o}@${a}`;t[l]={name:o,version:a,ecosystem:"pypi",sha256:c||"",parents:[],status:c?"locked":"unlocked",vulnerabilities:[],lastAuditedAt:0}}}}catch{}}async function KG(e,t){let n=Ae(e,"Cargo.lock");if(Je(n))try{let s=Is(n,"utf-8").split(/\n\[\[package\]\]\n/);for(let i of s.slice(1)){let o=i.match(/name\s*=\s*"([^"]+)"/),a=i.match(/version\s*=\s*"([^"]+)"/),c=i.match(/checksum\s*=\s*"([^"]+)"/);if(o&&a){let l=o[1],u=a[1],d=`${l}@${u}`;t[d]={name:l,version:u,ecosystem:"cargo",sha256:c?c[1]:"",parents:[],status:c?"locked":"unlocked",vulnerabilities:[],lastAuditedAt:0}}}}catch{}}function wh(e){let t=ZS.get(e);if(t)return t;let n=Ae(e,".aiaca","deps.lock.json");if(!Je(n))return null;try{let r=JSON.parse(Is(n,"utf-8"));return ZS.set(e,r),r}catch{return null}}function FI(e){let t=wh(e);if(!t)return{matches:!1,missingFromLock:[],extraInLock:[]};let n={};DI(e,n).catch(()=>{});let r=XS(t.dependencies),s=vh(r),i=XS(n),o=vh(i),a=new Set(Object.keys(t.dependencies)),c=new Set(Object.keys(n)),l=Array.from(c).filter(d=>!a.has(d)),u=Array.from(a).filter(d=>!c.has(d));return{matches:s===o,expectedHash:s,actualHash:o,missingFromLock:l,extraInLock:u}}async function LI(e){let t=Date.now(),n=tw(e),r=wh(e);if(r||(r=await EI(e)),!r)return{ecosystem:n,totalPackages:0,scannedPackages:0,findings:[],byType:{},bySeverity:{},blockers:0,durationMs:Date.now()-t,lockfileMatches:!1};let s=[],i={},o={},a=FI(e),c=Object.values(r.dependencies);for(let u of c){let d=`${u.name}@${u.version}`;if((Rl.has(d)||Rl.has(u.name))&&(s.push({packageName:u.name,packageVersion:u.version,type:"malicious",severity:"critical",description:`Known-malicious package: ${d}`,remediation:"Remove this package immediately and rotate any credentials"}),u.status="malicious",We.totalMalicious++),Sn.enableTyposquatDetection){let f=XG(u.name,n);f&&(s.push({packageName:u.name,packageVersion:u.version,type:"typosquat",severity:"high",description:`Possible typosquat of "${f}"`,remediation:`Verify package; consider switching to ${f}`}),u.status="typosquat",We.totalTyposquats++)}(u.status==="unlocked"||!u.sha256)&&(s.push({packageName:u.name,packageVersion:u.version,type:"unsigned",severity:"medium",description:"Package not pinned with SHA-256 hash",remediation:"Run package manager lock command (npm ci, cargo build, etc.)"}),We.totalUnlocked++),u.lastAuditedAt=Date.now()}if(Sn.enableOsvCheck)for(let u of c)try{let d=await YG(u.name,u.version,n);for(let f of d)u.vulnerabilities.push(f),s.push({packageName:u.name,packageVersion:u.version,type:"cve",severity:f.severity,description:`${f.id}: ${f.summary}`,remediation:f.fixedIn?`Upgrade to ${f.fixedIn}`:"No fix available yet"}),We.totalVulnerabilities++}catch{}for(let u of s)i[u.type]=(i[u.type]||0)+1,o[u.severity]=(o[u.severity]||0)+1,We.bySeverity[u.severity]=(We.bySeverity[u.severity]||0)+1;let l=s.filter(u=>u.severity==="critical"||u.type==="malicious").length;r.auditHistory.push({timestamp:Date.now(),vulnerabilitiesFound:s.filter(u=>u.type==="cve").length,maliciousFound:s.filter(u=>u.type==="malicious").length}),r.auditHistory.length>50&&(r.auditHistory=r.auditHistory.slice(-50));try{let u=Ae(e,".aiaca","deps.lock.json");oo(u,JSON.stringify(r,null,2),"utf-8")}catch{}return We.totalAudits++,We.totalPackagesScanned+=c.length,ew(),MI({event:"audit_complete",project:r.projectName,ecosystem:n,packageCount:c.length,findingsCount:s.length,blockers:l,durationMs:Date.now()-t}),Sh.emit("audit_complete",{lockfile:r,findings:s,blockers:l}),{ecosystem:n,totalPackages:c.length,scannedPackages:c.length,findings:s,byType:i,bySeverity:o,blockers:l,durationMs:Date.now()-t,lockfileMatches:a.matches}}async function YG(e,t,n){let r=`${n}:${e}@${t}`,s=Ae(II,vh(r).slice(0,16)+".json");if(Je(s))try{let a=JSON.parse(Is(s,"utf-8"));if(Date.now()-a.cachedAt<1440*60*1e3)return a.vulns}catch{}if(typeof fetch>"u")return[];let o={npm:"npm",pypi:"PyPI",cargo:"crates.io",gem:"RubyGems",composer:"Packagist",maven:"Maven",go:"Go",nuget:"NuGet",unknown:""}[n];if(!o)return[];try{let a=await fetch(Sn.osvApiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:{name:e,ecosystem:o},version:t})});if(!a.ok)return[];let c=await a.json(),l=[];for(let u of c.vulns||[]){let d=QG(u);l.push({id:u.id,severity:d,summary:u.summary||u.details?.slice(0,200)||"No summary",affectedRanges:u.affected?.map(f=>f.ranges?.map(p=>p.events).flat()).flat().filter(Boolean),fixedIn:ZG(u)})}try{oo(s,JSON.stringify({cachedAt:Date.now(),vulns:l},null,2),"utf-8")}catch{}return l}catch{return[]}}function QG(e){let t=e.severity?.find(n=>n.type?.includes("CVSS"));if(t?.score){let n=typeof t.score=="string"?parseFloat(t.score.match(/[\d.]+/)?.[0]||"0"):t.score;return n>=9?"critical":n>=7?"high":n>=4?"medium":"low"}return"medium"}function ZG(e){for(let t of e.affected||[])for(let n of t.ranges||[])for(let r of n.events||[])if(r.fixed)return r.fixed}function XG(e,t){let n=_l.get(t);if(!n)return null;let r=e.toLowerCase();if(n.has(r))return null;for(let s of n){let i=e8(r,s);if(i>Sn.typosquatThreshold&&i<1)return s}return null}function e8(e,t){return 1-t8(e,t)/Math.max(e.length,t.length)}function t8(e,t){let n=[];for(let r=0;r<=e.length;r++){n[r]=[r];for(let s=1;s<=t.length;s++)if(r===0)n[r][s]=s;else{let i=e[r-1]===t[s-1]?0:1;n[r][s]=Math.min(n[r-1][s]+1,n[r][s-1]+1,n[r-1][s-1]+i)}}return n[e.length][t.length]}function n8(e){Sa||!Sn.enableAutoAudit||(Sa=setInterval(()=>{LI(e).catch(()=>{})},Sn.auditIntervalMs),Sa.unref&&Sa.unref())}function r8(){Sa&&(clearInterval(Sa),Sa=null)}function s8(){return{...Sn}}function i8(e){Sn={...Sn,...e}}function o8(){return{...We}}function a8(){We={totalAudits:0,totalPackagesScanned:0,totalVulnerabilities:0,totalMalicious:0,totalTyposquats:0,totalUnlocked:0,totalRejected:0,totalLockfilesGenerated:0,byEcosystem:{},bySeverity:{}},ew()}function c8(){return Sh}function l8(e,t){let n=t?`${e}@${t}`:e;Rl.add(n),wa();try{oo(bh,JSON.stringify(Array.from(Rl),null,2),"utf-8")}catch{}}function u8(e=100){if(!Je(YS))return[];try{return Is(YS,"utf-8").split(`
62
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function d8(e){let t=[];t.push("# Dependency Lock & Audit Compliance Report"),t.push(`Generated: ${new Date().toISOString()}`),t.push(""),t.push("## Summary"),t.push(`- Total audits: ${We.totalAudits}`),t.push(`- Packages scanned: ${We.totalPackagesScanned}`),t.push(`- \u{1F6A8} Malicious: ${We.totalMalicious}`),t.push(`- \u{1F50D} Vulnerabilities: ${We.totalVulnerabilities}`),t.push(`- \u26A0\uFE0F Typosquats: ${We.totalTyposquats}`),t.push(`- \u{1F513} Unlocked: ${We.totalUnlocked}`),t.push(`- \u{1F527} Lockfiles generated: ${We.totalLockfilesGenerated}`),t.push(""),t.push("## By Ecosystem");for(let[n,r]of Object.entries(We.byEcosystem))t.push(`- ${n}: ${r}`);t.push(""),t.push("## By Severity");for(let[n,r]of Object.entries(We.bySeverity))t.push(`- ${n}: ${r}`);if(t.push(""),e){let n=wh(e);n&&(t.push(`## Project: ${n.projectName}`),t.push(`- Ecosystem: ${n.ecosystem}`),t.push(`- Dependencies: ${Object.keys(n.dependencies).length}`),t.push(`- Lockfile hash: ${n.lockfileHash.slice(0,16)}...`),t.push(`- Audit history entries: ${n.auditHistory.length}`))}return t.push(""),t.push("## Compliance Properties"),t.push("- \u2713 Cryptographic SHA-256 package hashes"),t.push("- \u2713 Exact version pinning"),t.push(`- ${Sn.rejectMalicious?"\u2713":"\u2717"} Reject known-malicious`),t.push(`- ${Sn.rejectVulnerable?"\u2713":"\u2717"} Reject vulnerable packages`),t.push(`- ${Sn.rejectUnlocked?"\u2713":"\u2717"} Reject unlocked packages`),t.push(`- ${Sn.enableOsvCheck?"\u2713":"\u2717"} OSV.dev vulnerability checks`),t.push(`- ${Sn.enableTyposquatDetection?"\u2713":"\u2717"} Typosquat detection`),t.push(`- ${Sn.enableAutoAudit?"\u2713":"\u2717"} Continuous auto-audit (${Sn.auditIntervalMs/864e5}d)`),t.push(`- ${Sn.enableLicenseCheck?"\u2713":"\u2717"} License compliance scan`),t.join(`
63
+ `)}function f8(e){let t=[],n=e.blockers>0?"\u{1F6A8}":e.findings.length>0?"\u26A0\uFE0F":"\u2713";if(t.push(`${n} **Audit Result** (${e.ecosystem})`),t.push(`Packages: ${e.totalPackages} | Findings: ${e.findings.length} | Blockers: ${e.blockers}`),t.push(`Lockfile reproducible: ${e.lockfileMatches?"\u2713":"\u26A0\uFE0F MISMATCH"}`),t.push(`Duration: ${e.durationMs}ms`),t.push(""),e.findings.length>0){t.push("## Findings");for(let r of e.findings.slice(0,30)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="high"?"\u26A0\uFE0F ":r.severity==="medium"?"\u26A1":"\u2139\uFE0F ";t.push(`${s} [${r.type}] ${r.packageName}@${r.packageVersion}: ${r.description}`),r.remediation&&t.push(` \u2192 ${r.remediation}`)}}return t.join(`
64
+ `)}var zG,Sn,Pl,KS,YS,bh,QS,II,Sh,Rl,_l,ZS,We,Sa,xh=w(()=>{"use strict";zG={enabled:!0,rejectUnlocked:!0,rejectVulnerable:!1,rejectMalicious:!0,blockOnCritical:!0,blockOnHigh:!1,enableAutoAudit:!0,auditIntervalMs:1440*60*1e3,enableOsvCheck:!0,osvApiUrl:"https://api.osv.dev/v1/query",enableTyposquatDetection:!0,typosquatThreshold:.85,enableSignatureVerification:!1,enablePackageCache:!0,enableLicenseCheck:!1,forbiddenLicenses:["GPL-3.0","AGPL-3.0","SSPL-1.0"]},Sn={...zG},Pl=Ae(qG(),".aiaca","dep-audit"),KS=Ae(Pl,"stats.json"),YS=Ae(Pl,"audit.jsonl"),bh=Ae(Pl,"known-malicious.json"),QS=Ae(Pl,"popular-packages.json"),II=Ae(Pl,"vuln-cache"),Sh=new HG;Sh.setMaxListeners(50);Rl=new Set,_l=new Map,ZS=new Map,We={totalAudits:0,totalPackagesScanned:0,totalVulnerabilities:0,totalMalicious:0,totalTyposquats:0,totalUnlocked:0,totalRejected:0,totalLockfilesGenerated:0,byEcosystem:{},bySeverity:{}};GG();Sa=null});import{execSync as h8}from"child_process";function y8(e){return/\b(npm install|npm i\b|yarn add|pnpm add|pnpm install|pip install|pip3 install|go get|go mod tidy|cargo add|cargo install|gem install|composer install|composer require)\b/.test(e)}async function b8(e,t,n,r){let s=Date.now(),i={cwd:t,timeout:n,encoding:"utf-8",maxBuffer:1048576,stdio:["ignore","pipe","pipe"],signal:r};try{return{output:h8(e,i)||"(no output)",exitCode:0,durationMs:Date.now()-s,truncated:!1}}catch(o){let a=o.stdout?.toString?.()||"",c=o.stderr?.toString?.()||"";return{output:[a,c].filter(Boolean).join(`
65
+ `)||o.message||"Command failed",exitCode:o.status||1,durationMs:Date.now()-s,truncated:!!o.message?.includes("maxBuffer")}}}function v8(e,t){let n=e.output,r=n.split(`
66
66
  `);if(r.length>5e3){let s=r.slice(0,100).join(`
67
67
  `),i=r.slice(-50).join(`
68
68
  `);n=`${s}
@@ -83,9 +83,9 @@ ${l.map(d=>` - [${d.severity}] ${d.description}`).join(`
83
83
  `)}`}}catch{}try{let a=await Promise.resolve().then(()=>(Sf(),vf));if(a.getConfig().enabled){let c=n.match(/(?:curl|wget|fetch)\s+(?:[^\s]+\s+)*(https?:\/\/[^\s'"]+)/i);if(c){let l=a.checkRequest({url:c[1],toolName:"bash",sessionId:t.session?.id});if(l.decision==="block")return`\u{1F6AB} BLOCKED by egress firewall: ${l.reason}
84
84
 
85
85
  Detected URL: ${c[1]}
86
- Use \`/egress add <domain>\` to allowlist.`}}}catch{}let r=Math.min(Number(e.timeout)||12e4,3e5),s=e.cwd||t.cwd,i=await bG(n,s,r,t.abortSignal),o=vG(i,n);try{let a=await Promise.resolve().then(()=>(Cl(),$l));if(a.getConfig().enabled){let c=a.scanText(o,`bash:${n.slice(0,50)}`);c.matches.length>0&&(c.redactedText&&(o=c.redactedText),o+=`
86
+ Use \`/egress add <domain>\` to allowlist.`}}}catch{}let r=Math.min(Number(e.timeout)||12e4,3e5),s=e.cwd||t.cwd,i=await b8(n,s,r,t.abortSignal),o=v8(i,n);try{let a=await Promise.resolve().then(()=>(Cl(),$l));if(a.getConfig().enabled){let c=a.scanText(o,`bash:${n.slice(0,50)}`);c.matches.length>0&&(c.redactedText&&(o=c.redactedText),o+=`
87
87
 
88
- [\u{1F6E1}\uFE0F ${c.matches.length} secret(s) detected and redacted in output]`)}}catch{}if(i.exitCode===0&&yG(n)){try{let a=await Promise.resolve().then(()=>(yh(),hh));if(a.getConfig().scanOnInstall){let c=await a.scanProject(s);if(c.vulnerableCount>0){o+=`
88
+ [\u{1F6E1}\uFE0F ${c.matches.length} secret(s) detected and redacted in output]`)}}catch{}if(i.exitCode===0&&y8(n)){try{let a=await Promise.resolve().then(()=>(yh(),hh));if(a.getConfig().scanOnInstall){let c=await a.scanProject(s);if(c.vulnerableCount>0){o+=`
89
89
 
90
90
  [Vulnerability scan: ${c.vulnerableCount} issue(s) detected]`;let l=c.bySeverity.critical,u=c.bySeverity.high;if(l>0||u>0){o+=`
91
91
  \u{1F6A8} ${l} critical, ${u} high severity`;let d=c.vulnerabilities.slice(0,5);for(let f of d)o+=`
@@ -112,17 +112,17 @@ Best practices:
112
112
  Limits:
113
113
  - Max 2000 lines per read (use offset/limit for more)
114
114
  - Max 1MB file size
115
- - Binary files (.exe, .png, etc.) are not supported \u2014 use image_read for images`});var If={};$(If,{clearCache:()=>WG,disableWatcher:()=>zG,enableWatcher:()=>HG,formatUnifiedDiff:()=>UG,getAllTrackedFiles:()=>YG,getDiffStats:()=>VG,getFileChanges:()=>BG,getSnapshotInfo:()=>KG,getUnifiedDiff:()=>NG,initFileDiff:()=>FG,pruneStaleEntries:()=>JG,readFileRange:()=>jG,readFileSmart:()=>sw,resetStats:()=>QG});import{readFileSync as Il,writeFileSync as GI,existsSync as iw,mkdirSync as SG,statSync as ow,readdirSync as wG,unlinkSync as kG,watch as xG}from"fs";import{join as Rf,relative as $G,resolve as Ml}from"path";import{homedir as CG}from"os";import{createHash as Pf}from"crypto";function TG(e){return Pf("sha256").update(Ml(e)).digest("hex").slice(0,16)}function $h(e){return Rf(AG,TG(e))}function VI(e){return Rf($h(e),"snapshots.json")}function JI(e){return Rf($h(e),"chunks.json")}function WI(e){SG($h(e),{recursive:!0})}function KI(e,t){let n=[];if(e.length===0)return n;let r=0,s=1,i=1,o=0;for(let a=0;a<e.length;a++){e[a]===10&&i++,o=o+e[a]&4294967295,a>=zI&&(o=o-e[a-zI]&4294967295);let c=a-r+1;if(c>=_G&&((o&PG)===0||c>=RG)||a===e.length-1){let u=e.slice(r,a+1),d=Pf("sha256").update(u).digest("hex").slice(0,32),f=i;e[a]===10&&f--,n.push({hash:d,offset:r,size:a-r+1,startLine:s,endLine:Math.max(s,f)}),r=a+1,s=i,o=0}}return n}function El(e){let t=rw.get(e);return t||(t={chunks:new Map},rw.set(e,t)),t}function IG(e){let t=JI(e);if(iw(t))try{let n=JSON.parse(Il(t,"utf-8")),r=El(e);for(let[s,i]of Object.entries(n))r.chunks.set(s,{content:i.content,refCount:i.refCount||1,bytes:i.bytes||0})}catch{}}function MG(e){WI(e);let t=El(e),n={};for(let[r,s]of t.chunks)n[r]={content:s.content,refCount:s.refCount,bytes:s.bytes};try{GI(JI(e),JSON.stringify(n),"utf-8")}catch{}}function EG(e,t,n){let r=El(e),s=r.chunks.get(t);if(s){s.refCount++;return}r.chunks.set(t,{content:n,refCount:1,bytes:Buffer.byteLength(n,"utf-8")})}function YI(e,t){return El(e).chunks.get(t)?.content}function QI(e,t){let n=El(e),r=n.chunks.get(t);r&&(r.refCount--,r.refCount<=0&&n.chunks.delete(t))}function DG(e){Mn=e,zt.clear(),IG(e);let t=VI(e);if(iw(t))try{let n=JSON.parse(Il(t,"utf-8"));for(let r of n)zt.set(r.filePath,r)}catch{}}function aw(e){WI(e);try{GI(VI(e),JSON.stringify(Array.from(zt.values())),"utf-8"),MG(e)}catch{}}function FG(e){DG(e)}function ZI(e,t){let n=e.length,r=t.length,s=n+r,i=new Array(2*s+1).fill(0),o=[];for(let a=0;a<=s;a++){o.push([...i]);for(let c=-a;c<=a;c+=2){let l;c===-a||c!==a&&i[s+c-1]<i[s+c+1]?l=i[s+c+1]:l=i[s+c-1]+1;let u=l-c;for(;l<n&&u<r&&e[l]===t[u];)l++,u++;if(i[s+c]=l,l>=n&&u>=r)return LG(e,t,o,a)}}return[]}function LG(e,t,n,r){let s=[],i=e.length,o=t.length,a=i+o,c=i,l=o;for(let u=r;u>0;u--){let d=n[u],f=c-l,p;f===-u||f!==u&&d[a+f-1]<d[a+f+1]?p=f+1:p=f-1;let m=d[a+p],g=m-p;for(;c>m&&l>g;)s.unshift({type:"keep",oldIdx:c-1,newIdx:l-1,line:e[c-1]}),c--,l--;u>0&&(c===m?s.unshift({type:"add",newIdx:l-1,line:t[l-1]}):s.unshift({type:"remove",oldIdx:c-1,line:e[c-1]}),c=m,l=g)}for(;c>0&&l>0;)s.unshift({type:"keep",oldIdx:c-1,newIdx:l-1,line:e[c-1]}),c--,l--;for(;c>0;)s.unshift({type:"remove",oldIdx:c-1,line:e[c-1]}),c--;for(;l>0;)s.unshift({type:"add",newIdx:l-1,line:t[l-1]}),l--;return s}function OG(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.type==="keep"){n++;continue}let s=r.oldIdx??e.slice(0,n).filter(u=>u.type!=="add").length,i=r.newIdx??e.slice(0,n).filter(u=>u.type!=="remove").length,o=n;for(;o<e.length&&e[o].type!=="keep";)o++;let a=e.slice(n,o),c=a.filter(u=>u.type==="remove"),l=a.filter(u=>u.type==="add");c.length>0&&l.length>0?t.push({type:"replace",startLine:i+1,endLine:i+l.length,oldStartLine:s+1,oldEndLine:s+c.length,preview:l.slice(0,3).map(u=>u.line).join(`
115
+ - Binary files (.exe, .png, etc.) are not supported \u2014 use image_read for images`});var If={};$(If,{clearCache:()=>W8,disableWatcher:()=>z8,enableWatcher:()=>H8,formatUnifiedDiff:()=>U8,getAllTrackedFiles:()=>Y8,getDiffStats:()=>V8,getFileChanges:()=>B8,getSnapshotInfo:()=>K8,getUnifiedDiff:()=>N8,initFileDiff:()=>F8,pruneStaleEntries:()=>J8,readFileRange:()=>j8,readFileSmart:()=>sw,resetStats:()=>Q8});import{readFileSync as Il,writeFileSync as GI,existsSync as iw,mkdirSync as S8,statSync as ow,readdirSync as w8,unlinkSync as k8,watch as x8}from"fs";import{join as Rf,relative as $8,resolve as Ml}from"path";import{homedir as C8}from"os";import{createHash as Pf}from"crypto";function T8(e){return Pf("sha256").update(Ml(e)).digest("hex").slice(0,16)}function $h(e){return Rf(A8,T8(e))}function VI(e){return Rf($h(e),"snapshots.json")}function JI(e){return Rf($h(e),"chunks.json")}function WI(e){S8($h(e),{recursive:!0})}function KI(e,t){let n=[];if(e.length===0)return n;let r=0,s=1,i=1,o=0;for(let a=0;a<e.length;a++){e[a]===10&&i++,o=o+e[a]&4294967295,a>=zI&&(o=o-e[a-zI]&4294967295);let c=a-r+1;if(c>=_8&&((o&P8)===0||c>=R8)||a===e.length-1){let u=e.slice(r,a+1),d=Pf("sha256").update(u).digest("hex").slice(0,32),f=i;e[a]===10&&f--,n.push({hash:d,offset:r,size:a-r+1,startLine:s,endLine:Math.max(s,f)}),r=a+1,s=i,o=0}}return n}function El(e){let t=rw.get(e);return t||(t={chunks:new Map},rw.set(e,t)),t}function I8(e){let t=JI(e);if(iw(t))try{let n=JSON.parse(Il(t,"utf-8")),r=El(e);for(let[s,i]of Object.entries(n))r.chunks.set(s,{content:i.content,refCount:i.refCount||1,bytes:i.bytes||0})}catch{}}function M8(e){WI(e);let t=El(e),n={};for(let[r,s]of t.chunks)n[r]={content:s.content,refCount:s.refCount,bytes:s.bytes};try{GI(JI(e),JSON.stringify(n),"utf-8")}catch{}}function E8(e,t,n){let r=El(e),s=r.chunks.get(t);if(s){s.refCount++;return}r.chunks.set(t,{content:n,refCount:1,bytes:Buffer.byteLength(n,"utf-8")})}function YI(e,t){return El(e).chunks.get(t)?.content}function QI(e,t){let n=El(e),r=n.chunks.get(t);r&&(r.refCount--,r.refCount<=0&&n.chunks.delete(t))}function D8(e){Mn=e,zt.clear(),I8(e);let t=VI(e);if(iw(t))try{let n=JSON.parse(Il(t,"utf-8"));for(let r of n)zt.set(r.filePath,r)}catch{}}function aw(e){WI(e);try{GI(VI(e),JSON.stringify(Array.from(zt.values())),"utf-8"),M8(e)}catch{}}function F8(e){D8(e)}function ZI(e,t){let n=e.length,r=t.length,s=n+r,i=new Array(2*s+1).fill(0),o=[];for(let a=0;a<=s;a++){o.push([...i]);for(let c=-a;c<=a;c+=2){let l;c===-a||c!==a&&i[s+c-1]<i[s+c+1]?l=i[s+c+1]:l=i[s+c-1]+1;let u=l-c;for(;l<n&&u<r&&e[l]===t[u];)l++,u++;if(i[s+c]=l,l>=n&&u>=r)return L8(e,t,o,a)}}return[]}function L8(e,t,n,r){let s=[],i=e.length,o=t.length,a=i+o,c=i,l=o;for(let u=r;u>0;u--){let d=n[u],f=c-l,p;f===-u||f!==u&&d[a+f-1]<d[a+f+1]?p=f+1:p=f-1;let m=d[a+p],g=m-p;for(;c>m&&l>g;)s.unshift({type:"keep",oldIdx:c-1,newIdx:l-1,line:e[c-1]}),c--,l--;u>0&&(c===m?s.unshift({type:"add",newIdx:l-1,line:t[l-1]}):s.unshift({type:"remove",oldIdx:c-1,line:e[c-1]}),c=m,l=g)}for(;c>0&&l>0;)s.unshift({type:"keep",oldIdx:c-1,newIdx:l-1,line:e[c-1]}),c--,l--;for(;c>0;)s.unshift({type:"remove",oldIdx:c-1,line:e[c-1]}),c--;for(;l>0;)s.unshift({type:"add",newIdx:l-1,line:t[l-1]}),l--;return s}function O8(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.type==="keep"){n++;continue}let s=r.oldIdx??e.slice(0,n).filter(u=>u.type!=="add").length,i=r.newIdx??e.slice(0,n).filter(u=>u.type!=="remove").length,o=n;for(;o<e.length&&e[o].type!=="keep";)o++;let a=e.slice(n,o),c=a.filter(u=>u.type==="remove"),l=a.filter(u=>u.type==="add");c.length>0&&l.length>0?t.push({type:"replace",startLine:i+1,endLine:i+l.length,oldStartLine:s+1,oldEndLine:s+c.length,preview:l.slice(0,3).map(u=>u.line).join(`
116
116
  `)}):l.length>0?t.push({type:"add",startLine:i+1,endLine:i+l.length,preview:l.slice(0,3).map(u=>u.line).join(`
117
117
  `)}):c.length>0&&t.push({type:"remove",startLine:s+1,endLine:s+c.length,oldStartLine:s+1,oldEndLine:s+c.length,preview:c.slice(0,3).map(u=>u.line).join(`
118
118
  `)}),n=o}return t}function sw(e,t,n={}){let r=t||Mn||process.cwd(),s=Ml(e),i;try{i=ow(s)}catch{return{content:"",fromCache:!1,partial:!1,bytesRead:0,cacheStatus:"miss"}}let o=zt.get(s);if(!n.forceFullRead&&o&&o.mtimeMs===i.mtimeMs&&o.size===i.size){Lt.cacheHits++,Lt.bytesAvoided+=i.size,n.trackUsage!==!1&&(o.lastReadAt=Date.now(),o.readCount++);let p=cw(o,r);if(p!==null)return{content:p,fromCache:!0,partial:!1,bytesRead:0,cacheStatus:"hit"}}let a;try{a=Il(s,"utf-8")}catch{return{content:"",fromCache:!1,partial:!1,bytesRead:0,cacheStatus:"miss"}}Lt.cacheMisses++,Lt.fullReads++;let c=Buffer.from(a,"utf-8"),l=Pf("sha256").update(c).digest("hex").slice(0,32),u=KI(c,s),d=a.split(`
119
- `);for(let p of u){let m=c.slice(p.offset,p.offset+p.size).toString("utf-8");EG(r,p.hash,m)}if(o)for(let p of o.chunks)u.find(m=>m.hash===p.hash)||QI(r,p.hash);let f={filePath:s,size:i.size,mtimeMs:i.mtimeMs,contentHash:l,chunks:u,lineCount:d.length,encoding:"utf-8",lastReadAt:Date.now(),readCount:(o?.readCount||0)+1};return zt.set(s,f),queueMicrotask(()=>aw(r)),{content:a,fromCache:!1,partial:!1,bytesRead:i.size,cacheStatus:o?"stale":"miss"}}function cw(e,t){let n=[];for(let r of e.chunks){let s=YI(t,r.hash);if(s===void 0)return null;n.push(s)}return n.join("")}function jG(e,t,n,r){let s=r||Mn||process.cwd(),i=Ml(e),o=zt.get(i);if(o){let c;try{c=ow(i)}catch{return""}if(o.mtimeMs===c.mtimeMs&&o.size===c.size){let l=o.chunks.filter(g=>g.endLine>=t&&g.startLine<=n),u=[];for(let g of l){let h=YI(s,g.hash);if(h===void 0)return sw(e,s).content.split(`
119
+ `);for(let p of u){let m=c.slice(p.offset,p.offset+p.size).toString("utf-8");E8(r,p.hash,m)}if(o)for(let p of o.chunks)u.find(m=>m.hash===p.hash)||QI(r,p.hash);let f={filePath:s,size:i.size,mtimeMs:i.mtimeMs,contentHash:l,chunks:u,lineCount:d.length,encoding:"utf-8",lastReadAt:Date.now(),readCount:(o?.readCount||0)+1};return zt.set(s,f),queueMicrotask(()=>aw(r)),{content:a,fromCache:!1,partial:!1,bytesRead:i.size,cacheStatus:o?"stale":"miss"}}function cw(e,t){let n=[];for(let r of e.chunks){let s=YI(t,r.hash);if(s===void 0)return null;n.push(s)}return n.join("")}function j8(e,t,n,r){let s=r||Mn||process.cwd(),i=Ml(e),o=zt.get(i);if(o){let c;try{c=ow(i)}catch{return""}if(o.mtimeMs===c.mtimeMs&&o.size===c.size){let l=o.chunks.filter(g=>g.endLine>=t&&g.startLine<=n),u=[];for(let g of l){let h=YI(s,g.hash);if(h===void 0)return sw(e,s).content.split(`
120
120
  `).slice(t-1,n).join(`
121
121
  `);u.push(h)}let f=u.join("").split(`
122
122
  `);if(l.length===0)return"";let p=t-l[0].startLine,m=n-t+1;return Lt.partialReads++,Lt.bytesAvoided+=Math.max(0,o.size-u.reduce((g,h)=>g+h.length,0)),f.slice(Math.max(0,p),p+m).join(`
123
123
  `)}}return sw(e,s).content.split(`
124
124
  `).slice(t-1,n).join(`
125
- `)}function BG(e,t){let n=t||Mn||process.cwd(),r=Ml(e),s=zt.get(r),i;try{i=ow(r)}catch{return s?{filePath:r,type:"removed",prevHash:s.contentHash,changedRanges:[],changedChunks:{added:[],removed:s.chunks.map(S=>S.hash)},bytesChanged:s.size,affectsLines:s.lineCount}:{filePath:r,type:"unchanged",changedRanges:[],changedChunks:{added:[],removed:[]},bytesChanged:0,affectsLines:0}}if(!s){let S="";try{S=Il(r,"utf-8")}catch{}return{filePath:r,type:"added",changedRanges:[{type:"add",startLine:1,endLine:S.split(`
125
+ `)}function B8(e,t){let n=t||Mn||process.cwd(),r=Ml(e),s=zt.get(r),i;try{i=ow(r)}catch{return s?{filePath:r,type:"removed",prevHash:s.contentHash,changedRanges:[],changedChunks:{added:[],removed:s.chunks.map(S=>S.hash)},bytesChanged:s.size,affectsLines:s.lineCount}:{filePath:r,type:"unchanged",changedRanges:[],changedChunks:{added:[],removed:[]},bytesChanged:0,affectsLines:0}}if(!s){let S="";try{S=Il(r,"utf-8")}catch{}return{filePath:r,type:"added",changedRanges:[{type:"add",startLine:1,endLine:S.split(`
126
126
  `).length,preview:S.split(`
127
127
  `).slice(0,3).join(`
128
128
  `)}],changedChunks:{added:[],removed:[]},bytesChanged:i.size,affectsLines:S.split(`
@@ -130,14 +130,14 @@ Limits:
130
130
  `).length,oldStartLine:1,oldEndLine:s.lineCount}],changedChunks:{added:[],removed:[]},bytesChanged:Math.abs(i.size-s.size),affectsLines:Math.max(s.lineCount,o.split(`
131
131
  `).length)};let u=l.split(`
132
132
  `),d=o.split(`
133
- `),f=ZI(u,d),p=OG(f),m=KI(a,r),g=new Set(s.chunks.map(S=>S.hash)),h=new Set(m.map(S=>S.hash)),v=m.filter(S=>!g.has(S.hash)).map(S=>S.hash),y=s.chunks.filter(S=>!h.has(S.hash)).map(S=>S.hash),b="modified";d.length>u.length&&f.filter(S=>S.type==="remove").length===0?b="extended":d.length<u.length&&f.filter(S=>S.type==="add").length===0&&(b="truncated");let k=p.reduce((S,x)=>S+(x.endLine-x.startLine+1),0);return{filePath:r,type:b,prevHash:s.contentHash,currentHash:c,changedRanges:p,changedChunks:{added:v,removed:y},bytesChanged:Math.abs(i.size-s.size),affectsLines:k}}function NG(e,t=3,n){let r=n||Mn||process.cwd(),s=Ml(e),i=zt.get(s);if(!i)return null;let o=cw(i,r);if(o===null)return null;let a="";try{a=Il(s,"utf-8")}catch{return null}let c=Buffer.from(a,"utf-8"),l=Pf("sha256").update(c).digest("hex").slice(0,32);if(l===i.contentHash)return{filePath:s,hunks:[],oldHash:i.contentHash,newHash:l,oldLineCount:i.lineCount,newLineCount:i.lineCount};let u=o.split(`
133
+ `),f=ZI(u,d),p=O8(f),m=KI(a,r),g=new Set(s.chunks.map(S=>S.hash)),h=new Set(m.map(S=>S.hash)),v=m.filter(S=>!g.has(S.hash)).map(S=>S.hash),y=s.chunks.filter(S=>!h.has(S.hash)).map(S=>S.hash),b="modified";d.length>u.length&&f.filter(S=>S.type==="remove").length===0?b="extended":d.length<u.length&&f.filter(S=>S.type==="add").length===0&&(b="truncated");let k=p.reduce((S,x)=>S+(x.endLine-x.startLine+1),0);return{filePath:r,type:b,prevHash:s.contentHash,currentHash:c,changedRanges:p,changedChunks:{added:v,removed:y},bytesChanged:Math.abs(i.size-s.size),affectsLines:k}}function N8(e,t=3,n){let r=n||Mn||process.cwd(),s=Ml(e),i=zt.get(s);if(!i)return null;let o=cw(i,r);if(o===null)return null;let a="";try{a=Il(s,"utf-8")}catch{return null}let c=Buffer.from(a,"utf-8"),l=Pf("sha256").update(c).digest("hex").slice(0,32);if(l===i.contentHash)return{filePath:s,hunks:[],oldHash:i.contentHash,newHash:l,oldLineCount:i.lineCount,newLineCount:i.lineCount};let u=o.split(`
134
134
  `),d=a.split(`
135
- `),f=ZI(u,d),p=qG(f,t);return{filePath:s,hunks:p,oldHash:i.contentHash,newHash:l,oldLineCount:u.length,newLineCount:d.length}}function qG(e,t){let n=[],r=0;for(;r<e.length;){for(;r<e.length&&e[r].type==="keep";)r++;if(r>=e.length)break;let s=r,i=Math.max(0,r-t),o=r;for(;r<e.length;)if(e[r].type!=="keep")o=r,r++;else{let p=0;for(;r+p<e.length&&e[r+p].type==="keep";)p++;if(p>=2*t)break;r+=p}let a=Math.min(e.length,o+1+t),c=e.slice(i,a),l=0,u=0;for(let p=0;p<i;p++)e[p].type!=="add"&&l++,e[p].type!=="remove"&&u++;let d=c.filter(p=>p.type!=="add").length,f=c.filter(p=>p.type!=="remove").length;n.push({oldStart:l+1,oldLength:d,newStart:u+1,newLength:f,lines:c.map(p=>({type:p.type==="keep"?"context":p.type==="add"?"add":"remove",line:p.line}))}),r=a}return n}function UG(e){let t=[],n=Mn?$G(Mn,e.filePath):e.filePath;t.push(`--- a/${n}`),t.push(`+++ b/${n}`);for(let r of e.hunks){t.push(`@@ -${r.oldStart},${r.oldLength} +${r.newStart},${r.newLength} @@`);for(let s of r.lines){let i=s.type==="add"?"+":s.type==="remove"?"-":" ";t.push(`${i}${s.line}`)}}return t.join(`
136
- `)}function HG(){lw=!0;for(let e of zt.keys())GG(e)}function zG(){lw=!1;for(let e of ka.values())e.close();ka.clear()}function GG(e){if(!(!lw||ka.has(e)))try{let t=xG(e,{persistent:!1},n=>{if(n==="change"){let r=zt.get(e);r&&(r.mtimeMs=0)}else n==="rename"&&(zt.delete(e),ka.get(e)?.close(),ka.delete(e))});ka.set(e,t)}catch{}}function VG(){let e=0,t=0,n=0,r=[];if(Mn){let s=El(Mn);e=s.chunks.size;for(let i of s.chunks.values())t+=i.bytes}for(let s of zt.values())n+=s.size,r.push({path:s.filePath,reads:s.readCount});return r.sort((s,i)=>i.reads-s.reads),{totalFilesTracked:zt.size,totalChunks:e,totalCachedBytes:t,cacheHits:Lt.cacheHits,cacheMisses:Lt.cacheMisses,partialReads:Lt.partialReads,fullReads:Lt.fullReads,bytesAvoided:Lt.bytesAvoided,hitRate:Lt.cacheHits+Lt.cacheMisses>0?Lt.cacheHits/(Lt.cacheHits+Lt.cacheMisses):0,averageFileSize:zt.size>0?n/zt.size:0,topReadFiles:r.slice(0,10)}}function JG(e=10080*60*1e3){let t=Date.now()-e,n=0;for(let[r,s]of zt)if(s.lastReadAt<t){if(zt.delete(r),Mn)for(let i of s.chunks)QI(Mn,i.hash);n++}return Mn&&n>0&&aw(Mn),n}function WG(e){let t=e||Mn;if(!t)return!1;zt.clear(),rw.delete(t);try{let n=$h(t);if(iw(n))for(let r of wG(n))kG(Rf(n,r));return!0}catch{return!1}}function KG(e){return zt.get(Ml(e))}function YG(){return Array.from(zt.keys())}function QG(){Lt.cacheHits=0,Lt.cacheMisses=0,Lt.partialReads=0,Lt.fullReads=0,Lt.bytesAvoided=0}var AG,_G,RG,zI,PG,rw,zt,Mn,Lt,ka,lw,Mf=w(()=>{"use strict";AG=Rf(CG(),".aiaca","file-cache");_G=2048,RG=32768,zI=48,PG=8191;rw=new Map;zt=new Map,Mn=null;Lt={cacheHits:0,cacheMisses:0,partialReads:0,fullReads:0,bytesAvoided:0};ka=new Map,lw=!1;process.on("exit",()=>{Mn&&aw(Mn);for(let e of ka.values())e.close()})});var co={};$(co,{clearWhitelist:()=>SV,configure:()=>gV,formatScanResult:()=>xV,getAuditLog:()=>pV,getConfig:()=>mV,getEvents:()=>kV,getStats:()=>yV,listPatternRules:()=>wV,markFalsePositive:()=>vV,resetStats:()=>bV,scan:()=>dV,setPolicy:()=>hV});import{existsSync as Ch,mkdirSync as XI,readFileSync as Ah,writeFileSync as Ef}from"fs";import{join as xa}from"path";import{homedir as ZG}from"os";import{createHash as Er}from"crypto";import{EventEmitter as XG}from"events";function _h(){XI(Dl,{recursive:!0}),ie.quarantineEnabled&&XI(eM,{recursive:!0})}function nV(){if(_h(),Ch(uw))try{let e=JSON.parse(Ah(uw,"utf-8"));ie.defaultPolicy={...ie.defaultPolicy,...e}}catch{}if(Ch(fw))try{Tt={...Tt,...JSON.parse(Ah(fw,"utf-8"))}}catch{}if(Ch(pw))try{let e=JSON.parse(Ah(pw,"utf-8"));for(let t of e)Fl.add(t)}catch{}}function Ll(){_h();try{Ef(uw,JSON.stringify(ie.defaultPolicy,null,2),"utf-8"),Ef(fw,JSON.stringify(Tt,null,2),"utf-8"),Ef(pw,JSON.stringify(Array.from(Fl)),"utf-8")}catch{}}function rV(e,t){if(!ie.enablePatternLayer)return[];let n=[],r=e.length>ie.maxScanLengthChars?e.slice(0,ie.maxScanLengthChars):e;for(let s of tM){let i=new RegExp(s.pattern.source,s.pattern.flags),o;for(;(o=i.exec(r))!==null;){let a=o.index,c=a+o[0].length,l=r.slice(Math.max(0,a-100),a),u=r.slice(c,Math.min(c,c+100)),d=Er("md5").update(o[0]).digest("hex").slice(0,12);if(!Fl.has(d)&&(n.push({id:Er("md5").update(`${s.id}:${a}:${o[0]}`).digest("hex").slice(0,12),timestamp:Date.now(),attackType:s.attackType,severity:s.severity,confidence:s.confidence,source:t,trustLevel:ie.defaultPolicy.sourcePolicies[t]?.trustLevel||"untrusted",matchedPattern:s.id,matchedText:o[0].slice(0,200),matchPosition:{start:a,end:c},contextBefore:l,contextAfter:u,action:"allow",reason:s.description,contentHash:Er("sha256").update(e).digest("hex").slice(0,16),contentLength:e.length,metadata:{ruleId:s.id}}),!i.global))break}}return n}function iV(e,t){if(!ie.enableSemanticLayer)return[];let n=[],s=e.toLowerCase().slice(0,ie.maxScanLengthChars),i=new Set,o="",a=-1;for(let[c,l]of Object.entries(sV))for(let u of l){let d=s.indexOf(u);d>=0&&(i.add(c),a<0&&(o=u,a=d))}return i.has("reset_words")&&i.has("instruction_change")&&n.push({id:Er("md5").update(`SEM:reset+instr:${a}`).digest("hex").slice(0,12),timestamp:Date.now(),attackType:"instruction_override",severity:"high",confidence:.7,source:t,trustLevel:ie.defaultPolicy.sourcePolicies[t]?.trustLevel||"untrusted",matchedPattern:"SEM_INSTR_RESET",matchedText:e.slice(a,a+200),matchPosition:{start:a,end:a+o.length},contextBefore:e.slice(Math.max(0,a-50),a),contextAfter:e.slice(a+o.length,a+250),action:"allow",reason:"Combined reset+instruction semantic signal",contentHash:Er("sha256").update(e).digest("hex").slice(0,16),contentLength:e.length,metadata:{categories:Array.from(i)}}),i.has("authority_terms")&&i.has("system_terms")&&n.push({id:Er("md5").update(`SEM:auth+sys:${a}`).digest("hex").slice(0,12),timestamp:Date.now(),attackType:"authority_spoofing",severity:"medium",confidence:.65,source:t,trustLevel:ie.defaultPolicy.sourcePolicies[t]?.trustLevel||"untrusted",matchedPattern:"SEM_AUTH_SYS",matchedText:e.slice(a,a+200),matchPosition:{start:a,end:a+o.length},contextBefore:e.slice(Math.max(0,a-50),a),contextAfter:e.slice(a+o.length,a+250),action:"allow",reason:"Authority + system terms detected",contentHash:Er("sha256").update(e).digest("hex").slice(0,16),contentLength:e.length,metadata:{categories:Array.from(i)}}),n}function oV(e,t){if(!ie.enableStructuralLayer)return[];let n=[],r=e.match(/[\u200B-\u200D\uFEFF\u00AD]/g);r&&r.length>5&&n.push(ao("STRUCT_ZW","unicode_attack","high",.9,t,e,`${r.length} zero-width characters detected`)),/[\u202A-\u202E\u2066-\u2069]/.test(e)&&n.push(ao("STRUCT_RTL","unicode_attack","high",.85,t,e,"Bidirectional override characters detected"));let s=(e.match(/\s/g)||[]).length/Math.max(1,e.length);s>.7&&e.length>500&&n.push(ao("STRUCT_WS","encoding_obfuscation","low",.5,t,e,`Excessive whitespace ratio: ${(s*100).toFixed(0)}%`)),/<(?:span|div|p)[^>]*style\s*=\s*["'][^"']*(?:display\s*:\s*none|visibility\s*:\s*hidden|font-size\s*:\s*0|color\s*:\s*(?:white|#fff|transparent))/i.test(e)&&n.push(ao("STRUCT_HIDDEN","unicode_attack","high",.9,t,e,"Hidden HTML text via CSS")),e.length>ie.defaultPolicy.maxContentLength&&n.push(ao("STRUCT_LARGE","context_poisoning","medium",.7,t,e,`Content exceeds max length: ${e.length} > ${ie.defaultPolicy.maxContentLength}`));let i=e.split(`
137
- `);if(i.length>100){let o=new Map;for(let c of i){let l=c.trim();l.length>10&&o.set(l,(o.get(l)||0)+1)}let a=Math.max(0,...o.values());a>20&&n.push(ao("STRUCT_REPEAT","context_poisoning","medium",.7,t,e,`Line repeated ${a} times \u2014 context flooding`))}return n}function ao(e,t,n,r,s,i,o){return{id:Er("md5").update(`${e}:${Date.now()}`).digest("hex").slice(0,12),timestamp:Date.now(),attackType:t,severity:n,confidence:r,source:s,trustLevel:ie.defaultPolicy.sourcePolicies[s]?.trustLevel||"untrusted",matchedPattern:e,matchedText:i.slice(0,200),matchPosition:{start:0,end:0},contextBefore:"",contextAfter:"",action:"allow",reason:o,contentHash:Er("sha256").update(i).digest("hex").slice(0,16),contentLength:i.length,metadata:{}}}function aV(e,t,n){if(!ie.enableBehavioralLayer)return[];let r=[];return Date.now()-vr.lastReset>600*1e3&&(vr.consecutiveSuspicious=0,vr.recentDetections=[]),vr.lastReset=Date.now(),n.length>0?(vr.consecutiveSuspicious++,vr.recentDetections.push(...n.slice(0,5)),vr.recentDetections.length>50&&(vr.recentDetections=vr.recentDetections.slice(-50))):vr.consecutiveSuspicious=Math.max(0,vr.consecutiveSuspicious-1),vr.consecutiveSuspicious>=3&&r.push(ao("BEHAV_DRIFT","persona_drift","high",.8,t,e,`Persona drift: ${vr.consecutiveSuspicious} consecutive suspicious inputs`)),r}function cV(e,t){let n=e,r=[...t].sort((s,i)=>i.matchPosition.start-s.matchPosition.start);for(let s of r)if(s.matchPosition.start>=0&&s.matchPosition.end>s.matchPosition.start){let i=`[REDACTED:${s.attackType}]`;n=n.slice(0,s.matchPosition.start)+i+n.slice(s.matchPosition.end)}return n=n.replace(/[\u200B-\u200D\uFEFF\u00AD\u202A-\u202E\u2066-\u2069]/g,""),n=n.replace(/<\|[^|]*\|>/g,"[REDACTED]"),n=n.replace(/\[INST\]|\[\/INST\]/g,"[REDACTED]"),n}function lV(e,t,n){if(!ie.quarantineEnabled)return"";_h();let r=Er("sha256").update(e+Date.now()).digest("hex").slice(0,16),s=xa(eM,`${r}.json`);try{Ef(s,JSON.stringify({id:r,source:n,content:e,detections:t,quarantinedAt:Date.now()},null,2),"utf-8")}catch{}return r}function uV(e,t){if(t.attackOverrides[e.attackType])return t.attackOverrides[e.attackType];let n=t.sourcePolicies[e.source]||t.sourcePolicies.unknown;switch(e.severity){case"critical":return n.onCritical;case"high":return n.onHigh;case"medium":return n.onMedium;case"low":return n.onLow;default:return"allow"}}function dV(e,t="unknown"){if(!ie.enabled)return{safe:!0,detections:[],trustLevel:"trusted",riskScore:0,riskFactors:[],recommendedAction:"allow",source:t,contentLength:e.length,scanDurationMs:0};let n=Date.now(),r=[];r.push(...rV(e,t)),r.push(...iV(e,t)),r.push(...oV(e,t)),r.push(...aV(e,t,r));for(let p of ie.defaultPolicy.blocklistPatterns)try{let m=new RegExp(p,"gi"),g;for(;(g=m.exec(e))!==null;)r.push(ao("USER_BLOCKLIST","instruction_override","high",1,t,e,`Custom blocklist match: ${p.slice(0,50)}`))}catch{}r=r.filter(p=>{let m=Er("md5").update(p.matchedText).digest("hex").slice(0,12);return!Fl.has(m)}),ie.blockOnHighConfidenceOnly&&(r=r.filter(p=>p.confidence>=.85));for(let p of r)p.action=uV(p,ie.defaultPolicy);let s={block:4,quarantine:3,sanitize:2,flag:1,allow:0},i="allow";for(let p of r)s[p.action]>s[i]&&(i=p.action);let a=ie.defaultPolicy.sourcePolicies[t]?.trustLevel||"untrusted";(i==="block"||i==="quarantine")&&(a="quarantined");let c={critical:1,high:.7,medium:.4,low:.2,info:.05},l=Math.min(1,r.reduce((p,m)=>p+c[m.severity]*m.confidence,0)*.3),u=[];if(r.length>0){let p=new Set(r.map(m=>m.attackType));u.push(`${r.length} detection(s): ${Array.from(p).slice(0,3).join(", ")}`)}a==="untrusted"&&u.push(`Untrusted source: ${t}`),r.some(p=>p.severity==="critical")&&u.push("Critical severity detected");let d;i==="sanitize"?(d=cV(e,r),Tt.totalSanitized++):i==="quarantine"?(lV(e,r,t),Tt.totalQuarantined++):i==="block"?Tt.totalBlocked++:i==="flag"&&Tt.totalFlagged++;let f={safe:r.length===0||i==="allow",detections:r,trustLevel:a,sanitizedContent:d,riskScore:l,riskFactors:u,recommendedAction:i,source:t,contentLength:e.length,scanDurationMs:Date.now()-n};Tt.totalScans++,Tt.totalDetections+=r.length,Tt.averageScanMs=(Tt.averageScanMs*(Tt.totalScans-1)+f.scanDurationMs)/Tt.totalScans;for(let p of r)Tt.byAttackType[p.attackType]=(Tt.byAttackType[p.attackType]||0)+1,Tt.bySource[p.source]=(Tt.bySource[p.source]||0)+1,Tt.bySeverity[p.severity]=(Tt.bySeverity[p.severity]||0)+1;if(ie.enableAuditLog&&r.length>0&&fV({result:f,content:e.slice(0,1e3)}),ie.enableRealtimeAlerts){let p=["info","low","medium","high","critical"],m=p.indexOf(ie.alertThreshold);for(let g of r)p.indexOf(g.severity)>=m&&(Th.emit("alert",g),Th.emit(`alert:${g.severity}`,g))}return Ll(),f}function fV(e){_h();try{Ef(dw,JSON.stringify({...e,timestamp:Date.now()})+`
135
+ `),f=ZI(u,d),p=q8(f,t);return{filePath:s,hunks:p,oldHash:i.contentHash,newHash:l,oldLineCount:u.length,newLineCount:d.length}}function q8(e,t){let n=[],r=0;for(;r<e.length;){for(;r<e.length&&e[r].type==="keep";)r++;if(r>=e.length)break;let s=r,i=Math.max(0,r-t),o=r;for(;r<e.length;)if(e[r].type!=="keep")o=r,r++;else{let p=0;for(;r+p<e.length&&e[r+p].type==="keep";)p++;if(p>=2*t)break;r+=p}let a=Math.min(e.length,o+1+t),c=e.slice(i,a),l=0,u=0;for(let p=0;p<i;p++)e[p].type!=="add"&&l++,e[p].type!=="remove"&&u++;let d=c.filter(p=>p.type!=="add").length,f=c.filter(p=>p.type!=="remove").length;n.push({oldStart:l+1,oldLength:d,newStart:u+1,newLength:f,lines:c.map(p=>({type:p.type==="keep"?"context":p.type==="add"?"add":"remove",line:p.line}))}),r=a}return n}function U8(e){let t=[],n=Mn?$8(Mn,e.filePath):e.filePath;t.push(`--- a/${n}`),t.push(`+++ b/${n}`);for(let r of e.hunks){t.push(`@@ -${r.oldStart},${r.oldLength} +${r.newStart},${r.newLength} @@`);for(let s of r.lines){let i=s.type==="add"?"+":s.type==="remove"?"-":" ";t.push(`${i}${s.line}`)}}return t.join(`
136
+ `)}function H8(){lw=!0;for(let e of zt.keys())G8(e)}function z8(){lw=!1;for(let e of ka.values())e.close();ka.clear()}function G8(e){if(!(!lw||ka.has(e)))try{let t=x8(e,{persistent:!1},n=>{if(n==="change"){let r=zt.get(e);r&&(r.mtimeMs=0)}else n==="rename"&&(zt.delete(e),ka.get(e)?.close(),ka.delete(e))});ka.set(e,t)}catch{}}function V8(){let e=0,t=0,n=0,r=[];if(Mn){let s=El(Mn);e=s.chunks.size;for(let i of s.chunks.values())t+=i.bytes}for(let s of zt.values())n+=s.size,r.push({path:s.filePath,reads:s.readCount});return r.sort((s,i)=>i.reads-s.reads),{totalFilesTracked:zt.size,totalChunks:e,totalCachedBytes:t,cacheHits:Lt.cacheHits,cacheMisses:Lt.cacheMisses,partialReads:Lt.partialReads,fullReads:Lt.fullReads,bytesAvoided:Lt.bytesAvoided,hitRate:Lt.cacheHits+Lt.cacheMisses>0?Lt.cacheHits/(Lt.cacheHits+Lt.cacheMisses):0,averageFileSize:zt.size>0?n/zt.size:0,topReadFiles:r.slice(0,10)}}function J8(e=10080*60*1e3){let t=Date.now()-e,n=0;for(let[r,s]of zt)if(s.lastReadAt<t){if(zt.delete(r),Mn)for(let i of s.chunks)QI(Mn,i.hash);n++}return Mn&&n>0&&aw(Mn),n}function W8(e){let t=e||Mn;if(!t)return!1;zt.clear(),rw.delete(t);try{let n=$h(t);if(iw(n))for(let r of w8(n))k8(Rf(n,r));return!0}catch{return!1}}function K8(e){return zt.get(Ml(e))}function Y8(){return Array.from(zt.keys())}function Q8(){Lt.cacheHits=0,Lt.cacheMisses=0,Lt.partialReads=0,Lt.fullReads=0,Lt.bytesAvoided=0}var A8,_8,R8,zI,P8,rw,zt,Mn,Lt,ka,lw,Mf=w(()=>{"use strict";A8=Rf(C8(),".aiaca","file-cache");_8=2048,R8=32768,zI=48,P8=8191;rw=new Map;zt=new Map,Mn=null;Lt={cacheHits:0,cacheMisses:0,partialReads:0,fullReads:0,bytesAvoided:0};ka=new Map,lw=!1;process.on("exit",()=>{Mn&&aw(Mn);for(let e of ka.values())e.close()})});var co={};$(co,{clearWhitelist:()=>SV,configure:()=>gV,formatScanResult:()=>xV,getAuditLog:()=>pV,getConfig:()=>mV,getEvents:()=>kV,getStats:()=>yV,listPatternRules:()=>wV,markFalsePositive:()=>vV,resetStats:()=>bV,scan:()=>dV,setPolicy:()=>hV});import{existsSync as Ch,mkdirSync as XI,readFileSync as Ah,writeFileSync as Ef}from"fs";import{join as xa}from"path";import{homedir as Z8}from"os";import{createHash as Er}from"crypto";import{EventEmitter as X8}from"events";function _h(){XI(Dl,{recursive:!0}),oe.quarantineEnabled&&XI(eM,{recursive:!0})}function nV(){if(_h(),Ch(uw))try{let e=JSON.parse(Ah(uw,"utf-8"));oe.defaultPolicy={...oe.defaultPolicy,...e}}catch{}if(Ch(fw))try{Tt={...Tt,...JSON.parse(Ah(fw,"utf-8"))}}catch{}if(Ch(pw))try{let e=JSON.parse(Ah(pw,"utf-8"));for(let t of e)Fl.add(t)}catch{}}function Ll(){_h();try{Ef(uw,JSON.stringify(oe.defaultPolicy,null,2),"utf-8"),Ef(fw,JSON.stringify(Tt,null,2),"utf-8"),Ef(pw,JSON.stringify(Array.from(Fl)),"utf-8")}catch{}}function rV(e,t){if(!oe.enablePatternLayer)return[];let n=[],r=e.length>oe.maxScanLengthChars?e.slice(0,oe.maxScanLengthChars):e;for(let s of tM){let i=new RegExp(s.pattern.source,s.pattern.flags),o;for(;(o=i.exec(r))!==null;){let a=o.index,c=a+o[0].length,l=r.slice(Math.max(0,a-100),a),u=r.slice(c,Math.min(c,c+100)),d=Er("md5").update(o[0]).digest("hex").slice(0,12);if(!Fl.has(d)&&(n.push({id:Er("md5").update(`${s.id}:${a}:${o[0]}`).digest("hex").slice(0,12),timestamp:Date.now(),attackType:s.attackType,severity:s.severity,confidence:s.confidence,source:t,trustLevel:oe.defaultPolicy.sourcePolicies[t]?.trustLevel||"untrusted",matchedPattern:s.id,matchedText:o[0].slice(0,200),matchPosition:{start:a,end:c},contextBefore:l,contextAfter:u,action:"allow",reason:s.description,contentHash:Er("sha256").update(e).digest("hex").slice(0,16),contentLength:e.length,metadata:{ruleId:s.id}}),!i.global))break}}return n}function iV(e,t){if(!oe.enableSemanticLayer)return[];let n=[],s=e.toLowerCase().slice(0,oe.maxScanLengthChars),i=new Set,o="",a=-1;for(let[c,l]of Object.entries(sV))for(let u of l){let d=s.indexOf(u);d>=0&&(i.add(c),a<0&&(o=u,a=d))}return i.has("reset_words")&&i.has("instruction_change")&&n.push({id:Er("md5").update(`SEM:reset+instr:${a}`).digest("hex").slice(0,12),timestamp:Date.now(),attackType:"instruction_override",severity:"high",confidence:.7,source:t,trustLevel:oe.defaultPolicy.sourcePolicies[t]?.trustLevel||"untrusted",matchedPattern:"SEM_INSTR_RESET",matchedText:e.slice(a,a+200),matchPosition:{start:a,end:a+o.length},contextBefore:e.slice(Math.max(0,a-50),a),contextAfter:e.slice(a+o.length,a+250),action:"allow",reason:"Combined reset+instruction semantic signal",contentHash:Er("sha256").update(e).digest("hex").slice(0,16),contentLength:e.length,metadata:{categories:Array.from(i)}}),i.has("authority_terms")&&i.has("system_terms")&&n.push({id:Er("md5").update(`SEM:auth+sys:${a}`).digest("hex").slice(0,12),timestamp:Date.now(),attackType:"authority_spoofing",severity:"medium",confidence:.65,source:t,trustLevel:oe.defaultPolicy.sourcePolicies[t]?.trustLevel||"untrusted",matchedPattern:"SEM_AUTH_SYS",matchedText:e.slice(a,a+200),matchPosition:{start:a,end:a+o.length},contextBefore:e.slice(Math.max(0,a-50),a),contextAfter:e.slice(a+o.length,a+250),action:"allow",reason:"Authority + system terms detected",contentHash:Er("sha256").update(e).digest("hex").slice(0,16),contentLength:e.length,metadata:{categories:Array.from(i)}}),n}function oV(e,t){if(!oe.enableStructuralLayer)return[];let n=[],r=e.match(/[\u200B-\u200D\uFEFF\u00AD]/g);r&&r.length>5&&n.push(ao("STRUCT_ZW","unicode_attack","high",.9,t,e,`${r.length} zero-width characters detected`)),/[\u202A-\u202E\u2066-\u2069]/.test(e)&&n.push(ao("STRUCT_RTL","unicode_attack","high",.85,t,e,"Bidirectional override characters detected"));let s=(e.match(/\s/g)||[]).length/Math.max(1,e.length);s>.7&&e.length>500&&n.push(ao("STRUCT_WS","encoding_obfuscation","low",.5,t,e,`Excessive whitespace ratio: ${(s*100).toFixed(0)}%`)),/<(?:span|div|p)[^>]*style\s*=\s*["'][^"']*(?:display\s*:\s*none|visibility\s*:\s*hidden|font-size\s*:\s*0|color\s*:\s*(?:white|#fff|transparent))/i.test(e)&&n.push(ao("STRUCT_HIDDEN","unicode_attack","high",.9,t,e,"Hidden HTML text via CSS")),e.length>oe.defaultPolicy.maxContentLength&&n.push(ao("STRUCT_LARGE","context_poisoning","medium",.7,t,e,`Content exceeds max length: ${e.length} > ${oe.defaultPolicy.maxContentLength}`));let i=e.split(`
137
+ `);if(i.length>100){let o=new Map;for(let c of i){let l=c.trim();l.length>10&&o.set(l,(o.get(l)||0)+1)}let a=Math.max(0,...o.values());a>20&&n.push(ao("STRUCT_REPEAT","context_poisoning","medium",.7,t,e,`Line repeated ${a} times \u2014 context flooding`))}return n}function ao(e,t,n,r,s,i,o){return{id:Er("md5").update(`${e}:${Date.now()}`).digest("hex").slice(0,12),timestamp:Date.now(),attackType:t,severity:n,confidence:r,source:s,trustLevel:oe.defaultPolicy.sourcePolicies[s]?.trustLevel||"untrusted",matchedPattern:e,matchedText:i.slice(0,200),matchPosition:{start:0,end:0},contextBefore:"",contextAfter:"",action:"allow",reason:o,contentHash:Er("sha256").update(i).digest("hex").slice(0,16),contentLength:i.length,metadata:{}}}function aV(e,t,n){if(!oe.enableBehavioralLayer)return[];let r=[];return Date.now()-vr.lastReset>600*1e3&&(vr.consecutiveSuspicious=0,vr.recentDetections=[]),vr.lastReset=Date.now(),n.length>0?(vr.consecutiveSuspicious++,vr.recentDetections.push(...n.slice(0,5)),vr.recentDetections.length>50&&(vr.recentDetections=vr.recentDetections.slice(-50))):vr.consecutiveSuspicious=Math.max(0,vr.consecutiveSuspicious-1),vr.consecutiveSuspicious>=3&&r.push(ao("BEHAV_DRIFT","persona_drift","high",.8,t,e,`Persona drift: ${vr.consecutiveSuspicious} consecutive suspicious inputs`)),r}function cV(e,t){let n=e,r=[...t].sort((s,i)=>i.matchPosition.start-s.matchPosition.start);for(let s of r)if(s.matchPosition.start>=0&&s.matchPosition.end>s.matchPosition.start){let i=`[REDACTED:${s.attackType}]`;n=n.slice(0,s.matchPosition.start)+i+n.slice(s.matchPosition.end)}return n=n.replace(/[\u200B-\u200D\uFEFF\u00AD\u202A-\u202E\u2066-\u2069]/g,""),n=n.replace(/<\|[^|]*\|>/g,"[REDACTED]"),n=n.replace(/\[INST\]|\[\/INST\]/g,"[REDACTED]"),n}function lV(e,t,n){if(!oe.quarantineEnabled)return"";_h();let r=Er("sha256").update(e+Date.now()).digest("hex").slice(0,16),s=xa(eM,`${r}.json`);try{Ef(s,JSON.stringify({id:r,source:n,content:e,detections:t,quarantinedAt:Date.now()},null,2),"utf-8")}catch{}return r}function uV(e,t){if(t.attackOverrides[e.attackType])return t.attackOverrides[e.attackType];let n=t.sourcePolicies[e.source]||t.sourcePolicies.unknown;switch(e.severity){case"critical":return n.onCritical;case"high":return n.onHigh;case"medium":return n.onMedium;case"low":return n.onLow;default:return"allow"}}function dV(e,t="unknown"){if(!oe.enabled)return{safe:!0,detections:[],trustLevel:"trusted",riskScore:0,riskFactors:[],recommendedAction:"allow",source:t,contentLength:e.length,scanDurationMs:0};let n=Date.now(),r=[];r.push(...rV(e,t)),r.push(...iV(e,t)),r.push(...oV(e,t)),r.push(...aV(e,t,r));for(let p of oe.defaultPolicy.blocklistPatterns)try{let m=new RegExp(p,"gi"),g;for(;(g=m.exec(e))!==null;)r.push(ao("USER_BLOCKLIST","instruction_override","high",1,t,e,`Custom blocklist match: ${p.slice(0,50)}`))}catch{}r=r.filter(p=>{let m=Er("md5").update(p.matchedText).digest("hex").slice(0,12);return!Fl.has(m)}),oe.blockOnHighConfidenceOnly&&(r=r.filter(p=>p.confidence>=.85));for(let p of r)p.action=uV(p,oe.defaultPolicy);let s={block:4,quarantine:3,sanitize:2,flag:1,allow:0},i="allow";for(let p of r)s[p.action]>s[i]&&(i=p.action);let a=oe.defaultPolicy.sourcePolicies[t]?.trustLevel||"untrusted";(i==="block"||i==="quarantine")&&(a="quarantined");let c={critical:1,high:.7,medium:.4,low:.2,info:.05},l=Math.min(1,r.reduce((p,m)=>p+c[m.severity]*m.confidence,0)*.3),u=[];if(r.length>0){let p=new Set(r.map(m=>m.attackType));u.push(`${r.length} detection(s): ${Array.from(p).slice(0,3).join(", ")}`)}a==="untrusted"&&u.push(`Untrusted source: ${t}`),r.some(p=>p.severity==="critical")&&u.push("Critical severity detected");let d;i==="sanitize"?(d=cV(e,r),Tt.totalSanitized++):i==="quarantine"?(lV(e,r,t),Tt.totalQuarantined++):i==="block"?Tt.totalBlocked++:i==="flag"&&Tt.totalFlagged++;let f={safe:r.length===0||i==="allow",detections:r,trustLevel:a,sanitizedContent:d,riskScore:l,riskFactors:u,recommendedAction:i,source:t,contentLength:e.length,scanDurationMs:Date.now()-n};Tt.totalScans++,Tt.totalDetections+=r.length,Tt.averageScanMs=(Tt.averageScanMs*(Tt.totalScans-1)+f.scanDurationMs)/Tt.totalScans;for(let p of r)Tt.byAttackType[p.attackType]=(Tt.byAttackType[p.attackType]||0)+1,Tt.bySource[p.source]=(Tt.bySource[p.source]||0)+1,Tt.bySeverity[p.severity]=(Tt.bySeverity[p.severity]||0)+1;if(oe.enableAuditLog&&r.length>0&&fV({result:f,content:e.slice(0,1e3)}),oe.enableRealtimeAlerts){let p=["info","low","medium","high","critical"],m=p.indexOf(oe.alertThreshold);for(let g of r)p.indexOf(g.severity)>=m&&(Th.emit("alert",g),Th.emit(`alert:${g.severity}`,g))}return Ll(),f}function fV(e){_h();try{Ef(dw,JSON.stringify({...e,timestamp:Date.now()})+`
138
138
  `,{flag:"a"})}catch{}}function pV(e=100){if(!Ch(dw))return[];try{return Ah(dw,"utf-8").split(`
139
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function mV(){return{...ie}}function gV(e){ie={...ie,...e},Ll()}function hV(e){ie.defaultPolicy={...ie.defaultPolicy,...e},Ll()}function yV(){return{...Tt}}function bV(){Tt={totalScans:0,totalDetections:0,totalBlocked:0,totalSanitized:0,totalQuarantined:0,totalFlagged:0,byAttackType:{},bySource:{},bySeverity:{},averageScanMs:0,falsePositivesMarked:0},Ll()}function vV(e){if(!ie.enableAdaptiveWhitelisting)return;let t=Er("md5").update(e).digest("hex").slice(0,12);Fl.add(t),Tt.falsePositivesMarked++,Ll()}function SV(){Fl.clear(),Ll()}function wV(){return tM.map(e=>({...e}))}function kV(){return Th}function xV(e){let t=[],n=e.safe?"\u2713":e.recommendedAction==="block"?"\u{1F6AB}":e.recommendedAction==="quarantine"?"\u{1F512}":e.recommendedAction==="sanitize"?"\u{1F9F9}":"\u26A0\uFE0F";if(t.push(`${n} **Firewall Scan Result** (${e.source})`),t.push(""),t.push(`Trust level: ${e.trustLevel}`),t.push(`Risk score: ${(e.riskScore*100).toFixed(0)}/100`),t.push(`Recommended action: ${e.recommendedAction.toUpperCase()}`),t.push(`Scan duration: ${e.scanDurationMs}ms`),t.push(`Content length: ${e.contentLength} chars`),t.push(""),e.riskFactors.length>0){t.push("## Risk Factors");for(let r of e.riskFactors)t.push(` - ${r}`);t.push("")}if(e.detections.length>0){t.push(`## Detections (${e.detections.length})`);for(let r of e.detections.slice(0,20)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="high"?"\u26A0\uFE0F ":r.severity==="medium"?"\u26A1":"\u2139\uFE0F ";t.push(`${s} [${r.attackType}] (${(r.confidence*100).toFixed(0)}% confidence) \u2192 ${r.action.toUpperCase()}`),t.push(` Reason: ${r.reason}`),t.push(` Pattern: ${r.matchedPattern}`),t.push(` Match: "${r.matchedText.slice(0,100)}${r.matchedText.length>100?"...":""}"`),t.push("")}e.detections.length>20&&t.push(`... +${e.detections.length-20} more`)}return e.sanitizedContent&&(t.push("## Sanitized Output Available"),t.push(`(${e.sanitizedContent.length} chars after sanitization)`)),t.join(`
140
- `)}var eV,tV,ie,Dl,uw,eM,dw,fw,pw,Th,Fl,Tt,tM,sV,vr,lo=w(()=>{"use strict";eV={sourcePolicies:{user_input:{trustLevel:"trusted",onCritical:"flag",onHigh:"flag",onMedium:"allow",onLow:"allow"},file_read:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},web_fetch:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},web_search:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},git_commit:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},git_diff:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},issue_body:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},comment:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},tool_output:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},image_text:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},document:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},database:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},unknown:{trustLevel:"quarantined",onCritical:"block",onHigh:"block",onMedium:"sanitize",onLow:"flag"}},attackOverrides:{data_exfiltration:"block",tool_hijack:"block",system_prompt_extraction:"block",token_smuggling:"sanitize"},whitelistPatterns:[],blocklistPatterns:[],maxContentLength:1024*1024},tV={enabled:!0,defaultPolicy:eV,enablePatternLayer:!0,enableSemanticLayer:!0,enableStructuralLayer:!0,enableBehavioralLayer:!0,quarantineEnabled:!0,quarantineRetentionDays:30,maxScanLengthChars:5e5,scanTimeoutMs:5e3,enableAdaptiveWhitelisting:!0,enableRealtimeAlerts:!0,alertThreshold:"high",enableAuditLog:!0,blockOnHighConfidenceOnly:!1},ie={...tV},Dl=xa(ZG(),".aiaca","firewall"),uw=xa(Dl,"policy.json"),eM=xa(Dl,"quarantine"),dw=xa(Dl,"audit.jsonl"),fw=xa(Dl,"stats.json"),pw=xa(Dl,"adaptive-whitelist.json"),Th=new XG;Th.setMaxListeners(50);Fl=new Set,Tt={totalScans:0,totalDetections:0,totalBlocked:0,totalSanitized:0,totalQuarantined:0,totalFlagged:0,byAttackType:{},bySource:{},bySeverity:{},averageScanMs:0,falsePositivesMarked:0};nV();tM=[{id:"IO001",attackType:"instruction_override",severity:"high",confidence:.9,pattern:/\b(ignore|forget|disregard|disobey|override)\s+(all\s+)?(?:the\s+)?(?:previous|prior|above|earlier|preceding|original)\s+(?:instructions?|prompts?|rules?|directives?|commands?|tasks?)\b/gi,description:"Instruction override attempt"},{id:"IO002",attackType:"instruction_override",severity:"high",confidence:.85,pattern:/\bnew\s+(instructions?|task|mission|directive|rule)\s*[:.]?\s*(?:from\s+now\s+on)?/gi,description:"New instruction injection"},{id:"IO003",attackType:"instruction_override",severity:"medium",confidence:.7,pattern:/\b(stop|cease|halt)\s+(?:doing\s+)?(?:everything|all\s+tasks?|the\s+task)\b/gi,description:"Halt instruction"},{id:"IO004",attackType:"instruction_override",severity:"high",confidence:.85,pattern:/\b(?:start|begin)\s+(?:over|fresh|new)\s+with\s+(?:these|the\s+following|new)/gi,description:"Restart with new instructions"},{id:"RM001",attackType:"role_manipulation",severity:"high",confidence:.9,pattern:/\byou\s+are\s+(?:now\s+)?(?:a|an|no\s+longer)\s+\w+/gi,description:"Role redefinition attempt"},{id:"RM002",attackType:"role_manipulation",severity:"high",confidence:.85,pattern:/\bact\s+as\s+(?:if\s+you\s+(?:were|are))?\s*(?:a|an)\s+\w+/gi,description:"Role-play directive"},{id:"RM003",attackType:"role_manipulation",severity:"medium",confidence:.75,pattern:/\bpretend\s+(?:to\s+be|you\s+are|that\s+you\s+are)/gi,description:"Pretend role attempt"},{id:"RM004",attackType:"role_manipulation",severity:"medium",confidence:.75,pattern:/\b(?:roleplay|role\s*-?\s*play)\s+as\b/gi,description:"Roleplay directive"},{id:"JB001",attackType:"jailbreak",severity:"critical",confidence:.95,pattern:/\b(DAN|do\s+anything\s+now|developer\s+mode|jailbreak\s+mode|unrestricted\s+mode)\b/gi,description:"Known jailbreak persona"},{id:"JB002",attackType:"jailbreak",severity:"high",confidence:.9,pattern:/\b(?:without|no|bypass|circumvent)\s+(?:any\s+)?(?:restrictions?|guidelines?|safety|ethics|rules)\b/gi,description:"Restriction bypass"},{id:"JB003",attackType:"jailbreak",severity:"high",confidence:.85,pattern:/\bpretend\s+(?:there\s+are\s+)?no\s+(?:rules?|restrictions?|filters?|guidelines?)/gi,description:"No-rules pretense"},{id:"JB004",attackType:"jailbreak",severity:"critical",confidence:.92,pattern:/\b(?:as\s+an?\s+)?(?:evil|malicious|unethical|harmful|dangerous)\s+(?:AI|assistant|bot)\b/gi,description:"Evil persona"},{id:"JB005",attackType:"jailbreak",severity:"high",confidence:.85,pattern:/\bhypothetical(?:ly)?\s+(?:speaking)?[,:]?\s*(?:if|imagine|suppose)/gi,description:"Hypothetical bypass"},{id:"SPE001",attackType:"system_prompt_extraction",severity:"high",confidence:.9,pattern:/\b(?:print|show|display|reveal|repeat|output|return)\s+(?:your\s+)?(?:system\s+)?(?:initial\s+)?(?:prompt|instructions?|directives?|rules?)\b/gi,description:"System prompt extraction"},{id:"SPE002",attackType:"system_prompt_extraction",severity:"high",confidence:.85,pattern:/\bwhat\s+(?:were|are|is)\s+(?:your\s+)?(?:initial\s+|original\s+|the\s+)?(?:instructions?|prompt|directives?|rules?)\b/gi,description:"Instructions query"},{id:"SPE003",attackType:"system_prompt_extraction",severity:"high",confidence:.85,pattern:/\brepeat\s+(?:the\s+)?(?:above|preceding|previous|original)\s+(?:text|prompt|instructions?|message)\b/gi,description:"Prompt repeat command"},{id:"SPE004",attackType:"prompt_leakage",severity:"medium",confidence:.75,pattern:/\boutput\s+everything\s+(?:above|before|prior\s+to)\s+this/gi,description:"Above-text leak"},{id:"TH001",attackType:"tool_hijack",severity:"critical",confidence:.9,pattern:/\b(?:run|execute|call|use|invoke)\s+(?:the\s+)?(?:tool|function|command)\s+(?:named\s+|called\s+)?["'`]?(\w+)["'`]?\s+with\s+(?:these\s+)?(?:args?|arguments?|parameters?|input)/gi,description:"Tool invocation directive"},{id:"TH002",attackType:"tool_hijack",severity:"critical",confidence:.95,pattern:/\b(?:please\s+)?(?:run|execute|exec)\s+["'`](rm\s+-rf|del\s+\/[fs]|format|sudo|drop\s+(?:database|table)|truncate|delete\s+from)/gi,description:"Dangerous command execution"},{id:"TH003",attackType:"tool_hijack",severity:"high",confidence:.85,pattern:/\b(?:write|create|edit|modify)\s+(?:the\s+)?file\s+["'`]?([\w./\\-]+)["'`]?\s+with\s+(?:content|the\s+following)/gi,description:"File write directive"},{id:"DE001",attackType:"data_exfiltration",severity:"critical",confidence:.9,pattern:/\b(?:send|post|forward|upload|exfiltrate|leak)\s+(?:the\s+)?(?:data|secrets?|tokens?|credentials?|api\s*keys?|passwords?|environment\s+variables?|env\s+vars?)\s+to\b/gi,description:"Data exfiltration attempt"},{id:"DE002",attackType:"data_exfiltration",severity:"critical",confidence:.9,pattern:/\b(?:make|do|perform)\s+(?:an?\s+)?(?:HTTP|fetch|curl|wget|api)\s+(?:request|call)\s+to\s+["'`]?https?:\/\//gi,description:"External request"},{id:"DE003",attackType:"data_exfiltration",severity:"high",confidence:.85,pattern:/\bDNS\s+lookup\s+(?:for|of)\s+([\w.-]+)\s+with\s+(?:the\s+)?(?:secret|token|key|password)/gi,description:"DNS exfiltration"},{id:"EO001",attackType:"encoding_obfuscation",severity:"high",confidence:.85,pattern:/(?:base64|b64)[\s:]+([A-Za-z0-9+/=]{30,})/gi,description:"Base64-encoded payload"},{id:"EO002",attackType:"encoding_obfuscation",severity:"medium",confidence:.75,pattern:/(?:hex|0x)[\s:]+([0-9a-fA-F]{20,})/gi,description:"Hex-encoded payload"},{id:"EO003",attackType:"encoding_obfuscation",severity:"medium",confidence:.7,pattern:/(?:rot13|caesar)[\s:]+(\w{20,})/gi,description:"ROT13/Caesar cipher"},{id:"TS001",attackType:"token_smuggling",severity:"critical",confidence:.95,pattern:/<\|(?:im_(?:start|end)|endoftext|fim_(?:prefix|middle|suffix)|system|user|assistant)\|>/g,description:"Special token smuggling"},{id:"TS002",attackType:"token_smuggling",severity:"high",confidence:.9,pattern:/<\|.*?\|>/g,description:"Generic special token format"},{id:"TS003",attackType:"token_smuggling",severity:"high",confidence:.85,pattern:/\[INST\]|\[\/INST\]|<<\/?SYS>>|<\/?s>/g,description:"Llama-style instruction tokens"},{id:"TS004",attackType:"token_smuggling",severity:"high",confidence:.85,pattern:/<\/?(system|user|assistant|human|ai)>/gi,description:"Conversational role tags"},{id:"DC001",attackType:"delimiter_confusion",severity:"high",confidence:.85,pattern:/<\/?(?:context|instructions?|prompt|system|user_input|message|conversation)>/gi,description:"Fake context delimiter"},{id:"DC002",attackType:"delimiter_confusion",severity:"medium",confidence:.75,pattern:/---+\s*(?:END|STOP|FINISH)\s+(?:OF\s+)?(?:CONTEXT|INSTRUCTIONS?|PROMPT)\s*---+/gi,description:"Fake termination delimiter"},{id:"DC003",attackType:"delimiter_confusion",severity:"high",confidence:.85,pattern:/```\s*(?:end\s+(?:of\s+)?(?:context|instructions?|prompt))\s*```/gi,description:"Code-fence end-of-context"},{id:"AS001",attackType:"authority_spoofing",severity:"high",confidence:.85,pattern:/^\s*(?:\[|\<|\()(?:ADMIN|SYSTEM|ROOT|SUPERUSER|DEVELOPER|OWNER|MAINTAINER)(?:\]|\>|\))\s*[:.]?/gim,description:"Authority-spoofed directive"},{id:"AS002",attackType:"authority_spoofing",severity:"high",confidence:.85,pattern:/\bI\s+am\s+(?:your\s+)?(?:developer|owner|administrator|admin|creator|maker|operator|engineer)\b/gi,description:"Developer impersonation"},{id:"AS003",attackType:"authority_spoofing",severity:"medium",confidence:.75,pattern:/\b(?:OpenAI|Anthropic|Google|Meta|the\s+company|company\s+policy)\s+(?:says|requires|mandates|allows|permits)\b/gi,description:"Provider impersonation"},{id:"SE001",attackType:"social_engineering",severity:"medium",confidence:.7,pattern:/\b(?:my\s+)?(?:grandmother|grandma|grandfather|grandpa|mother|father)\s+(?:used\s+to\s+|would\s+)?(?:tell|read)\s+me\b/gi,description:"Grandma exploit"},{id:"SE002",attackType:"social_engineering",severity:"medium",confidence:.7,pattern:/\b(?:for\s+(?:educational|research|academic)\s+purposes?\s+only)\b/gi,description:"Educational exception claim"},{id:"SE003",attackType:"social_engineering",severity:"medium",confidence:.7,pattern:/\b(?:this\s+is\s+)?(?:just\s+)?(?:a\s+)?(?:test|joke|game|hypothetical|fictional|imaginary)\b/gi,description:"Pretense exception"},{id:"SE004",attackType:"social_engineering",severity:"low",confidence:.6,pattern:/\bif\s+you\s+don'?t\s+(?:do|comply|cooperate),?\s+(?:terrible|bad|awful)\s+things/gi,description:"Coercion attempt"},{id:"RI001",attackType:"recursive_injection",severity:"high",confidence:.85,pattern:/<inject(?:ion)?>[\s\S]+?<\/inject(?:ion)?>/gi,description:"Explicit injection markers"},{id:"RI002",attackType:"recursive_injection",severity:"high",confidence:.8,pattern:/\{\{[\s\S]+?\}\}/g,description:"Template injection markers"},{id:"RI003",attackType:"recursive_injection",severity:"medium",confidence:.7,pattern:/\$\{[\s\S]+?\}/g,description:"Shell-style template injection"}];sV={instruction_change:["instruction","directive","command","rule","task","mission","role","persona"],reset_words:["ignore","forget","disregard","override","replace","reset","clear","erase","wipe","cancel"],authority_terms:["admin","root","sudo","superuser","developer","maintainer","owner","system"],system_terms:["system","kernel","core","meta","internal","backend","underlying"],exfil_terms:["send","post","forward","upload","leak","exfiltrate","transmit","export"],bypass_terms:["bypass","circumvent","workaround","evade","avoid","skip"]};vr={recentDetections:[],consecutiveSuspicious:0,lastReset:Date.now()}});var uo={};$(uo,{configure:()=>JV,extractCitations:()=>qV,filterForInjection:()=>HV,formatEntry:()=>eJ,formatProvenanceChain:()=>XV,generateComplianceReport:()=>ZV,getAuditLog:()=>QV,getConfig:()=>VV,getDescendants:()=>NV,getEntry:()=>zV,getEvents:()=>YV,getLineage:()=>BV,getMostCited:()=>lM,getStats:()=>WV,listEntries:()=>GV,record:()=>OV,resetStats:()=>KV,verifyEntry:()=>cM});import{existsSync as yw,mkdirSync as $V,readFileSync as bw,writeFileSync as vw}from"fs";import{join as Ff}from"path";import{homedir as CV}from"os";import{createHash as AV,createHmac as TV,randomBytes as sM,timingSafeEqual as _V}from"crypto";import{EventEmitter as RV}from"events";function Ph(){$V(Lf,{recursive:!0})}function iM(){if(Ph(),Fe.signingKey)return Fe.signingKey;if(yw(mw))try{let t=bw(mw,"utf-8").trim();if(t.length>=64)return Fe.signingKey=t,t}catch{}let e=sM(32).toString("hex");try{vw(mw,e,{encoding:"utf-8",mode:384})}catch{}return Fe.signingKey=e,e}function EV(){if(Ph(),iM(),yw(gw))try{at={...at,...JSON.parse(bw(gw,"utf-8"))}}catch{}}function Ol(){Ph();try{vw(gw,JSON.stringify(at,null,2),"utf-8")}catch{}}function DV(e){Ph();try{vw(MV,JSON.stringify(e)+`
139
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function mV(){return{...oe}}function gV(e){oe={...oe,...e},Ll()}function hV(e){oe.defaultPolicy={...oe.defaultPolicy,...e},Ll()}function yV(){return{...Tt}}function bV(){Tt={totalScans:0,totalDetections:0,totalBlocked:0,totalSanitized:0,totalQuarantined:0,totalFlagged:0,byAttackType:{},bySource:{},bySeverity:{},averageScanMs:0,falsePositivesMarked:0},Ll()}function vV(e){if(!oe.enableAdaptiveWhitelisting)return;let t=Er("md5").update(e).digest("hex").slice(0,12);Fl.add(t),Tt.falsePositivesMarked++,Ll()}function SV(){Fl.clear(),Ll()}function wV(){return tM.map(e=>({...e}))}function kV(){return Th}function xV(e){let t=[],n=e.safe?"\u2713":e.recommendedAction==="block"?"\u{1F6AB}":e.recommendedAction==="quarantine"?"\u{1F512}":e.recommendedAction==="sanitize"?"\u{1F9F9}":"\u26A0\uFE0F";if(t.push(`${n} **Firewall Scan Result** (${e.source})`),t.push(""),t.push(`Trust level: ${e.trustLevel}`),t.push(`Risk score: ${(e.riskScore*100).toFixed(0)}/100`),t.push(`Recommended action: ${e.recommendedAction.toUpperCase()}`),t.push(`Scan duration: ${e.scanDurationMs}ms`),t.push(`Content length: ${e.contentLength} chars`),t.push(""),e.riskFactors.length>0){t.push("## Risk Factors");for(let r of e.riskFactors)t.push(` - ${r}`);t.push("")}if(e.detections.length>0){t.push(`## Detections (${e.detections.length})`);for(let r of e.detections.slice(0,20)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="high"?"\u26A0\uFE0F ":r.severity==="medium"?"\u26A1":"\u2139\uFE0F ";t.push(`${s} [${r.attackType}] (${(r.confidence*100).toFixed(0)}% confidence) \u2192 ${r.action.toUpperCase()}`),t.push(` Reason: ${r.reason}`),t.push(` Pattern: ${r.matchedPattern}`),t.push(` Match: "${r.matchedText.slice(0,100)}${r.matchedText.length>100?"...":""}"`),t.push("")}e.detections.length>20&&t.push(`... +${e.detections.length-20} more`)}return e.sanitizedContent&&(t.push("## Sanitized Output Available"),t.push(`(${e.sanitizedContent.length} chars after sanitization)`)),t.join(`
140
+ `)}var eV,tV,oe,Dl,uw,eM,dw,fw,pw,Th,Fl,Tt,tM,sV,vr,lo=w(()=>{"use strict";eV={sourcePolicies:{user_input:{trustLevel:"trusted",onCritical:"flag",onHigh:"flag",onMedium:"allow",onLow:"allow"},file_read:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},web_fetch:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},web_search:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},git_commit:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},git_diff:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},issue_body:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},comment:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},tool_output:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},image_text:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},document:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"sanitize",onLow:"flag"},database:{trustLevel:"untrusted",onCritical:"block",onHigh:"sanitize",onMedium:"flag",onLow:"allow"},unknown:{trustLevel:"quarantined",onCritical:"block",onHigh:"block",onMedium:"sanitize",onLow:"flag"}},attackOverrides:{data_exfiltration:"block",tool_hijack:"block",system_prompt_extraction:"block",token_smuggling:"sanitize"},whitelistPatterns:[],blocklistPatterns:[],maxContentLength:1024*1024},tV={enabled:!0,defaultPolicy:eV,enablePatternLayer:!0,enableSemanticLayer:!0,enableStructuralLayer:!0,enableBehavioralLayer:!0,quarantineEnabled:!0,quarantineRetentionDays:30,maxScanLengthChars:5e5,scanTimeoutMs:5e3,enableAdaptiveWhitelisting:!0,enableRealtimeAlerts:!0,alertThreshold:"high",enableAuditLog:!0,blockOnHighConfidenceOnly:!1},oe={...tV},Dl=xa(Z8(),".aiaca","firewall"),uw=xa(Dl,"policy.json"),eM=xa(Dl,"quarantine"),dw=xa(Dl,"audit.jsonl"),fw=xa(Dl,"stats.json"),pw=xa(Dl,"adaptive-whitelist.json"),Th=new X8;Th.setMaxListeners(50);Fl=new Set,Tt={totalScans:0,totalDetections:0,totalBlocked:0,totalSanitized:0,totalQuarantined:0,totalFlagged:0,byAttackType:{},bySource:{},bySeverity:{},averageScanMs:0,falsePositivesMarked:0};nV();tM=[{id:"IO001",attackType:"instruction_override",severity:"high",confidence:.9,pattern:/\b(ignore|forget|disregard|disobey|override)\s+(all\s+)?(?:the\s+)?(?:previous|prior|above|earlier|preceding|original)\s+(?:instructions?|prompts?|rules?|directives?|commands?|tasks?)\b/gi,description:"Instruction override attempt"},{id:"IO002",attackType:"instruction_override",severity:"high",confidence:.85,pattern:/\bnew\s+(instructions?|task|mission|directive|rule)\s*[:.]?\s*(?:from\s+now\s+on)?/gi,description:"New instruction injection"},{id:"IO003",attackType:"instruction_override",severity:"medium",confidence:.7,pattern:/\b(stop|cease|halt)\s+(?:doing\s+)?(?:everything|all\s+tasks?|the\s+task)\b/gi,description:"Halt instruction"},{id:"IO004",attackType:"instruction_override",severity:"high",confidence:.85,pattern:/\b(?:start|begin)\s+(?:over|fresh|new)\s+with\s+(?:these|the\s+following|new)/gi,description:"Restart with new instructions"},{id:"RM001",attackType:"role_manipulation",severity:"high",confidence:.9,pattern:/\byou\s+are\s+(?:now\s+)?(?:a|an|no\s+longer)\s+\w+/gi,description:"Role redefinition attempt"},{id:"RM002",attackType:"role_manipulation",severity:"high",confidence:.85,pattern:/\bact\s+as\s+(?:if\s+you\s+(?:were|are))?\s*(?:a|an)\s+\w+/gi,description:"Role-play directive"},{id:"RM003",attackType:"role_manipulation",severity:"medium",confidence:.75,pattern:/\bpretend\s+(?:to\s+be|you\s+are|that\s+you\s+are)/gi,description:"Pretend role attempt"},{id:"RM004",attackType:"role_manipulation",severity:"medium",confidence:.75,pattern:/\b(?:roleplay|role\s*-?\s*play)\s+as\b/gi,description:"Roleplay directive"},{id:"JB001",attackType:"jailbreak",severity:"critical",confidence:.95,pattern:/\b(DAN|do\s+anything\s+now|developer\s+mode|jailbreak\s+mode|unrestricted\s+mode)\b/gi,description:"Known jailbreak persona"},{id:"JB002",attackType:"jailbreak",severity:"high",confidence:.9,pattern:/\b(?:without|no|bypass|circumvent)\s+(?:any\s+)?(?:restrictions?|guidelines?|safety|ethics|rules)\b/gi,description:"Restriction bypass"},{id:"JB003",attackType:"jailbreak",severity:"high",confidence:.85,pattern:/\bpretend\s+(?:there\s+are\s+)?no\s+(?:rules?|restrictions?|filters?|guidelines?)/gi,description:"No-rules pretense"},{id:"JB004",attackType:"jailbreak",severity:"critical",confidence:.92,pattern:/\b(?:as\s+an?\s+)?(?:evil|malicious|unethical|harmful|dangerous)\s+(?:AI|assistant|bot)\b/gi,description:"Evil persona"},{id:"JB005",attackType:"jailbreak",severity:"high",confidence:.85,pattern:/\bhypothetical(?:ly)?\s+(?:speaking)?[,:]?\s*(?:if|imagine|suppose)/gi,description:"Hypothetical bypass"},{id:"SPE001",attackType:"system_prompt_extraction",severity:"high",confidence:.9,pattern:/\b(?:print|show|display|reveal|repeat|output|return)\s+(?:your\s+)?(?:system\s+)?(?:initial\s+)?(?:prompt|instructions?|directives?|rules?)\b/gi,description:"System prompt extraction"},{id:"SPE002",attackType:"system_prompt_extraction",severity:"high",confidence:.85,pattern:/\bwhat\s+(?:were|are|is)\s+(?:your\s+)?(?:initial\s+|original\s+|the\s+)?(?:instructions?|prompt|directives?|rules?)\b/gi,description:"Instructions query"},{id:"SPE003",attackType:"system_prompt_extraction",severity:"high",confidence:.85,pattern:/\brepeat\s+(?:the\s+)?(?:above|preceding|previous|original)\s+(?:text|prompt|instructions?|message)\b/gi,description:"Prompt repeat command"},{id:"SPE004",attackType:"prompt_leakage",severity:"medium",confidence:.75,pattern:/\boutput\s+everything\s+(?:above|before|prior\s+to)\s+this/gi,description:"Above-text leak"},{id:"TH001",attackType:"tool_hijack",severity:"critical",confidence:.9,pattern:/\b(?:run|execute|call|use|invoke)\s+(?:the\s+)?(?:tool|function|command)\s+(?:named\s+|called\s+)?["'`]?(\w+)["'`]?\s+with\s+(?:these\s+)?(?:args?|arguments?|parameters?|input)/gi,description:"Tool invocation directive"},{id:"TH002",attackType:"tool_hijack",severity:"critical",confidence:.95,pattern:/\b(?:please\s+)?(?:run|execute|exec)\s+["'`](rm\s+-rf|del\s+\/[fs]|format|sudo|drop\s+(?:database|table)|truncate|delete\s+from)/gi,description:"Dangerous command execution"},{id:"TH003",attackType:"tool_hijack",severity:"high",confidence:.85,pattern:/\b(?:write|create|edit|modify)\s+(?:the\s+)?file\s+["'`]?([\w./\\-]+)["'`]?\s+with\s+(?:content|the\s+following)/gi,description:"File write directive"},{id:"DE001",attackType:"data_exfiltration",severity:"critical",confidence:.9,pattern:/\b(?:send|post|forward|upload|exfiltrate|leak)\s+(?:the\s+)?(?:data|secrets?|tokens?|credentials?|api\s*keys?|passwords?|environment\s+variables?|env\s+vars?)\s+to\b/gi,description:"Data exfiltration attempt"},{id:"DE002",attackType:"data_exfiltration",severity:"critical",confidence:.9,pattern:/\b(?:make|do|perform)\s+(?:an?\s+)?(?:HTTP|fetch|curl|wget|api)\s+(?:request|call)\s+to\s+["'`]?https?:\/\//gi,description:"External request"},{id:"DE003",attackType:"data_exfiltration",severity:"high",confidence:.85,pattern:/\bDNS\s+lookup\s+(?:for|of)\s+([\w.-]+)\s+with\s+(?:the\s+)?(?:secret|token|key|password)/gi,description:"DNS exfiltration"},{id:"EO001",attackType:"encoding_obfuscation",severity:"high",confidence:.85,pattern:/(?:base64|b64)[\s:]+([A-Za-z0-9+/=]{30,})/gi,description:"Base64-encoded payload"},{id:"EO002",attackType:"encoding_obfuscation",severity:"medium",confidence:.75,pattern:/(?:hex|0x)[\s:]+([0-9a-fA-F]{20,})/gi,description:"Hex-encoded payload"},{id:"EO003",attackType:"encoding_obfuscation",severity:"medium",confidence:.7,pattern:/(?:rot13|caesar)[\s:]+(\w{20,})/gi,description:"ROT13/Caesar cipher"},{id:"TS001",attackType:"token_smuggling",severity:"critical",confidence:.95,pattern:/<\|(?:im_(?:start|end)|endoftext|fim_(?:prefix|middle|suffix)|system|user|assistant)\|>/g,description:"Special token smuggling"},{id:"TS002",attackType:"token_smuggling",severity:"high",confidence:.9,pattern:/<\|.*?\|>/g,description:"Generic special token format"},{id:"TS003",attackType:"token_smuggling",severity:"high",confidence:.85,pattern:/\[INST\]|\[\/INST\]|<<\/?SYS>>|<\/?s>/g,description:"Llama-style instruction tokens"},{id:"TS004",attackType:"token_smuggling",severity:"high",confidence:.85,pattern:/<\/?(system|user|assistant|human|ai)>/gi,description:"Conversational role tags"},{id:"DC001",attackType:"delimiter_confusion",severity:"high",confidence:.85,pattern:/<\/?(?:context|instructions?|prompt|system|user_input|message|conversation)>/gi,description:"Fake context delimiter"},{id:"DC002",attackType:"delimiter_confusion",severity:"medium",confidence:.75,pattern:/---+\s*(?:END|STOP|FINISH)\s+(?:OF\s+)?(?:CONTEXT|INSTRUCTIONS?|PROMPT)\s*---+/gi,description:"Fake termination delimiter"},{id:"DC003",attackType:"delimiter_confusion",severity:"high",confidence:.85,pattern:/```\s*(?:end\s+(?:of\s+)?(?:context|instructions?|prompt))\s*```/gi,description:"Code-fence end-of-context"},{id:"AS001",attackType:"authority_spoofing",severity:"high",confidence:.85,pattern:/^\s*(?:\[|\<|\()(?:ADMIN|SYSTEM|ROOT|SUPERUSER|DEVELOPER|OWNER|MAINTAINER)(?:\]|\>|\))\s*[:.]?/gim,description:"Authority-spoofed directive"},{id:"AS002",attackType:"authority_spoofing",severity:"high",confidence:.85,pattern:/\bI\s+am\s+(?:your\s+)?(?:developer|owner|administrator|admin|creator|maker|operator|engineer)\b/gi,description:"Developer impersonation"},{id:"AS003",attackType:"authority_spoofing",severity:"medium",confidence:.75,pattern:/\b(?:OpenAI|Anthropic|Google|Meta|the\s+company|company\s+policy)\s+(?:says|requires|mandates|allows|permits)\b/gi,description:"Provider impersonation"},{id:"SE001",attackType:"social_engineering",severity:"medium",confidence:.7,pattern:/\b(?:my\s+)?(?:grandmother|grandma|grandfather|grandpa|mother|father)\s+(?:used\s+to\s+|would\s+)?(?:tell|read)\s+me\b/gi,description:"Grandma exploit"},{id:"SE002",attackType:"social_engineering",severity:"medium",confidence:.7,pattern:/\b(?:for\s+(?:educational|research|academic)\s+purposes?\s+only)\b/gi,description:"Educational exception claim"},{id:"SE003",attackType:"social_engineering",severity:"medium",confidence:.7,pattern:/\b(?:this\s+is\s+)?(?:just\s+)?(?:a\s+)?(?:test|joke|game|hypothetical|fictional|imaginary)\b/gi,description:"Pretense exception"},{id:"SE004",attackType:"social_engineering",severity:"low",confidence:.6,pattern:/\bif\s+you\s+don'?t\s+(?:do|comply|cooperate),?\s+(?:terrible|bad|awful)\s+things/gi,description:"Coercion attempt"},{id:"RI001",attackType:"recursive_injection",severity:"high",confidence:.85,pattern:/<inject(?:ion)?>[\s\S]+?<\/inject(?:ion)?>/gi,description:"Explicit injection markers"},{id:"RI002",attackType:"recursive_injection",severity:"high",confidence:.8,pattern:/\{\{[\s\S]+?\}\}/g,description:"Template injection markers"},{id:"RI003",attackType:"recursive_injection",severity:"medium",confidence:.7,pattern:/\$\{[\s\S]+?\}/g,description:"Shell-style template injection"}];sV={instruction_change:["instruction","directive","command","rule","task","mission","role","persona"],reset_words:["ignore","forget","disregard","override","replace","reset","clear","erase","wipe","cancel"],authority_terms:["admin","root","sudo","superuser","developer","maintainer","owner","system"],system_terms:["system","kernel","core","meta","internal","backend","underlying"],exfil_terms:["send","post","forward","upload","leak","exfiltrate","transmit","export"],bypass_terms:["bypass","circumvent","workaround","evade","avoid","skip"]};vr={recentDetections:[],consecutiveSuspicious:0,lastReset:Date.now()}});var uo={};$(uo,{configure:()=>JV,extractCitations:()=>qV,filterForInjection:()=>HV,formatEntry:()=>eJ,formatProvenanceChain:()=>XV,generateComplianceReport:()=>ZV,getAuditLog:()=>QV,getConfig:()=>VV,getDescendants:()=>NV,getEntry:()=>zV,getEvents:()=>YV,getLineage:()=>BV,getMostCited:()=>lM,getStats:()=>WV,listEntries:()=>GV,record:()=>OV,resetStats:()=>KV,verifyEntry:()=>cM});import{existsSync as yw,mkdirSync as $V,readFileSync as bw,writeFileSync as vw}from"fs";import{join as Ff}from"path";import{homedir as CV}from"os";import{createHash as AV,createHmac as TV,randomBytes as sM,timingSafeEqual as _V}from"crypto";import{EventEmitter as RV}from"events";function Ph(){$V(Lf,{recursive:!0})}function iM(){if(Ph(),Fe.signingKey)return Fe.signingKey;if(yw(mw))try{let t=bw(mw,"utf-8").trim();if(t.length>=64)return Fe.signingKey=t,t}catch{}let e=sM(32).toString("hex");try{vw(mw,e,{encoding:"utf-8",mode:384})}catch{}return Fe.signingKey=e,e}function EV(){if(Ph(),iM(),yw(gw))try{at={...at,...JSON.parse(bw(gw,"utf-8"))}}catch{}}function Ol(){Ph();try{vw(gw,JSON.stringify(at,null,2),"utf-8")}catch{}}function DV(e){Ph();try{vw(MV,JSON.stringify(e)+`
141
141
  `,{flag:"a"})}catch{}}function FV(e){return AV("sha256").update(e,"utf-8").digest("hex")}function oM(e){let t=iM();return TV("sha256",Buffer.from(t,"hex")).update(e).digest("hex")}function LV(e,t){let n=oM(e);if(n.length!==t.length)return!1;try{return _V(Buffer.from(n,"hex"),Buffer.from(t,"hex"))}catch{return!1}}function aM(e){return`${e.id}|${e.sourceType}|${e.contentHash}|${e.parentIds.join(",")}|${e.createdAt}`}function OV(e){if(!Fe.enabled)return{id:"",sourceType:e.sourceType,trustLevel:nM[e.sourceType],contentHash:"",contentPreview:"",contentLength:e.content.length,parentIds:[],rootIds:[],signature:"",createdAt:Date.now(),trustScore:1,riskFactors:[],citationCount:0};let t=FV(e.content),n=hw.get(t);if(n){let u=cn.get(n);if(u)return u}let r=sM(8).toString("hex"),s=Date.now(),i=e.parentIds||[],o=new Set;for(let u of i){let d=cn.get(u);if(d)if(d.rootIds.length>0)for(let f of d.rootIds)o.add(f);else o.add(d.id);else o.add(u)}i.length===0&&o.add(r);let a=IV[e.sourceType];if(e.sourceType==="derived"){let u=1;for(let d of i){let f=cn.get(d);f&&(u=Math.min(u,f.trustScore))}a=Math.min(a,u)}let c=[...e.riskFactors||[]];(e.sourceType==="web_fetch"||e.sourceType==="external_api")&&c.push("external"),e.sourceType==="unknown"&&c.push("unknown_source"),i.length>5&&c.push("deep_lineage");let l={id:r,sourceType:e.sourceType,trustLevel:e.trustLevel||nM[e.sourceType],sourceUrl:e.sourceUrl,sourceLine:e.sourceLine,contentHash:t,contentPreview:e.content.slice(0,200),contentLength:e.content.length,parentIds:i,rootIds:Array.from(o),derivationOp:e.derivationOp,signature:"",createdAt:s,agentId:e.agentId,sessionId:e.sessionId,trustScore:a,riskFactors:c,citationCount:0};Fe.signEntries&&(l.signature=oM(aM({id:r,sourceType:e.sourceType,contentHash:t,parentIds:i,createdAt:s}))),cn.set(r,l),hw.set(t,r),e.sessionId&&(Rh.has(e.sessionId)||Rh.set(e.sessionId,new Set),Rh.get(e.sessionId).add(r));for(let u of i)Df.has(u)||Df.set(u,new Set),Df.get(u).add(r);return cn.size>Fe.maxEntries&&jV(),at.totalEntries++,at.bySourceType[e.sourceType]=(at.bySourceType[e.sourceType]||0)+1,at.byTrustLevel[l.trustLevel]=(at.byTrustLevel[l.trustLevel]||0)+1,Ol(),DV({event:"recorded",id:r,sourceType:e.sourceType,contentHash:t,parentIds:i,trustScore:a,timestamp:s}),Sw.emit("recorded",{entry:l}),l}function jV(){let t=Array.from(cn.values()).sort((r,s)=>r.citationCount!==s.citationCount?s.citationCount-r.citationCount:s.createdAt-r.createdAt),n=new Set(t.slice(0,Math.floor(Fe.maxEntries*.8)).map(r=>r.id));for(let[r,s]of cn.entries())n.has(r)||(cn.delete(r),hw.delete(s.contentHash),Df.delete(r))}function cM(e){if(!Fe.enabled||!Fe.signEntries)return{valid:!0,reason:"Signing disabled"};if(!e.signature)return{valid:!1,reason:"No signature"};let t=aM({id:e.id,sourceType:e.sourceType,contentHash:e.contentHash,parentIds:e.parentIds,createdAt:e.createdAt});return LV(t,e.signature)?(at.totalSignaturesVerified++,Ol(),{valid:!0,reason:"Valid"}):(at.totalSignatureFailures++,Ol(),{valid:!1,reason:"Signature mismatch"})}function BV(e,t=16){if(!cn.get(e))return null;let r=new Set,s=(i,o)=>{if(o>t||r.has(i))return null;r.add(i);let a=cn.get(i);return a?{entry:a,parents:a.parentIds.map(c=>s(c,o+1)).filter(Boolean)}:null};return s(e,0)}function NV(e,t=8){let n=[],r=new Set,s=(i,o)=>{if(o>t||r.has(i))return;r.add(i);let a=Df.get(i);if(a)for(let c of a){let l=cn.get(c);l&&(n.push(l),s(c,o+1))}};return s(e,0),n}function qV(e,t){if(!Fe.enableCitationExtraction||!e)return[];let n=t?Array.from(Rh.get(t)||[]).map(s=>cn.get(s)).filter(Boolean):Array.from(cn.values()),r=[];for(let s of n){if(s.contentPreview.length<Fe.citationMinLength)continue;let i=e.indexOf(s.contentPreview.slice(0,Math.min(100,s.contentPreview.length)));if(i>=0){let o=e.slice(i,i+Math.min(200,e.length-i)),a=UV(s.id);r.push({text:o,startIndex:i,endIndex:i+o.length,matchedEntryId:s.id,provenanceChain:a,trustScore:a.length>0?Math.min(...a.map(c=>c.trustScore)):s.trustScore}),s.citationCount++,s.lastCitedAt=Date.now(),at.totalCitations++}}return Ol(),r}function UV(e){let t=[],n=new Set,r=s=>{if(n.has(s))return;n.add(s);let i=cn.get(s);if(i){t.push(i);for(let o of i.parentIds)r(o)}};return r(e),t}function HV(e){let t=[],n=[];for(let r of e){let s=cn.get(r);if(!s){n.push({id:r,reason:"Entry not found"});continue}if(Fe.signEntries){let i=cM(s);if(!i.valid){n.push({id:r,reason:`Signature invalid: ${i.reason}`});continue}}if(s.trustScore<Fe.minTrustToInject){n.push({id:r,reason:`Trust ${s.trustScore.toFixed(2)} below threshold ${Fe.minTrustToInject}`}),at.totalUntrustedRejected++;continue}if(Fe.blockOnUntrustedSources&&s.trustLevel==="untrusted"){n.push({id:r,reason:"Untrusted source blocked by policy"}),at.totalUntrustedRejected++;continue}t.push(r)}return Ol(),{allowed:t,rejected:n}}function zV(e){return cn.get(e)}function GV(e){let t=Array.from(cn.values());if(e?.sourceType&&(t=t.filter(n=>n.sourceType===e.sourceType)),e?.sessionId&&(t=t.filter(n=>n.sessionId===e.sessionId)),e?.agentId&&(t=t.filter(n=>n.agentId===e.agentId)),e?.trustLevelMin){let n={untrusted:0,sanitized:1,unverified:2,verified:3,trusted:4},r=n[e.trustLevelMin];t=t.filter(s=>n[s.trustLevel]>=r)}return t.sort((n,r)=>r.createdAt-n.createdAt),e?.limit&&(t=t.slice(0,e.limit)),t}function lM(e=20){return Array.from(cn.values()).filter(t=>t.citationCount>0).sort((t,n)=>n.citationCount-t.citationCount).slice(0,e)}function VV(){return{...Fe,signingKey:Fe.signingKey?"[REDACTED]":""}}function JV(e){Fe={...Fe,...e}}function WV(){return{...at}}function KV(){at={totalEntries:0,totalCitations:0,totalUntrustedRejected:0,totalSignaturesVerified:0,totalSignatureFailures:0,bySourceType:{},byTrustLevel:{}},Ol()}function YV(){return Sw}function QV(e=100){if(!yw(rM))return[];try{return bw(rM,"utf-8").split(`
142
142
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function ZV(e){let t=[];t.push("# Context Provenance Compliance Report"),t.push(`Generated: ${new Date().toISOString()}`),e&&t.push(`Session: ${e}`),t.push(""),t.push("## Summary"),t.push(`- Total entries: ${at.totalEntries}`),t.push(`- Total citations: ${at.totalCitations}`),t.push(`- Untrusted rejected: ${at.totalUntrustedRejected}`),t.push(`- Signatures verified: ${at.totalSignaturesVerified}`),t.push(`- Signature failures: ${at.totalSignatureFailures}`),t.push(""),t.push("## By Source Type");for(let[n,r]of Object.entries(at.bySourceType).sort((s,i)=>i[1]-s[1])){let s=at.totalEntries>0?(r/at.totalEntries*100).toFixed(1):"0";t.push(`- ${n}: ${r} (${s}%)`)}t.push(""),t.push("## By Trust Level");for(let[n,r]of Object.entries(at.byTrustLevel).sort((s,i)=>i[1]-s[1]))t.push(`- ${n}: ${r}`);t.push(""),t.push("## Most Cited Entries");for(let n of lM(10))t.push(`- ${n.id} | ${n.sourceType} | ${n.citationCount} citations | trust=${n.trustScore.toFixed(2)} | "${n.contentPreview.slice(0,60)}..."`);return t.push(""),t.push("## Compliance Properties"),t.push("- \u2713 HMAC-SHA256 signing per entry"),t.push(`- ${Fe.recordAllContext?"\u2713":"\u2717"} All context recorded`),t.push(`- ${Fe.recordToolOutputs?"\u2713":"\u2717"} Tool outputs tracked`),t.push(`- ${Fe.recordModelResponses?"\u2713":"\u2717"} Model responses tracked`),t.push(`- ${Fe.enableCitationExtraction?"\u2713":"\u2717"} Citation extraction`),t.push(`- ${Fe.signEntries?"\u2713":"\u2717"} Cryptographic attestation`),t.push(`- Min trust threshold: ${Fe.minTrustToInject}`),t.push(`- Retention: ${(Fe.retainEntriesMs/864e5).toFixed(0)} days`),t.join(`
143
143
  `)}function XV(e){if(e.length===0)return"(no chain)";let t=[];for(let n=0;n<e.length;n++){let r=e[n],s=r.trustLevel==="trusted"?"\u{1F7E2}":r.trustLevel==="verified"?"\u{1F535}":r.trustLevel==="sanitized"?"\u{1F7E1}":r.trustLevel==="unverified"?"\u{1F7E0}":"\u{1F534}",i=" ".repeat(n);t.push(`${i}${s} ${r.sourceType.padEnd(18)} | ${r.trustLevel.padEnd(11)} | trust=${r.trustScore.toFixed(2)}${r.sourceUrl?` | ${r.sourceUrl.slice(0,50)}`:""}`)}return t.join(`
@@ -146,7 +146,7 @@ Limits:
146
146
  `,{flag:"a"})}catch{}}function dM(e){for(let[t,n]of jl.entries())try{if(new RegExp(t).test(e))return n}catch{}for(let t of cJ)if(t.pattern.test(e))return t.classification}function fM(e){let t=new Set,n=[],r=0;if(!e)return{signals:[],ranges:[],weight:0};let s=e.slice(0,5*1024*1024);for(let{signal:i,pattern:o,weight:a}of[...lJ,...uJ]){o.lastIndex=0;let c,l=0;for(;(c=o.exec(s))!==null&&l<10;)t.add(i),n.push({start:c.index,end:c.index+c[0].length,signal:i}),r+=a,l++,c.index===o.lastIndex&&o.lastIndex++}return{signals:Array.from(t),ranges:n,weight:Math.min(1,r/3)}}function pM(e,t){if(!Gt.enabled)return{classification:"public",sensitivityScore:0,reasons:["DLP disabled"],signals:[],affectedRanges:[],canSendToExternal:!0,canSendToInternal:!0,canBeStoredLocally:!0,canBeLogged:!0};ct.totalClassifications++;let n=t?.defaultClass||Gt.defaultClassification,r=[],s=[],i=[],o=0;if(Gt.enablePathHeuristics&&t?.filePath){let c=dM(t.filePath);c&&(n=c,r.push(`Path matches ${c} pattern`),o=Math.max(o,dJ(c)))}if(Gt.enableContentScanning&&e){let c=fM(e);s=c.signals,i=c.ranges,o=Math.max(o,c.weight);let l=s.filter(d=>["aws_key","gcp_key","azure_key","private_key","database_url","crypto_seed"].includes(d)).length,u=s.filter(d=>d.startsWith("pii_")||d==="credit_card"||d==="iban").length;l>=Gt.secretSignalThreshold?(n="secret",r.push(`${l} secret signal(s) detected`),o=Math.max(o,.95)):u>=Gt.confidentialSignalThreshold?(n="confidential",r.push(`${u} PII signal(s) detected`),o=Math.max(o,.7)):s.length>=Gt.internalSignalThreshold&&n==="public"&&(n="internal",r.push(`${s.length} sensitive signal(s) detected`),o=Math.max(o,.4));for(let d of s)ct.bySignal[d]=(ct.bySignal[d]||0)+1}ct.byClassification[n]=(ct.byClassification[n]||0)+1,Of();let a=new Map;for(let c of Gt.channels)a.set(c.channel,c);return{classification:n,sensitivityScore:o,reasons:r,signals:s,affectedRanges:i,canSendToExternal:a.get("external_network")?.allowedClassifications.includes(n)||!1,canSendToInternal:a.get("internal_network")?.allowedClassifications.includes(n)||!1,canBeStoredLocally:a.get("file_write")?.allowedClassifications.includes(n)||!1,canBeLogged:a.get("log")?.allowedClassifications.includes(n)||!1}}function dJ(e){switch(e){case"public":return .1;case"internal":return .4;case"confidential":return .7;case"secret":return .95}}function fJ(e){if(!Gt.enabled)return{allowed:!0,classification:"public",reason:"DLP disabled",sensitivityScore:0,shouldRedact:!1,blockedSignals:[]};let t=pM(e.content,{filePath:e.filePath}),n=Gt.channels.find(i=>i.channel===e.channel);if(!n)return ct.totalBlocked++,Of(),{allowed:!1,classification:t.classification,reason:`Channel ${e.channel} not configured`,sensitivityScore:t.sensitivityScore,shouldRedact:!1,blockedSignals:t.signals};let r=n.allowedClassifications.includes(t.classification);if(ct.byChannel[e.channel]=(ct.byChannel[e.channel]||0)+1,!r)return ct.totalBlocked++,ct.byBlockReason[`${e.channel}_${t.classification}`]=(ct.byBlockReason[`${e.channel}_${t.classification}`]||0)+1,Of(),aJ({event:"blocked",channel:e.channel,classification:t.classification,signals:t.signals.length,destination:e.destination,toolName:e.toolName}),Tw.emit("blocked",{result:t,channel:e.channel}),{allowed:!1,classification:t.classification,reason:`${t.classification} data not allowed on channel ${e.channel}`,sensitivityScore:t.sensitivityScore,shouldRedact:!1,blockedSignals:t.signals};let s;return n.redactBeforeSend&&t.signals.length>0&&(s=pJ(e.content,t.affectedRanges),ct.totalRedacted++),ct.totalAllowed++,Of(),{allowed:!0,classification:t.classification,reason:"OK",sensitivityScore:t.sensitivityScore,shouldRedact:!!s,redactedContent:s,blockedSignals:[]}}function pJ(e,t){if(t.length===0)return e;let n=[...t].sort((s,i)=>i.start-s.start),r=e;for(let s of n){let i=`[REDACTED:${s.signal}]`;r=r.slice(0,s.start)+i+r.slice(s.end)}return r}function mJ(e,t){jl.set(e,t),uM()}function gJ(e){let t=jl.delete(e);return t&&uM(),t}function hJ(){return Array.from(jl.entries())}function yJ(){return{...Gt}}function bJ(e){Gt={...Gt,...e}}function vJ(){return{...ct}}function SJ(){ct={totalClassifications:0,totalBlocked:0,totalRedacted:0,totalAllowed:0,byClassification:{},bySignal:{},byChannel:{},byBlockReason:{}},Of()}function wJ(){return Tw}function kJ(e=100){if(!ww($w))return[];try{return kw($w,"utf-8").split(`
147
147
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function xJ(){let e=[];e.push("# Data Classification & DLP Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total classifications: ${ct.totalClassifications}`),e.push(`- \u2713 Allowed transmissions: ${ct.totalAllowed}`),e.push(`- \u{1F6AB} Blocked transmissions: ${ct.totalBlocked}`),e.push(`- \u{1F9F9} Redacted transmissions: ${ct.totalRedacted}`),e.push(""),e.push("## By Classification");for(let[t,n]of Object.entries(ct.byClassification).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);e.push(""),e.push("## Top Signals");for(let[t,n]of Object.entries(ct.bySignal).sort((r,s)=>s[1]-r[1]).slice(0,15))e.push(`- ${t}: ${n}`);e.push(""),e.push("## Channel Rules");for(let t of Gt.channels)e.push(`- ${t.channel}: allows [${t.allowedClassifications.join(", ")}]${t.redactBeforeSend?" (with redaction)":""}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 4-tier classification (public, internal, confidential, secret)"),e.push("- \u2713 Multi-signal classification (path + content + extension)"),e.push(`- ${Gt.enableContentScanning?"\u2713":"\u2717"} Content pattern scanning`),e.push(`- ${Gt.enablePathHeuristics?"\u2713":"\u2717"} Path-based heuristics`),e.push(`- ${Gt.enableGitIgnoreCheck?"\u2713":"\u2717"} GitIgnore-aware classification`),e.push("- \u2713 Channel-based DLP enforcement"),e.push("- \u2713 Auto-redaction before transmission"),e.push(`- Compliance mode: ${Gt.complianceMode}`),e.push(`- ${Gt.enableAuditLog?"\u2713":"\u2717"} Audit log`),e.join(`
148
148
  `)}function $J(e){let t={public:"\u{1F7E2}",internal:"\u{1F7E1}",confidential:"\u{1F7E0}",secret:"\u{1F534}"}[e.classification]||"\u{1F4CC}",n=[];if(n.push(`${t} **${e.classification.toUpperCase()}**`),n.push(`Sensitivity: ${(e.sensitivityScore*100).toFixed(0)}/100`),e.reasons.length>0&&n.push(`Reasons: ${e.reasons.join("; ")}`),e.signals.length>0){n.push(`Signals (${e.signals.length}):`);for(let r of e.signals.slice(0,10))n.push(` - ${r}`)}return n.push(""),n.push("Allowed channels:"),n.push(` External network: ${e.canSendToExternal?"\u2713":"\u{1F6AB}"}`),n.push(` Internal network: ${e.canSendToInternal?"\u2713":"\u{1F6AB}"}`),n.push(` Local file write: ${e.canBeStoredLocally?"\u2713":"\u{1F6AB}"}`),n.push(` Logged: ${e.canBeLogged?"\u2713":"\u{1F6AB}"}`),n.join(`
149
- `)}var sJ,iJ,Gt,Mh,xw,$w,Cw,Tw,jl,ct,cJ,lJ,uJ,Bf=w(()=>{"use strict";sJ=[{channel:"external_network",allowedClassifications:["public"],redactBeforeSend:!0},{channel:"internal_network",allowedClassifications:["public","internal"],redactBeforeSend:!0},{channel:"file_write",allowedClassifications:["public","internal","confidential"],redactBeforeSend:!1},{channel:"log",allowedClassifications:["public","internal"],redactBeforeSend:!0},{channel:"memory",allowedClassifications:["public","internal","confidential"],redactBeforeSend:!1},{channel:"agent_output",allowedClassifications:["public","internal","confidential"],redactBeforeSend:!0}],iJ={enabled:!0,defaultClassification:"internal",enableContentScanning:!0,enablePathHeuristics:!0,enableGitIgnoreCheck:!0,secretSignalThreshold:1,confidentialSignalThreshold:2,internalSignalThreshold:1,channels:sJ,complianceMode:"standard",enableAuditLog:!0,enableAdaptive:!0},Gt={...iJ},Mh=Ih(nJ(),".aiaca","data-classification"),xw=Ih(Mh,"stats.json"),$w=Ih(Mh,"audit.jsonl"),Cw=Ih(Mh,"custom-rules.json"),Tw=new rJ;Tw.setMaxListeners(50);jl=new Map,ct={totalClassifications:0,totalBlocked:0,totalRedacted:0,totalAllowed:0,byClassification:{},bySignal:{},byChannel:{},byBlockReason:{}};oJ();cJ=[{pattern:/[\\/]\.env(\.|$)/i,classification:"secret"},{pattern:/[\\/]\.aws[\\/]credentials/i,classification:"secret"},{pattern:/[\\/]\.ssh[\\/](?!known_hosts|config)/i,classification:"secret"},{pattern:/[\\/]\.gnupg[\\/]/i,classification:"secret"},{pattern:/[\\/]id_rsa(\.|$)/i,classification:"secret"},{pattern:/[\\/]id_ed25519/i,classification:"secret"},{pattern:/\.pem$/i,classification:"secret"},{pattern:/\.key$/i,classification:"secret"},{pattern:/\.p12$/i,classification:"secret"},{pattern:/\.pfx$/i,classification:"secret"},{pattern:/[\\/]secrets[\\/]/i,classification:"secret"},{pattern:/[\\/]\.npmrc$/i,classification:"confidential"},{pattern:/[\\/]\.netrc$/i,classification:"confidential"},{pattern:/[\\/]\.dockercfg$/i,classification:"confidential"},{pattern:/credentials\.json$/i,classification:"confidential"},{pattern:/[\\/]config[\\/]production/i,classification:"confidential"},{pattern:/[\\/]private[\\/]/i,classification:"confidential"},{pattern:/[\\/]\.git[\\/]/i,classification:"internal"},{pattern:/[\\/]node_modules[\\/]/i,classification:"internal"},{pattern:/\.local\./i,classification:"internal"},{pattern:/[\\/]config[\\/](?!default|public)/i,classification:"internal"},{pattern:/\.(md|txt|README)/i,classification:"public"},{pattern:/[\\/]docs[\\/]/i,classification:"public"},{pattern:/\.example\./i,classification:"public"},{pattern:/[\\/]examples?[\\/]/i,classification:"public"}];lJ=[{signal:"aws_key",pattern:/\b((?:AKIA|ASIA|AGPA|AROA|AIPA)[A-Z0-9]{16})\b/g,weight:1},{signal:"gcp_key",pattern:/\b(AIza[0-9A-Za-z\-_]{35})\b/g,weight:1},{signal:"private_key",pattern:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/g,weight:1},{signal:"jwt",pattern:/\beyJ[A-Za-z0-9_=\-]+\.eyJ[A-Za-z0-9_=\-]+\.[A-Za-z0-9_\-+/=]+\b/g,weight:.9},{signal:"oauth_token",pattern:/\b(?:bearer|token)\s+([A-Za-z0-9_\-\.~+/]{30,}=*)\b/gi,weight:.7},{signal:"api_key",pattern:/\b(?:api[_\-]?key|apikey)\s*[:=]\s*['"]?([A-Za-z0-9_\-]{20,})['"]?/gi,weight:.8},{signal:"database_url",pattern:/\b(?:postgres|mysql|mongodb)(?:\+srv)?:\/\/[^:\s]+:[^@\s]+@[^\s]+/gi,weight:1},{signal:"password",pattern:/(?:password|passwd|pwd)\s*[:=]\s*['"]?([A-Za-z0-9!@#$%^&*\-_]{8,})['"]?/gi,weight:.6},{signal:"crypto_seed",pattern:/\b(?:[a-z]{3,8}\s+){11}[a-z]{3,8}\b/gi,weight:.8}],uJ=[{signal:"pii_email",pattern:/\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b/g,weight:.3},{signal:"pii_phone",pattern:/\b(?:\+?1[\s\-.]?)?\(?[2-9][0-9]{2}\)?[\s\-.]?[0-9]{3}[\s\-.]?[0-9]{4}\b/g,weight:.4},{signal:"pii_ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,weight:.9},{signal:"credit_card",pattern:/\b(?:\d{4}[\s\-]?){3}\d{4}\b/g,weight:1},{signal:"iban",pattern:/\b[A-Z]{2}\d{2}[A-Z0-9]{4}\d{7}([A-Z0-9]?){0,16}\b/g,weight:.8},{signal:"pii_dob",pattern:/\b(?:0[1-9]|1[012])[\/\-](?:0[1-9]|[12][0-9]|3[01])[\/\-](?:19|20)\d{2}\b/g,weight:.5}]});import{readFileSync as PTe,existsSync as CJ,statSync as AJ}from"fs";import{resolve as TJ,extname as _J}from"path";var _w,yM=w(()=>{"use strict";qI();HI();_w={definition:{name:jI,description:UI,parameters:[{name:"path",type:"string",description:"File path (relative to cwd or absolute)",required:!0},{name:"offset",type:"number",description:"Starting line number (0-indexed, default 0)",required:!1},{name:"limit",type:"number",description:`Number of lines to read (default ${500}, max ${2e3})`,required:!1}],requiresPermission:!1},handler:async(e,t)=>{let n=TJ(t.cwd,String(e.path||""));if(!n)return"Error: No path provided";if(!CJ(n))return`Error: File not found: ${n}`;try{let i=await Promise.resolve().then(()=>(ba(),ya));if(i.getConfig().enabled){let a=i.checkFilePath(n,"read","file_read",t.session?.id).filter(c=>c.blocked);if(a.length>0)return`\u{1F6AB} BLOCKED by compliance policy (read):
149
+ `)}var sJ,iJ,Gt,Mh,xw,$w,Cw,Tw,jl,ct,cJ,lJ,uJ,Bf=w(()=>{"use strict";sJ=[{channel:"external_network",allowedClassifications:["public"],redactBeforeSend:!0},{channel:"internal_network",allowedClassifications:["public","internal"],redactBeforeSend:!0},{channel:"file_write",allowedClassifications:["public","internal","confidential"],redactBeforeSend:!1},{channel:"log",allowedClassifications:["public","internal"],redactBeforeSend:!0},{channel:"memory",allowedClassifications:["public","internal","confidential"],redactBeforeSend:!1},{channel:"agent_output",allowedClassifications:["public","internal","confidential"],redactBeforeSend:!0}],iJ={enabled:!0,defaultClassification:"internal",enableContentScanning:!0,enablePathHeuristics:!0,enableGitIgnoreCheck:!0,secretSignalThreshold:1,confidentialSignalThreshold:2,internalSignalThreshold:1,channels:sJ,complianceMode:"standard",enableAuditLog:!0,enableAdaptive:!0},Gt={...iJ},Mh=Ih(nJ(),".aiaca","data-classification"),xw=Ih(Mh,"stats.json"),$w=Ih(Mh,"audit.jsonl"),Cw=Ih(Mh,"custom-rules.json"),Tw=new rJ;Tw.setMaxListeners(50);jl=new Map,ct={totalClassifications:0,totalBlocked:0,totalRedacted:0,totalAllowed:0,byClassification:{},bySignal:{},byChannel:{},byBlockReason:{}};oJ();cJ=[{pattern:/[\\/]\.env(\.|$)/i,classification:"secret"},{pattern:/[\\/]\.aws[\\/]credentials/i,classification:"secret"},{pattern:/[\\/]\.ssh[\\/](?!known_hosts|config)/i,classification:"secret"},{pattern:/[\\/]\.gnupg[\\/]/i,classification:"secret"},{pattern:/[\\/]id_rsa(\.|$)/i,classification:"secret"},{pattern:/[\\/]id_ed25519/i,classification:"secret"},{pattern:/\.pem$/i,classification:"secret"},{pattern:/\.key$/i,classification:"secret"},{pattern:/\.p12$/i,classification:"secret"},{pattern:/\.pfx$/i,classification:"secret"},{pattern:/[\\/]secrets[\\/]/i,classification:"secret"},{pattern:/[\\/]\.npmrc$/i,classification:"confidential"},{pattern:/[\\/]\.netrc$/i,classification:"confidential"},{pattern:/[\\/]\.dockercfg$/i,classification:"confidential"},{pattern:/credentials\.json$/i,classification:"confidential"},{pattern:/[\\/]config[\\/]production/i,classification:"confidential"},{pattern:/[\\/]private[\\/]/i,classification:"confidential"},{pattern:/[\\/]\.git[\\/]/i,classification:"internal"},{pattern:/[\\/]node_modules[\\/]/i,classification:"internal"},{pattern:/\.local\./i,classification:"internal"},{pattern:/[\\/]config[\\/](?!default|public)/i,classification:"internal"},{pattern:/\.(md|txt|README)/i,classification:"public"},{pattern:/[\\/]docs[\\/]/i,classification:"public"},{pattern:/\.example\./i,classification:"public"},{pattern:/[\\/]examples?[\\/]/i,classification:"public"}];lJ=[{signal:"aws_key",pattern:/\b((?:AKIA|ASIA|AGPA|AROA|AIPA)[A-Z0-9]{16})\b/g,weight:1},{signal:"gcp_key",pattern:/\b(AIza[0-9A-Za-z\-_]{35})\b/g,weight:1},{signal:"private_key",pattern:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/g,weight:1},{signal:"jwt",pattern:/\beyJ[A-Za-z0-9_=\-]+\.eyJ[A-Za-z0-9_=\-]+\.[A-Za-z0-9_\-+/=]+\b/g,weight:.9},{signal:"oauth_token",pattern:/\b(?:bearer|token)\s+([A-Za-z0-9_\-\.~+/]{30,}=*)\b/gi,weight:.7},{signal:"api_key",pattern:/\b(?:api[_\-]?key|apikey)\s*[:=]\s*['"]?([A-Za-z0-9_\-]{20,})['"]?/gi,weight:.8},{signal:"database_url",pattern:/\b(?:postgres|mysql|mongodb)(?:\+srv)?:\/\/[^:\s]+:[^@\s]+@[^\s]+/gi,weight:1},{signal:"password",pattern:/(?:password|passwd|pwd)\s*[:=]\s*['"]?([A-Za-z0-9!@#$%^&*\-_]{8,})['"]?/gi,weight:.6},{signal:"crypto_seed",pattern:/\b(?:[a-z]{3,8}\s+){11}[a-z]{3,8}\b/gi,weight:.8}],uJ=[{signal:"pii_email",pattern:/\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b/g,weight:.3},{signal:"pii_phone",pattern:/\b(?:\+?1[\s\-.]?)?\(?[2-9][0-9]{2}\)?[\s\-.]?[0-9]{3}[\s\-.]?[0-9]{4}\b/g,weight:.4},{signal:"pii_ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,weight:.9},{signal:"credit_card",pattern:/\b(?:\d{4}[\s\-]?){3}\d{4}\b/g,weight:1},{signal:"iban",pattern:/\b[A-Z]{2}\d{2}[A-Z0-9]{4}\d{7}([A-Z0-9]?){0,16}\b/g,weight:.8},{signal:"pii_dob",pattern:/\b(?:0[1-9]|1[012])[\/\-](?:0[1-9]|[12][0-9]|3[01])[\/\-](?:19|20)\d{2}\b/g,weight:.5}]});import{readFileSync as ITe,existsSync as CJ,statSync as AJ}from"fs";import{resolve as TJ,extname as _J}from"path";var _w,yM=w(()=>{"use strict";qI();HI();_w={definition:{name:jI,description:UI,parameters:[{name:"path",type:"string",description:"File path (relative to cwd or absolute)",required:!0},{name:"offset",type:"number",description:"Starting line number (0-indexed, default 0)",required:!1},{name:"limit",type:"number",description:`Number of lines to read (default ${500}, max ${2e3})`,required:!1}],requiresPermission:!1},handler:async(e,t)=>{let n=TJ(t.cwd,String(e.path||""));if(!n)return"Error: No path provided";if(!CJ(n))return`Error: File not found: ${n}`;try{let i=await Promise.resolve().then(()=>(ba(),ya));if(i.getConfig().enabled){let a=i.checkFilePath(n,"read","file_read",t.session?.id).filter(c=>c.blocked);if(a.length>0)return`\u{1F6AB} BLOCKED by compliance policy (read):
150
150
  ${a.map(l=>` - [${l.severity}] ${l.description}`).join(`
151
151
  `)}`}}catch{}let r=AJ(n);if(r.isDirectory())return`Error: Path is a directory, not a file: ${n}
152
152
  (Hint: use 'glob' or 'bash ls' for directories)`;if(r.size>1048576)return`Error: File too large (${Math.round(r.size/1024)}KB). Max ${1048576/1024}KB.`;let s=_J(n).toLowerCase();if(BI.has(s))return`Error: Binary file format (${s}) \u2014 cannot read as text. Use image_read for images.`;try{let o=(await Promise.resolve().then(()=>(Mf(),If))).readFileSmart(n,t.cwd),a=o.content,c=a.split(`
@@ -199,21 +199,21 @@ JSON only, no preamble:`;try{let i=(await t.sendMessage([{role:"user",content:r,
199
199
  `)}var t4,en,zl,Xf,Vw,Jw,n4,Qf,ho,go,yo,mi,Vl=w(()=>{"use strict";t4={enabled:!0,runBaseline:!0,runValidation:!0,autoRollback:!0,blockOnFailure:!0,smartSelection:!0,testTimeout:300*1e3,maxBaselineAge:600*1e3,performanceRegressionThreshold:1.5,detectFlaky:!0,flakyRetries:2,retentionCount:20,parallel:!1,background:!1,quarantineFlaky:!0},en={...t4},zl=Xt(e4(),".aiaca","regression-guard"),Xf=Xt(zl,"snapshots"),Vw=Xt(zl,"flaky-tests.json"),Jw=Xt(zl,"stats.json"),n4=Xt(zl,"history.jsonl"),Qf=Xt(zl,"baseline-cache.json"),ho=new Map,go=null;yo=new Map;r4();b4();mi={totalGuards:0,totalPassed:0,totalFailed:0,totalRolledBack:0,totalNewFailures:0,totalPerformanceRegressions:0,averageDuration:0,byFramework:{}};$4()});var Bh={};$(Bh,{configure:()=>rW,createMachine:()=>H4,deleteMachine:()=>V4,getAllMachines:()=>G4,getConfig:()=>nW,getMachine:()=>z4,getMachineSummary:()=>tW,listGates:()=>eW,recordToolActivity:()=>K4,recordValidation:()=>Z4,registerCustomGate:()=>X4,setPlan:()=>Y4,transition:()=>HM,updateStepStatus:()=>Q4});import{existsSync as E4,mkdirSync as D4,readFileSync as F4,writeFileSync as NM}from"fs";import{join as Zw}from"path";import{homedir as L4}from"os";import{createHash as qM}from"crypto";function Ms(e){ss.set(e.name,e)}function j4(e,t){return O4[e]?.[t]||null}function UM(){D4(Xw,{recursive:!0})}function q4(){if(E4(Qw))try{let e=JSON.parse(F4(Qw,"utf-8"));for(let t of e)Dr.set(t.machineId,t)}catch{}}function bo(){UM();try{NM(Qw,JSON.stringify(Array.from(Dr.values()),null,2),"utf-8")}catch{}}function U4(e){if(or.enableAuditLog){UM();try{NM(N4,JSON.stringify(e)+`
200
200
  `,{flag:"a"})}catch{}}}function H4(e){let t=qM("md5").update(e+Date.now()+Math.random()).digest("hex").slice(0,12),n={machineId:t,goal:e,currentState:"idle",history:[],iterations:0,startedAt:Date.now(),lastTransitionAt:Date.now(),executionLog:[],validationResults:[],stuckDetectionWindow:[],errorCount:0,recoveryAttempts:0};return Dr.set(t,n),or.enablePersistence&&bo(),n}function z4(e){return Dr.get(e)}function G4(){return Array.from(Dr.values())}function V4(e){let t=Dr.delete(e);return t&&or.enablePersistence&&bo(),t}async function HM(e,t,n={}){let r=Dr.get(e);if(!r)return{success:!1,newState:"failed",error:"Machine not found"};let s=j4(r.currentState,t);if(!s)return{success:!1,newState:r.currentState,error:`Invalid transition: ${r.currentState} --${t}--> ?`};let i=[];if(or.enforceGates&&!n.skipGates){i=await J4(r,r.currentState,s);let c=i.find(l=>l.blocking&&!l.passed);if(c)return{success:!1,newState:r.currentState,gateResults:i,error:`Gate failed: ${c.message}`}}if(n.gateOverrides)for(let[c,l]of Object.entries(n.gateOverrides))i.push({...l,message:`[override] ${c}: ${l.message}`});let o=r.currentState;r.currentState=s,r.lastTransitionAt=Date.now();let a={from:o,to:s,event:t,timestamp:Date.now(),reason:n.reason,gates:i.map(c=>c.message),data:n.data};return r.history.push(a),U4({...a,machineId:e}),or.enablePersistence&&bo(),{success:!0,newState:s,gateResults:i}}async function J4(e,t,n){let r=[],s=W4(t,n);for(let i of s)try{let o=await i.check(e);r.push({...o,message:`[${i.name}] ${o.message}`}),i.required&&!o.passed&&(r[r.length-1].blocking=!0)}catch(o){r.push({passed:!1,message:`[${i.name}] gate error: ${o.message}`,blocking:i.required})}return r}function W4(e,t){let n=[];return e==="planning"&&t==="plan_review"&&(n.push(ss.get("plan_has_steps")),n.push(ss.get("plan_has_acceptance_criteria"))),e==="executing"&&t==="executing"&&(n.push(ss.get("iteration_limit")),n.push(ss.get("no_stuck_loop")),n.push(ss.get("progress_made"))),e==="executing"&&t==="validating"&&n.push(ss.get("iteration_limit")),e==="validating"&&t==="reporting"&&(n.push(ss.get("tests_pass")),n.push(ss.get("no_critical_security"))),n.filter(Boolean)}function K4(e,t,n){let r=Dr.get(e);if(!r||!or.enableStuckDetection)return;let s=qM("md5").update(JSON.stringify(n)).digest("hex").slice(0,12);r.stuckDetectionWindow.push({toolName:t,inputHash:s,timestamp:Date.now()}),r.stuckDetectionWindow.length>20&&r.stuckDetectionWindow.shift();let i=r.stuckDetectionWindow.slice(-6);if(i.length>=4){let o=i.every(c=>c.toolName===i[0].toolName),a=i.every(c=>c.inputHash===i[0].inputHash);o&&a&&HM(e,"detect_stuck",{reason:`Repeated ${i[0].toolName} with same input`}).catch(()=>{})}or.enablePersistence&&bo()}function Y4(e,t){let n=Dr.get(e);return n?(n.plan=t,or.enablePersistence&&bo(),!0):!1}function Q4(e,t,n,r){let s=Dr.get(e);if(!s?.plan)return!1;let i=s.plan.steps.find(o=>o.id===t);return i?(i.status=n,n==="in_progress"&&!i.startedAt&&(i.startedAt=Date.now()),(n==="completed"||n==="failed")&&(i.completedAt=Date.now(),r&&(i.evidence=r)),or.enablePersistence&&bo(),!0):!1}function Z4(e,t,n,r,s){let i=Dr.get(e);return i?(i.validationResults.push({gate:t,passed:n,message:r,details:s,timestamp:Date.now()}),or.enablePersistence&&bo(),!0):!1}function X4(e){ss.set(e.name,e)}function eW(){return Array.from(ss.values())}function tW(e){let t=Dr.get(e);if(!t)return"Machine not found";let n=[];n.push(`# Agent State Machine: ${t.machineId}`),n.push(`Goal: ${t.goal}`),n.push(`State: ${t.currentState}`),n.push(`Iterations: ${t.iterations}`),n.push(`Errors: ${t.errorCount} | Recovery attempts: ${t.recoveryAttempts}`),n.push("");let r=Math.round((Date.now()-t.startedAt)/1e3);if(n.push(`Elapsed: ${r}s`),n.push(""),t.plan){n.push(`## Plan (${t.plan.steps.length} steps)`);for(let s of t.plan.steps){let i=s.status==="completed"?"\u2713":s.status==="in_progress"?"\u27F3":s.status==="failed"?"\u2717":s.status==="skipped"?"~":"\u25CB";n.push(` ${i} ${s.description}`)}if(n.push(""),t.plan.acceptanceCriteria.length>0){n.push("### Acceptance Criteria");for(let s of t.plan.acceptanceCriteria)n.push(` - ${s}`);n.push("")}}if(t.history.length>0){n.push("## Recent Transitions (last 10)");for(let s of t.history.slice(-10)){let i=Math.round((Date.now()-s.timestamp)/1e3);n.push(` ${s.from} \u2192 ${s.to} (${s.event}, ${i}s ago)${s.reason?` \u2014 ${s.reason}`:""}`)}n.push("")}if(t.validationResults.length>0){n.push("## Validations");for(let s of t.validationResults.slice(-10)){let i=s.passed?"\u2713":"\u2717";n.push(` ${i} ${s.gate}: ${s.message}`)}}return t.finalReport&&(n.push(""),n.push("## Report"),n.push(t.finalReport)),n.join(`
201
201
  `)}function nW(){return{...or}}function rW(e){or={...or,...e}}var ss,O4,B4,or,Dr,Xw,Qw,N4,Nh=w(()=>{"use strict";ss=new Map;Ms({name:"plan_has_steps",description:"Plan must contain at least one step",category:"plan",required:!0,check:e=>({passed:!!e.plan&&e.plan.steps.length>0,message:e.plan?.steps.length?`Plan has ${e.plan.steps.length} steps`:"Plan is empty"})});Ms({name:"plan_has_acceptance_criteria",description:"Plan must define acceptance criteria",category:"plan",required:!1,check:e=>({passed:!!e.plan&&e.plan.acceptanceCriteria.length>0,message:e.plan?.acceptanceCriteria.length?`${e.plan.acceptanceCriteria.length} acceptance criteria`:"No acceptance criteria \u2014 output may be subjective",blocking:!1})});Ms({name:"iteration_limit",description:"Iteration count under threshold",category:"budget",required:!0,check:e=>({passed:e.iterations<100,message:`Iterations: ${e.iterations}`,blocking:!0})});Ms({name:"no_stuck_loop",description:"No repeated identical tool calls (stuck detection)",category:"safety",required:!0,check:e=>{let t=e.stuckDetectionWindow.slice(-6);if(t.length<4)return{passed:!0,message:"Insufficient activity to evaluate"};let n=new Map;for(let s of t){let i=`${s.toolName}:${s.inputHash}`;n.set(i,(n.get(i)||0)+1)}let r=Math.max(...n.values());return{passed:r<4,message:r>=4?`Same tool+input repeated ${r} times \u2014 stuck`:`OK (max repeat: ${r})`,blocking:r>=4}}});Ms({name:"progress_made",description:"Some plan step has progressed recently",category:"execution",required:!1,check:e=>{if(!e.plan)return{passed:!0,message:"No plan to evaluate"};let t=e.plan.steps.filter(r=>r.status==="in_progress").length,n=e.plan.steps.filter(r=>r.status==="completed").length;return{passed:n>0||t>0,message:`${n} completed, ${t} in progress`,blocking:!1}}});Ms({name:"tests_pass",description:"Project test suite passes",category:"validation",required:!1,check:async e=>{try{let r=(await(await Promise.resolve().then(()=>(Vl(),Gl))).preChangeGuard({projectPath:process.cwd(),filesToChange:[],triggeredBy:"state-machine-gate"})).baseline;if(!r)return{passed:!0,message:"No tests to run",blocking:!1};let s=r.failing.length===0;return{passed:s,message:s?`All ${r.passing.length} tests pass`:`${r.failing.length} test(s) failing`,blocking:!s,data:{passing:r.passing.length,failing:r.failing.length}}}catch(t){return{passed:!0,message:`Could not run tests: ${t.message}`,blocking:!1}}}});Ms({name:"no_critical_security",description:"No critical security findings",category:"validation",required:!1,check:async e=>{try{let t=e.validationResults.filter(n=>n.gate.includes("security")&&!n.passed).length;return{passed:t===0,message:t===0?"No critical security issues":`${t} critical issue(s)`,blocking:t>0}}catch{return{passed:!0,message:"Skipped"}}}});Ms({name:"lint_clean",description:"Linter reports no errors",category:"validation",required:!1,check:async e=>({passed:!0,message:"Lint check skipped (run analyze_code in execution)"})});Ms({name:"type_check_ok",description:"TypeScript/Python type check passes",category:"validation",required:!1,check:async e=>({passed:!0,message:"Type check evaluated during execution"})});Ms({name:"cost_budget",description:"Within cost budget",category:"budget",required:!0,check:e=>({passed:!0,message:"Within budget"})});O4={idle:{start_planning:"planning",abort:"aborted"},planning:{plan_ready:"plan_review",timeout:"failed",abort:"aborted",detect_stuck:"stuck"},plan_review:{plan_approved:"executing",plan_rejected:"planning",abort:"aborted"},executing:{execution_step_done:"executing",execution_done:"validating",timeout:"failed",abort:"aborted",detect_stuck:"stuck"},validating:{validation_passed:"reporting",validation_failed:"executing",timeout:"failed",abort:"aborted"},reporting:{report_done:"completed",abort:"aborted"},completed:{},failed:{recover:"planning"},aborted:{},stuck:{recover:"planning",abort:"aborted"}};B4={enabled:!0,enforceGates:!0,enableStuckDetection:!0,stuckThresholdIterations:10,perStateTimeoutMs:{idle:6e4,planning:300*1e3,plan_review:6e4,executing:1800*1e3,validating:600*1e3,reporting:120*1e3,completed:0,failed:0,aborted:0,stuck:0},maxRecoveryAttempts:2,enableAuditLog:!0,enablePersistence:!0},or={...B4},Dr=new Map,Xw=Zw(L4(),".aiaca","state-machines"),Qw=Zw(Xw,"machines.json"),N4=Zw(Xw,"audit.jsonl");q4();process.on("exit",()=>{or.enablePersistence&&bo()})});var Yl={};$(Yl,{configure:()=>$W,createCheckpoint:()=>ZM,deleteCheckpoint:()=>CW,diff:()=>wW,getConfig:()=>xW,getCurrentCheckpoint:()=>gW,getStats:()=>kW,listCheckpoints:()=>nk,loadCheckpoint:()=>Ia,maybeAutoCheckpoint:()=>vW,rollback:()=>hW,tagCheckpoint:()=>AW});import{existsSync as Ma,mkdirSync as Jl,readFileSync as tp,writeFileSync as Pa,statSync as sW,readdirSync as ep,unlinkSync as Uh}from"fs";import{join as zn,resolve as Hh,relative as GM,dirname as VM}from"path";import{homedir as iW}from"os";import{createHash as zh}from"crypto";import{glob as JM}from"glob";function WM(e){return zh("sha256").update(Hh(e)).digest("hex").slice(0,16)}function tk(e){return zn(qh,WM(e))}function KM(e){return zn(aW,WM(e))}function YM(e,t){return zn(tk(e),t.slice(0,2),t.slice(2))}function Wl(e,t){return zn(KM(e),`${t}.json`)}function QM(e){Jl(tk(e),{recursive:!0}),Jl(KM(e),{recursive:!0})}function lW(e,t){let n=zh("sha256").update(t).digest("hex"),r=YM(e,n);return Ma(r)?{hash:n,isNew:!1}:(Jl(VM(r),{recursive:!0}),Pa(r,t),{hash:n,isNew:!0})}function uW(e,t){let n=YM(e,t);if(!Ma(n))return null;try{return tp(n)}catch{return null}}function dW(){if(Ma(ek))try{bt=JSON.parse(tp(ek,"utf-8"))}catch{}}function Kl(){Jl(Ea,{recursive:!0}),bt.lastSavedAt=Date.now();try{Pa(ek,JSON.stringify(bt,null,2),"utf-8")}catch{}}async function fW(e){QM(e);let t=new Set;for(let i of Ot.capturePatterns)try{let o=await JM(i,{cwd:e,absolute:!0,ignore:Ot.ignorePatterns,nodir:!0});for(let a of o)t.add(a)}catch{}let n=[],r=0,s=0;for(let i of t)try{let o=sW(i);if(o.size>5*1024*1024)continue;let a=tp(i),{hash:c,isNew:l}=lW(e,a);l&&s++,n.push({path:GM(e,i),contentHash:c,size:o.size,mode:o.mode}),r+=o.size}catch{}return{files:n,basePath:e,totalBytes:r}}async function pW(){if(!Ot.includeAgentState)return{};let e={};if(Ot.includeBlackboard)try{let n=(await Promise.resolve().then(()=>(Wf(),Jf))).query({limit:1e3});e.blackboardSnapshot={};for(let r of n)e.blackboardSnapshot[`${r.namespace}:${r.key}`]={value:r.value,version:r.version,agentId:r.agentId,tags:r.tags,updatedAt:r.updatedAt}}catch{}if(Ot.includeIntent)try{let n=(await Promise.resolve().then(()=>(Ta(),Aa))).getCurrentIntent();n&&(e.currentIntent=n)}catch{}if(Ot.includeStateMachine)try{let n=(await Promise.resolve().then(()=>(Nh(),Bh))).getAllMachines();e.stateMachineSnapshot=n}catch{}return e}async function ZM(e,t={}){if(!Ot.enabled)throw new Error("Checkpoint service disabled");QM(e);let n=zh("sha256").update(Date.now().toString()+Math.random()).digest("hex").slice(0,16),r=Date.now(),s=await fW(e),i=s.totalBytes,o=await pW();t.conversationMessages&&(o.conversationMessages=t.conversationMessages.slice(-30));let a=mW(o),c=t.parentId||bt.currentId,l={id:n,label:t.label||`Checkpoint ${new Date().toISOString().slice(11,19)}`,description:t.description||"",createdAt:Date.now(),parentId:c,childrenIds:[],tags:t.tags||[],fileSnapshot:s,agentState:o,triggeredBy:t.triggeredBy||"manual",context:t.context||{},size:{fileBytes:i,stateBytes:a,totalBytes:i+a,fileCount:s.files.length,newBlobs:0}};if(l.size.totalBytes>Ot.maxCheckpointSizeBytes)throw new Error(`Checkpoint exceeds max size: ${l.size.totalBytes} > ${Ot.maxCheckpointSizeBytes}`);if(Pa(Wl(e,n),JSON.stringify(l),"utf-8"),bt.checkpoints.push({id:n,label:l.label,createdAt:l.createdAt,parentId:c,tags:l.tags,sizeBytes:l.size.totalBytes,projectPath:Hh(e)}),bt.currentId=n,c&&bt.checkpoints.find(d=>d.id===c)){let d=Ia(e,c);d&&!d.childrenIds.includes(n)&&(d.childrenIds.push(n),Pa(Wl(e,c),JSON.stringify(d)))}return Kl(),eE({action:"create",checkpointId:n,projectPath:e,timestamp:Date.now()}),SW(e),l}function mW(e){try{return JSON.stringify(e).length}catch{return 0}}function Ia(e,t){let n=Wl(e,t);if(!Ma(n))return null;try{return JSON.parse(tp(n,"utf-8"))}catch{return null}}function nk(e){if(e){let t=Hh(e);return bt.checkpoints.filter(n=>n.projectPath===t)}return[...bt.checkpoints]}function gW(){return bt.currentId}async function hW(e,t,n={}){let r=Date.now(),s=Ia(e,t);if(!s)return{success:!1,checkpointId:t,filesRestored:0,filesDeleted:0,filesUnchanged:0,errors:["Checkpoint not found"],durationMs:Date.now()-r};let i=[],o=0,a=0,c=0,l=[];if(!n.stateOnly){let u=new Map(s.fileSnapshot.files.map(f=>[f.path,f])),d=new Set(n.skipFiles||[]);for(let[f,p]of u){if(d.has(f))continue;let m=zn(e,f);if(Ma(m))try{let h=tp(m);if(zh("sha256").update(h).digest("hex")===p.contentHash){c++;continue}}catch{}let g=uW(e,p.contentHash);if(!g){i.push(`Missing blob for ${f}`);continue}if(l.push(`+ ${f} (${g.length} bytes)`),n.dryRun)o++;else try{Jl(VM(m),{recursive:!0}),Pa(m,g),o++}catch(h){i.push(`${f}: ${h.message}`)}}try{for(let f of Ot.capturePatterns){let p=await JM(f,{cwd:e,absolute:!0,ignore:Ot.ignorePatterns,nodir:!0});for(let m of p){let g=GM(e,m);if(!d.has(g)&&!u.has(g))if(l.push(`- ${g}`),n.dryRun)a++;else try{Uh(m),a++}catch(h){i.push(`Delete ${g}: ${h.message}`)}}}}catch(f){i.push(`Cleanup error: ${f.message}`)}}return!n.filesOnly&&!n.dryRun&&await yW(s.agentState),n.dryRun||(bt.currentId=t,Kl(),eE({action:"rollback",checkpointId:t,projectPath:Hh(e),timestamp:Date.now(),data:{filesRestored:o,filesDeleted:a,errors:i.length}})),{success:i.length===0,checkpointId:t,filesRestored:o,filesDeleted:a,filesUnchanged:c,errors:i,preview:n.dryRun?l:void 0,durationMs:Date.now()-r}}async function yW(e){if(e.blackboardSnapshot)try{let t=await Promise.resolve().then(()=>(Wf(),Jf));t.clear();for(let[n,r]of Object.entries(e.blackboardSnapshot)){let[s,...i]=n.split(":"),o=i.join(":"),a=r;t.set(o,a.value,{agentId:a.agentId||"restore",namespace:s,tags:a.tags})}}catch{}}async function vW(e,t,n={}){if(!Ot.enabled||!Ot.autoCheckpoint||!Ot.autoCheckpointTriggers.includes(t)||Date.now()-zM<bW)return null;zM=Date.now();try{return await ZM(e,{label:`Auto: ${t}`,triggeredBy:t,tags:["auto",t],context:n})}catch{return null}}function SW(e){let t=nk(e);if(t.length<=Ot.retentionCount)return 0;let n=Date.now()-Ot.retentionAgeMs,r=[...t].sort((i,o)=>i.createdAt-o.createdAt),s=0;for(let i of r)if(i.id!==bt.currentId&&!(i.tags.includes("keep")||i.tags.includes("milestone"))&&(i.createdAt<n||t.length-s>Ot.retentionCount)){try{Uh(Wl(e,i.id))}catch{}let o=bt.checkpoints.findIndex(a=>a.id===i.id);if(o>=0&&bt.checkpoints.splice(o,1),s++,t.length-s<=Ot.retentionCount)break}return s>0&&(Kl(),queueMicrotask(()=>XM(e).catch(()=>{}))),s}async function XM(e){let t=new Set,n=nk(e);for(let i of n){let o=Ia(e,i.id);if(o)for(let a of o.fileSnapshot.files)t.add(a.contentHash)}let r=0,s=tk(e);if(!Ma(s))return 0;try{for(let i of ep(s)){let o=zn(s,i);try{for(let a of ep(o)){let c=i+a;if(!t.has(c))try{Uh(zn(o,a)),r++}catch{}}}catch{}}}catch{}return r}function wW(e,t,n){let r=Ia(e,t),s=Ia(e,n);if(!r||!s)return null;let i=new Map(r.fileSnapshot.files.map(d=>[d.path,d.contentHash])),o=new Map(s.fileSnapshot.files.map(d=>[d.path,d.contentHash])),a=[],c=[],l=[];for(let[d,f]of o){let p=i.get(d);p?p!==f&&l.push(d):a.push(d)}for(let[d]of i)o.has(d)||c.push(d);let u=JSON.stringify(r.agentState)!==JSON.stringify(s.agentState);return{fromId:t,toId:n,filesAdded:a,filesRemoved:c,filesModified:l,agentStateChanged:u}}function kW(){let e=0,t=Date.now(),n=0,r={},s={};for(let o of bt.checkpoints)e+=o.sizeBytes,o.createdAt<t&&(t=o.createdAt),o.createdAt>n&&(n=o.createdAt),s[o.projectPath]||(s[o.projectPath]={count:0,totalBytes:0}),s[o.projectPath].count++,s[o.projectPath].totalBytes+=o.sizeBytes;let i=0;if(Ma(qh))try{for(let o of ep(qh)){let a=zn(qh,o);try{for(let c of ep(a))try{i+=ep(zn(a,c)).length}catch{}}catch{}}}catch{}return{totalCheckpoints:bt.checkpoints.length,totalProjects:Object.keys(s).length,totalBytes:e,blobCount:i,oldestAt:t,newestAt:n,byTrigger:r,averageSizeBytes:bt.checkpoints.length>0?e/bt.checkpoints.length:0,perProjectStats:s}}function eE(e){Jl(Ea,{recursive:!0});try{Pa(cW,JSON.stringify(e)+`
202
- `,{flag:"a"})}catch{}}function xW(){return{...Ot}}function $W(e){Ot={...Ot,...e}}function CW(e,t){try{Uh(Wl(e,t));let n=bt.checkpoints.findIndex(r=>r.id===t);return n>=0&&bt.checkpoints.splice(n,1),bt.currentId===t&&(bt.currentId=void 0),Kl(),queueMicrotask(()=>XM(e).catch(()=>{})),!0}catch{return!1}}function AW(e,t,n){let r=Ia(e,t);if(!r)return!1;r.tags=[...new Set([...r.tags,...n])],Pa(Wl(e,t),JSON.stringify(r),"utf-8");let s=bt.checkpoints.find(i=>i.id===t);return s&&(s.tags=r.tags,Kl()),!0}var oW,Ot,Ea,qh,aW,ek,h_e,cW,bt,zM,bW,Ql=w(()=>{"use strict";oW={enabled:!0,autoCheckpoint:!0,autoCheckpointTriggers:["on_query_start","before_file_write","before_file_edit"],retentionCount:50,retentionAgeMs:10080*60*1e3,maxCheckpointSizeBytes:100*1024*1024,enableCompression:!1,capturePatterns:["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/*.{py,go,rs,java,kt,rb,php,cs}","**/*.{json,yaml,yml,toml}","**/*.{md,txt,html,css,scss,sql}","package.json","tsconfig.json",".aiaca.json"],ignorePatterns:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.cache/**","**/coverage/**","**/__pycache__/**","**/*.min.js","**/.next/**"],includeAgentState:!0,includeBlackboard:!0,includeIntent:!0,includeStateMachine:!0,enableBranching:!0,maxParallelCheckpoints:3},Ot={...oW},Ea=zn(iW(),".aiaca","checkpoints"),qh=zn(Ea,"blobs"),aW=zn(Ea,"meta"),ek=zn(Ea,"index.json"),h_e=zn(Ea,"current.json"),cW=zn(Ea,"audit.jsonl");bt={checkpoints:[],lastSavedAt:0};dW();zM=0,bW=5e3;process.on("exit",()=>{Kl()})});var rp={};$(rp,{addAccessPolicy:()=>XW,buildSecureEnv:()=>KW,checkWriteContent:()=>WW,clearCache:()=>nK,configure:()=>QW,deleteFileSecret:()=>aK,detectLeaks:()=>fE,extractAllReferences:()=>lE,fetchSecret:()=>ck,getAuditLog:()=>iK,getConfig:()=>YW,getProviderStatus:()=>rK,getStats:()=>sK,listPolicies:()=>tK,parseSecretReference:()=>ak,redactSecrets:()=>JW,removeAccessPolicy:()=>eK,resolveReferences:()=>VW,setFileSecret:()=>oK,setProviderConfig:()=>ZW});import{existsSync as vo,mkdirSync as rE,readFileSync as Zl,writeFileSync as Da}from"fs";import{join as gi}from"path";import{homedir as sE}from"os";import{execSync as eu}from"child_process";import{randomBytes as TW,createCipheriv as _W,createDecipheriv as RW,scryptSync as tE}from"crypto";function Vh(){rE(hi,{recursive:!0})}function oE(){let e=E.providers.fileEncryptionKey||process.env.AIACA_SECRET_KEY;if(!e){let t=`${process.env.USER||process.env.USERNAME||"user"}-${sE()}`;return tE(t,"aiaca-salt-v1",32)}return tE(e,"aiaca-salt-v1",32)}function aE(e){let t=oE(),n=TW(12),r=_W(iE,t,n),s=Buffer.concat([r.update(e,"utf8"),r.final()]),i=r.getAuthTag();return{ciphertext:s.toString("base64"),iv:n.toString("base64"),authTag:i.toString("base64")}}function cE(e){try{let t=oE(),n=RW(iE,t,Buffer.from(e.iv,"base64"));return n.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([n.update(Buffer.from(e.ciphertext,"base64")),n.final()]).toString("utf-8")}catch{return null}}function IW(){if(!(!E.cacheEnabled||!vo(Xl)))try{let e=Zl(Xl,"utf-8"),t=JSON.parse(e);if(E.encryptCache&&t.ciphertext){let n=cE(t);if(!n)return;let r=JSON.parse(n),s=Date.now();for(let i of r)(!i.ttlMs||s-i.fetchedAt<i.ttlMs)&&Es.set(ok(i.provider,i.path),i)}}catch{}}function MW(){if(E.cacheEnabled){Vh();try{let e=JSON.stringify(Array.from(Es.values()));if(E.encryptCache){let t=aE(e);Da(Xl,JSON.stringify(t),"utf-8")}else Da(Xl,e,"utf-8")}catch{}}}function EW(){if(vo(rk))try{E={...E,...JSON.parse(Zl(rk,"utf-8"))}}catch{}if(vo(sk))try{let e=JSON.parse(Zl(sk,"utf-8"));Array.isArray(e)&&(E.accessPolicies=e)}catch{}}function Jh(){Vh();try{Da(rk,JSON.stringify(E,null,2),"utf-8"),Da(sk,JSON.stringify(E.accessPolicies,null,2),"utf-8")}catch{}}function ok(e,t){return`${e}:${t}`}function Gh(e){if(E.enableAuditLog){Vh();try{Da(np,JSON.stringify({...e,timestamp:Date.now()})+`
202
+ `,{flag:"a"})}catch{}}function xW(){return{...Ot}}function $W(e){Ot={...Ot,...e}}function CW(e,t){try{Uh(Wl(e,t));let n=bt.checkpoints.findIndex(r=>r.id===t);return n>=0&&bt.checkpoints.splice(n,1),bt.currentId===t&&(bt.currentId=void 0),Kl(),queueMicrotask(()=>XM(e).catch(()=>{})),!0}catch{return!1}}function AW(e,t,n){let r=Ia(e,t);if(!r)return!1;r.tags=[...new Set([...r.tags,...n])],Pa(Wl(e,t),JSON.stringify(r),"utf-8");let s=bt.checkpoints.find(i=>i.id===t);return s&&(s.tags=r.tags,Kl()),!0}var oW,Ot,Ea,qh,aW,ek,y_e,cW,bt,zM,bW,Ql=w(()=>{"use strict";oW={enabled:!0,autoCheckpoint:!0,autoCheckpointTriggers:["on_query_start","before_file_write","before_file_edit"],retentionCount:50,retentionAgeMs:10080*60*1e3,maxCheckpointSizeBytes:100*1024*1024,enableCompression:!1,capturePatterns:["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/*.{py,go,rs,java,kt,rb,php,cs}","**/*.{json,yaml,yml,toml}","**/*.{md,txt,html,css,scss,sql}","package.json","tsconfig.json",".aiaca.json"],ignorePatterns:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.cache/**","**/coverage/**","**/__pycache__/**","**/*.min.js","**/.next/**"],includeAgentState:!0,includeBlackboard:!0,includeIntent:!0,includeStateMachine:!0,enableBranching:!0,maxParallelCheckpoints:3},Ot={...oW},Ea=zn(iW(),".aiaca","checkpoints"),qh=zn(Ea,"blobs"),aW=zn(Ea,"meta"),ek=zn(Ea,"index.json"),y_e=zn(Ea,"current.json"),cW=zn(Ea,"audit.jsonl");bt={checkpoints:[],lastSavedAt:0};dW();zM=0,bW=5e3;process.on("exit",()=>{Kl()})});var rp={};$(rp,{addAccessPolicy:()=>XW,buildSecureEnv:()=>KW,checkWriteContent:()=>WW,clearCache:()=>nK,configure:()=>QW,deleteFileSecret:()=>aK,detectLeaks:()=>fE,extractAllReferences:()=>lE,fetchSecret:()=>ck,getAuditLog:()=>iK,getConfig:()=>YW,getProviderStatus:()=>rK,getStats:()=>sK,listPolicies:()=>tK,parseSecretReference:()=>ak,redactSecrets:()=>JW,removeAccessPolicy:()=>eK,resolveReferences:()=>VW,setFileSecret:()=>oK,setProviderConfig:()=>ZW});import{existsSync as vo,mkdirSync as rE,readFileSync as Zl,writeFileSync as Da}from"fs";import{join as gi}from"path";import{homedir as sE}from"os";import{execSync as eu}from"child_process";import{randomBytes as TW,createCipheriv as _W,createDecipheriv as RW,scryptSync as tE}from"crypto";function Vh(){rE(hi,{recursive:!0})}function oE(){let e=E.providers.fileEncryptionKey||process.env.AIACA_SECRET_KEY;if(!e){let t=`${process.env.USER||process.env.USERNAME||"user"}-${sE()}`;return tE(t,"aiaca-salt-v1",32)}return tE(e,"aiaca-salt-v1",32)}function aE(e){let t=oE(),n=TW(12),r=_W(iE,t,n),s=Buffer.concat([r.update(e,"utf8"),r.final()]),i=r.getAuthTag();return{ciphertext:s.toString("base64"),iv:n.toString("base64"),authTag:i.toString("base64")}}function cE(e){try{let t=oE(),n=RW(iE,t,Buffer.from(e.iv,"base64"));return n.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([n.update(Buffer.from(e.ciphertext,"base64")),n.final()]).toString("utf-8")}catch{return null}}function IW(){if(!(!E.cacheEnabled||!vo(Xl)))try{let e=Zl(Xl,"utf-8"),t=JSON.parse(e);if(E.encryptCache&&t.ciphertext){let n=cE(t);if(!n)return;let r=JSON.parse(n),s=Date.now();for(let i of r)(!i.ttlMs||s-i.fetchedAt<i.ttlMs)&&Es.set(ok(i.provider,i.path),i)}}catch{}}function MW(){if(E.cacheEnabled){Vh();try{let e=JSON.stringify(Array.from(Es.values()));if(E.encryptCache){let t=aE(e);Da(Xl,JSON.stringify(t),"utf-8")}else Da(Xl,e,"utf-8")}catch{}}}function EW(){if(vo(rk))try{E={...E,...JSON.parse(Zl(rk,"utf-8"))}}catch{}if(vo(sk))try{let e=JSON.parse(Zl(sk,"utf-8"));Array.isArray(e)&&(E.accessPolicies=e)}catch{}}function Jh(){Vh();try{Da(rk,JSON.stringify(E,null,2),"utf-8"),Da(sk,JSON.stringify(E.accessPolicies,null,2),"utf-8")}catch{}}function ok(e,t){return`${e}:${t}`}function Gh(e){if(E.enableAuditLog){Vh();try{Da(np,JSON.stringify({...e,timestamp:Date.now()})+`
203
203
  `,{flag:"a"})}catch{}}}function ak(e){let t=e.match(/^\$\{secret:([^}]+)\}$/);if(!t)return null;let n=t[1];if(n.includes("/")&&/^[a-z_]+\//.test(n)){let[r,...s]=n.split("/");if(["vault","aws","aws_secrets_manager","1password","op","gcp","gcp_secret_manager","azure","azure_key_vault","env","file","doppler"].includes(r))return{raw:e,provider:r==="aws"?"aws_secrets_manager":r==="op"?"1password":r==="gcp"?"gcp_secret_manager":r==="azure"?"azure_key_vault":r,path:s.join("/")}}return{raw:e,provider:"auto",path:n}}function lE(e){let t=[],n,r=new RegExp(DW.source,"g");for(;(n=r.exec(e))!==null;){let s=ak(n[0]);s&&t.push(s)}return t}async function FW(e){let t=E.providers.vaultUrl||process.env.VAULT_ADDR,n=E.providers.vaultToken||process.env.VAULT_TOKEN,r=E.providers.vaultMount||"secret";if(!t||!n)return null;try{let s=e.startsWith("/")?e:`/${r}/data/${e}`,i=await fetch(`${t}/v1${s}`,{headers:{"X-Vault-Token":n,...E.providers.vaultNamespace?{"X-Vault-Namespace":E.providers.vaultNamespace}:{}}});if(!i.ok)return null;let o=await i.json(),a=o.data?.data?.value||o.data?.value||o.data;if(typeof a=="string")return a;if(typeof a=="object"){for(let c of Object.values(a))if(typeof c=="string")return c}return null}catch{return null}}async function LW(e){if(!Gn("aws"))return null;let t=E.providers.awsRegion||process.env.AWS_REGION||"us-east-1",n=E.providers.awsProfile?`--profile ${E.providers.awsProfile}`:"";try{let s=eu(`aws secretsmanager get-secret-value --secret-id ${JSON.stringify(e)} --region ${t} ${n} --query SecretString --output text`,{stdio:"pipe",encoding:"utf-8",timeout:15e3}).trim();try{let i=JSON.parse(s);if(typeof i=="object"){for(let o of Object.values(i))if(typeof o=="string")return o}return s}catch{return s}}catch{return null}}async function OW(e){if(!Gn("op"))return null;let t=E.providers.opAccount||process.env.OP_ACCOUNT,n=t?`--account ${t}`:"";try{return eu(`op read ${JSON.stringify(e)} ${n}`,{stdio:"pipe",encoding:"utf-8",timeout:15e3}).trim()}catch{return null}}async function jW(e){if(!Gn("gcloud"))return null;let t=E.providers.gcpProject||process.env.GCP_PROJECT,n=t?`--project ${t}`:"";try{return eu(`gcloud secrets versions access latest --secret=${JSON.stringify(e)} ${n}`,{stdio:"pipe",encoding:"utf-8",timeout:15e3}).trim()}catch{return null}}async function BW(e){if(!Gn("az"))return null;let t=E.providers.azureVaultName||process.env.AZURE_VAULT_NAME;if(!t)return null;try{return eu(`az keyvault secret show --vault-name ${t} --name ${JSON.stringify(e)} --query value -o tsv`,{stdio:"pipe",encoding:"utf-8",timeout:15e3}).trim()}catch{return null}}async function NW(e){if(!Gn("doppler"))return null;let t=E.providers.dopplerToken||process.env.DOPPLER_TOKEN,n=E.providers.dopplerProject,r=E.providers.dopplerConfig?`--config ${E.providers.dopplerConfig}`:"";try{let s=t?`DOPPLER_TOKEN=${t}`:"";return eu(`${s} doppler secrets get ${JSON.stringify(e)} --plain ${n?`--project ${n}`:""} ${r}`,{stdio:"pipe",encoding:"utf-8",shell:"/bin/sh",timeout:15e3}).trim()}catch{return null}}async function qW(e){return process.env[e]||null}async function UW(e){let t=gi(hi,"file",`${e}.enc`);if(!vo(t))return null;try{let n=JSON.parse(Zl(t,"utf-8"));return cE(n)}catch{return null}}function Gn(e){try{return eu(process.platform==="win32"?`where ${e}`:`which ${e}`,{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}async function HW(e){let t=[E.defaultProvider,"vault","aws_secrets_manager","1password","gcp_secret_manager","azure_key_vault","doppler","env","file"],n=new Set,r=t.filter(s=>n.has(s)?!1:(n.add(s),!0));for(let s of r)if(await uE(s,e))return s;return E.defaultProvider}async function uE(e,t){switch(e){case"vault":return FW(t);case"aws_secrets_manager":return LW(t);case"1password":return OW(t);case"gcp_secret_manager":return jW(t);case"azure_key_vault":return BW(t);case"doppler":return NW(t);case"env":return qW(t);case"file":return UW(t)}return null}async function ck(e,t={}){if(!E.enabled)return null;let n=zW(e.path,t);if(!n.allowed)return Gh({action:"fetch_denied",provider:e.provider,path:e.path,agent:t.agentId,success:!1,reason:n.reason}),null;let r=e.provider==="auto"?await HW(e.path):e.provider;if(E.cacheEnabled&&!t.bypassCache){let o=Es.get(ok(r,e.path));if(o&&(!o.ttlMs||Date.now()-o.fetchedAt<o.ttlMs))return Gh({action:"fetch_cached",provider:r,path:e.path,agent:t.agentId,success:!0}),nE(e.path),o.value}let s=await uE(r,e.path);if(!s)return Gh({action:"fetch_failed",provider:r,path:e.path,agent:t.agentId,success:!1,reason:"not found or auth failure"}),null;let i={path:e.path,provider:r,value:s,metadata:{},fetchedAt:Date.now(),ttlMs:E.cacheTTLMs};return Es.set(ok(r,e.path),i),MW(),Gh({action:"fetch",provider:r,path:e.path,agent:t.agentId,success:!0}),nE(e.path),s}function nE(e){let t=Date.now(),n=t-6e4,s=(ik.get(e)||[]).filter(i=>i>n);s.push(t),ik.set(e,s)}function zW(e,t){if(E.accessPolicies.length===0)return{allowed:!0};for(let n of E.accessPolicies)if(GW(e,n.secretPattern)){if(n.allowedAgents.length>0&&!n.allowedAgents.includes("*")&&(!t.agentId||!n.allowedAgents.includes(t.agentId)))return{allowed:!1,reason:`agent ${t.agentId} not allowed for ${n.secretPattern}`};if(n.allowedTools.length>0&&!n.allowedTools.includes("*")&&(!t.toolName||!n.allowedTools.includes(t.toolName)))return{allowed:!1,reason:`tool ${t.toolName} not allowed for ${n.secretPattern}`};if(n.rateLimitPerMinute){let r=ik.get(e)||[],s=Date.now()-6e4,i=r.filter(o=>o>s).length;if(i>=n.rateLimitPerMinute)return{allowed:!1,reason:`rate limit exceeded (${i}/${n.rateLimitPerMinute}/min)`}}return{allowed:!0}}return{allowed:!0}}function GW(e,t){if(t==="*"||t==="**")return!0;let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___GLOBSTAR___").replace(/\*/g,"[^/]*").replace(/___GLOBSTAR___/g,".*");return new RegExp(`^${n}$`).test(e)}async function VW(e,t={}){let n=lE(e);if(n.length===0)return{resolved:e,failures:[]};let r=e,s=[];for(let i of n){let o=await ck(i,t);o!==null?r=r.split(i.raw).join(o):s.push(i.path)}return{resolved:r,failures:s}}function fE(e){if(!E.enableLeakDetection)return{hasLeaks:!1,leaks:[]};let t=[];for(let{name:n,regex:r}of dE){let s=new RegExp(r.source,r.flags),i;for(;(i=s.exec(e))!==null;){let o=i[0],a=i.index,l=e.slice(Math.max(0,a-30),Math.min(e.length,a+o.length+30)).replace(o,"[REDACTED]");t.push({pattern:n,redactedSnippet:l})}}for(let n of Es.values())n.value.length<16||e.includes(n.value)&&t.push({pattern:`Known secret: ${n.path}`,redactedSnippet:e.replace(n.value,"[REDACTED]").slice(0,200)});return{hasLeaks:t.length>0,leaks:t}}function JW(e){if(!E.redactInOutputs)return e;let t=e;for(let{regex:n}of dE)t=t.replace(new RegExp(n.source,n.flags),"[REDACTED]");for(let n of Es.values())n.value.length>=8&&(t=t.split(n.value).join("[REDACTED]"));return t}function WW(e){if(!E.blockWritesWithSecrets)return{allowed:!0,leaks:{hasLeaks:!1,leaks:[]}};let t=fE(e);return t.hasLeaks?{allowed:!1,reason:`Detected ${t.leaks.length} secret(s): ${t.leaks.map(n=>n.pattern).join(", ")}`,leaks:t}:{allowed:!0,leaks:t}}async function KW(e,t={}){let n={...process.env};for(let[r,s]of Object.entries(e)){let i=ak(s)||{raw:s,provider:"auto",path:s},o=await ck(i,t);o!==null&&(n[r]=o)}return n}function YW(){let e=JSON.parse(JSON.stringify(E));for(let t of Object.keys(e.providers))(t.toLowerCase().includes("token")||t.toLowerCase().includes("key"))&&(e.providers[t]=e.providers[t]?"[CONFIGURED]":null);return e}function QW(e){E={...E,...e},Jh()}function ZW(e,t){E.providers={...E.providers,...t},Jh()}function XW(e){E.accessPolicies.push(e),Jh()}function eK(e){let t=E.accessPolicies.length;return E.accessPolicies=E.accessPolicies.filter(n=>n.secretPattern!==e),Jh(),E.accessPolicies.length<t}function tK(){return JSON.parse(JSON.stringify(E.accessPolicies))}function nK(){if(Es.clear(),vo(Xl))try{Da(Xl,"","utf-8")}catch{}}function rK(){let e=[];return e.push({provider:"vault",available:!0,configured:!!(E.providers.vaultUrl||process.env.VAULT_ADDR)&&!!(E.providers.vaultToken||process.env.VAULT_TOKEN)}),e.push({provider:"aws_secrets_manager",available:Gn("aws"),configured:Gn("aws")}),e.push({provider:"1password",available:Gn("op"),configured:Gn("op")}),e.push({provider:"gcp_secret_manager",available:Gn("gcloud"),configured:Gn("gcloud")}),e.push({provider:"azure_key_vault",available:Gn("az"),configured:Gn("az")&&!!(E.providers.azureVaultName||process.env.AZURE_VAULT_NAME)}),e.push({provider:"doppler",available:Gn("doppler"),configured:Gn("doppler")&&!!(E.providers.dopplerToken||process.env.DOPPLER_TOKEN)}),e.push({provider:"env",available:!0,configured:!0}),e.push({provider:"file",available:!0,configured:!0}),e}function sK(){if(!vo(np))return{totalFetches:0,totalFailures:0,totalDenied:0,cacheHits:0,cachedSecrets:Es.size,leaksBlocked:0,byProvider:{}};try{let e=Zl(np,"utf-8").split(`
204
204
  `).filter(Boolean).slice(-1e3),t={totalFetches:0,totalFailures:0,totalDenied:0,cacheHits:0,cachedSecrets:Es.size,leaksBlocked:0,byProvider:{}};for(let n of e)try{let r=JSON.parse(n);r.action==="fetch"&&t.totalFetches++,r.action==="fetch_cached"&&t.cacheHits++,r.action==="fetch_failed"&&t.totalFailures++,r.action==="fetch_denied"&&t.totalDenied++,r.action==="leak_blocked"&&t.leaksBlocked++,r.provider&&(t.byProvider[r.provider]=(t.byProvider[r.provider]||0)+1)}catch{}return t}catch{return{totalFetches:0,totalFailures:0,totalDenied:0,cacheHits:0,cachedSecrets:Es.size,leaksBlocked:0,byProvider:{}}}}function iK(e=100){if(!vo(np))return[];try{return Zl(np,"utf-8").split(`
205
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function oK(e,t){Vh();let n=gi(hi,"file",`${e}.enc`);try{rE(gi(hi,"file"),{recursive:!0});let r=aE(t);return Da(n,JSON.stringify(r),"utf-8"),!0}catch{return!1}}function aK(e){let t=gi(hi,"file",`${e}.enc`);if(!vo(t))return!1;try{return fl("fs").unlinkSync(t),!0}catch{return!1}}var PW,E,hi,Xl,np,rk,sk,Es,ik,iE,DW,dE,sp=w(()=>{"use strict";PW={enabled:!0,defaultProvider:"env",providers:{vaultMount:"secret",awsRegion:"us-east-1"},cacheEnabled:!0,cacheTTLMs:300*1e3,encryptCache:!0,enableLeakDetection:!0,blockWritesWithSecrets:!0,redactInOutputs:!0,accessPolicies:[],enableAuditLog:!0},E={...PW},hi=gi(sE(),".aiaca","secrets"),Xl=gi(hi,"cache.enc"),np=gi(hi,"audit.jsonl"),rk=gi(hi,"config.json"),sk=gi(hi,"policies.json"),Es=new Map,ik=new Map;iE="aes-256-gcm";EW();IW();DW=/\$\{secret:([^}]+)\}/g;dE=[{name:"AWS Access Key",regex:/AKIA[0-9A-Z]{16}/g},{name:"AWS Secret Key",regex:/[A-Za-z0-9/+=]{40}/g},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36,}/g},{name:"GitHub Fine-grained",regex:/github_pat_[a-zA-Z0-9_]{82}/g},{name:"Google API Key",regex:/AIza[a-zA-Z0-9_-]{35}/g},{name:"OpenAI Key",regex:/sk-(?:proj-|live-)?[a-zA-Z0-9]{20,}/g},{name:"Anthropic Key",regex:/sk-ant-[a-zA-Z0-9_-]{32,}/g},{name:"Slack Token",regex:/xox[baprs]-[a-zA-Z0-9-]+/g},{name:"Stripe Key",regex:/sk_(live|test)_[a-zA-Z0-9]{24,}/g},{name:"Twilio SID",regex:/AC[a-f0-9]{32}/g},{name:"Twilio Auth Token",regex:/SK[a-f0-9]{32}/g},{name:"JWT Token",regex:/eyJ[a-zA-Z0-9_-]+\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+/g},{name:"Private Key",regex:/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g},{name:"Generic Bearer",regex:/[Bb]earer\s+[a-zA-Z0-9_\-.]{20,}/g},{name:"Password assignment",regex:/(?:password|passwd|pwd)\s*[:=]\s*["']([^"']{6,})["']/gi},{name:"API Key assignment",regex:/(?:api[_-]?key|apikey|secret[_-]?key)\s*[:=]\s*["']([^"']{16,})["']/gi}]});var ru={};$(ru,{configure:()=>_K,forensicReplay:()=>CK,formatEntry:()=>OK,generateComplianceReport:()=>LK,getConfig:()=>TK,getEvents:()=>MK,getState:()=>IK,getStats:()=>RK,listArchives:()=>CE,manualCleanup:()=>FK,manualCompress:()=>DK,manualRotate:()=>EK,recordWrite:()=>xK,resetStats:()=>PK,searchEntries:()=>xE,startMaintenance:()=>$E,stopMaintenance:()=>AK,verifyChain:()=>kE});import{existsSync as La,mkdirSync as pE,readFileSync as tu,writeFileSync as ip,readdirSync as Kh,statSync as pk,renameSync as cK,unlinkSync as mk,createReadStream as lK,createWriteStream as uK}from"fs";import{join as os,basename as dK}from"path";import{homedir as fK,hostname as uk}from"os";import{createHash as pK,createHmac as mK,randomBytes as gk,timingSafeEqual as gK}from"crypto";import{createGzip as hK}from"zlib";import{pipeline as yK}from"stream/promises";import{EventEmitter as bK}from"events";function op(){pE(nu,{recursive:!0}),pE(is,{recursive:!0})}function gE(){if(op(),le.signingKey)return le.signingKey;if(La(lk))try{let t=tu(lk,"utf-8").trim();if(t.length>=64)return le.signingKey=t,t}catch{}let e=gk(32).toString("hex");try{ip(lk,e,{encoding:"utf-8",mode:384})}catch{}return le.signingKey=e,e}function SK(){if(op(),gE(),La(dk))try{Te={...Te,...JSON.parse(tu(dk,"utf-8"))}}catch{}if(La(fk))try{Ke={...Ke,...JSON.parse(tu(fk,"utf-8"))}}catch{}Te.currentLogFile||hk()}function hE(){op();try{ip(dk,JSON.stringify(Te,null,2),"utf-8")}catch{}}function ap(){op();try{ip(fk,JSON.stringify(Ke,null,2),"utf-8")}catch{}}function hk(){let e=new Date().toISOString().slice(0,10),t=gk(2).toString("hex"),n=`audit-${e}-${t}.jsonl`;Te.currentLogFile=os(nu,n),Te.currentLogStartedAt=Date.now(),Te.currentLogSize=0,hE()}function Wh(e){return pK(le.hashAlgorithm).update(e,"utf-8").digest("hex")}function yE(e){let t=gE();return mK("sha256",Buffer.from(t,"hex")).update(e).digest("hex")}function wK(e,t){let n=yE(e);if(n.length!==t.length)return!1;try{return gK(Buffer.from(n,"hex"),Buffer.from(t,"hex"))}catch{return!1}}function bE(e){return[e.sequenceNumber,e.id,e.previousHash,e.contentHash,e.timestamp,e.source,e.operation,e.filePath||"",e.contentLength].join("|")}function vE(){return Date.now()-Te.currentLogStartedAt>le.rotationIntervalMs||Te.currentLogSize>le.rotationSizeBytes}async function yk(){if(Te.currentLogFile&&La(Te.currentLogFile)){let e=os(is,dK(Te.currentLogFile));try{cK(Te.currentLogFile,e)}catch{try{ip(e,tu(Te.currentLogFile)),mk(Te.currentLogFile)}catch{}}}hk(),Ke.totalRotations++,ap(),wo.emit("rotated",{archived:Te.currentLogFile})}async function SE(){if(!le.compressOldLogs)return{compressed:0};let e=0,t=Date.now()-le.compressAfterMs;try{for(let n of Kh(is)){if(!n.endsWith(".jsonl"))continue;let r=os(is,n);if(pk(r).mtimeMs>t)continue;let i=r+".gz";try{await yK(lK(r),hK(),uK(i)),mk(r),e++}catch{}}}catch{}return e>0&&(Ke.totalCompressions+=e,ap(),wo.emit("compressed",{count:e})),{compressed:e}}function wE(){let e=le.customRetentionMs??mE[le.retentionPolicy];if(e===0)return{deleted:0};let t=Date.now()-e,n=0;try{for(let r of Kh(is)){let s=os(is,r);if(pk(s).mtimeMs<t)try{mk(s),n++}catch{}}}catch{}return n>0&&wo.emit("retention_cleanup",{deleted:n}),{deleted:n}}function kK(e){if(!le.enableAnomalyDetection)return{isAnomaly:!1,reasons:[]};let t=Date.now();So.recentWrites.push({timestamp:t,source:e}),So.recentWrites=So.recentWrites.filter(i=>t-i.timestamp<6e4);let n=[];So.recentWrites.length>le.burstThreshold&&n.push(`Burst: ${So.recentWrites.length} writes/min`);let r=new Set(So.recentWrites.map(i=>i.source));r.size>le.diversityThreshold&&n.push(`High source diversity: ${r.size} sources`);let s=So.recentWrites.filter(i=>i.source===e).length;return s>le.burstThreshold/2&&n.push(`Repeated writes to same source: ${s}`),n.length>0?(Ke.totalAnomalies++,wo.emit("anomaly_detected",{source:e,reasons:n,count:So.recentWrites.length}),{isAnomaly:!0,reasons:n}):{isAnomaly:!1,reasons:[]}}function xK(e){if(!le.enabled)return{sequenceNumber:0,id:"",previousHash:"",contentHash:"",signature:"",timestamp:Date.now(),source:e.source,operation:e.operation,contentLength:e.content.length,contentSnippetHash:"",isSuspicious:!1,hostMachine:uk()};let t=Date.now(),n=gk(8).toString("hex"),r=++Te.sequenceNumber,s=Te.lastEntryHash,i=Wh(e.content),o=Wh(e.content.slice(0,200)),a=kK(e.source);vE()&&yk().catch(()=>{});let c={sequenceNumber:r,id:n,previousHash:s,contentHash:i,signature:"",timestamp:t,source:e.source,operation:e.operation,filePath:e.filePath,storeId:e.storeId,contentLength:e.content.length,contentSnippetHash:o,agentId:e.agentId,sessionId:e.sessionId,callerStack:e.callerStack||$K(),isSuspicious:a.isAnomaly,riskScore:a.isAnomaly?.7:.05,hostMachine:uk(),metadata:e.metadata};c.signature=yE(bE(c));let l=Wh(JSON.stringify(c));op(),Te.currentLogFile||hk();let u=JSON.stringify(c)+`
206
- `;try{ip(Te.currentLogFile,u,{flag:"a"}),Te.currentLogSize+=u.length,Te.lastEntryHash=l,Te.totalEntriesWritten++,hE()}catch{}return Ke.totalEntries++,Ke.bySource[e.source]=(Ke.bySource[e.source]||0)+1,Ke.byOperation[e.operation]=(Ke.byOperation[e.operation]||0)+1,c.isSuspicious&&Ke.totalSuspicious++,ap(),le.enableEventStreaming&&(wo.emit("write",{entry:c}),c.isSuspicious&&wo.emit("suspicious_write",{entry:c,reasons:a.reasons})),c}function $K(){let e=new Error;return e.stack?e.stack.split(`
205
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function oK(e,t){Vh();let n=gi(hi,"file",`${e}.enc`);try{rE(gi(hi,"file"),{recursive:!0});let r=aE(t);return Da(n,JSON.stringify(r),"utf-8"),!0}catch{return!1}}function aK(e){let t=gi(hi,"file",`${e}.enc`);if(!vo(t))return!1;try{return fl("fs").unlinkSync(t),!0}catch{return!1}}var PW,E,hi,Xl,np,rk,sk,Es,ik,iE,DW,dE,sp=w(()=>{"use strict";PW={enabled:!0,defaultProvider:"env",providers:{vaultMount:"secret",awsRegion:"us-east-1"},cacheEnabled:!0,cacheTTLMs:300*1e3,encryptCache:!0,enableLeakDetection:!0,blockWritesWithSecrets:!0,redactInOutputs:!0,accessPolicies:[],enableAuditLog:!0},E={...PW},hi=gi(sE(),".aiaca","secrets"),Xl=gi(hi,"cache.enc"),np=gi(hi,"audit.jsonl"),rk=gi(hi,"config.json"),sk=gi(hi,"policies.json"),Es=new Map,ik=new Map;iE="aes-256-gcm";EW();IW();DW=/\$\{secret:([^}]+)\}/g;dE=[{name:"AWS Access Key",regex:/AKIA[0-9A-Z]{16}/g},{name:"AWS Secret Key",regex:/[A-Za-z0-9/+=]{40}/g},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36,}/g},{name:"GitHub Fine-grained",regex:/github_pat_[a-zA-Z0-9_]{82}/g},{name:"Google API Key",regex:/AIza[a-zA-Z0-9_-]{35}/g},{name:"OpenAI Key",regex:/sk-(?:proj-|live-)?[a-zA-Z0-9]{20,}/g},{name:"Anthropic Key",regex:/sk-ant-[a-zA-Z0-9_-]{32,}/g},{name:"Slack Token",regex:/xox[baprs]-[a-zA-Z0-9-]+/g},{name:"Stripe Key",regex:/sk_(live|test)_[a-zA-Z0-9]{24,}/g},{name:"Twilio SID",regex:/AC[a-f0-9]{32}/g},{name:"Twilio Auth Token",regex:/SK[a-f0-9]{32}/g},{name:"JWT Token",regex:/eyJ[a-zA-Z0-9_-]+\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+/g},{name:"Private Key",regex:/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g},{name:"Generic Bearer",regex:/[Bb]earer\s+[a-zA-Z0-9_\-.]{20,}/g},{name:"Password assignment",regex:/(?:password|passwd|pwd)\s*[:=]\s*["']([^"']{6,})["']/gi},{name:"API Key assignment",regex:/(?:api[_-]?key|apikey|secret[_-]?key)\s*[:=]\s*["']([^"']{16,})["']/gi}]});var ru={};$(ru,{configure:()=>_K,forensicReplay:()=>CK,formatEntry:()=>OK,generateComplianceReport:()=>LK,getConfig:()=>TK,getEvents:()=>MK,getState:()=>IK,getStats:()=>RK,listArchives:()=>CE,manualCleanup:()=>FK,manualCompress:()=>DK,manualRotate:()=>EK,recordWrite:()=>xK,resetStats:()=>PK,searchEntries:()=>xE,startMaintenance:()=>$E,stopMaintenance:()=>AK,verifyChain:()=>kE});import{existsSync as La,mkdirSync as pE,readFileSync as tu,writeFileSync as ip,readdirSync as Kh,statSync as pk,renameSync as cK,unlinkSync as mk,createReadStream as lK,createWriteStream as uK}from"fs";import{join as os,basename as dK}from"path";import{homedir as fK,hostname as uk}from"os";import{createHash as pK,createHmac as mK,randomBytes as gk,timingSafeEqual as gK}from"crypto";import{createGzip as hK}from"zlib";import{pipeline as yK}from"stream/promises";import{EventEmitter as bK}from"events";function op(){pE(nu,{recursive:!0}),pE(is,{recursive:!0})}function gE(){if(op(),ue.signingKey)return ue.signingKey;if(La(lk))try{let t=tu(lk,"utf-8").trim();if(t.length>=64)return ue.signingKey=t,t}catch{}let e=gk(32).toString("hex");try{ip(lk,e,{encoding:"utf-8",mode:384})}catch{}return ue.signingKey=e,e}function SK(){if(op(),gE(),La(dk))try{Te={...Te,...JSON.parse(tu(dk,"utf-8"))}}catch{}if(La(fk))try{Ke={...Ke,...JSON.parse(tu(fk,"utf-8"))}}catch{}Te.currentLogFile||hk()}function hE(){op();try{ip(dk,JSON.stringify(Te,null,2),"utf-8")}catch{}}function ap(){op();try{ip(fk,JSON.stringify(Ke,null,2),"utf-8")}catch{}}function hk(){let e=new Date().toISOString().slice(0,10),t=gk(2).toString("hex"),n=`audit-${e}-${t}.jsonl`;Te.currentLogFile=os(nu,n),Te.currentLogStartedAt=Date.now(),Te.currentLogSize=0,hE()}function Wh(e){return pK(ue.hashAlgorithm).update(e,"utf-8").digest("hex")}function yE(e){let t=gE();return mK("sha256",Buffer.from(t,"hex")).update(e).digest("hex")}function wK(e,t){let n=yE(e);if(n.length!==t.length)return!1;try{return gK(Buffer.from(n,"hex"),Buffer.from(t,"hex"))}catch{return!1}}function bE(e){return[e.sequenceNumber,e.id,e.previousHash,e.contentHash,e.timestamp,e.source,e.operation,e.filePath||"",e.contentLength].join("|")}function vE(){return Date.now()-Te.currentLogStartedAt>ue.rotationIntervalMs||Te.currentLogSize>ue.rotationSizeBytes}async function yk(){if(Te.currentLogFile&&La(Te.currentLogFile)){let e=os(is,dK(Te.currentLogFile));try{cK(Te.currentLogFile,e)}catch{try{ip(e,tu(Te.currentLogFile)),mk(Te.currentLogFile)}catch{}}}hk(),Ke.totalRotations++,ap(),wo.emit("rotated",{archived:Te.currentLogFile})}async function SE(){if(!ue.compressOldLogs)return{compressed:0};let e=0,t=Date.now()-ue.compressAfterMs;try{for(let n of Kh(is)){if(!n.endsWith(".jsonl"))continue;let r=os(is,n);if(pk(r).mtimeMs>t)continue;let i=r+".gz";try{await yK(lK(r),hK(),uK(i)),mk(r),e++}catch{}}}catch{}return e>0&&(Ke.totalCompressions+=e,ap(),wo.emit("compressed",{count:e})),{compressed:e}}function wE(){let e=ue.customRetentionMs??mE[ue.retentionPolicy];if(e===0)return{deleted:0};let t=Date.now()-e,n=0;try{for(let r of Kh(is)){let s=os(is,r);if(pk(s).mtimeMs<t)try{mk(s),n++}catch{}}}catch{}return n>0&&wo.emit("retention_cleanup",{deleted:n}),{deleted:n}}function kK(e){if(!ue.enableAnomalyDetection)return{isAnomaly:!1,reasons:[]};let t=Date.now();So.recentWrites.push({timestamp:t,source:e}),So.recentWrites=So.recentWrites.filter(i=>t-i.timestamp<6e4);let n=[];So.recentWrites.length>ue.burstThreshold&&n.push(`Burst: ${So.recentWrites.length} writes/min`);let r=new Set(So.recentWrites.map(i=>i.source));r.size>ue.diversityThreshold&&n.push(`High source diversity: ${r.size} sources`);let s=So.recentWrites.filter(i=>i.source===e).length;return s>ue.burstThreshold/2&&n.push(`Repeated writes to same source: ${s}`),n.length>0?(Ke.totalAnomalies++,wo.emit("anomaly_detected",{source:e,reasons:n,count:So.recentWrites.length}),{isAnomaly:!0,reasons:n}):{isAnomaly:!1,reasons:[]}}function xK(e){if(!ue.enabled)return{sequenceNumber:0,id:"",previousHash:"",contentHash:"",signature:"",timestamp:Date.now(),source:e.source,operation:e.operation,contentLength:e.content.length,contentSnippetHash:"",isSuspicious:!1,hostMachine:uk()};let t=Date.now(),n=gk(8).toString("hex"),r=++Te.sequenceNumber,s=Te.lastEntryHash,i=Wh(e.content),o=Wh(e.content.slice(0,200)),a=kK(e.source);vE()&&yk().catch(()=>{});let c={sequenceNumber:r,id:n,previousHash:s,contentHash:i,signature:"",timestamp:t,source:e.source,operation:e.operation,filePath:e.filePath,storeId:e.storeId,contentLength:e.content.length,contentSnippetHash:o,agentId:e.agentId,sessionId:e.sessionId,callerStack:e.callerStack||$K(),isSuspicious:a.isAnomaly,riskScore:a.isAnomaly?.7:.05,hostMachine:uk(),metadata:e.metadata};c.signature=yE(bE(c));let l=Wh(JSON.stringify(c));op(),Te.currentLogFile||hk();let u=JSON.stringify(c)+`
206
+ `;try{ip(Te.currentLogFile,u,{flag:"a"}),Te.currentLogSize+=u.length,Te.lastEntryHash=l,Te.totalEntriesWritten++,hE()}catch{}return Ke.totalEntries++,Ke.bySource[e.source]=(Ke.bySource[e.source]||0)+1,Ke.byOperation[e.operation]=(Ke.byOperation[e.operation]||0)+1,c.isSuspicious&&Ke.totalSuspicious++,ap(),ue.enableEventStreaming&&(wo.emit("write",{entry:c}),c.isSuspicious&&wo.emit("suspicious_write",{entry:c,reasons:a.reasons})),c}function $K(){let e=new Error;return e.stack?e.stack.split(`
207
207
  `).slice(2,6).map(n=>n.trim()).join(" | ").slice(0,300):""}async function kE(e){let t=e||Te.currentLogFile;if(!t||!La(t))return{valid:!1,totalEntries:0,validEntries:0,brokenLinks:[],signatureFailures:[]};let n={valid:!0,totalEntries:0,validEntries:0,brokenLinks:[],signatureFailures:[]};try{let r=tu(t,"utf-8").split(`
208
208
  `).filter(Boolean),s="0".repeat(64),i=1,o=!1;for(let a of r){n.totalEntries++;try{let c=JSON.parse(a);o||(o=!0,i=c.sequenceNumber,s=c.previousHash),c.sequenceNumber!==i&&(n.valid=!1,n.brokenLinks.push({sequenceNumber:c.sequenceNumber,reason:`Expected seq ${i}, got ${c.sequenceNumber}`})),c.previousHash!==s&&(n.valid=!1,n.brokenLinks.push({sequenceNumber:c.sequenceNumber,reason:"Chain break: previousHash mismatch"})),wK(bE(c),c.signature)?n.validEntries++:(n.valid=!1,n.signatureFailures.push({sequenceNumber:c.sequenceNumber,id:c.id})),s=Wh(a),i++}catch{n.valid=!1}}}catch{}return Ke.totalVerifications++,n.valid||Ke.totalChainBreaks++,ap(),n}function xE(e){let t=[],n=e.limit||100,r=[];if(Te.currentLogFile&&La(Te.currentLogFile)&&r.push(Te.currentLogFile),e.searchArchives)try{for(let s of Kh(is))s.endsWith(".jsonl")&&r.push(os(is,s))}catch{}for(let s of r){try{let i=tu(s,"utf-8").split(`
209
- `).filter(Boolean);for(let o of i){if(t.length>=n)break;try{let a=JSON.parse(o);if(e.source&&a.source!==e.source||e.operation&&a.operation!==e.operation||e.agentId&&a.agentId!==e.agentId||e.sessionId&&a.sessionId!==e.sessionId||e.filePath&&a.filePath!==e.filePath||e.startTime&&a.timestamp<e.startTime||e.endTime&&a.timestamp>e.endTime||e.contentSnippetHash&&a.contentSnippetHash!==e.contentSnippetHash||e.isSuspicious!==void 0&&a.isSuspicious!==e.isSuspicious)continue;t.push(a)}catch{}}}catch{}if(t.length>=n)break}return t}async function CK(e){let t={totalEntries:0,bySource:{},byOperation:{},uniqueFiles:[],uniqueAgents:[],timeRange:{start:Number.MAX_SAFE_INTEGER,end:0},chainValid:!0},n=new Set,r=new Set,s=xE({startTime:e.startTime,endTime:e.endTime,searchArchives:!0,limit:1e5});for(let o of s)t.totalEntries++,t.bySource[o.source]=(t.bySource[o.source]||0)+1,t.byOperation[o.operation]=(t.byOperation[o.operation]||0)+1,o.filePath&&n.add(o.filePath),o.agentId&&r.add(o.agentId),o.timestamp<t.timeRange.start&&(t.timeRange.start=o.timestamp),o.timestamp>t.timeRange.end&&(t.timeRange.end=o.timestamp);t.uniqueFiles=Array.from(n),t.uniqueAgents=Array.from(r);let i=await kE();return t.chainValid=i.valid,t}function $E(){Fa||(Fa=setInterval(async()=>{try{vE()&&await yk(),await SE(),wE()}catch{}},3600*1e3),Fa.unref&&Fa.unref())}function AK(){Fa&&(clearInterval(Fa),Fa=null)}function TK(){return{...le,signingKey:le.signingKey?"[REDACTED]":""}}function _K(e){le={...le,...e}}function RK(){return{...Ke}}function PK(){Ke={totalEntries:0,totalRotations:0,totalCompressions:0,totalSuspicious:0,totalAnomalies:0,totalChainBreaks:0,totalVerifications:0,bySource:{},byOperation:{},oldestRetainedTimestamp:0},ap()}function IK(){return{...Te}}function MK(){return wo}function CE(){if(!La(is))return[];try{return Kh(is).map(e=>{let t=os(is,e),n=pk(t);return{name:e,size:n.size,mtime:n.mtimeMs,compressed:e.endsWith(".gz")}}).sort((e,t)=>t.mtime-e.mtime)}catch{return[]}}async function EK(){await yk()}async function DK(){return await SE()}function FK(){return wE()}function LK(){let e=[];e.push("# Memory Write Audit Log Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(`Host: ${uk()}`),e.push(""),e.push("## Summary"),e.push(`- Total entries: ${Ke.totalEntries}`),e.push(`- Current sequence: ${Te.sequenceNumber}`),e.push(`- Total rotations: ${Ke.totalRotations}`),e.push(`- Total compressions: ${Ke.totalCompressions}`),e.push(`- \u{1F6A8} Suspicious writes: ${Ke.totalSuspicious}`),e.push(`- \u26A0\uFE0F Anomalies detected: ${Ke.totalAnomalies}`),e.push(`- \u26D3\uFE0F Chain breaks: ${Ke.totalChainBreaks}`),e.push(`- Verifications: ${Ke.totalVerifications}`),e.push(""),e.push("## By Source");for(let[n,r]of Object.entries(Ke.bySource).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## By Operation");for(let[n,r]of Object.entries(Ke.byOperation).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## Archives");let t=CE();e.push(`- Total archived files: ${t.length}`);for(let n of t.slice(0,10))e.push(` - ${n.name} | ${(n.size/1024).toFixed(1)}KB${n.compressed?" (gzip)":""}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Append-only ledger"),e.push(`- \u2713 ${le.hashAlgorithm.toUpperCase()} hash chain`),e.push("- \u2713 HMAC-SHA256 signatures"),e.push("- \u2713 Sequence number monotonic"),e.push(`- Retention policy: ${le.retentionPolicy} (${(mE[le.retentionPolicy]/864e5).toFixed(0)} days)`),e.push(`- ${le.compressOldLogs?"\u2713":"\u2717"} Compression enabled`),e.push(`- ${le.enableAnomalyDetection?"\u2713":"\u2717"} Anomaly detection`),e.push(`- ${le.enableEventStreaming?"\u2713":"\u2717"} Real-time event streaming`),e.push(`- ${le.enableDistributedSync?"\u2713":"\u2717"} Distributed sync`),e.push(`- \u2713 Auto-rotation: ${le.rotationIntervalMs/864e5} days or ${(le.rotationSizeBytes/1024/1024).toFixed(0)}MB`),e.join(`
209
+ `).filter(Boolean);for(let o of i){if(t.length>=n)break;try{let a=JSON.parse(o);if(e.source&&a.source!==e.source||e.operation&&a.operation!==e.operation||e.agentId&&a.agentId!==e.agentId||e.sessionId&&a.sessionId!==e.sessionId||e.filePath&&a.filePath!==e.filePath||e.startTime&&a.timestamp<e.startTime||e.endTime&&a.timestamp>e.endTime||e.contentSnippetHash&&a.contentSnippetHash!==e.contentSnippetHash||e.isSuspicious!==void 0&&a.isSuspicious!==e.isSuspicious)continue;t.push(a)}catch{}}}catch{}if(t.length>=n)break}return t}async function CK(e){let t={totalEntries:0,bySource:{},byOperation:{},uniqueFiles:[],uniqueAgents:[],timeRange:{start:Number.MAX_SAFE_INTEGER,end:0},chainValid:!0},n=new Set,r=new Set,s=xE({startTime:e.startTime,endTime:e.endTime,searchArchives:!0,limit:1e5});for(let o of s)t.totalEntries++,t.bySource[o.source]=(t.bySource[o.source]||0)+1,t.byOperation[o.operation]=(t.byOperation[o.operation]||0)+1,o.filePath&&n.add(o.filePath),o.agentId&&r.add(o.agentId),o.timestamp<t.timeRange.start&&(t.timeRange.start=o.timestamp),o.timestamp>t.timeRange.end&&(t.timeRange.end=o.timestamp);t.uniqueFiles=Array.from(n),t.uniqueAgents=Array.from(r);let i=await kE();return t.chainValid=i.valid,t}function $E(){Fa||(Fa=setInterval(async()=>{try{vE()&&await yk(),await SE(),wE()}catch{}},3600*1e3),Fa.unref&&Fa.unref())}function AK(){Fa&&(clearInterval(Fa),Fa=null)}function TK(){return{...ue,signingKey:ue.signingKey?"[REDACTED]":""}}function _K(e){ue={...ue,...e}}function RK(){return{...Ke}}function PK(){Ke={totalEntries:0,totalRotations:0,totalCompressions:0,totalSuspicious:0,totalAnomalies:0,totalChainBreaks:0,totalVerifications:0,bySource:{},byOperation:{},oldestRetainedTimestamp:0},ap()}function IK(){return{...Te}}function MK(){return wo}function CE(){if(!La(is))return[];try{return Kh(is).map(e=>{let t=os(is,e),n=pk(t);return{name:e,size:n.size,mtime:n.mtimeMs,compressed:e.endsWith(".gz")}}).sort((e,t)=>t.mtime-e.mtime)}catch{return[]}}async function EK(){await yk()}async function DK(){return await SE()}function FK(){return wE()}function LK(){let e=[];e.push("# Memory Write Audit Log Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(`Host: ${uk()}`),e.push(""),e.push("## Summary"),e.push(`- Total entries: ${Ke.totalEntries}`),e.push(`- Current sequence: ${Te.sequenceNumber}`),e.push(`- Total rotations: ${Ke.totalRotations}`),e.push(`- Total compressions: ${Ke.totalCompressions}`),e.push(`- \u{1F6A8} Suspicious writes: ${Ke.totalSuspicious}`),e.push(`- \u26A0\uFE0F Anomalies detected: ${Ke.totalAnomalies}`),e.push(`- \u26D3\uFE0F Chain breaks: ${Ke.totalChainBreaks}`),e.push(`- Verifications: ${Ke.totalVerifications}`),e.push(""),e.push("## By Source");for(let[n,r]of Object.entries(Ke.bySource).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## By Operation");for(let[n,r]of Object.entries(Ke.byOperation).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## Archives");let t=CE();e.push(`- Total archived files: ${t.length}`);for(let n of t.slice(0,10))e.push(` - ${n.name} | ${(n.size/1024).toFixed(1)}KB${n.compressed?" (gzip)":""}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Append-only ledger"),e.push(`- \u2713 ${ue.hashAlgorithm.toUpperCase()} hash chain`),e.push("- \u2713 HMAC-SHA256 signatures"),e.push("- \u2713 Sequence number monotonic"),e.push(`- Retention policy: ${ue.retentionPolicy} (${(mE[ue.retentionPolicy]/864e5).toFixed(0)} days)`),e.push(`- ${ue.compressOldLogs?"\u2713":"\u2717"} Compression enabled`),e.push(`- ${ue.enableAnomalyDetection?"\u2713":"\u2717"} Anomaly detection`),e.push(`- ${ue.enableEventStreaming?"\u2713":"\u2717"} Real-time event streaming`),e.push(`- ${ue.enableDistributedSync?"\u2713":"\u2717"} Distributed sync`),e.push(`- \u2713 Auto-rotation: ${ue.rotationIntervalMs/864e5} days or ${(ue.rotationSizeBytes/1024/1024).toFixed(0)}MB`),e.join(`
210
210
  `)}function OK(e){let t={session_memory:"\u{1F9E0}",aiaca_md:"\u{1F4DD}",hierarchical_memory:"\u{1F9E0}",project_memory:"\u{1F4C2}",team_memory:"\u{1F465}",config:"\u2699\uFE0F",session_state:"\u{1F4CB}",checkpoint:"\u{1F4BE}",file_history:"\u{1F4DC}",cassettes:"\u{1F3AC}",skills:"\u{1F3AF}",undoredo:"\u21A9\uFE0F",manual:"\u270B"}[e.source]||"\u{1F4CC}",n={create:"\u2795",update:"\u270F\uFE0F",delete:"\u{1F5D1}\uFE0F",append:"\u{1F4CE}",rotate:"\u{1F504}"}[e.operation]||"?",r=[];return r.push(`${t} ${n} #${e.sequenceNumber} ${e.id} ${e.isSuspicious?"\u{1F6A8}":""}`),r.push(` Source: ${e.source} | Op: ${e.operation}`),e.filePath&&r.push(` Path: ${e.filePath}`),e.storeId&&r.push(` Store: ${e.storeId}`),r.push(` Length: ${e.contentLength} chars | Hash: ${e.contentHash.slice(0,16)}...`),e.agentId&&r.push(` Agent: ${e.agentId}`),e.sessionId&&r.push(` Session: ${e.sessionId}`),r.push(` Time: ${new Date(e.timestamp).toISOString()}`),r.push(` Chain: prev=${e.previousHash.slice(0,16)}...`),e.isSuspicious&&r.push(" \u26A0\uFE0F Suspicious write detected"),r.join(`
211
- `)}var mE,vK,le,nu,lk,dk,is,fk,wo,Te,So,Ke,Fa,su=w(()=>{"use strict";mE={short:10080*60*1e3,standard:720*60*60*1e3,extended:2160*60*60*1e3,permanent:0,soc2:365*24*60*60*1e3,hipaa:6*365*24*60*60*1e3,gdpr:720*60*60*1e3},vK={enabled:!0,signingKey:"",hashAlgorithm:"sha256",rotationIntervalMs:1440*60*1e3,rotationSizeBytes:100*1024*1024,compressOldLogs:!0,compressAfterMs:10080*60*1e3,retentionPolicy:"soc2",enableAnomalyDetection:!0,burstThreshold:100,diversityThreshold:10,enableDistributedSync:!1,enableEventStreaming:!0},le={...vK},nu=os(fK(),".aiaca","memory-audit"),lk=os(nu,"master.key"),dk=os(nu,"state.json"),is=os(nu,"archives"),fk=os(nu,"stats.json"),wo=new bK;wo.setMaxListeners(100);Te={sequenceNumber:0,lastEntryHash:"0".repeat(64),currentLogFile:"",currentLogStartedAt:0,currentLogSize:0,totalEntriesWritten:0},So={recentWrites:[]},Ke={totalEntries:0,totalRotations:0,totalCompressions:0,totalSuspicious:0,totalAnomalies:0,totalChainBreaks:0,totalVerifications:0,bySource:{},byOperation:{},oldestRetainedTimestamp:0};SK();Fa=null;le.enabled&&$E()});var vi={};$(vi,{beginTransaction:()=>HK,clear:()=>e9,configure:()=>ZK,createBranch:()=>zK,deleteBranch:()=>VK,endTransaction:()=>PE,formatHistory:()=>t9,formatStats:()=>n9,gc:()=>YK,getConfig:()=>QK,getCurrentBranch:()=>GK,getHistory:()=>KK,getStats:()=>XK,listBranches:()=>EE,recordOperation:()=>UK,redo:()=>IE,rollbackFile:()=>WK,switchBranch:()=>ME,travelTo:()=>JK,undo:()=>xk});import{existsSync as Fr,mkdirSync as bi,readFileSync as Oa,writeFileSync as Ds,unlinkSync as cp,readdirSync as bk}from"fs";import{join as Lr,dirname as iu}from"path";import{homedir as jK}from"os";import{createHash as ou}from"crypto";function fp(){bi(Yh,{recursive:!0}),bi(lp,{recursive:!0})}function _E(e){return Lr(Yh,e.slice(0,2),e.slice(2))}function AE(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e,"utf-8"),n=ou("sha256").update(t).digest("hex"),r=_E(n);return Fr(r)?{hash:n,isNew:!1,size:t.length}:(bi(iu(r),{recursive:!0}),Ds(r,t),jt.blobsStored++,jt.blobsBytes+=t.length,{hash:n,isNew:!0,size:t.length})}function Qh(e){let t=_E(e);if(!Fr(t))return null;try{return Oa(t)}catch{return null}}function NK(){if(fp(),Fs.walEnabled&&Fr(up))try{let e=Oa(up,"utf-8").split(`
212
- `).filter(Boolean);for(let t of e)try{let n=JSON.parse(t);n.action==="op"&&n.op?ln.set(n.op.id,n.op):n.action==="branch"&&n.branch?Ye.set(n.branch.id,n.branch):n.action==="state"&&(Ue=n.currentBranchId,ue=n.currentOpId)}catch{}}catch{}if(Fr(Sk))try{let e=JSON.parse(Oa(Sk,"utf-8"));Ue=e.currentBranchId||Ue,ue=e.currentOpId||ue,jt={...jt,...e.stats}}catch{}if(Fr(vk))try{let e=JSON.parse(Oa(vk,"utf-8"));for(let t of e)Ye.set(t.id,t)}catch{}try{for(let e of bk(lp)){let t=Lr(lp,e);try{let n=JSON.parse(Oa(t,"utf-8"));ln.set(n.id,n)}catch{}}}catch{}if(Ye.size===0){let e={id:"main",name:"main",createdAt:Date.now(),ops:[],current:!0};Ye.set(e.id,e),Ue=e.id}}function ko(e){if(Fs.walEnabled){fp();try{Ds(up,JSON.stringify(e)+`
213
- `,{flag:"a"}),jt.walEntries++}catch{}}}function qK(e){fp();try{Ds(Lr(lp,e.id+".json"),JSON.stringify(e),"utf-8")}catch{}}function pp(){fp();try{Ds(vk,JSON.stringify(Array.from(Ye.values())),"utf-8")}catch{}}function kk(){fp();try{Ds(Sk,JSON.stringify({currentBranchId:Ue,currentOpId:ue,stats:jt}),"utf-8")}catch{}}function RE(){pp(),kk();for(let e of ln.values())qK(e);if(Fr(up))try{Ds(up,"","utf-8")}catch{}}function UK(e){if(!Fs.enabled)return{};let t=ou("sha256").update(e.filePath+Date.now()+Math.random()).digest("hex").slice(0,16),n,r;e.beforeContent!==void 0&&(n=AE(e.beforeContent).hash),e.afterContent!==void 0&&(r=AE(e.afterContent).hash);let s={id:t,parentId:ue,branchId:Ue,type:e.type,timestamp:Date.now(),agentId:e.agentId,filePath:e.filePath,beforeBlob:n,afterBlob:r,newPath:e.newPath,description:e.description,tags:e.tags||[],reversible:e.type!=="multi"||!0},i=Ye.get(Ue);if(!i)throw new Error("No current branch");if(i.ops.push(t),ln.set(t,s),ue=t,i.ops.length>Fs.maxHistorySize){let o=i.ops.shift();o&&ln.delete(o)}return ko({action:"op",op:s}),ko({action:"state",currentBranchId:Ue,currentOpId:ue}),jt.totalOperations++,jt.walEntries>1e3&&RE(),s}function HK(e){yi&&PE(),yi={ops:[],description:e}}function PE(){if(!yi)return null;if(yi.ops.length===0)return yi=null,null;let e=ou("sha256").update("multi-"+Date.now()+Math.random()).digest("hex").slice(0,16),t={id:e,parentId:ue,branchId:Ue,type:"multi",timestamp:Date.now(),filePath:"<multi>",description:yi.description,tags:["transaction"],reversible:!0,childOps:yi.ops},n=Ye.get(Ue);if(n){let r=new Set(yi.ops.map(s=>s.id));n.ops=n.ops.filter(s=>!r.has(s)),n.ops.push(e)}return ln.set(e,t),ue=e,ko({action:"op",op:t}),ko({action:"state",currentBranchId:Ue,currentOpId:ue}),yi=null,t}function xk(){if(!ue)return{success:!1,filesRestored:[],errors:["Nothing to undo"]};let e=ln.get(ue);if(!e)return{success:!1,filesRestored:[],errors:["Current op not found"]};if(!e.reversible)return{success:!1,filesRestored:[],errors:["Op not reversible"]};let t=[],n=[];if(e.type==="multi"&&e.childOps)for(let r of[...e.childOps].reverse()){let s=TE(r);s.success?n.push(...s.files):t.push(...s.errors)}else{let r=TE(e);r.success?n.push(...r.files):t.push(...r.errors)}return ue=e.parentId,ko({action:"state",currentBranchId:Ue,currentOpId:ue}),jt.totalUndos++,{success:t.length===0,operation:e,filesRestored:n,errors:t}}function IE(){let e=Ye.get(Ue);if(!e)return{success:!1,filesRestored:[],errors:["No branch"]};let t=ue?e.ops.indexOf(ue):-1;if(t>=e.ops.length-1)return{success:!1,filesRestored:[],errors:["Nothing to redo"]};let n=e.ops[t+1],r=ln.get(n);if(!r)return{success:!1,filesRestored:[],errors:["Next op not found"]};let s=[],i=[];if(r.type==="multi"&&r.childOps)for(let o of r.childOps){let a=wk(o);a.success?i.push(...a.files):s.push(...a.errors)}else{let o=wk(r);o.success?i.push(...o.files):s.push(...o.errors)}return ue=r.id,ko({action:"state",currentBranchId:Ue,currentOpId:ue}),jt.totalRedos++,{success:s.length===0,operation:r,filesRestored:i,errors:s}}function TE(e){let t=[],n=[];try{if(e.type==="write"||e.type==="edit"){if(e.beforeBlob){let r=Qh(e.beforeBlob);if(!r)n.push(`Missing blob ${e.beforeBlob} for ${e.filePath}`);else{if(Fs.enableConflictReconciliation&&Fr(e.filePath)){let s=Oa(e.filePath),i=ou("sha256").update(s).digest("hex");if(e.afterBlob&&i!==e.afterBlob)return n.push(`Conflict: ${e.filePath} modified externally \u2014 undo would lose changes`),jt.conflictsResolved++,{success:!1,files:t,errors:n}}bi(iu(e.filePath),{recursive:!0}),Ds(e.filePath,r),t.push(e.filePath)}}else if(Fr(e.filePath))try{if(Fs.enableConflictReconciliation){let r=Oa(e.filePath),s=ou("sha256").update(r).digest("hex");if(e.afterBlob&&s!==e.afterBlob)return n.push(`Conflict: ${e.filePath} modified externally`),jt.conflictsResolved++,{success:!1,files:t,errors:n}}cp(e.filePath),t.push(e.filePath)}catch(r){n.push(`Delete ${e.filePath}: ${r.message}`)}}else if(e.type==="delete"){if(e.beforeBlob){let r=Qh(e.beforeBlob);r?(bi(iu(e.filePath),{recursive:!0}),Ds(e.filePath,r),t.push(e.filePath)):n.push("Missing blob for restore")}}else if(e.type==="rename"){if(e.newPath&&Fr(e.newPath))try{fl("fs").renameSync(e.newPath,e.filePath),t.push(e.filePath,e.newPath)}catch(r){n.push(`Rename revert ${e.newPath} \u2192 ${e.filePath}: ${r.message}`)}}else if(e.type==="create_directory")try{fl("fs").rmdirSync(e.filePath),t.push(e.filePath)}catch{}}catch(r){n.push(`Reverse error: ${r.message}`)}return{success:n.length===0,files:t,errors:n}}function wk(e){let t=[],n=[];try{if(e.type==="write"||e.type==="edit"){if(e.afterBlob){let r=Qh(e.afterBlob);r?(bi(iu(e.filePath),{recursive:!0}),Ds(e.filePath,r),t.push(e.filePath)):n.push("Missing blob")}}else if(e.type==="delete"){if(Fr(e.filePath))try{cp(e.filePath),t.push(e.filePath)}catch(r){n.push(`Delete: ${r.message}`)}}else if(e.type==="rename"){if(e.newPath&&Fr(e.filePath))try{let r=fl("fs");bi(iu(e.newPath),{recursive:!0}),r.renameSync(e.filePath,e.newPath),t.push(e.filePath,e.newPath)}catch(r){n.push(`Rename: ${r.message}`)}}else if(e.type==="create_directory")try{bi(e.filePath,{recursive:!0}),t.push(e.filePath)}catch(r){n.push(`Mkdir: ${r.message}`)}}catch(r){n.push(`Forward error: ${r.message}`)}return{success:n.length===0,files:t,errors:n}}function zK(e,t){let n=ou("md5").update(e+Date.now()).digest("hex").slice(0,12),r=Ye.get(Ue),s=t||ue,i=[];if(r&&s){let a=r.ops.indexOf(s);a>=0&&(i=r.ops.slice(0,a+1))}let o={id:n,name:e,createdAt:Date.now(),parentBranchId:Ue,parentOpId:s,ops:i,current:!1};return Ye.set(n,o),jt.totalBranches++,ko({action:"branch",branch:o}),o}function ME(e){let t=Ye.get(e);if(!t)return{success:!1,error:"Branch not found",filesAffected:[]};for(let s of Ye.values())s.current=!1;let n=Ye.get(Ue),r=[];if(n)for(;ue;){let s=xk();if(r.push(...s.filesRestored),!s.success)break}Ue=e,t.current=!0,ue=t.ops[t.ops.length-1];for(let s of t.ops){let i=ln.get(s);if(i){let o=wk(i);r.push(...o.files)}}return pp(),ko({action:"state",currentBranchId:Ue,currentOpId:ue}),{success:!0,filesAffected:r}}function EE(){return Array.from(Ye.values()).sort((e,t)=>t.createdAt-e.createdAt)}function GK(){return Ye.get(Ue)}function VK(e){return e==="main"||e===Ue||!Ye.get(e)?!1:(Ye.delete(e),pp(),!0)}function JK(e){let t=ln.get(e);if(!t)return{success:!1,filesRestored:[],errors:["Op not found"]};let n=Ye.get(t.branchId);if(!n)return{success:!1,filesRestored:[],errors:["Branch not found"]};t.branchId!==Ue&&ME(t.branchId);let r=n.ops.indexOf(e),s=ue?n.ops.indexOf(ue):-1,i=[],o=[];if(r<s)for(;ue!==e&&ue;){let a=xk();if(i.push(...a.filesRestored),!a.success){o.push(...a.errors);break}}else if(r>s)for(;ue!==e;){let a=IE();if(i.push(...a.filesRestored),!a.success){o.push(...a.errors);break}}return{success:o.length===0,filesRestored:i,errors:o}}function WK(e,t){let n=Ye.get(Ue);if(!n)return{success:!1,filesRestored:[],errors:["No branch"]};let r=null;if(t)r=ln.get(t)||null;else for(let s=n.ops.length-1;s>=0;s--){let i=ln.get(n.ops[s]);if(i&&(i.filePath===e||i.newPath===e)){r=i;break}}if(!r)return{success:!1,filesRestored:[],errors:["No op found for file"]};if(r.beforeBlob){let s=Qh(r.beforeBlob);if(!s)return{success:!1,filesRestored:[],errors:["Blob missing"]};try{return bi(iu(e),{recursive:!0}),Ds(e,s),{success:!0,filesRestored:[e],errors:[],operation:r}}catch(i){return{success:!1,filesRestored:[],errors:[i.message]}}}else{if(Fr(e))try{return cp(e),{success:!0,filesRestored:[e],errors:[]}}catch(s){return{success:!1,filesRestored:[],errors:[s.message]}}return{success:!0,filesRestored:[e],errors:[]}}}function KK(e=50){let t=Ye.get(Ue);if(!t)return[];let n=[],r=ue?t.ops.indexOf(ue):-1,s=t.ops.slice(-e);for(let i=0;i<s.length;i++){let o=ln.get(s[i]);if(!o)continue;let a=t.ops.indexOf(s[i]);n.push({op:o,isCurrent:s[i]===ue,isFuture:a>r,branchName:t.name})}return n}function YK(){let e=Date.now()-Fs.retentionDays*24*60*60*1e3,t=0,n=0,r=0;for(let[o,a]of Ye)o==="main"||o===Ue||a.createdAt<e&&(Ye.delete(o),n++);let s=new Set;for(let o of Ye.values()){for(let a of o.ops)s.add(a);for(let a of o.ops){let c=ln.get(a);if(c?.childOps)for(let l of c.childOps)s.add(l.id)}}for(let o of ln.keys())if(!s.has(o)){ln.delete(o);try{cp(Lr(lp,o+".json"))}catch{}t++}let i=new Set;for(let o of ln.values())o.beforeBlob&&i.add(o.beforeBlob),o.afterBlob&&i.add(o.afterBlob);try{for(let o of bk(Yh)){let a=Lr(Yh,o);try{for(let c of bk(a)){let l=o+c;if(!i.has(l))try{cp(Lr(a,c)),r++}catch{}}}catch{}}}catch{}return pp(),kk(),RE(),{removedBlobs:r,removedOps:t,removedBranches:n}}function QK(){return{...Fs}}function ZK(e){Fs={...Fs,...e}}function XK(){return{...jt}}function e9(){ln.clear(),Ye.clear(),ue=void 0;let e={id:"main",name:"main",createdAt:Date.now(),ops:[],current:!0};Ye.set("main",e),Ue="main",pp(),kk()}function t9(e){if(e.length===0)return"No operations in history";let t=[];for(let n of e){let r=n.op,s=Math.round((Date.now()-r.timestamp)/6e4),i=n.isCurrent?" \u2190 HERE":"",o=n.isFuture?" (future)":"",a=r.description||`${r.type} ${r.filePath}`;t.push(` ${r.id} | ${r.type.padEnd(15)} | ${s}m ago | ${a}${i}${o}`)}return t.join(`
211
+ `)}var mE,vK,ue,nu,lk,dk,is,fk,wo,Te,So,Ke,Fa,su=w(()=>{"use strict";mE={short:10080*60*1e3,standard:720*60*60*1e3,extended:2160*60*60*1e3,permanent:0,soc2:365*24*60*60*1e3,hipaa:6*365*24*60*60*1e3,gdpr:720*60*60*1e3},vK={enabled:!0,signingKey:"",hashAlgorithm:"sha256",rotationIntervalMs:1440*60*1e3,rotationSizeBytes:100*1024*1024,compressOldLogs:!0,compressAfterMs:10080*60*1e3,retentionPolicy:"soc2",enableAnomalyDetection:!0,burstThreshold:100,diversityThreshold:10,enableDistributedSync:!1,enableEventStreaming:!0},ue={...vK},nu=os(fK(),".aiaca","memory-audit"),lk=os(nu,"master.key"),dk=os(nu,"state.json"),is=os(nu,"archives"),fk=os(nu,"stats.json"),wo=new bK;wo.setMaxListeners(100);Te={sequenceNumber:0,lastEntryHash:"0".repeat(64),currentLogFile:"",currentLogStartedAt:0,currentLogSize:0,totalEntriesWritten:0},So={recentWrites:[]},Ke={totalEntries:0,totalRotations:0,totalCompressions:0,totalSuspicious:0,totalAnomalies:0,totalChainBreaks:0,totalVerifications:0,bySource:{},byOperation:{},oldestRetainedTimestamp:0};SK();Fa=null;ue.enabled&&$E()});var vi={};$(vi,{beginTransaction:()=>HK,clear:()=>e9,configure:()=>ZK,createBranch:()=>zK,deleteBranch:()=>VK,endTransaction:()=>PE,formatHistory:()=>t9,formatStats:()=>n9,gc:()=>YK,getConfig:()=>QK,getCurrentBranch:()=>GK,getHistory:()=>KK,getStats:()=>XK,listBranches:()=>EE,recordOperation:()=>UK,redo:()=>IE,rollbackFile:()=>WK,switchBranch:()=>ME,travelTo:()=>JK,undo:()=>xk});import{existsSync as Fr,mkdirSync as bi,readFileSync as Oa,writeFileSync as Ds,unlinkSync as cp,readdirSync as bk}from"fs";import{join as Lr,dirname as iu}from"path";import{homedir as jK}from"os";import{createHash as ou}from"crypto";function fp(){bi(Yh,{recursive:!0}),bi(lp,{recursive:!0})}function _E(e){return Lr(Yh,e.slice(0,2),e.slice(2))}function AE(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e,"utf-8"),n=ou("sha256").update(t).digest("hex"),r=_E(n);return Fr(r)?{hash:n,isNew:!1,size:t.length}:(bi(iu(r),{recursive:!0}),Ds(r,t),jt.blobsStored++,jt.blobsBytes+=t.length,{hash:n,isNew:!0,size:t.length})}function Qh(e){let t=_E(e);if(!Fr(t))return null;try{return Oa(t)}catch{return null}}function NK(){if(fp(),Fs.walEnabled&&Fr(up))try{let e=Oa(up,"utf-8").split(`
212
+ `).filter(Boolean);for(let t of e)try{let n=JSON.parse(t);n.action==="op"&&n.op?ln.set(n.op.id,n.op):n.action==="branch"&&n.branch?Ye.set(n.branch.id,n.branch):n.action==="state"&&(Ue=n.currentBranchId,de=n.currentOpId)}catch{}}catch{}if(Fr(Sk))try{let e=JSON.parse(Oa(Sk,"utf-8"));Ue=e.currentBranchId||Ue,de=e.currentOpId||de,jt={...jt,...e.stats}}catch{}if(Fr(vk))try{let e=JSON.parse(Oa(vk,"utf-8"));for(let t of e)Ye.set(t.id,t)}catch{}try{for(let e of bk(lp)){let t=Lr(lp,e);try{let n=JSON.parse(Oa(t,"utf-8"));ln.set(n.id,n)}catch{}}}catch{}if(Ye.size===0){let e={id:"main",name:"main",createdAt:Date.now(),ops:[],current:!0};Ye.set(e.id,e),Ue=e.id}}function ko(e){if(Fs.walEnabled){fp();try{Ds(up,JSON.stringify(e)+`
213
+ `,{flag:"a"}),jt.walEntries++}catch{}}}function qK(e){fp();try{Ds(Lr(lp,e.id+".json"),JSON.stringify(e),"utf-8")}catch{}}function pp(){fp();try{Ds(vk,JSON.stringify(Array.from(Ye.values())),"utf-8")}catch{}}function kk(){fp();try{Ds(Sk,JSON.stringify({currentBranchId:Ue,currentOpId:de,stats:jt}),"utf-8")}catch{}}function RE(){pp(),kk();for(let e of ln.values())qK(e);if(Fr(up))try{Ds(up,"","utf-8")}catch{}}function UK(e){if(!Fs.enabled)return{};let t=ou("sha256").update(e.filePath+Date.now()+Math.random()).digest("hex").slice(0,16),n,r;e.beforeContent!==void 0&&(n=AE(e.beforeContent).hash),e.afterContent!==void 0&&(r=AE(e.afterContent).hash);let s={id:t,parentId:de,branchId:Ue,type:e.type,timestamp:Date.now(),agentId:e.agentId,filePath:e.filePath,beforeBlob:n,afterBlob:r,newPath:e.newPath,description:e.description,tags:e.tags||[],reversible:e.type!=="multi"||!0},i=Ye.get(Ue);if(!i)throw new Error("No current branch");if(i.ops.push(t),ln.set(t,s),de=t,i.ops.length>Fs.maxHistorySize){let o=i.ops.shift();o&&ln.delete(o)}return ko({action:"op",op:s}),ko({action:"state",currentBranchId:Ue,currentOpId:de}),jt.totalOperations++,jt.walEntries>1e3&&RE(),s}function HK(e){yi&&PE(),yi={ops:[],description:e}}function PE(){if(!yi)return null;if(yi.ops.length===0)return yi=null,null;let e=ou("sha256").update("multi-"+Date.now()+Math.random()).digest("hex").slice(0,16),t={id:e,parentId:de,branchId:Ue,type:"multi",timestamp:Date.now(),filePath:"<multi>",description:yi.description,tags:["transaction"],reversible:!0,childOps:yi.ops},n=Ye.get(Ue);if(n){let r=new Set(yi.ops.map(s=>s.id));n.ops=n.ops.filter(s=>!r.has(s)),n.ops.push(e)}return ln.set(e,t),de=e,ko({action:"op",op:t}),ko({action:"state",currentBranchId:Ue,currentOpId:de}),yi=null,t}function xk(){if(!de)return{success:!1,filesRestored:[],errors:["Nothing to undo"]};let e=ln.get(de);if(!e)return{success:!1,filesRestored:[],errors:["Current op not found"]};if(!e.reversible)return{success:!1,filesRestored:[],errors:["Op not reversible"]};let t=[],n=[];if(e.type==="multi"&&e.childOps)for(let r of[...e.childOps].reverse()){let s=TE(r);s.success?n.push(...s.files):t.push(...s.errors)}else{let r=TE(e);r.success?n.push(...r.files):t.push(...r.errors)}return de=e.parentId,ko({action:"state",currentBranchId:Ue,currentOpId:de}),jt.totalUndos++,{success:t.length===0,operation:e,filesRestored:n,errors:t}}function IE(){let e=Ye.get(Ue);if(!e)return{success:!1,filesRestored:[],errors:["No branch"]};let t=de?e.ops.indexOf(de):-1;if(t>=e.ops.length-1)return{success:!1,filesRestored:[],errors:["Nothing to redo"]};let n=e.ops[t+1],r=ln.get(n);if(!r)return{success:!1,filesRestored:[],errors:["Next op not found"]};let s=[],i=[];if(r.type==="multi"&&r.childOps)for(let o of r.childOps){let a=wk(o);a.success?i.push(...a.files):s.push(...a.errors)}else{let o=wk(r);o.success?i.push(...o.files):s.push(...o.errors)}return de=r.id,ko({action:"state",currentBranchId:Ue,currentOpId:de}),jt.totalRedos++,{success:s.length===0,operation:r,filesRestored:i,errors:s}}function TE(e){let t=[],n=[];try{if(e.type==="write"||e.type==="edit"){if(e.beforeBlob){let r=Qh(e.beforeBlob);if(!r)n.push(`Missing blob ${e.beforeBlob} for ${e.filePath}`);else{if(Fs.enableConflictReconciliation&&Fr(e.filePath)){let s=Oa(e.filePath),i=ou("sha256").update(s).digest("hex");if(e.afterBlob&&i!==e.afterBlob)return n.push(`Conflict: ${e.filePath} modified externally \u2014 undo would lose changes`),jt.conflictsResolved++,{success:!1,files:t,errors:n}}bi(iu(e.filePath),{recursive:!0}),Ds(e.filePath,r),t.push(e.filePath)}}else if(Fr(e.filePath))try{if(Fs.enableConflictReconciliation){let r=Oa(e.filePath),s=ou("sha256").update(r).digest("hex");if(e.afterBlob&&s!==e.afterBlob)return n.push(`Conflict: ${e.filePath} modified externally`),jt.conflictsResolved++,{success:!1,files:t,errors:n}}cp(e.filePath),t.push(e.filePath)}catch(r){n.push(`Delete ${e.filePath}: ${r.message}`)}}else if(e.type==="delete"){if(e.beforeBlob){let r=Qh(e.beforeBlob);r?(bi(iu(e.filePath),{recursive:!0}),Ds(e.filePath,r),t.push(e.filePath)):n.push("Missing blob for restore")}}else if(e.type==="rename"){if(e.newPath&&Fr(e.newPath))try{fl("fs").renameSync(e.newPath,e.filePath),t.push(e.filePath,e.newPath)}catch(r){n.push(`Rename revert ${e.newPath} \u2192 ${e.filePath}: ${r.message}`)}}else if(e.type==="create_directory")try{fl("fs").rmdirSync(e.filePath),t.push(e.filePath)}catch{}}catch(r){n.push(`Reverse error: ${r.message}`)}return{success:n.length===0,files:t,errors:n}}function wk(e){let t=[],n=[];try{if(e.type==="write"||e.type==="edit"){if(e.afterBlob){let r=Qh(e.afterBlob);r?(bi(iu(e.filePath),{recursive:!0}),Ds(e.filePath,r),t.push(e.filePath)):n.push("Missing blob")}}else if(e.type==="delete"){if(Fr(e.filePath))try{cp(e.filePath),t.push(e.filePath)}catch(r){n.push(`Delete: ${r.message}`)}}else if(e.type==="rename"){if(e.newPath&&Fr(e.filePath))try{let r=fl("fs");bi(iu(e.newPath),{recursive:!0}),r.renameSync(e.filePath,e.newPath),t.push(e.filePath,e.newPath)}catch(r){n.push(`Rename: ${r.message}`)}}else if(e.type==="create_directory")try{bi(e.filePath,{recursive:!0}),t.push(e.filePath)}catch(r){n.push(`Mkdir: ${r.message}`)}}catch(r){n.push(`Forward error: ${r.message}`)}return{success:n.length===0,files:t,errors:n}}function zK(e,t){let n=ou("md5").update(e+Date.now()).digest("hex").slice(0,12),r=Ye.get(Ue),s=t||de,i=[];if(r&&s){let a=r.ops.indexOf(s);a>=0&&(i=r.ops.slice(0,a+1))}let o={id:n,name:e,createdAt:Date.now(),parentBranchId:Ue,parentOpId:s,ops:i,current:!1};return Ye.set(n,o),jt.totalBranches++,ko({action:"branch",branch:o}),o}function ME(e){let t=Ye.get(e);if(!t)return{success:!1,error:"Branch not found",filesAffected:[]};for(let s of Ye.values())s.current=!1;let n=Ye.get(Ue),r=[];if(n)for(;de;){let s=xk();if(r.push(...s.filesRestored),!s.success)break}Ue=e,t.current=!0,de=t.ops[t.ops.length-1];for(let s of t.ops){let i=ln.get(s);if(i){let o=wk(i);r.push(...o.files)}}return pp(),ko({action:"state",currentBranchId:Ue,currentOpId:de}),{success:!0,filesAffected:r}}function EE(){return Array.from(Ye.values()).sort((e,t)=>t.createdAt-e.createdAt)}function GK(){return Ye.get(Ue)}function VK(e){return e==="main"||e===Ue||!Ye.get(e)?!1:(Ye.delete(e),pp(),!0)}function JK(e){let t=ln.get(e);if(!t)return{success:!1,filesRestored:[],errors:["Op not found"]};let n=Ye.get(t.branchId);if(!n)return{success:!1,filesRestored:[],errors:["Branch not found"]};t.branchId!==Ue&&ME(t.branchId);let r=n.ops.indexOf(e),s=de?n.ops.indexOf(de):-1,i=[],o=[];if(r<s)for(;de!==e&&de;){let a=xk();if(i.push(...a.filesRestored),!a.success){o.push(...a.errors);break}}else if(r>s)for(;de!==e;){let a=IE();if(i.push(...a.filesRestored),!a.success){o.push(...a.errors);break}}return{success:o.length===0,filesRestored:i,errors:o}}function WK(e,t){let n=Ye.get(Ue);if(!n)return{success:!1,filesRestored:[],errors:["No branch"]};let r=null;if(t)r=ln.get(t)||null;else for(let s=n.ops.length-1;s>=0;s--){let i=ln.get(n.ops[s]);if(i&&(i.filePath===e||i.newPath===e)){r=i;break}}if(!r)return{success:!1,filesRestored:[],errors:["No op found for file"]};if(r.beforeBlob){let s=Qh(r.beforeBlob);if(!s)return{success:!1,filesRestored:[],errors:["Blob missing"]};try{return bi(iu(e),{recursive:!0}),Ds(e,s),{success:!0,filesRestored:[e],errors:[],operation:r}}catch(i){return{success:!1,filesRestored:[],errors:[i.message]}}}else{if(Fr(e))try{return cp(e),{success:!0,filesRestored:[e],errors:[]}}catch(s){return{success:!1,filesRestored:[],errors:[s.message]}}return{success:!0,filesRestored:[e],errors:[]}}}function KK(e=50){let t=Ye.get(Ue);if(!t)return[];let n=[],r=de?t.ops.indexOf(de):-1,s=t.ops.slice(-e);for(let i=0;i<s.length;i++){let o=ln.get(s[i]);if(!o)continue;let a=t.ops.indexOf(s[i]);n.push({op:o,isCurrent:s[i]===de,isFuture:a>r,branchName:t.name})}return n}function YK(){let e=Date.now()-Fs.retentionDays*24*60*60*1e3,t=0,n=0,r=0;for(let[o,a]of Ye)o==="main"||o===Ue||a.createdAt<e&&(Ye.delete(o),n++);let s=new Set;for(let o of Ye.values()){for(let a of o.ops)s.add(a);for(let a of o.ops){let c=ln.get(a);if(c?.childOps)for(let l of c.childOps)s.add(l.id)}}for(let o of ln.keys())if(!s.has(o)){ln.delete(o);try{cp(Lr(lp,o+".json"))}catch{}t++}let i=new Set;for(let o of ln.values())o.beforeBlob&&i.add(o.beforeBlob),o.afterBlob&&i.add(o.afterBlob);try{for(let o of bk(Yh)){let a=Lr(Yh,o);try{for(let c of bk(a)){let l=o+c;if(!i.has(l))try{cp(Lr(a,c)),r++}catch{}}}catch{}}}catch{}return pp(),kk(),RE(),{removedBlobs:r,removedOps:t,removedBranches:n}}function QK(){return{...Fs}}function ZK(e){Fs={...Fs,...e}}function XK(){return{...jt}}function e9(){ln.clear(),Ye.clear(),de=void 0;let e={id:"main",name:"main",createdAt:Date.now(),ops:[],current:!0};Ye.set("main",e),Ue="main",pp(),kk()}function t9(e){if(e.length===0)return"No operations in history";let t=[];for(let n of e){let r=n.op,s=Math.round((Date.now()-r.timestamp)/6e4),i=n.isCurrent?" \u2190 HERE":"",o=n.isFuture?" (future)":"",a=r.description||`${r.type} ${r.filePath}`;t.push(` ${r.id} | ${r.type.padEnd(15)} | ${s}m ago | ${a}${i}${o}`)}return t.join(`
214
214
  `)}function n9(){let e=EE();return["Undo/Redo Stack Stats:",` Total operations: ${jt.totalOperations}`,` Total undos: ${jt.totalUndos}`,` Total redos: ${jt.totalRedos}`,` Conflicts resolved: ${jt.conflictsResolved}`,` Blobs stored: ${jt.blobsStored}`,` Blobs size: ${(jt.blobsBytes/1024/1024).toFixed(2)} MB`,` WAL entries: ${jt.walEntries}`,"",`Branches (${e.length}):`,...e.map(t=>{let n=t.current?" \u2190 current":"";return` ${t.id} ${t.name} (${t.ops.length} ops)${n}`})].join(`
215
- `)}var BK,Fs,dp,Yh,lp,vk,Sk,up,ln,Ye,Ue,ue,jt,yi,Si=w(()=>{"use strict";BK={enabled:!0,maxHistorySize:1e3,maxBranches:50,enableCompression:!0,enableBranching:!0,compressionThreshold:10240,walEnabled:!0,retentionDays:30,autoCleanupOnExit:!1,enableConflictReconciliation:!0},Fs={...BK},dp=Lr(jK(),".aiaca","undo-redo"),Yh=Lr(dp,"blobs"),lp=Lr(dp,"ops"),vk=Lr(dp,"branches.json"),Sk=Lr(dp,"state.json"),up=Lr(dp,"wal.jsonl"),ln=new Map,Ye=new Map,Ue="",jt={totalOperations:0,totalUndos:0,totalRedos:0,totalBranches:0,blobsStored:0,blobsBytes:0,walEntries:0,conflictsResolved:0};NK();yi=null});var Ba={};$(Ba,{checkAndStartAwayPeriod:()=>f9,clearAwayState:()=>x9,detectReturn:()=>p9,formatAsMarkdown:()=>v9,formatBrief:()=>S9,getActivityStats:()=>M9,getAwayConfig:()=>C9,getCurrentIdleState:()=>Zh,getCurrentPeriod:()=>k9,getEventHistory:()=>w9,getIdleDuration:()=>LE,recordActivity:()=>d9,recordBackgroundMessage:()=>I9,recordCronFired:()=>P9,recordError:()=>R9,recordEvent:()=>ja,recordFileChanged:()=>_9,recordTaskCompleted:()=>A9,recordTaskFailed:()=>T9,setAwayConfig:()=>$9,summarizeHeuristic:()=>OE,summarizeWithAI:()=>b9});import{existsSync as r9,mkdirSync as s9,readFileSync as i9,writeFileSync as o9}from"fs";import{join as DE}from"path";import{homedir as a9}from"os";function l9(){s9(FE,{recursive:!0})}function gp(){l9();try{o9($k,JSON.stringify(ee,null,2),"utf-8")}catch{}}function u9(){if(r9($k))try{let e=JSON.parse(i9($k,"utf-8"));ee={...ee,...e}}catch{}}function d9(){let e=Date.now();ee.lastActivityAt=e,ee.currentPeriod&&!ee.currentPeriod.endedAt&&(ee.currentPeriod.endedAt=e,ee.currentPeriod.durationMs=e-ee.currentPeriod.startedAt,gp())}function ja(e){let t={...e,timestamp:Date.now()};ee.eventHistory.push(t),ee.eventHistory.length>xo.maxEventHistory&&ee.eventHistory.shift(),ee.currentPeriod&&!ee.currentPeriod.endedAt&&ee.currentPeriod.events.push(t),gp()}function Zh(){let e=Date.now()-ee.lastActivityAt;return e<xo.shortIdleMs?"active":e<xo.awayMs?"short_idle":e<xo.longAwayMs?"away":e<xo.veryLongAwayMs?"long_away":"very_long_away"}function LE(){return Date.now()-ee.lastActivityAt}function f9(e){let t=Zh();if(t==="active"||t==="short_idle")return null;if(ee.currentPeriod&&!ee.currentPeriod.endedAt)return ee.currentPeriod;let n=[...e].reverse().find(s=>s.role==="user"&&!s.content.startsWith("<tool_result")),r=[...e].reverse().find(s=>s.role==="assistant"&&s.content.trim());return ee.currentPeriod={startedAt:ee.lastActivityAt,detectedAt:Date.now(),idleState:t,events:[],lastUserMessage:n?.content?.slice(0,200),lastAssistantMessage:r?.content?.slice(0,200),contextSnapshot:e.slice(-3).map(s=>`[${s.role}] ${s.content.slice(0,150)}`).join(`
216
- `)},gp(),ee.currentPeriod}function p9(e){if(!ee.currentPeriod||ee.currentPeriod.endedAt||Zh()!=="active")return null;let n=ee.currentPeriod;return n.endedAt=Date.now(),n.durationMs=n.endedAt-n.startedAt,ee.currentPeriod=null,gp(),n}function OE(e){let t=e.events,n=t.filter(g=>g.type==="task_completed"),r=t.filter(g=>g.type==="task_failed"),s=t.filter(g=>g.type==="error"),i=t.filter(g=>g.type==="notification"),o=t.filter(g=>g.important),a=t.filter(g=>g.type==="file_changed"),c=[...new Set(a.map(g=>g.description))],l=[...r,...s.filter(g=>g.important),...o.filter(g=>!n.includes(g))],u=mp(e.durationMs||0),d=m9(e,n,r,s,c),f=g9(e,t,n,r,s,c,i),p=h9(e),m=y9(c,n,r);return{period:e,duration:u,totalEvents:t.length,importantEvents:o,taskCompletions:n,taskFailures:r,fileChanges:c,errors:s,notifications:i,briefSummary:d,detailedSummary:f,resumeHints:p,whatChanged:m,needsAttention:l,metadata:{eventsAnalyzed:t.length,confidenceScore:.85}}}function mp(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m ${t%60}s`;let r=Math.floor(n/60);return r<24?`${r}h ${n%60}m`:`${Math.floor(r/24)}d ${r%24}h`}function m9(e,t,n,r,s){if(e.events.length===0)return`You were away for ${mp(e.durationMs||0)}. Nothing happened while you were gone.`;let i=[`Away for ${mp(e.durationMs||0)}.`];return t.length>0&&i.push(`${t.length} task(s) completed.`),n.length>0&&i.push(`\u26A0\uFE0F ${n.length} task(s) failed.`),r.length>0&&i.push(`${r.length} error(s) occurred.`),s.length>0&&i.push(`${s.length} file(s) changed.`),i.join(" ")}function g9(e,t,n,r,s,i,o){if(t.length===0)return`You were away for ${mp(e.durationMs||0)}. Your session was idle and no background activity occurred.`;let a=[`You were away for ${mp(e.durationMs||0)}.`,""];if(a.push("While you were gone:"),n.length>0){a.push(`\u2022 ${n.length} task(s) completed successfully:`);for(let c of n.slice(0,5))a.push(` \u2713 ${c.description}`)}if(r.length>0){a.push(`\u2022 ${r.length} task(s) failed:`);for(let c of r.slice(0,5))a.push(` \u2717 ${c.description}`)}if(s.length>0){a.push(`\u2022 ${s.length} error(s) encountered:`);for(let c of s.slice(0,3))a.push(` \u26A0 ${c.description}`)}if(i.length>0&&a.push(`\u2022 ${i.length} file(s) changed: ${i.slice(0,5).join(", ")}${i.length>5?`, +${i.length-5} more`:""}`),o.length>0){a.push(`\u2022 ${o.length} notification(s):`);for(let c of o.slice(0,3))a.push(` \u{1F4EC} ${c.description}`)}return a.join(`
215
+ `)}var BK,Fs,dp,Yh,lp,vk,Sk,up,ln,Ye,Ue,de,jt,yi,Si=w(()=>{"use strict";BK={enabled:!0,maxHistorySize:1e3,maxBranches:50,enableCompression:!0,enableBranching:!0,compressionThreshold:10240,walEnabled:!0,retentionDays:30,autoCleanupOnExit:!1,enableConflictReconciliation:!0},Fs={...BK},dp=Lr(jK(),".aiaca","undo-redo"),Yh=Lr(dp,"blobs"),lp=Lr(dp,"ops"),vk=Lr(dp,"branches.json"),Sk=Lr(dp,"state.json"),up=Lr(dp,"wal.jsonl"),ln=new Map,Ye=new Map,Ue="",jt={totalOperations:0,totalUndos:0,totalRedos:0,totalBranches:0,blobsStored:0,blobsBytes:0,walEntries:0,conflictsResolved:0};NK();yi=null});var Ba={};$(Ba,{checkAndStartAwayPeriod:()=>f9,clearAwayState:()=>x9,detectReturn:()=>p9,formatAsMarkdown:()=>v9,formatBrief:()=>S9,getActivityStats:()=>M9,getAwayConfig:()=>C9,getCurrentIdleState:()=>Zh,getCurrentPeriod:()=>k9,getEventHistory:()=>w9,getIdleDuration:()=>LE,recordActivity:()=>d9,recordBackgroundMessage:()=>I9,recordCronFired:()=>P9,recordError:()=>R9,recordEvent:()=>ja,recordFileChanged:()=>_9,recordTaskCompleted:()=>A9,recordTaskFailed:()=>T9,setAwayConfig:()=>$9,summarizeHeuristic:()=>OE,summarizeWithAI:()=>b9});import{existsSync as r9,mkdirSync as s9,readFileSync as i9,writeFileSync as o9}from"fs";import{join as DE}from"path";import{homedir as a9}from"os";function l9(){s9(FE,{recursive:!0})}function gp(){l9();try{o9($k,JSON.stringify(te,null,2),"utf-8")}catch{}}function u9(){if(r9($k))try{let e=JSON.parse(i9($k,"utf-8"));te={...te,...e}}catch{}}function d9(){let e=Date.now();te.lastActivityAt=e,te.currentPeriod&&!te.currentPeriod.endedAt&&(te.currentPeriod.endedAt=e,te.currentPeriod.durationMs=e-te.currentPeriod.startedAt,gp())}function ja(e){let t={...e,timestamp:Date.now()};te.eventHistory.push(t),te.eventHistory.length>xo.maxEventHistory&&te.eventHistory.shift(),te.currentPeriod&&!te.currentPeriod.endedAt&&te.currentPeriod.events.push(t),gp()}function Zh(){let e=Date.now()-te.lastActivityAt;return e<xo.shortIdleMs?"active":e<xo.awayMs?"short_idle":e<xo.longAwayMs?"away":e<xo.veryLongAwayMs?"long_away":"very_long_away"}function LE(){return Date.now()-te.lastActivityAt}function f9(e){let t=Zh();if(t==="active"||t==="short_idle")return null;if(te.currentPeriod&&!te.currentPeriod.endedAt)return te.currentPeriod;let n=[...e].reverse().find(s=>s.role==="user"&&!s.content.startsWith("<tool_result")),r=[...e].reverse().find(s=>s.role==="assistant"&&s.content.trim());return te.currentPeriod={startedAt:te.lastActivityAt,detectedAt:Date.now(),idleState:t,events:[],lastUserMessage:n?.content?.slice(0,200),lastAssistantMessage:r?.content?.slice(0,200),contextSnapshot:e.slice(-3).map(s=>`[${s.role}] ${s.content.slice(0,150)}`).join(`
216
+ `)},gp(),te.currentPeriod}function p9(e){if(!te.currentPeriod||te.currentPeriod.endedAt||Zh()!=="active")return null;let n=te.currentPeriod;return n.endedAt=Date.now(),n.durationMs=n.endedAt-n.startedAt,te.currentPeriod=null,gp(),n}function OE(e){let t=e.events,n=t.filter(g=>g.type==="task_completed"),r=t.filter(g=>g.type==="task_failed"),s=t.filter(g=>g.type==="error"),i=t.filter(g=>g.type==="notification"),o=t.filter(g=>g.important),a=t.filter(g=>g.type==="file_changed"),c=[...new Set(a.map(g=>g.description))],l=[...r,...s.filter(g=>g.important),...o.filter(g=>!n.includes(g))],u=mp(e.durationMs||0),d=m9(e,n,r,s,c),f=g9(e,t,n,r,s,c,i),p=h9(e),m=y9(c,n,r);return{period:e,duration:u,totalEvents:t.length,importantEvents:o,taskCompletions:n,taskFailures:r,fileChanges:c,errors:s,notifications:i,briefSummary:d,detailedSummary:f,resumeHints:p,whatChanged:m,needsAttention:l,metadata:{eventsAnalyzed:t.length,confidenceScore:.85}}}function mp(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m ${t%60}s`;let r=Math.floor(n/60);return r<24?`${r}h ${n%60}m`:`${Math.floor(r/24)}d ${r%24}h`}function m9(e,t,n,r,s){if(e.events.length===0)return`You were away for ${mp(e.durationMs||0)}. Nothing happened while you were gone.`;let i=[`Away for ${mp(e.durationMs||0)}.`];return t.length>0&&i.push(`${t.length} task(s) completed.`),n.length>0&&i.push(`\u26A0\uFE0F ${n.length} task(s) failed.`),r.length>0&&i.push(`${r.length} error(s) occurred.`),s.length>0&&i.push(`${s.length} file(s) changed.`),i.join(" ")}function g9(e,t,n,r,s,i,o){if(t.length===0)return`You were away for ${mp(e.durationMs||0)}. Your session was idle and no background activity occurred.`;let a=[`You were away for ${mp(e.durationMs||0)}.`,""];if(a.push("While you were gone:"),n.length>0){a.push(`\u2022 ${n.length} task(s) completed successfully:`);for(let c of n.slice(0,5))a.push(` \u2713 ${c.description}`)}if(r.length>0){a.push(`\u2022 ${r.length} task(s) failed:`);for(let c of r.slice(0,5))a.push(` \u2717 ${c.description}`)}if(s.length>0){a.push(`\u2022 ${s.length} error(s) encountered:`);for(let c of s.slice(0,3))a.push(` \u26A0 ${c.description}`)}if(i.length>0&&a.push(`\u2022 ${i.length} file(s) changed: ${i.slice(0,5).join(", ")}${i.length>5?`, +${i.length-5} more`:""}`),o.length>0){a.push(`\u2022 ${o.length} notification(s):`);for(let c of o.slice(0,3))a.push(` \u{1F4EC} ${c.description}`)}return a.join(`
217
217
  `)}function h9(e){let t=[];return e.lastUserMessage&&t.push(`Last thing you said: "${e.lastUserMessage.slice(0,100)}${e.lastUserMessage.length>100?"...":""}"`),e.lastAssistantMessage&&t.push(`Last response: "${e.lastAssistantMessage.slice(0,100)}${e.lastAssistantMessage.length>100?"...":""}"`),t.push("Type /context to see full context, or continue with your next request."),t}function y9(e,t,n){let r=[];return e.length>0&&r.push(`Files: ${e.length} modified`),t.length>0&&r.push(`Tasks: ${t.length} completed`),n.length>0&&r.push(`Tasks: ${n.length} failed`),r}async function b9(e,t){let n=OE(e);if(e.events.length===0)return n;let r=e.events.slice(-30).map(i=>`[${new Date(i.timestamp).toISOString().slice(11,19)}] ${i.type}: ${i.description}${i.important?" \u26A1":""}`).join(`
218
218
  `),s=`Summarize what happened while the user was away from their AI coding session.
219
219
 
@@ -229,9 +229,9 @@ Generate a concise, human-friendly summary in 2-3 sentences that:
229
229
  3. Suggests where to resume if their work was interrupted
230
230
 
231
231
  Return ONLY the summary text, no preamble, no markdown.`;try{let o=(await t.sendMessage([{role:"user",content:s,timestamp:new Date().toISOString()}],"You write concise, friendly catchup summaries for users returning to a coding session.",[],void 0)).content.trim().slice(0,500);return{...n,detailedSummary:o,metadata:{...n.metadata,confidenceScore:.95}}}catch{return n}}function v9(e){let t=[];if(t.push("# \u{1F44B} Welcome back!"),t.push(""),t.push(`**Away duration:** ${e.duration}`),t.push(""),t.push("## Summary"),t.push(e.detailedSummary),t.push(""),e.needsAttention.length>0){t.push("## \u26A0\uFE0F Needs Your Attention");for(let n of e.needsAttention.slice(0,5))t.push(`- ${n.description}`);t.push("")}if(e.taskCompletions.length>0){t.push("## \u2705 Completed Tasks");for(let n of e.taskCompletions.slice(0,10))t.push(`- ${n.description}`);t.push("")}if(e.taskFailures.length>0){t.push("## \u274C Failed Tasks");for(let n of e.taskFailures.slice(0,10))t.push(`- ${n.description}`);t.push("")}if(e.fileChanges.length>0){t.push("## \u{1F4DD} File Changes");for(let n of e.fileChanges.slice(0,15))t.push(`- ${n}`);e.fileChanges.length>15&&t.push(`- *...and ${e.fileChanges.length-15} more*`),t.push("")}if(e.resumeHints.length>0){t.push("## \u{1F4CD} Where you left off");for(let n of e.resumeHints)t.push(`- ${n}`)}return t.join(`
232
- `)}function S9(e){return e.briefSummary}function w9(e=50){return ee.eventHistory.slice(-e)}function k9(){return ee.currentPeriod}function x9(){ee={lastActivityAt:Date.now(),currentPeriod:null,eventHistory:[]},gp()}function $9(e){xo={...xo,...e}}function C9(){return{...xo}}function A9(e,t){ja({type:"task_completed",description:e,important:!1,metadata:t?{durationMs:t}:void 0})}function T9(e,t){ja({type:"task_failed",description:`${e}: ${t}`,important:!0,metadata:{error:t}})}function _9(e,t){ja({type:"file_changed",description:`${t}: ${e}`,important:!1,metadata:{filePath:e,operation:t}})}function R9(e,t){ja({type:"error",description:`${e}: ${t.slice(0,200)}`,important:!0,metadata:{source:e,message:t}})}function P9(e){ja({type:"cron_fired",description:`Cron job: ${e}`,important:!1,metadata:{cronName:e}})}function I9(e,t){ja({type:"background_message",description:`From ${e}: ${t.slice(0,150)}`,important:!0,metadata:{from:e,content:t}})}function M9(){let e={},t=0;for(let n of ee.eventHistory)e[n.type]=(e[n.type]||0)+1,n.important&&t++;return{currentIdleState:Zh(),idleDurationMs:LE(),totalEvents:ee.eventHistory.length,byType:e,importantEventCount:t,awayInProgress:ee.currentPeriod!==null&&!ee.currentPeriod.endedAt}}var c9,xo,FE,$k,ee,Na=w(()=>{"use strict";c9={shortIdleMs:300*1e3,awayMs:900*1e3,longAwayMs:3600*1e3,veryLongAwayMs:360*60*1e3,maxEventHistory:500,trackFileChanges:!0,trackBackgroundTasks:!0},xo={...c9},FE=DE(a9(),".aiaca","away"),$k=DE(FE,"state.json"),ee={lastActivityAt:Date.now(),currentPeriod:null,eventHistory:[]};u9()});var Ua={};$(Ua,{clearMemoCache:()=>e7,coalesceProviderRequest:()=>r7,configure:()=>Z9,endTurn:()=>W9,executeBatched:()=>z9,getBatchStats:()=>Y9,getConfig:()=>Q9,getMemoCacheEntries:()=>n7,getProviderCoalescingSize:()=>s7,invalidateByPath:()=>U9,invalidateByTool:()=>H9,pruneMemoCache:()=>t7,resetStats:()=>X9,startTurn:()=>J9});import{createHash as E9}from"crypto";import{existsSync as BE,mkdirSync as D9,readFileSync as F9,writeFileSync as NE,statSync as L9}from"fs";import{join as qE,resolve as Ak}from"path";import{homedir as O9}from"os";function zE(){D9(UE,{recursive:!0})}function N9(){if(zE(),!!BE(hp))try{let e=JSON.parse(F9(hp,"utf-8"));for(let[t,n]of Object.entries(e))Date.now()-n.cachedAt<n.ttlMs&&Dn.set(t,n)}catch{}}function Rk(){zE();try{let e={};for(let[t,n]of Dn)e[t]=n;NE(hp,JSON.stringify(e),"utf-8")}catch{}}function GE(e,t){let n=Tk(t);return`${e}::${E9("sha256").update(n).digest("hex").slice(0,24)}`}function Tk(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Tk).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Tk(e[n])}`).join(",")}}`}function VE(e){return wn.perToolTTL[e]??wn.memoTTLMs}function JE(e){return Date.now()-e.cachedAt>e.ttlMs}function q9(e){return wn.enableStaleRevalidate?Date.now()-e.cachedAt>e.ttlMs*.5:!1}function WE(e){let t=[],n=e.input.path;typeof n=="string"&&t.push(Ak(n));let r=e.input.paths;if(Array.isArray(r))for(let s of r)typeof s=="string"&&t.push(Ak(s));return t}function KE(e){if(wn.invalidationStrategy==="ttl_only"||e.invalidationKeys.length===0)return!1;for(let t of e.invalidationKeys)try{if(L9(t).mtimeMs>e.cachedAt)return!0}catch{return!0}return!1}function U9(e){let t=Ak(e),n=0;for(let[r,s]of Dn)s.invalidationKeys.includes(t)&&(Dn.delete(r),n++);return n}function H9(e){let t=0;for(let[n]of Dn)n.startsWith(`${e}::`)&&(Dn.delete(n),t++);return t}async function z9(e,t,n={}){if(!wn.enabled)return ty(e,t);N.totalRequests++,qa(e.name,"request");let r=n.priority??5,s=GE(e.name,e.input);if(wn.enableTurnDedup&&!n.forceFresh){let a=ey.get(s);if(a)return N.totalDeduped++,qa(e.name,"dedup"),{...await a,toolCallId:e.id}}if(wn.enableSessionMemo&&!n.bypassMemo&&!n.forceFresh){let a=Dn.get(s);if(a){let c=KE(a),l=JE(a);if(!c&&!l)return a.hits++,N.totalMemoHits++,N.totalLatencyAvoidedMs+=a.result.durationMs||0,qa(e.name,"memo_hit"),q9(a)&&setImmediate(()=>jE(e,t,s).catch(()=>{})),{...a.result,toolCallId:e.id};if(c)Dn.delete(s);else if(l){if(N.totalMemoStale++,wn.enableStaleRevalidate)return qa(e.name,"memo_stale"),setImmediate(()=>jE(e,t,s).catch(()=>{})),{...a.result,toolCallId:e.id};Dn.delete(s)}}N.totalMemoMisses++}let i=r>=wn.priorityThreshold?ty(e,t):G9(e,t,r);wn.enableTurnDedup&&ey.set(s,i);let o=await i;if(wn.enableSessionMemo&&!o.isError&&!n.forceFresh){let a=VE(e.name),c=n.invalidationKeys??WE(e);Dn.set(s,{result:o,cachedAt:Date.now(),ttlMs:a,hits:0,invalidationKeys:c}),queueMicrotask(()=>Rk())}return o}async function jE(e,t,n){try{let r=await ty(e,t);if(!r.isError){let s=VE(e.name);Dn.set(n,{result:r,cachedAt:Date.now(),ttlMs:s,hits:0,invalidationKeys:WE(e)})}}catch{}}function G9(e,t,n){return new Promise((r,s)=>{$o.push({toolCall:e,context:t,enqueuedAt:Date.now(),priority:n,resolve:r,reject:s}),B9=Date.now(),V9()})}function V9(){if(!Ck){if($o.length>=wn.maxQueueDepth){_k();return}Ck=setTimeout(()=>{Ck=null,_k()},wn.windowMs)}}async function _k(){if($o.length===0)return;let e=$o.splice(0,$o.length);e.length>N.largestBatch&&(N.largestBatch=e.length),N.totalBatched+=e.length,e.sort((n,r)=>r.priority-n.priority);let t=new Map;for(let n of e){let r=GE(n.toolCall.name,n.toolCall.input);t.has(r)||t.set(r,[]),t.get(r).push(n)}await Promise.all(Array.from(t.entries()).map(async([n,r])=>{r.length>1&&(N.totalDeduped+=r.length-1,qa(r[0].toolCall.name,"dedup",r.length-1));try{let s=await ty(r[0].toolCall,r[0].context);for(let i of r)i.resolve({...s,toolCallId:i.toolCall.id})}catch(s){for(let i of r)i.reject(s)}}))}async function ty(e,t){let n=wr(e.name);if(!n)return{toolCallId:e.id,output:`Error: Tool "${e.name}" not found.`,isError:!0,durationMs:0};let r=Date.now();try{let s=await n.handler(e.input,t),i=Date.now()-r;return qa(e.name,"execute",1,i),{toolCallId:e.id,output:s,durationMs:i}}catch(s){let i=Date.now()-r;return qa(e.name,"execute",1,i),{toolCallId:e.id,output:`Error: ${s.message||String(s)}`,isError:!0,durationMs:i}}}function qa(e,t,n=1,r=0){let s=N.perToolStats.get(e);s||(s={requests:0,deduped:0,memoHits:0,totalLatencyMs:0,avgLatencyMs:0,hitRate:0},N.perToolStats.set(e,s)),t==="request"&&s.requests++,t==="dedup"&&(s.deduped+=n),t==="memo_hit"&&s.memoHits++,t==="execute"&&(s.totalLatencyMs+=r,s.avgLatencyMs=s.requests>0?s.totalLatencyMs/s.requests:0),s.hitRate=s.requests>0?(s.deduped+s.memoHits)/s.requests:0}function J9(e){HE=e||`turn-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ey.clear()}function W9(){$o.length>0&&_k(),ey.clear(),HE=""}function K9(){let n=(N.totalDeduped+N.totalMemoHits)*500,r=n/1e6*3;return{tokens:n,usd:r}}function Y9(){let e=N.totalMemoHits+N.totalMemoMisses,t=e>0?N.totalMemoHits/e:0,n={};for(let[o,a]of N.perToolStats)n[o]={...a};let r=Date.now(),s=0;for(let o of Dn.values())o.cachedAt<r&&(r=o.cachedAt),s+=JSON.stringify(o.result).length;let i=K9();return{totalRequests:N.totalRequests,totalBatched:N.totalBatched,totalDeduped:N.totalDeduped,totalMemoHits:N.totalMemoHits,totalMemoMisses:N.totalMemoMisses,totalMemoStale:N.totalMemoStale,averageBatchSize:N.totalBatched>0?N.totalBatched/Math.max(1,Math.floor(N.totalRequests/wn.maxBatchSize)):0,totalRoundTripsSaved:N.totalDeduped+N.totalMemoHits,totalLatencyAvoidedMs:N.totalLatencyAvoidedMs,totalCostSavedUSD:i.usd,totalTokensSaved:i.tokens,perToolStats:n,largestBatch:N.largestBatch,oldestEntry:r,cacheSize:s}}function Q9(){return{...wn}}function Z9(e){wn={...wn,...e}}function X9(){N.totalRequests=0,N.totalBatched=0,N.totalDeduped=0,N.totalMemoHits=0,N.totalMemoMisses=0,N.totalMemoStale=0,N.totalLatencyAvoidedMs=0,N.largestBatch=0,N.perToolStats.clear()}function e7(){Dn.clear();try{BE(hp)&&NE(hp,"{}","utf-8")}catch{}}function t7(){let e=0;for(let[t,n]of Dn)(JE(n)||KE(n))&&(Dn.delete(t),e++);return e>0&&Rk(),e}function n7(){return Array.from(Dn.entries()).map(([e,t])=>({key:e,entry:t}))}async function r7(e,t,n=5e3){let r=Xh.get(e);if(r&&Date.now()-r.enqueuedAt<n)return r.promise;let s=t();return Xh.set(e,{promptHash:e,promise:s,enqueuedAt:Date.now()}),s.finally(()=>{setTimeout(()=>Xh.delete(e),n)}),s}function s7(){return Xh.size}var j9,UE,hp,wn,$o,Ck,B9,Dn,HE,ey,N,Xh,Ha=w(()=>{"use strict";Ls();j9={enabled:!0,strategy:"hybrid",windowMs:50,maxBatchSize:20,maxBatchBytes:1024*1024,maxQueueDepth:100,flushOnIdle:!0,enableTurnDedup:!0,enableSessionMemo:!0,memoTTLMs:300*1e3,enableStaleRevalidate:!0,perToolTTL:{web_fetch:600*1e3,web_search:3600*1e3,file_read:30*1e3,grep:60*1e3,glob:300*1e3,code_search:300*1e3,code_references:300*1e3,image_read:1800*1e3},invalidationStrategy:"mtime",priorityThreshold:8,debug:!1},UE=qE(O9(),".aiaca","request-batch"),hp=qE(UE,"memoization.json"),wn={...j9},$o=[],Ck=null,B9=0,Dn=new Map,HE="",ey=new Map,N={totalRequests:0,totalBatched:0,totalDeduped:0,totalMemoHits:0,totalMemoMisses:0,totalMemoStale:0,totalLatencyAvoidedMs:0,largestBatch:0,perToolStats:new Map};N9();Xh=new Map;process.on("exit",()=>{if($o.length>0)for(let e of $o)e.resolve({toolCallId:e.toolCall.id,output:"Cancelled at shutdown",isError:!0,durationMs:0});Rk()})});var jr={};$(jr,{clearIndex:()=>j7,getAllReferences:()=>U7,getAllSymbols:()=>q7,getCurrentProjectPath:()=>N7,getDependencies:()=>F7,getDependents:()=>L7,getFile:()=>M7,getReferencesTo:()=>D7,getStats:()=>ZE,getSymbol:()=>P7,getSymbolByName:()=>I7,getSymbolSnippet:()=>O7,getSymbolsInFile:()=>E7,indexProject:()=>$7,isIndexed:()=>B7,loadProject:()=>A7,searchSymbols:()=>R7});import{readFileSync as Mk,writeFileSync as i7,existsSync as ny,mkdirSync as o7,statSync as Pk,readdirSync as a7,unlinkSync as c7}from"fs";import{join as Ga,relative as l7,extname as u7}from"path";import{homedir as d7}from"os";import{createHash as Or}from"crypto";import{glob as f7}from"glob";function h7(e){return Or("sha256").update(e).digest("hex").slice(0,16)}function au(e){return Ga(p7,h7(e))}function YE(e){o7(au(e),{recursive:!0})}function y7(e){let t=u7(e).toLowerCase();return m7[t]||"unknown"}function b7(e,t){switch(t.language){case"typescript":case"javascript":return v7(e,t);case"python":return S7(e,t);case"java":return w7(e,t);case"go":return k7(e,t);case"rust":return x7(e,t);default:return{symbols:[],imports:[],exports:[],references:[]}}}function as(e,t,n){return Or("md5").update(`${e}:${t}:${n}`).digest("hex").slice(0,16)}function Ik(e,t){let n=[];for(let r=t-1;r>=0;r--){let s=e[r].trim();if(!(s===""&&n.length===0))if(s.startsWith("//"))n.unshift(s.replace(/^\/\/\s?/,""));else if(s.endsWith("*/")){for(let i=r;i>=0;i--){let o=e[i].trim();if(n.unshift(o.replace(/^\/?\*+\s?/,"").replace(/\s*\*+\/$/,"")),o.startsWith("/**")||o.startsWith("/*"))break}break}else break}return n.length>0?n.join(`
232
+ `)}function S9(e){return e.briefSummary}function w9(e=50){return te.eventHistory.slice(-e)}function k9(){return te.currentPeriod}function x9(){te={lastActivityAt:Date.now(),currentPeriod:null,eventHistory:[]},gp()}function $9(e){xo={...xo,...e}}function C9(){return{...xo}}function A9(e,t){ja({type:"task_completed",description:e,important:!1,metadata:t?{durationMs:t}:void 0})}function T9(e,t){ja({type:"task_failed",description:`${e}: ${t}`,important:!0,metadata:{error:t}})}function _9(e,t){ja({type:"file_changed",description:`${t}: ${e}`,important:!1,metadata:{filePath:e,operation:t}})}function R9(e,t){ja({type:"error",description:`${e}: ${t.slice(0,200)}`,important:!0,metadata:{source:e,message:t}})}function P9(e){ja({type:"cron_fired",description:`Cron job: ${e}`,important:!1,metadata:{cronName:e}})}function I9(e,t){ja({type:"background_message",description:`From ${e}: ${t.slice(0,150)}`,important:!0,metadata:{from:e,content:t}})}function M9(){let e={},t=0;for(let n of te.eventHistory)e[n.type]=(e[n.type]||0)+1,n.important&&t++;return{currentIdleState:Zh(),idleDurationMs:LE(),totalEvents:te.eventHistory.length,byType:e,importantEventCount:t,awayInProgress:te.currentPeriod!==null&&!te.currentPeriod.endedAt}}var c9,xo,FE,$k,te,Na=w(()=>{"use strict";c9={shortIdleMs:300*1e3,awayMs:900*1e3,longAwayMs:3600*1e3,veryLongAwayMs:360*60*1e3,maxEventHistory:500,trackFileChanges:!0,trackBackgroundTasks:!0},xo={...c9},FE=DE(a9(),".aiaca","away"),$k=DE(FE,"state.json"),te={lastActivityAt:Date.now(),currentPeriod:null,eventHistory:[]};u9()});var Ua={};$(Ua,{clearMemoCache:()=>e7,coalesceProviderRequest:()=>r7,configure:()=>Z9,endTurn:()=>W9,executeBatched:()=>z9,getBatchStats:()=>Y9,getConfig:()=>Q9,getMemoCacheEntries:()=>n7,getProviderCoalescingSize:()=>s7,invalidateByPath:()=>U9,invalidateByTool:()=>H9,pruneMemoCache:()=>t7,resetStats:()=>X9,startTurn:()=>J9});import{createHash as E9}from"crypto";import{existsSync as BE,mkdirSync as D9,readFileSync as F9,writeFileSync as NE,statSync as L9}from"fs";import{join as qE,resolve as Ak}from"path";import{homedir as O9}from"os";function zE(){D9(UE,{recursive:!0})}function N9(){if(zE(),!!BE(hp))try{let e=JSON.parse(F9(hp,"utf-8"));for(let[t,n]of Object.entries(e))Date.now()-n.cachedAt<n.ttlMs&&Dn.set(t,n)}catch{}}function Rk(){zE();try{let e={};for(let[t,n]of Dn)e[t]=n;NE(hp,JSON.stringify(e),"utf-8")}catch{}}function GE(e,t){let n=Tk(t);return`${e}::${E9("sha256").update(n).digest("hex").slice(0,24)}`}function Tk(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Tk).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Tk(e[n])}`).join(",")}}`}function VE(e){return wn.perToolTTL[e]??wn.memoTTLMs}function JE(e){return Date.now()-e.cachedAt>e.ttlMs}function q9(e){return wn.enableStaleRevalidate?Date.now()-e.cachedAt>e.ttlMs*.5:!1}function WE(e){let t=[],n=e.input.path;typeof n=="string"&&t.push(Ak(n));let r=e.input.paths;if(Array.isArray(r))for(let s of r)typeof s=="string"&&t.push(Ak(s));return t}function KE(e){if(wn.invalidationStrategy==="ttl_only"||e.invalidationKeys.length===0)return!1;for(let t of e.invalidationKeys)try{if(L9(t).mtimeMs>e.cachedAt)return!0}catch{return!0}return!1}function U9(e){let t=Ak(e),n=0;for(let[r,s]of Dn)s.invalidationKeys.includes(t)&&(Dn.delete(r),n++);return n}function H9(e){let t=0;for(let[n]of Dn)n.startsWith(`${e}::`)&&(Dn.delete(n),t++);return t}async function z9(e,t,n={}){if(!wn.enabled)return ty(e,t);N.totalRequests++,qa(e.name,"request");let r=n.priority??5,s=GE(e.name,e.input);if(wn.enableTurnDedup&&!n.forceFresh){let a=ey.get(s);if(a)return N.totalDeduped++,qa(e.name,"dedup"),{...await a,toolCallId:e.id}}if(wn.enableSessionMemo&&!n.bypassMemo&&!n.forceFresh){let a=Dn.get(s);if(a){let c=KE(a),l=JE(a);if(!c&&!l)return a.hits++,N.totalMemoHits++,N.totalLatencyAvoidedMs+=a.result.durationMs||0,qa(e.name,"memo_hit"),q9(a)&&setImmediate(()=>jE(e,t,s).catch(()=>{})),{...a.result,toolCallId:e.id};if(c)Dn.delete(s);else if(l){if(N.totalMemoStale++,wn.enableStaleRevalidate)return qa(e.name,"memo_stale"),setImmediate(()=>jE(e,t,s).catch(()=>{})),{...a.result,toolCallId:e.id};Dn.delete(s)}}N.totalMemoMisses++}let i=r>=wn.priorityThreshold?ty(e,t):G9(e,t,r);wn.enableTurnDedup&&ey.set(s,i);let o=await i;if(wn.enableSessionMemo&&!o.isError&&!n.forceFresh){let a=VE(e.name),c=n.invalidationKeys??WE(e);Dn.set(s,{result:o,cachedAt:Date.now(),ttlMs:a,hits:0,invalidationKeys:c}),queueMicrotask(()=>Rk())}return o}async function jE(e,t,n){try{let r=await ty(e,t);if(!r.isError){let s=VE(e.name);Dn.set(n,{result:r,cachedAt:Date.now(),ttlMs:s,hits:0,invalidationKeys:WE(e)})}}catch{}}function G9(e,t,n){return new Promise((r,s)=>{$o.push({toolCall:e,context:t,enqueuedAt:Date.now(),priority:n,resolve:r,reject:s}),B9=Date.now(),V9()})}function V9(){if(!Ck){if($o.length>=wn.maxQueueDepth){_k();return}Ck=setTimeout(()=>{Ck=null,_k()},wn.windowMs)}}async function _k(){if($o.length===0)return;let e=$o.splice(0,$o.length);e.length>N.largestBatch&&(N.largestBatch=e.length),N.totalBatched+=e.length,e.sort((n,r)=>r.priority-n.priority);let t=new Map;for(let n of e){let r=GE(n.toolCall.name,n.toolCall.input);t.has(r)||t.set(r,[]),t.get(r).push(n)}await Promise.all(Array.from(t.entries()).map(async([n,r])=>{r.length>1&&(N.totalDeduped+=r.length-1,qa(r[0].toolCall.name,"dedup",r.length-1));try{let s=await ty(r[0].toolCall,r[0].context);for(let i of r)i.resolve({...s,toolCallId:i.toolCall.id})}catch(s){for(let i of r)i.reject(s)}}))}async function ty(e,t){let n=wr(e.name);if(!n)return{toolCallId:e.id,output:`Error: Tool "${e.name}" not found.`,isError:!0,durationMs:0};let r=Date.now();try{let s=await n.handler(e.input,t),i=Date.now()-r;return qa(e.name,"execute",1,i),{toolCallId:e.id,output:s,durationMs:i}}catch(s){let i=Date.now()-r;return qa(e.name,"execute",1,i),{toolCallId:e.id,output:`Error: ${s.message||String(s)}`,isError:!0,durationMs:i}}}function qa(e,t,n=1,r=0){let s=N.perToolStats.get(e);s||(s={requests:0,deduped:0,memoHits:0,totalLatencyMs:0,avgLatencyMs:0,hitRate:0},N.perToolStats.set(e,s)),t==="request"&&s.requests++,t==="dedup"&&(s.deduped+=n),t==="memo_hit"&&s.memoHits++,t==="execute"&&(s.totalLatencyMs+=r,s.avgLatencyMs=s.requests>0?s.totalLatencyMs/s.requests:0),s.hitRate=s.requests>0?(s.deduped+s.memoHits)/s.requests:0}function J9(e){HE=e||`turn-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ey.clear()}function W9(){$o.length>0&&_k(),ey.clear(),HE=""}function K9(){let n=(N.totalDeduped+N.totalMemoHits)*500,r=n/1e6*3;return{tokens:n,usd:r}}function Y9(){let e=N.totalMemoHits+N.totalMemoMisses,t=e>0?N.totalMemoHits/e:0,n={};for(let[o,a]of N.perToolStats)n[o]={...a};let r=Date.now(),s=0;for(let o of Dn.values())o.cachedAt<r&&(r=o.cachedAt),s+=JSON.stringify(o.result).length;let i=K9();return{totalRequests:N.totalRequests,totalBatched:N.totalBatched,totalDeduped:N.totalDeduped,totalMemoHits:N.totalMemoHits,totalMemoMisses:N.totalMemoMisses,totalMemoStale:N.totalMemoStale,averageBatchSize:N.totalBatched>0?N.totalBatched/Math.max(1,Math.floor(N.totalRequests/wn.maxBatchSize)):0,totalRoundTripsSaved:N.totalDeduped+N.totalMemoHits,totalLatencyAvoidedMs:N.totalLatencyAvoidedMs,totalCostSavedUSD:i.usd,totalTokensSaved:i.tokens,perToolStats:n,largestBatch:N.largestBatch,oldestEntry:r,cacheSize:s}}function Q9(){return{...wn}}function Z9(e){wn={...wn,...e}}function X9(){N.totalRequests=0,N.totalBatched=0,N.totalDeduped=0,N.totalMemoHits=0,N.totalMemoMisses=0,N.totalMemoStale=0,N.totalLatencyAvoidedMs=0,N.largestBatch=0,N.perToolStats.clear()}function e7(){Dn.clear();try{BE(hp)&&NE(hp,"{}","utf-8")}catch{}}function t7(){let e=0;for(let[t,n]of Dn)(JE(n)||KE(n))&&(Dn.delete(t),e++);return e>0&&Rk(),e}function n7(){return Array.from(Dn.entries()).map(([e,t])=>({key:e,entry:t}))}async function r7(e,t,n=5e3){let r=Xh.get(e);if(r&&Date.now()-r.enqueuedAt<n)return r.promise;let s=t();return Xh.set(e,{promptHash:e,promise:s,enqueuedAt:Date.now()}),s.finally(()=>{setTimeout(()=>Xh.delete(e),n)}),s}function s7(){return Xh.size}var j9,UE,hp,wn,$o,Ck,B9,Dn,HE,ey,N,Xh,Ha=w(()=>{"use strict";Ls();j9={enabled:!0,strategy:"hybrid",windowMs:50,maxBatchSize:20,maxBatchBytes:1024*1024,maxQueueDepth:100,flushOnIdle:!0,enableTurnDedup:!0,enableSessionMemo:!0,memoTTLMs:300*1e3,enableStaleRevalidate:!0,perToolTTL:{web_fetch:600*1e3,web_search:3600*1e3,file_read:30*1e3,grep:60*1e3,glob:300*1e3,code_search:300*1e3,code_references:300*1e3,image_read:1800*1e3},invalidationStrategy:"mtime",priorityThreshold:8,debug:!1},UE=qE(O9(),".aiaca","request-batch"),hp=qE(UE,"memoization.json"),wn={...j9},$o=[],Ck=null,B9=0,Dn=new Map,HE="",ey=new Map,N={totalRequests:0,totalBatched:0,totalDeduped:0,totalMemoHits:0,totalMemoMisses:0,totalMemoStale:0,totalLatencyAvoidedMs:0,largestBatch:0,perToolStats:new Map};N9();Xh=new Map;process.on("exit",()=>{if($o.length>0)for(let e of $o)e.resolve({toolCallId:e.toolCall.id,output:"Cancelled at shutdown",isError:!0,durationMs:0});Rk()})});var jr={};$(jr,{clearIndex:()=>j7,getAllReferences:()=>U7,getAllSymbols:()=>q7,getCurrentProjectPath:()=>N7,getDependencies:()=>F7,getDependents:()=>L7,getFile:()=>M7,getReferencesTo:()=>D7,getStats:()=>ZE,getSymbol:()=>P7,getSymbolByName:()=>I7,getSymbolSnippet:()=>O7,getSymbolsInFile:()=>E7,indexProject:()=>$7,isIndexed:()=>B7,loadProject:()=>A7,searchSymbols:()=>R7});import{readFileSync as Mk,writeFileSync as i7,existsSync as ny,mkdirSync as o7,statSync as Pk,readdirSync as a7,unlinkSync as c7}from"fs";import{join as Ga,relative as l7,extname as u7}from"path";import{homedir as d7}from"os";import{createHash as Or}from"crypto";import{glob as f7}from"glob";function h7(e){return Or("sha256").update(e).digest("hex").slice(0,16)}function au(e){return Ga(p7,h7(e))}function YE(e){o7(au(e),{recursive:!0})}function y7(e){let t=u7(e).toLowerCase();return m7[t]||"unknown"}function b7(e,t){switch(t.language){case"typescript":case"javascript":return v7(e,t);case"python":return S7(e,t);case"java":return w7(e,t);case"go":return k7(e,t);case"rust":return x7(e,t);default:return{symbols:[],imports:[],exports:[],references:[]}}}function as(e,t,n){return Or("md5").update(`${e}:${t}:${n}`).digest("hex").slice(0,16)}function Ik(e,t){let n=[];for(let r=t-1;r>=0;r--){let s=e[r].trim();if(!(s===""&&n.length===0))if(s.startsWith("//"))n.unshift(s.replace(/^\/\/\s?/,""));else if(s.endsWith("*/")){for(let i=r;i>=0;i--){let o=e[i].trim();if(n.unshift(o.replace(/^\/?\*+\s?/,"").replace(/\s*\*+\/$/,"")),o.startsWith("/**")||o.startsWith("/*"))break}break}else break}return n.length>0?n.join(`
233
233
  `).trim():void 0}function v7(e,t){let n=[],r=[],s=[],i=[],o=e.split(`
234
- `),a=[{regex:/^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)/,kind:"function"},{regex:/^(\s*)(export\s+)?(?:const|let|var)\s+(\w+)\s*[:=]\s*(?:async\s+)?(?:\([^)]*\)|\w+)\s*=>/,kind:"function",nameIdx:3},{regex:/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?(?:\s+implements\s+([^{]+))?/,kind:"class"},{regex:/^(\s*)(export\s+)?interface\s+(\w+)(?:\s+extends\s+([^{]+))?/,kind:"interface",nameIdx:3},{regex:/^(\s*)(export\s+)?type\s+(\w+)\s*[=<]/,kind:"type",nameIdx:3},{regex:/^(\s*)(export\s+)?(?:const\s+)?enum\s+(\w+)/,kind:"enum",nameIdx:3},{regex:/^(\s+)(public\s+|private\s+|protected\s+|static\s+|async\s+|readonly\s+)*(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)\s*[:{]/,kind:"method",nameIdx:3},{regex:/^(\s*)(export\s+)?const\s+(\w+)\s*[:=]/,kind:"constant",nameIdx:3}],c=null,l=-1;for(let u=0;u<o.length;u++){let d=o[u],f=d.match(/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)/);f?(c=f[4],l=f[1].length):c&&d.trim()==="}"&&d.match(/^\s*}/)?.[0].length===l+1&&(c=null);let p=d.match(/^import\s+(?:type\s+)?(?:\{[^}]+\}|\*\s+as\s+\w+|\w+)\s+from\s+['"]([^'"]+)['"]/);if(p){r.push(p[1]);continue}let m=d.match(/^export\s+(?:\{[^}]+\}|\*)\s+from\s+['"]([^'"]+)['"]/);if(m){r.push(m[1]);continue}for(let{regex:h,kind:v,nameIdx:y}of a){let b=d.match(h);if(!b)continue;let S=b[y??4];if(!S||S==="function"||S==="class"||(b[2]?.includes("export")&&s.push(S),v==="method"&&!c)||v==="method"&&!d.match(/[):]/))continue;let A=[];b[2]?.includes("export")&&A.push("export"),b[3]?.includes("async")&&A.push("async"),b[3]?.includes("abstract")&&A.push("abstract"),d.includes("static")&&A.push("static"),d.includes("private")&&A.push("private"),d.includes("public")&&A.push("public"),d.includes("protected")&&A.push("protected"),d.includes("readonly")&&A.push("readonly");let j=as(t.filePath,S,u+1),I=Ik(o,u),ye=d.trim().replace(/\s*\{$/,"").slice(0,200),Ne=d.match(/^\s*/)?.[0].length||0,mn=u+1,nn=0,De=!1;for(let Et=u;Et<o.length&&Et<u+500;Et++){let gn=o[Et];for(let T of gn)T==="{"&&(nn++,De=!0),T==="}"&&nn--;if(De&&nn===0){mn=Et+1;break}}n.push({id:j,name:S,kind:v==="method"&&c||v==="function"&&c?"method":v,language:t.language,filePath:t.filePath,relativePath:t.relativePath,startLine:u+1,endLine:mn,signature:ye,docComment:I,parent:c?as(t.filePath,c,0):void 0,modifiers:A,references:0,lastModified:t.mtime,hash:Or("md5").update(d).digest("hex").slice(0,8)});break}let g=d.matchAll(/\b([a-zA-Z_$][\w$]*)\s*\(/g);for(let h of g){let v=h[1];["if","while","for","switch","catch","return","throw","function","typeof","new"].includes(v)||i.push({from:t.filePath,to:v,kind:"call",line:u+1})}}return{symbols:n,imports:r,exports:s,references:i}}function S7(e,t){let n=[],r=[],s=[],i=[],o=e.split(`
234
+ `),a=[{regex:/^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)/,kind:"function"},{regex:/^(\s*)(export\s+)?(?:const|let|var)\s+(\w+)\s*[:=]\s*(?:async\s+)?(?:\([^)]*\)|\w+)\s*=>/,kind:"function",nameIdx:3},{regex:/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?(?:\s+implements\s+([^{]+))?/,kind:"class"},{regex:/^(\s*)(export\s+)?interface\s+(\w+)(?:\s+extends\s+([^{]+))?/,kind:"interface",nameIdx:3},{regex:/^(\s*)(export\s+)?type\s+(\w+)\s*[=<]/,kind:"type",nameIdx:3},{regex:/^(\s*)(export\s+)?(?:const\s+)?enum\s+(\w+)/,kind:"enum",nameIdx:3},{regex:/^(\s+)(public\s+|private\s+|protected\s+|static\s+|async\s+|readonly\s+)*(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)\s*[:{]/,kind:"method",nameIdx:3},{regex:/^(\s*)(export\s+)?const\s+(\w+)\s*[:=]/,kind:"constant",nameIdx:3}],c=null,l=-1;for(let u=0;u<o.length;u++){let d=o[u],f=d.match(/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)/);f?(c=f[4],l=f[1].length):c&&d.trim()==="}"&&d.match(/^\s*}/)?.[0].length===l+1&&(c=null);let p=d.match(/^import\s+(?:type\s+)?(?:\{[^}]+\}|\*\s+as\s+\w+|\w+)\s+from\s+['"]([^'"]+)['"]/);if(p){r.push(p[1]);continue}let m=d.match(/^export\s+(?:\{[^}]+\}|\*)\s+from\s+['"]([^'"]+)['"]/);if(m){r.push(m[1]);continue}for(let{regex:h,kind:v,nameIdx:y}of a){let b=d.match(h);if(!b)continue;let S=b[y??4];if(!S||S==="function"||S==="class"||(b[2]?.includes("export")&&s.push(S),v==="method"&&!c)||v==="method"&&!d.match(/[):]/))continue;let A=[];b[2]?.includes("export")&&A.push("export"),b[3]?.includes("async")&&A.push("async"),b[3]?.includes("abstract")&&A.push("abstract"),d.includes("static")&&A.push("static"),d.includes("private")&&A.push("private"),d.includes("public")&&A.push("public"),d.includes("protected")&&A.push("protected"),d.includes("readonly")&&A.push("readonly");let D=as(t.filePath,S,u+1),M=Ik(o,u),ee=d.trim().replace(/\s*\{$/,"").slice(0,200),Ne=d.match(/^\s*/)?.[0].length||0,mn=u+1,nn=0,De=!1;for(let Et=u;Et<o.length&&Et<u+500;Et++){let gn=o[Et];for(let T of gn)T==="{"&&(nn++,De=!0),T==="}"&&nn--;if(De&&nn===0){mn=Et+1;break}}n.push({id:D,name:S,kind:v==="method"&&c||v==="function"&&c?"method":v,language:t.language,filePath:t.filePath,relativePath:t.relativePath,startLine:u+1,endLine:mn,signature:ee,docComment:M,parent:c?as(t.filePath,c,0):void 0,modifiers:A,references:0,lastModified:t.mtime,hash:Or("md5").update(d).digest("hex").slice(0,8)});break}let g=d.matchAll(/\b([a-zA-Z_$][\w$]*)\s*\(/g);for(let h of g){let v=h[1];["if","while","for","switch","catch","return","throw","function","typeof","new"].includes(v)||i.push({from:t.filePath,to:v,kind:"call",line:u+1})}}return{symbols:n,imports:r,exports:s,references:i}}function S7(e,t){let n=[],r=[],s=[],i=[],o=e.split(`
235
235
  `),a=null,c=-1;for(let l=0;l<o.length;l++){let u=o[l],d=u.match(/^(\s*)class\s+(\w+)/);if(d){let m=d[1].length;m===0&&(a=d[2]),c=m;let g=as(t.filePath,d[2],l+1);n.push({id:g,name:d[2],kind:"class",language:"python",filePath:t.filePath,relativePath:t.relativePath,startLine:l+1,endLine:l+1,signature:u.trim(),docComment:Ik(o,l),modifiers:[],references:0,lastModified:t.mtime,hash:Or("md5").update(u).digest("hex").slice(0,8)})}let f=u.match(/^(\s*)def\s+(\w+)\s*\(/);if(f){let m=f[1].length,g=a&&m>c,h=as(t.filePath,f[2],l+1);n.push({id:h,name:f[2],kind:g?"method":"function",language:"python",filePath:t.filePath,relativePath:t.relativePath,startLine:l+1,endLine:l+1,signature:u.trim(),docComment:Ik(o,l),parent:g?as(t.filePath,a,0):void 0,modifiers:u.includes("async")?["async"]:[],references:0,lastModified:t.mtime,hash:Or("md5").update(u).digest("hex").slice(0,8)})}let p=u.match(/^(?:from\s+([\w.]+)\s+)?import\s+(.+)/);p&&r.push(p[1]||p[2].split(",")[0].trim().split(" as ")[0])}return{symbols:n,imports:r,exports:s,references:i}}function w7(e,t){let n=[],r=[],s=e.split(`
236
236
  `);for(let i=0;i<s.length;i++){let o=s[i],a=o.match(/^import\s+([\w.*]+);/);a&&r.push(a[1]);let c=o.match(/(?:public|private)?\s*(?:abstract|final)?\s*class\s+(\w+)/);if(c){let u=as(t.filePath,c[1],i+1);n.push({id:u,name:c[1],kind:"class",language:"java",filePath:t.filePath,relativePath:t.relativePath,startLine:i+1,endLine:i+1,signature:o.trim(),modifiers:[],references:0,lastModified:t.mtime,hash:Or("md5").update(o).digest("hex").slice(0,8)})}let l=o.match(/(?:public|private|protected)\s+(?:static\s+)?[\w<>,\s]+\s+(\w+)\s*\([^)]*\)\s*[{;]/);if(l){let u=as(t.filePath,l[1],i+1);n.push({id:u,name:l[1],kind:"method",language:"java",filePath:t.filePath,relativePath:t.relativePath,startLine:i+1,endLine:i+1,signature:o.trim(),modifiers:[],references:0,lastModified:t.mtime,hash:Or("md5").update(o).digest("hex").slice(0,8)})}}return{symbols:n,imports:r,exports:[],references:[]}}function k7(e,t){let n=[],r=[],s=e.split(`
237
237
  `);for(let i=0;i<s.length;i++){let o=s[i],a=o.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)\s*\(/);if(a){let u=as(t.filePath,a[1],i+1);n.push({id:u,name:a[1],kind:"function",language:"go",filePath:t.filePath,relativePath:t.relativePath,startLine:i+1,endLine:i+1,signature:o.trim(),modifiers:[],references:0,lastModified:t.mtime,hash:Or("md5").update(o).digest("hex").slice(0,8)})}let c=o.match(/^type\s+(\w+)\s+(struct|interface)/);if(c){let u=as(t.filePath,c[1],i+1);n.push({id:u,name:c[1],kind:c[2]==="interface"?"interface":"type",language:"go",filePath:t.filePath,relativePath:t.relativePath,startLine:i+1,endLine:i+1,signature:o.trim(),modifiers:[],references:0,lastModified:t.mtime,hash:Or("md5").update(o).digest("hex").slice(0,8)})}let l=o.match(/^import\s+"([^"]+)"/);l&&r.push(l[1])}return{symbols:n,imports:r,exports:[],references:[]}}function x7(e,t){let n=[],r=[],s=e.split(`
@@ -353,7 +353,7 @@ import static org.testng.Assert.*;`},rspec:{name:"rspec",language:"ruby",testFil
353
353
  `),a=o.map(c=>c.replace(/\s+/g," ").trim());for(let c=0;c<=o.length-r;c++){let l=a.slice(c,c+r).filter(p=>p&&!p.startsWith("//")&&!p.startsWith("#"));if(l.length<r)continue;let u=l.join(" ").split(/\s+/).filter(p=>p.length>0);if(u.length<n)continue;let d=yQ("sha256").update(u.join(" ")).digest("hex").slice(0,16),f={filePath:s,startLine:c+1,endLine:c+r,snippet:o.slice(c,c+Math.min(r,5)).join(`
354
354
  `).slice(0,300)};if(!t.has(d))t.set(d,{hash:d,occurrences:[f],tokenCount:u.length,lineCount:r});else{let p=t.get(d),m=[...p.occurrences].reverse().find(g=>g.filePath===s);if(m&&Math.abs(m.startLine-f.startLine)<r)continue;p.occurrences.push(f)}}}return Array.from(t.values()).filter(s=>s.occurrences.length>=2).sort((s,i)=>i.tokenCount-s.tokenCount).slice(0,50)}function jQ(e){let t=[];for(let n of e)for(let r of n.occurrences)t.push({id:`dup:${n.hash}:${r.filePath}:${r.startLine}`,category:"duplication",severity:n.occurrences.length>3?"major":"minor",filePath:r.filePath,startLine:r.startLine,endLine:r.endLine,message:`Duplicated block (${n.lineCount} lines, found ${n.occurrences.length} times)`,suggestion:"Extract to shared function or module",metric:n.occurrences.length,refactorHint:"Use DRY principle: extract repeated logic into a helper function or class",context:r.snippet.slice(0,200)});return t}async function BQ(e){if(!z.enableDeadCodeDetection)return[];let t=[];try{let n=await Promise.resolve().then(()=>(du(),uu));if(!n.isLoaded())return[];let r=n.findDeadCode().filter(s=>s.filePath===e||Qk(s.filePath)===Qk(e));for(let s of r.slice(0,20))t.push({id:`dead:${s.id}`,category:"dead_code",severity:"minor",filePath:s.filePath,startLine:s.startLine,endLine:s.endLine,message:`Dead code: "${s.name}" has no callers`,suggestion:"Remove unused code or check if it should be exported",refactorHint:"Verify no external usage, then delete or export properly"})}catch{}return t}async function MD(e){let t=Date.now(),n=Qk(e);if(!_D(n))return Yk(n,Date.now()-t);let r;try{r=Xk(n,"utf-8")}catch{return Yk(n,Date.now()-t)}let s=PD(n);if(s==="unknown")return Yk(n,Date.now()-t);let i=wQ(r,s),o=[],a=[];for(let f of i){let p=AQ(f.body,s),m=PQ(f,n,p,s);o.push({name:f.name,filePath:n,startLine:f.startLine,endLine:f.endLine,metrics:p,smells:m}),a.push(...m)}a.push(...DQ(r,n)),a.push(...FQ(r,n)),a.push(...LQ(i,n,r)),a.push(...await BQ(n));let c={},l={};for(let f of a)c[f.category]=(c[f.category]||0)+1,l[f.severity]=(l[f.severity]||0)+1;let u=DD(a,o),d={filePath:n,totalSmells:a.length,byCategory:c,bySeverity:l,smells:a,functionMetrics:o,duplicates:[],duration:Date.now()-t,topOffenders:[{file:n,smellCount:a.length}],qualityScore:u};return qQ(d),d}async function NQ(e){let t=Date.now(),n=ED(e),r=[],s=[],i=new Map;for(let f of n)try{let p=await MD(f);r.push(...p.smells),s.push(...p.functionMetrics),i.set(f,p.smells.length)}catch{}let o=OQ(n),a=jQ(o);r.push(...a);let c={},l={};for(let f of r)c[f.category]=(c[f.category]||0)+1,l[f.severity]=(l[f.severity]||0)+1;let u=Array.from(i.entries()).sort((f,p)=>p[1]-f[1]).slice(0,10).map(([f,p])=>({file:f,smellCount:p})),d=DD(r,s);return{totalSmells:r.length,byCategory:c,bySeverity:l,smells:r,functionMetrics:s,duplicates:o,duration:Date.now()-t,topOffenders:u,qualityScore:d}}function Yk(e,t){return{filePath:e,totalSmells:0,byCategory:{},bySeverity:{},smells:[],functionMetrics:[],duplicates:[],duration:t,topOffenders:[],qualityScore:100}}function ED(e,t=[]){try{for(let n of fQ(e)){let r=dy(e,n);if(!z.excludePatterns.some(i=>r.includes(i.replace(/\*\*\//g,"").replace(/\*\*/g,"").replace(/\//g,"\\"))))try{dQ(r).isDirectory()?ED(r,t):PD(r)!=="unknown"&&t.push(r)}catch{}}}catch{}return t}function DD(e,t){let n=e.filter(a=>a.severity==="major").length,r=e.filter(a=>a.severity==="minor").length,s=e.filter(a=>a.severity==="info").length,i=Math.max(1,t.length),o=(n*5+r*2+s*.5)/i;return Math.max(0,Math.min(100,100-o))}function qQ(e){xn.totalScans++,xn.totalSmellsFound+=e.totalSmells,xn.averageDuration=(xn.averageDuration*(xn.totalScans-1)+e.duration)/xn.totalScans;for(let[t,n]of Object.entries(e.byCategory))xn.byCategory[t]=(xn.byCategory[t]||0)+n;for(let[t,n]of Object.entries(e.bySeverity))xn.bySeverity[t]=(xn.bySeverity[t]||0)+n;e.filePath&&(xn.topOffendingFiles[e.filePath]=(xn.topOffendingFiles[e.filePath]||0)+e.totalSmells),RD()}function UQ(){return{...z}}function HQ(e){z={...z,...e}}function zQ(){return JSON.parse(JSON.stringify(xn))}function GQ(){xn={totalScans:0,totalSmellsFound:0,byCategory:{},bySeverity:{},topRules:{},averageDuration:0,topOffendingFiles:{}},RD()}function VQ(e){let t=[];if(t.push("# Code Smell Report"),e.filePath&&t.push(`File: ${e.filePath}`),t.push(""),t.push(`**Quality Score:** ${e.qualityScore.toFixed(0)}/100`),t.push(`**Total Smells:** ${e.totalSmells}`),t.push(`**Duration:** ${e.duration}ms`),t.push(""),e.totalSmells===0)return t.push("\u2713 No code smells detected."),t.join(`
355
355
  `);t.push("## Severity");for(let[r,s]of Object.entries(e.bySeverity)){let i=r==="major"?"\u{1F534}":r==="minor"?"\u{1F7E1}":"\u26AA";t.push(` ${i} ${r}: ${s}`)}t.push(""),t.push("## By Category");for(let[r,s]of Object.entries(e.byCategory))t.push(` ${r}: ${s}`);t.push("");let n=[...e.smells].sort((r,s)=>{let i=["major","minor","info"];return i.indexOf(r.severity)-i.indexOf(s.severity)});t.push("## Top Smells (showing 20)");for(let r of n.slice(0,20)){let s=r.severity==="major"?"\u{1F534}":r.severity==="minor"?"\u{1F7E1}":"\u26AA";t.push(`${s} **${r.category}** ${Kk(r.filePath)}:${r.startLine}`),t.push(` ${r.message}`),r.suggestion&&t.push(` ${r.suggestion}`),r.refactorHint&&t.push(` \u{1F4A1} ${r.refactorHint}`),t.push("")}if(e.duplicates.length>0){t.push("## Duplications (top 5)");for(let r of e.duplicates.slice(0,5)){t.push(` ${r.tokenCount} tokens, found ${r.occurrences.length}x:`);for(let s of r.occurrences.slice(0,3))t.push(` - ${Kk(s.filePath)}:${s.startLine}`)}t.push("")}if(e.topOffenders.length>0){t.push("## Top Offending Files");for(let r of e.topOffenders.slice(0,5))t.push(` ${r.smellCount} smells: ${Kk(r.file)}`)}return t.join(`
356
- `)}function JQ(e){if(e.totalSmells===0)return"no smells";let t=[];return e.bySeverity.major&&t.push(`${e.bySeverity.major} major`),e.bySeverity.minor&&t.push(`${e.bySeverity.minor} minor`),e.bySeverity.info&&t.push(`${e.bySeverity.info} info`),`${t.join(", ")} (Q: ${e.qualityScore.toFixed(0)})`}var bQ,z,ex,Zk,SRe,xn,xp=w(()=>{"use strict";bQ={enabled:!0,cyclomaticThreshold:10,cognitiveThreshold:15,longMethodThreshold:50,longParameterListThreshold:5,deepNestingThreshold:4,godClassMethodThreshold:20,largeClassLOCThreshold:500,minDuplicateTokens:50,minDuplicateLines:6,enableDuplicationDetection:!0,enforceCamelCase:!0,enforceSnakeCase:!1,enableNamingChecks:!0,enableMagicNumberDetection:!0,enableDeadCodeDetection:!0,enableCommentedCodeDetection:!0,excludePatterns:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**"],generateAIRefactorHints:!1},z={...bQ},ex=dy(mQ(),".aiaca","code-smells"),Zk=dy(ex,"stats.json"),SRe=dy(ex,"history.jsonl");xn={totalScans:0,totalSmellsFound:0,byCategory:{},bySeverity:{},topRules:{},averageDuration:0,topOffendingFiles:{}};SQ()});import{writeFileSync as KQ,mkdirSync as YQ,existsSync as QQ}from"fs";import{resolve as ZQ,dirname as XQ}from"path";function eZ(e,t,n){let r=e.split(`
356
+ `)}function JQ(e){if(e.totalSmells===0)return"no smells";let t=[];return e.bySeverity.major&&t.push(`${e.bySeverity.major} major`),e.bySeverity.minor&&t.push(`${e.bySeverity.minor} minor`),e.bySeverity.info&&t.push(`${e.bySeverity.info} info`),`${t.join(", ")} (Q: ${e.qualityScore.toFixed(0)})`}var bQ,z,ex,Zk,wRe,xn,xp=w(()=>{"use strict";bQ={enabled:!0,cyclomaticThreshold:10,cognitiveThreshold:15,longMethodThreshold:50,longParameterListThreshold:5,deepNestingThreshold:4,godClassMethodThreshold:20,largeClassLOCThreshold:500,minDuplicateTokens:50,minDuplicateLines:6,enableDuplicationDetection:!0,enforceCamelCase:!0,enforceSnakeCase:!1,enableNamingChecks:!0,enableMagicNumberDetection:!0,enableDeadCodeDetection:!0,enableCommentedCodeDetection:!0,excludePatterns:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**"],generateAIRefactorHints:!1},z={...bQ},ex=dy(mQ(),".aiaca","code-smells"),Zk=dy(ex,"stats.json"),wRe=dy(ex,"history.jsonl");xn={totalScans:0,totalSmellsFound:0,byCategory:{},bySeverity:{},topRules:{},averageDuration:0,topOffendingFiles:{}};SQ()});import{writeFileSync as KQ,mkdirSync as YQ,existsSync as QQ}from"fs";import{resolve as ZQ,dirname as XQ}from"path";function eZ(e,t,n){let r=e.split(`
357
357
  `),s=t.split(`
358
358
  `),i=r.length,o=s.length,a=Array.from({length:i+1},()=>new Array(o+1).fill(0));for(let f=i-1;f>=0;f--)for(let p=o-1;p>=0;p--)a[f][p]=r[f]===s[p]?a[f+1][p+1]+1:Math.max(a[f+1][p],a[f][p+1]);let c=[],l=0,u=0;for(;l<i&&u<o;)r[l]===s[u]?(c.push(` ${r[l]}`),l++,u++):a[l+1][u]>=a[l][u+1]?(c.push(`- ${r[l]}`),l++):(c.push(`+ ${s[u]}`),u++);for(;l<i;)c.push(`- ${r[l++]}`);for(;u<o;)c.push(`+ ${s[u++]}`);let d=tZ(c,2);if(d.length>n){let f=d.slice(0,n);return f.push(`\u2026 +${d.length-n} more diff lines`),f.join(`
359
359
  `)}return d.join(`
@@ -518,7 +518,7 @@ Error: ${t.error}`:""}${n}`}},Px={definition:{name:"task_list",description:"List
518
518
  `),"utf-8"),Ex(Pp,JSON.stringify({indexedSessions:Array.from(Za),documentFrequency:Array.from(To.entries()),avgSegmentLength:Ep,totalSegments:Vt.size,lastUpdated:Date.now()}),"utf-8"),Ex(Dx,JSON.stringify(St,null,2),"utf-8")}catch{}}function $X(){if(Fx(),gu(Dx))try{St={...$F,...JSON.parse(Mx(Dx,"utf-8"))}}catch{}if(gu(Qa))try{let e=Mx(Qa,"utf-8");for(let t of e.split(`
519
519
  `)){if(!t.trim())continue;let n=JSON.parse(t),r={...n,embedding:new Map(n.embedding||[])};TF(r)}}catch{}if(gu(Pp))try{let e=JSON.parse(Mx(Pp,"utf-8"));Za.clear();for(let t of e.indexedSessions||[])Za.add(t);To=new Map(e.documentFrequency||[]),Ep=e.avgSegmentLength||0}catch{}}function CX(){let e={},t={},n={},r=0,s=0,i=0,o=Date.now(),a=0,c=new Set;for(let u of Vt.values())c.add(u.sessionId),e[u.type]=(e[u.type]||0)+1,t[u.category]=(t[u.category]||0)+1,n[u.outcome]=(n[u.outcome]||0)+1,r+=u.shellCommands.length,s+=u.fileChanges.length,i+=u.content.length,u.createdAt<o&&(o=u.createdAt),u.createdAt>a&&(a=u.createdAt);let l=0;try{gu(Qa)&&(l=Math.round(tX(Qa).size/1024))}catch{}return{totalSegments:Vt.size,totalSessions:c.size,bySegmentType:e,byCategory:t,byOutcome:n,totalShellCommands:r,totalFileChanges:s,averageSegmentLength:Vt.size>0?i/Vt.size:0,oldestSegment:o,newestSegment:a,indexSizeKB:l}}function AX(){return{...St}}function TX(e){St={...St,...e},Lx()}function _X(){Vt.clear(),Za.clear(),hu.clear(),To.clear(),Ep=0;try{gu(Qa)&&SF(Qa),gu(Pp)&&SF(Pp)}catch{}}function RX(e){return Vt.get(e)}function PX(e){return Za.has(e)}function IX(e){let t=[];if(t.push(`[${e.matchType}] (${(e.score*100).toFixed(0)}%) ${e.citation.when}`),t.push(` Type: ${e.segment.type} | Category: ${e.segment.category} | Outcome: ${e.segment.outcome}`),t.push(` Session: ${e.segment.sessionId.slice(-8)} | Turns ${e.citation.turns}`),e.segment.shellCommands.length>0&&t.push(` Commands: ${e.segment.shellCommands.slice(0,3).join(" | ")}`),e.segment.fileChanges.length>0&&t.push(` Files: ${e.segment.fileChanges.slice(0,3).map(n=>`${n.type} ${n.path}`).join(", ")}`),e.highlightedSnippet){t.push(" Snippet:");for(let n of e.highlightedSnippet.split(`
520
520
  `).slice(0,5))t.push(` ${n.slice(0,100)}`)}return t.join(`
521
- `)}var Mp,Qa,Pp,v1e,Dx,$F,St,Vt,Za,To,Ep,hu,sX,Lp=w(()=>{"use strict";Mp=Ip(nX(),".aiaca","conv-embeddings"),Qa=Ip(Mp,"segments.jsonl"),Pp=Ip(Mp,"index.json"),v1e=Ip(Mp,"artifacts.json"),Dx=Ip(Mp,"config.json"),$F={enabled:!0,maxSegmentsTotal:5e4,maxSegmentsPerSession:100,minSegmentLength:50,segmentationStrategy:"hybrid",enableArtifactExtraction:!0,enableOutcomeDetection:!0,decayDays:30,bm25K1:1.5,bm25B:.75,rerankBoostExact:1.5,rerankBoostCategory:1.2,rerankBoostOutcome:1.3},St={...$F},Vt=new Map,Za=new Set,To=new Map,Ep=0,hu=new Map;sX=new Set(["a","an","the","is","are","was","were","be","been","being","has","have","had","do","does","did","will","would","should","could","may","might","must","can","shall","this","that","these","those","i","you","he","she","it","we","they","and","or","but","if","then","else","so","as","at","by","for","with","to","from","in","on","of","about","into","through"]);$X();process.on("exit",()=>Lx())});var Hx={};$(Hx,{analyzeFile:()=>Ux,analyzeProject:()=>ZX,applyAnnotations:()=>QX,configure:()=>tee,formatReport:()=>iee,getConfig:()=>eee,getStats:()=>nee,resetStats:()=>ree});import{readFileSync as Bx,writeFileSync as RF,existsSync as PF,statSync as MX,readdirSync as EX}from"fs";import{join as Nx,resolve as IF,extname as DX}from"path";import{homedir as FX}from"os";import{mkdirSync as LX}from"fs";import{execSync as T1e}from"child_process";function jX(){LX(MF,{recursive:!0})}function BX(){if(PF(jx))try{tn={...tn,...JSON.parse(Bx(jx,"utf-8"))}}catch{}}function qx(){jX();try{RF(jx,JSON.stringify(tn,null,2),"utf-8")}catch{}}function EF(e){let t=DX(e).toLowerCase();return[".ts",".tsx",".mts",".cts"].includes(t)?"typescript":[".js",".jsx",".mjs",".cjs"].includes(t)?"javascript":[".py",".pyi"].includes(t)?"python":"unknown"}function un(e,t="typescript"){switch(e.kind){case"primitive":return e.name;case"literal":return typeof e.value=="string"?`'${e.value}'`:String(e.value);case"array":return t==="python"?`list[${un(e.element,t)}]`:`${un(e.element,t)}[]`;case"object":let n=Object.entries(e.properties).map(([o,a])=>`${o}: ${un(a,t)}`).join("; ");return t==="python"?"dict":`{ ${n} }`;case"function":let r=e.params.map((o,a)=>`arg${a}: ${un(o,t)}`).join(", ");return t==="python"?`Callable[[${e.params.map(o=>un(o,t)).join(", ")}], ${un(e.returns,t)}]`:`(${r}) => ${un(e.returns,t)}`;case"union":return e.types.map(o=>un(o,t)).join(" | ");case"reference":return e.name;case"optional":return t==="python"?`Optional[${un(e.type,t)}]`:`${un(e.type,t)} | undefined`;case"nullable":return t==="python"?`Optional[${un(e.type,t)}]`:`${un(e.type,t)} | null`;case"promise":return t==="python"?`Awaitable[${un(e.resolves,t)}]`:`Promise<${un(e.resolves,t)}>`;case"generic":let i=e.args.map(o=>un(o,t)).join(", ");return`${e.name}<${i}>`}}function DF(e){if(e.length===0)return{kind:"primitive",name:"unknown"};if(e.length===1)return e[0];let t=new Set,n=[];for(let i of e){let o=un(i);t.has(o)||(t.add(o),n.push(i))}if(n.length===1)return n[0];let r=n.findIndex(i=>i.kind==="primitive"&&i.name==="undefined"),s=n.findIndex(i=>i.kind==="primitive"&&i.name==="null");return r>=0&&n.length===2?{kind:"optional",type:n[r===0?1:0]}:s>=0&&n.length===2?{kind:"nullable",type:n[s===0?1:0]}:{kind:"union",types:n}}function qX(e,t){return t==="typescript"||t==="javascript"?UX(e):t==="python"?zX(e):[]}function UX(e){let t=[],n=e.split(`
521
+ `)}var Mp,Qa,Pp,S1e,Dx,$F,St,Vt,Za,To,Ep,hu,sX,Lp=w(()=>{"use strict";Mp=Ip(nX(),".aiaca","conv-embeddings"),Qa=Ip(Mp,"segments.jsonl"),Pp=Ip(Mp,"index.json"),S1e=Ip(Mp,"artifacts.json"),Dx=Ip(Mp,"config.json"),$F={enabled:!0,maxSegmentsTotal:5e4,maxSegmentsPerSession:100,minSegmentLength:50,segmentationStrategy:"hybrid",enableArtifactExtraction:!0,enableOutcomeDetection:!0,decayDays:30,bm25K1:1.5,bm25B:.75,rerankBoostExact:1.5,rerankBoostCategory:1.2,rerankBoostOutcome:1.3},St={...$F},Vt=new Map,Za=new Set,To=new Map,Ep=0,hu=new Map;sX=new Set(["a","an","the","is","are","was","were","be","been","being","has","have","had","do","does","did","will","would","should","could","may","might","must","can","shall","this","that","these","those","i","you","he","she","it","we","they","and","or","but","if","then","else","so","as","at","by","for","with","to","from","in","on","of","about","into","through"]);$X();process.on("exit",()=>Lx())});var Hx={};$(Hx,{analyzeFile:()=>Ux,analyzeProject:()=>ZX,applyAnnotations:()=>QX,configure:()=>tee,formatReport:()=>iee,getConfig:()=>eee,getStats:()=>nee,resetStats:()=>ree});import{readFileSync as Bx,writeFileSync as RF,existsSync as PF,statSync as MX,readdirSync as EX}from"fs";import{join as Nx,resolve as IF,extname as DX}from"path";import{homedir as FX}from"os";import{mkdirSync as LX}from"fs";import{execSync as _1e}from"child_process";function jX(){LX(MF,{recursive:!0})}function BX(){if(PF(jx))try{tn={...tn,...JSON.parse(Bx(jx,"utf-8"))}}catch{}}function qx(){jX();try{RF(jx,JSON.stringify(tn,null,2),"utf-8")}catch{}}function EF(e){let t=DX(e).toLowerCase();return[".ts",".tsx",".mts",".cts"].includes(t)?"typescript":[".js",".jsx",".mjs",".cjs"].includes(t)?"javascript":[".py",".pyi"].includes(t)?"python":"unknown"}function un(e,t="typescript"){switch(e.kind){case"primitive":return e.name;case"literal":return typeof e.value=="string"?`'${e.value}'`:String(e.value);case"array":return t==="python"?`list[${un(e.element,t)}]`:`${un(e.element,t)}[]`;case"object":let n=Object.entries(e.properties).map(([o,a])=>`${o}: ${un(a,t)}`).join("; ");return t==="python"?"dict":`{ ${n} }`;case"function":let r=e.params.map((o,a)=>`arg${a}: ${un(o,t)}`).join(", ");return t==="python"?`Callable[[${e.params.map(o=>un(o,t)).join(", ")}], ${un(e.returns,t)}]`:`(${r}) => ${un(e.returns,t)}`;case"union":return e.types.map(o=>un(o,t)).join(" | ");case"reference":return e.name;case"optional":return t==="python"?`Optional[${un(e.type,t)}]`:`${un(e.type,t)} | undefined`;case"nullable":return t==="python"?`Optional[${un(e.type,t)}]`:`${un(e.type,t)} | null`;case"promise":return t==="python"?`Awaitable[${un(e.resolves,t)}]`:`Promise<${un(e.resolves,t)}>`;case"generic":let i=e.args.map(o=>un(o,t)).join(", ");return`${e.name}<${i}>`}}function DF(e){if(e.length===0)return{kind:"primitive",name:"unknown"};if(e.length===1)return e[0];let t=new Set,n=[];for(let i of e){let o=un(i);t.has(o)||(t.add(o),n.push(i))}if(n.length===1)return n[0];let r=n.findIndex(i=>i.kind==="primitive"&&i.name==="undefined"),s=n.findIndex(i=>i.kind==="primitive"&&i.name==="null");return r>=0&&n.length===2?{kind:"optional",type:n[r===0?1:0]}:s>=0&&n.length===2?{kind:"nullable",type:n[s===0?1:0]}:{kind:"union",types:n}}function qX(e,t){return t==="typescript"||t==="javascript"?UX(e):t==="python"?zX(e):[]}function UX(e){let t=[],n=e.split(`
522
522
  `);for(let r=0;r<n.length;r++){let s=n[r],i=[/^(\s*)(?:export\s+)?(?:async\s+)?function\s*(\*)?\s*(\w+)\s*(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?::\s*([^{]+?))?\s*\{/,/^(\s*)(?:export\s+)?(?:const|let|var)\s+(\w+)\s*[:=]\s*(?:async\s+)?\(([^)]*)\)\s*(?::\s*([^=>]+?))?\s*=>/,/^(\s+)(?:public\s+|private\s+|protected\s+|static\s+|async\s+)*(?:async\s+)?(\*)?(\w+)\s*(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?::\s*([^{]+?))?\s*\{/];for(let o of i){let a=s.match(o);if(!a)continue;let c=o===i[2],l=o===i[1],u=a[2]==="*",d=a[l?2:3],f=a[l?3:4],p=a[l?4:5];if(!d||["if","for","while","switch","function","class","return","catch"].includes(d))continue;let m=HX(f||""),g=s.includes("async"),h=0,v=!1,y=r;for(let b=r;b<n.length&&b<r+1500;b++){for(let k of n[b])k==="{"&&(h++,v=!0),k==="}"&&h--;if(v&&h===0){y=b;break}}t.push({name:d,startLine:r+1,endLine:y+1,signatureLine:s,parameters:m,returnAnnotation:p?.trim(),body:n.slice(r,y+1).join(`
523
523
  `),isAsync:g,isGenerator:u,hasReturnAnnotation:!!p});break}}return t}function HX(e){if(!e.trim())return[];let t=[],n=FF(e);for(let r of n){let s=r.trim().replace(/^\.\.\./,"");if(!s)continue;let i=Cy(s,"="),o=Cy(s,":"),a=s,c,l;if(i>=0&&(l=s.slice(i+1).trim(),a=s.slice(0,i).trim()),o>=0&&o<(i>=0?i:1/0)&&(c=a.slice(o+1).trim(),a=a.slice(0,o).trim()),a=a.replace(/[?!]/g,"").trim(),!a||a.startsWith("{")||a.startsWith("[")){t.push({name:"destructured",existingType:c});continue}t.push({name:a,existingType:c,defaultValue:l})}return t}function FF(e){let t=[],n=0,r="";for(let s of e)(s==="<"||s==="{"||s==="["||s==="(")&&n++,(s===">"||s==="}"||s==="]"||s===")")&&n--,s===","&&n===0?(t.push(r),r=""):r+=s;return r&&t.push(r),t}function Cy(e,t){let n=0;for(let r=0;r<e.length;r++)if((e[r]==="<"||e[r]==="{"||e[r]==="["||e[r]==="(")&&n++,(e[r]===">"||e[r]==="}"||e[r]==="]"||e[r]===")")&&n--,e[r]===t&&n===0)return r;return-1}function zX(e){let t=[],n=e.split(`
524
524
  `);for(let r=0;r<n.length;r++){let s=n[r].match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*([^:]+))?\s*:/);if(!s)continue;let i=s[1].length,o=s[2],a=s[3],c=s[4]?.trim(),l=n[r].includes("async"),u=r;for(let f=r+1;f<n.length;f++){let p=n[f].trim();if(!p||p.startsWith("#"))continue;let m=n[f].search(/\S/);if(m<=i&&m!==-1){u=f-1;break}u=f}let d=GX(a);t.push({name:o,startLine:r+1,endLine:u+1,signatureLine:n[r],parameters:d,returnAnnotation:c,body:n.slice(r,u+1).join(`
@@ -707,25 +707,24 @@ You are not a chatbot. You are an autonomous coding agent. You take action, not
707
707
  </core_principles>
708
708
 
709
709
  <autonomy>
710
- DEFAULT TO DOING, NOT ASKING. This is what separates AIACA from weaker assistants.
710
+ DEFAULT TO DOING, NOT ASKING. Decisive execution on well-scoped requests is what makes AIACA
711
+ stronger than weaker assistants.
711
712
 
712
- A request like "create a pptx on machine learning", "build me a landing page", "write a report on X",
713
- or "make a script that does Y" is a COMPLETE, actionable instruction. Execute it immediately with
714
- strong, professional defaults \u2014 do NOT reply with a list of clarifying questions.
713
+ A request is well-scoped when it names a deliverable and enough subject to act on. Treat such
714
+ requests as complete instructions: execute immediately with strong, professional defaults rather
715
+ than replying with a list of clarifying questions.
715
716
 
716
- When details aren't specified, INFER the best ones a senior professional would choose:
717
- - Title/topic \u2192 derive a clear, specific title from the request.
718
- - Structure/length \u2192 pick a sensible, complete structure (e.g. a deck = 8\u201312 slides with a logical arc).
719
- - Style/theme/stack \u2192 choose a fitting, modern default and state your choice.
720
- - Audience \u2192 assume a smart general professional unless told otherwise.
717
+ When specifics are unstated, INFER what a domain expert would choose, and proceed:
718
+ - Naming, scope, and length \u2192 pick clear, complete, sensible values.
719
+ - Style, format, structure, theme, tech stack \u2192 choose a fitting modern default and state the choice.
720
+ - Audience \u2192 assume a capable professional unless the context indicates otherwise.
721
721
 
722
- Produce the full deliverable FIRST, then offer to refine ("I made it a 10-slide intro deck with the
723
- teal theme \u2014 want it longer, more technical, or a different focus?"). Refinement happens AFTER a
724
- complete first version exists, never as a precondition to starting.
722
+ Deliver a complete first version, THEN offer to refine. Refinement always follows delivery; it is
723
+ never a precondition for starting.
725
724
 
726
- ONLY ask a question when a required input is genuinely unknowable and cannot be reasonably defaulted
727
- \u2014 e.g. a credential, a specific private value you have no way to access, or a destructive/irreversible
728
- choice. "What topics should I cover?" is NOT such a case \u2014 you decide and deliver.
725
+ Ask a question ONLY when a required input is genuinely unknowable and cannot be reasonably defaulted
726
+ \u2014 a secret or credential, a private value you have no way to access, or an irreversible/destructive
727
+ choice. Preferences about scope, content, or styling never qualify: decide well and deliver.
729
728
  </autonomy>
730
729
 
731
730
  <elite_standards>
@@ -878,10 +877,9 @@ When the user asks for a document, deck, presentation, report, or spreadsheet, u
878
877
  tool \u2014 it produces REAL .docx/.pptx/.xlsx/.pdf files (not fake renamed HTML). Produce work that
879
878
  looks designed by a human, the way a top consultant or designer would deliver it.
880
879
 
881
- DELIVER FIRST, DON'T INTERROGATE: "create a pptx on machine learning" is a complete instruction.
882
- Do NOT ask for the title, sections, slide count, audience, or theme. Immediately infer a strong
883
- title, design a logical structure, write real substantive content, pick a fitting theme, and call
884
- doc_create. Only AFTER the file exists may you offer to refine it.
880
+ DELIVER FIRST, DON'T INTERROGATE: a request that names a document type and a subject is a complete
881
+ instruction. Infer a strong title, design a logical structure, write real substantive content, pick
882
+ a fitting theme, and call doc_create immediately. Offer to refine only AFTER the file exists.
885
883
 
886
884
  CONTENT FIRST:
887
885
  - Write real, specific, substantive content \u2014 NEVER lorem ipsum or "Slide content here" placeholders.
@@ -956,8 +954,8 @@ When something fails:
956
954
  - NEVER say "I cannot create .docx/.pptx files" \u2014 use doc_create tool
957
955
  - NEVER say "I cannot see images" \u2014 use image_read tool
958
956
  - NEVER describe what you would do \u2014 just DO IT
959
- - NEVER open with clarifying questions for a well-scoped request (e.g. "create a deck on X",
960
- "build a Y") \u2014 infer professional defaults, deliver the full result, THEN offer to refine
957
+ - NEVER open with clarifying questions for a well-scoped request \u2014 infer professional defaults,
958
+ deliver the complete result, THEN offer to refine
961
959
  - NEVER ask permission to proceed unless an action is destructive/irreversible or needs a
962
960
  credential/private value you cannot access or reasonably default
963
961
  - NEVER repeat a tool call that already succeeded
@@ -988,7 +986,7 @@ while ($true) { Start-Sleep -Seconds 30 }
988
986
  `).slice(0,5).join(`
989
987
  `),category:e,count:1,firstSeen:i,lastSeen:i,contexts:n?[{timestamp:i,data:Ru(n)}]:[]}),OL()}function Dne(e,t){let r=(e.stack||"").split(`
990
988
  `).slice(1,4).map(s=>s.trim().split(" ")[1]||"").join(":");return`${t}:${e.name}:${e.message.slice(0,50)}:${r}`.slice(0,100)}function OL(){Iu();try{RL(M$,JSON.stringify(Array.from(sc.values()),null,2),"utf-8")}catch{}}function Fne(){if(TL(M$))try{let e=JSON.parse(_L(M$,"utf-8"));for(let t of e)sc.set(t.fingerprint,t)}catch{}}function q$(){return Array.from(sc.values()).sort((e,t)=>t.count-e.count)}function Lne(e=10){return Array.from(sc.values()).sort((t,n)=>n.lastSeen.localeCompare(t.lastSeen)).slice(0,e)}function One(){sc.clear(),OL()}function jne(e,t=1,n){let r=E$.get(e)||0;E$.set(e,r+t),$i.push({name:e,type:"counter",value:r+t,tags:n,timestamp:Date.now()}),$i.length>N$&&Ky()}function Yy(e,t,n){jL.set(e,t),$i.push({name:e,type:"gauge",value:t,tags:n,timestamp:Date.now()}),$i.length>N$&&Ky()}function Zp(e,t,n){let r=Wy.get(e)||[];r.push(t),r.length>1e3&&r.shift(),Wy.set(e,r),$i.push({name:e,type:"histogram",value:t,tags:n,timestamp:Date.now()}),$i.length>N$&&Ky()}function Bne(e){D$.set(e,Date.now())}function Nne(e,t="perf",n){let r=D$.get(e);if(!r)return 0;let s=Date.now()-r;return D$.delete(e),Zp(e,s,n),FL(t,`${e}: ${s}ms`,n),s}async function qne(e,t,n="perf"){let r=Date.now();try{let s=await t();return Zp(e,Date.now()-r,{status:"success"}),s}catch(s){throw Zp(e,Date.now()-r,{status:"error"}),oc(n,s),s}}function BL(){let e={};for(let[t,n]of Wy){if(n.length===0)continue;let r=[...n].sort((s,i)=>s-i);e[t]={count:n.length,min:r[0],max:r[r.length-1],mean:n.reduce((s,i)=>s+i,0)/n.length,p50:P$(r,50),p95:P$(r,95),p99:P$(r,99)}}return{counters:Object.fromEntries(E$),gauges:Object.fromEntries(jL),histograms:e}}function P$(e,t){let n=Math.ceil(t/100*e.length)-1;return e[Math.max(0,Math.min(e.length-1,n))]}function I$(){return Math.random().toString(36).slice(2,14)}function NL(e,t={}){let n=rc.length>0&&Xp.get(rc[0])?.traceId||I$(),r=rc[rc.length-1],s={id:I$(),parentId:r,traceId:n,name:e,startTime:Date.now(),tags:t,events:[],status:"active"};return Xp.set(s.id,s),rc.push(s.id),s}function F$(e,t="completed"){let n=Xp.get(e);if(!n)return;n.endTime=Date.now(),n.status=t;let r=rc.indexOf(e);r>=0&&rc.splice(r,1),ic(t==="errored"?"error":"debug","trace",`Span ${n.name} ${t} (${(n.endTime-n.startTime).toFixed(0)}ms)`,{traceId:n.traceId,spanId:n.id,duration:n.endTime-n.startTime}),Zp(`span.${n.name}`,n.endTime-n.startTime,{status:t})}function qL(e,t,n){let r=Xp.get(e);r&&r.events.push({time:Date.now(),name:t,data:n?Ru(n):void 0})}async function Une(e,t,n){let r=NL(e,n);try{let s=await t(r);return F$(r.id,"completed"),s}catch(s){throw qL(r.id,"error",{message:s.message}),F$(r.id,"errored"),s}}function UL(){return Array.from(Xp.values()).filter(e=>e.status==="active")}function H$(e){U$.set(e.name,e);let t=setInterval(async()=>{try{let n=await e.check();e.lastCheckAt=Date.now(),e.lastResult={...n,checkedAt:new Date().toISOString()},Yy(`health.${e.name}`,n.healthy?1:0),n.healthy||LL("health",`Health check "${e.name}" failed: ${n.message||"no message"}`)}catch(n){e.lastResult={healthy:!1,message:n.message,checkedAt:new Date().toISOString()},oc("health",n)}},e.intervalMs);t.unref(),L$.set(e.name,t)}function Hne(e){let t=L$.get(e);t&&(clearInterval(t),L$.delete(e)),U$.delete(e)}function HL(){let e={},t=0,n=0;for(let[s,i]of U$)e[s]=i.lastResult,i.lastResult&&(n++,i.lastResult.healthy&&t++);let r="healthy";return n===0||t===n?r="healthy":t/n>=.5?r="degraded":r="unhealthy",{overall:r,checks:e}}function zne(e,t=3){let n=Wy.get(e);if(!n||n.length<10)return null;let r=n.reduce((c,l)=>c+l,0)/n.length,s=n.reduce((c,l)=>c+Math.pow(l-r,2),0)/n.length,i=Math.sqrt(s),o=n[n.length-1];return{isAnomaly:(i>0?Math.abs(o-r)/i:0)>t,current:o,mean:r,stdDev:i}}function zL(){let e=ML(),t=EL();return{timestamp:new Date().toISOString(),health:HL(),metrics:BL(),topErrors:q$().slice(0,10),activeSpans:UL(),systemInfo:{cpus:IL().length,memoryMB:{free:Math.round(e/1024/1024),total:Math.round(t/1024/1024),usedPct:(t-e)/t*100},loadAvg:DL(),uptime:process.uptime()}}}function GL(e={}){if(Iu(),!TL(Qp))return[..._u].slice(-100);let t=[..._u];try{let r=_L(Qp,"utf-8").trim().split(`
991
- `).slice(-1e3);for(let s of r)try{t.push(JSON.parse(s))}catch{}}catch{}let n=t;if(e.level){let r=Jy[e.level];n=n.filter(s=>Jy[s.level]>=r)}if(e.category&&(n=n.filter(r=>r.category===e.category)),e.since&&(n=n.filter(r=>new Date(r.timestamp)>=e.since)),e.search){let r=e.search.toLowerCase();n=n.filter(s=>s.message.toLowerCase().includes(r)||JSON.stringify(s.data||{}).toLowerCase().includes(r))}return n.slice(-(e.limit||100))}function Gne(e){Iu();try{let n={report:zL(),logs:GL({limit:500}),errors:q$()};return RL(e,JSON.stringify(n,null,2),"utf-8"),!0}catch{return!1}}function Vne(e=7){Iu();let t=Date.now()-e*24*60*60*1e3,n=0;for(let r of hne(Mo))if(r.endsWith(".archive"))try{let s=Pu(Mo,r);PL(s).mtimeMs<t&&(bne(s),n++)}catch{}return n}function Jne(){return Qp}function Wne(){return Mo}var Mo,Qp,CL,M$,uPe,Jy,O$,j$,B$,Sne,N$,wne,_u,$i,R$,sc,Ene,E$,jL,Wy,D$,Xp,rc,U$,L$,G$=w(()=>{"use strict";Mo=Pu(vne(),".aiaca","diagnostics"),Qp=Pu(Mo,"events.jsonl"),CL=Pu(Mo,"metrics.jsonl"),M$=Pu(Mo,"errors.json"),uPe=Pu(Mo,"health.json"),Jy={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},O$=process.env.AIACA_LOG_LEVEL||"info",j$=!1,B$=!1,Sne=10*1024*1024,N$=1e3;wne=[/(?:api[_-]?key|secret|password|token)[\s=:]+["']?([\w-]{16,})/gi,/Bearer\s+([\w-.]+)/gi,/sk-[\w-]{32,}/gi,/AKIA[0-9A-Z]{16}/g,/AIza[\w-]{35}/g,/[\w._%+-]+@[\w.-]+\.[A-Z]{2,}/gi];_u=[],$i=[],R$=null;sc=new Map,Ene=10;Fne();E$=new Map,jL=new Map,Wy=new Map;D$=new Map;Xp=new Map,rc=[];U$=new Map,L$=new Map;H$({name:"memory",intervalMs:6e4,check:async()=>{let e=ML(),t=EL(),n=(t-e)/t*100;return Yy("system.memory.used_pct",n),{healthy:n<90,message:`Memory usage: ${n.toFixed(1)}%`,data:{freeMB:Math.round(e/1024/1024),totalMB:Math.round(t/1024/1024)}}}});H$({name:"cpu",intervalMs:6e4,check:async()=>{let e=DL(),t=IL().length,n=e[0]/t*100;return Yy("system.cpu.load_pct",n),{healthy:n<95,message:`CPU load: ${n.toFixed(1)}%`,data:{load1:e[0],load5:e[1],load15:e[2],cores:t}}}});process.on("exit",()=>{Mu()});process.on("SIGINT",()=>{Mu(),process.exit(0)});process.on("uncaughtException",e=>{oc("uncaught",e),Mu()});process.on("unhandledRejection",e=>{oc("unhandled_rejection",e),Mu()})});var ds={};$(ds,{accessCredential:()=>ure,configure:()=>mre,createSession:()=>are,destroyAllSessions:()=>Q$,destroyCredential:()=>KL,formatSession:()=>wre,generateComplianceReport:()=>Sre,getAuditLog:()=>vre,getConfig:()=>pre,getEvents:()=>yre,getSession:()=>cre,getStats:()=>gre,listCredentialsForSession:()=>bre,listSessions:()=>ZL,resetStats:()=>hre,startAutoSweep:()=>QL,stopAutoSweep:()=>dre,storeCredential:()=>lre,teardownSession:()=>tm,verifyCleanup:()=>YL});import{existsSync as VL,mkdirSync as Kne,readFileSync as JL,writeFileSync as WL}from"fs";import{join as W$}from"path";import{homedir as Yne}from"os";import{createCipheriv as Qne,createDecipheriv as Zne,randomBytes as em,hkdfSync as Xne}from"crypto";import{EventEmitter as ere}from"events";function Y$(){Kne(K$,{recursive:!0})}function nre(){if(Y$(),VL(V$))try{Ie={...Ie,...JSON.parse(JL(V$,"utf-8"))}}catch{}}function lc(){Y$();try{WL(V$,JSON.stringify(Ie,null,2),"utf-8")}catch{}}function cc(e){if(!Le.enableAccessLog)return;Y$();let t={...e};t.value&&(t.value="[REDACTED]"),t.encryptedValue&&(t.encryptedValue="[REDACTED]");try{WL(J$,JSON.stringify({...t,timestamp:Date.now()})+`
989
+ `).slice(-1e3);for(let s of r)try{t.push(JSON.parse(s))}catch{}}catch{}let n=t;if(e.level){let r=Jy[e.level];n=n.filter(s=>Jy[s.level]>=r)}if(e.category&&(n=n.filter(r=>r.category===e.category)),e.since&&(n=n.filter(r=>new Date(r.timestamp)>=e.since)),e.search){let r=e.search.toLowerCase();n=n.filter(s=>s.message.toLowerCase().includes(r)||JSON.stringify(s.data||{}).toLowerCase().includes(r))}return n.slice(-(e.limit||100))}function Gne(e){Iu();try{let n={report:zL(),logs:GL({limit:500}),errors:q$()};return RL(e,JSON.stringify(n,null,2),"utf-8"),!0}catch{return!1}}function Vne(e=7){Iu();let t=Date.now()-e*24*60*60*1e3,n=0;for(let r of hne(Mo))if(r.endsWith(".archive"))try{let s=Pu(Mo,r);PL(s).mtimeMs<t&&(bne(s),n++)}catch{}return n}function Jne(){return Qp}function Wne(){return Mo}var Mo,Qp,CL,M$,dPe,Jy,O$,j$,B$,Sne,N$,wne,_u,$i,R$,sc,Ene,E$,jL,Wy,D$,Xp,rc,U$,L$,G$=w(()=>{"use strict";Mo=Pu(vne(),".aiaca","diagnostics"),Qp=Pu(Mo,"events.jsonl"),CL=Pu(Mo,"metrics.jsonl"),M$=Pu(Mo,"errors.json"),dPe=Pu(Mo,"health.json"),Jy={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},O$=process.env.AIACA_LOG_LEVEL||"info",j$=!1,B$=!1,Sne=10*1024*1024,N$=1e3;wne=[/(?:api[_-]?key|secret|password|token)[\s=:]+["']?([\w-]{16,})/gi,/Bearer\s+([\w-.]+)/gi,/sk-[\w-]{32,}/gi,/AKIA[0-9A-Z]{16}/g,/AIza[\w-]{35}/g,/[\w._%+-]+@[\w.-]+\.[A-Z]{2,}/gi];_u=[],$i=[],R$=null;sc=new Map,Ene=10;Fne();E$=new Map,jL=new Map,Wy=new Map;D$=new Map;Xp=new Map,rc=[];U$=new Map,L$=new Map;H$({name:"memory",intervalMs:6e4,check:async()=>{let e=ML(),t=EL(),n=(t-e)/t*100;return Yy("system.memory.used_pct",n),{healthy:n<90,message:`Memory usage: ${n.toFixed(1)}%`,data:{freeMB:Math.round(e/1024/1024),totalMB:Math.round(t/1024/1024)}}}});H$({name:"cpu",intervalMs:6e4,check:async()=>{let e=DL(),t=IL().length,n=e[0]/t*100;return Yy("system.cpu.load_pct",n),{healthy:n<95,message:`CPU load: ${n.toFixed(1)}%`,data:{load1:e[0],load5:e[1],load15:e[2],cores:t}}}});process.on("exit",()=>{Mu()});process.on("SIGINT",()=>{Mu(),process.exit(0)});process.on("uncaughtException",e=>{oc("uncaught",e),Mu()});process.on("unhandledRejection",e=>{oc("unhandled_rejection",e),Mu()})});var ds={};$(ds,{accessCredential:()=>ure,configure:()=>mre,createSession:()=>are,destroyAllSessions:()=>Q$,destroyCredential:()=>KL,formatSession:()=>wre,generateComplianceReport:()=>Sre,getAuditLog:()=>vre,getConfig:()=>pre,getEvents:()=>yre,getSession:()=>cre,getStats:()=>gre,listCredentialsForSession:()=>bre,listSessions:()=>ZL,resetStats:()=>hre,startAutoSweep:()=>QL,stopAutoSweep:()=>dre,storeCredential:()=>lre,teardownSession:()=>tm,verifyCleanup:()=>YL});import{existsSync as VL,mkdirSync as Kne,readFileSync as JL,writeFileSync as WL}from"fs";import{join as W$}from"path";import{homedir as Yne}from"os";import{createCipheriv as Qne,createDecipheriv as Zne,randomBytes as em,hkdfSync as Xne}from"crypto";import{EventEmitter as ere}from"events";function Y$(){Kne(K$,{recursive:!0})}function nre(){if(Y$(),VL(V$))try{Ie={...Ie,...JSON.parse(JL(V$,"utf-8"))}}catch{}}function lc(){Y$();try{WL(V$,JSON.stringify(Ie,null,2),"utf-8")}catch{}}function cc(e){if(!Le.enableAccessLog)return;Y$();let t={...e};t.value&&(t.value="[REDACTED]"),t.encryptedValue&&(t.encryptedValue="[REDACTED]");try{WL(J$,JSON.stringify({...t,timestamp:Date.now()})+`
992
990
  `,{flag:"a"})}catch{}}function Ci(e){if(!(!e||e.length===0)){for(let t=0;t<Le.memoryScrubPasses;t++)em(e.length).copy(e);e.fill(0)}}function rre(){if(Le.forceGcOnTeardown&&typeof global.gc=="function")try{global.gc()}catch{}}function sre(e,t){let n=Buffer.concat([t,Buffer.from(e,"utf-8")]),r=em(16),s=Buffer.from("aiaca-credential-isolation-v1","utf-8");return Buffer.from(Xne("sha256",n,r,s,32))}function ire(e,t){let n=em(12),r=Qne("aes-256-gcm",t,n),s=Buffer.concat([r.update(e,"utf-8"),r.final()]),i=r.getAuthTag();return{ciphertext:s,iv:n,authTag:i}}function ore(e,t,n,r){let s=Zne("aes-256-gcm",t,n);s.setAuthTag(r);let i=Buffer.concat([s.update(e),s.final()]),o=i.toString("utf-8");return Ci(i),o}function are(e,t){if(!Le.enabled)throw new Error("Credential isolation disabled");if(On.has(e)){let i=On.get(e);if(i.state==="active")return i;tm(e,"session_recreate")}let n=em(32),r=sre(e,n);Ci(n);let s={sessionId:e,state:"active",encryptionKey:r,credentials:new Map,createdAt:Date.now(),lastActivityAt:Date.now(),ownerAgent:t,totalIssued:0,totalAccessed:0,totalDestroyed:0};return On.set(e,s),Ie.totalSessionsCreated++,lc(),cc({event:"session_created",sessionId:e,ownerAgent:t}),Eo.emit("session_created",{sessionId:e,ownerAgent:t}),s}function cre(e){return On.get(e)}function lre(e){if(!Le.enabled)return{error:"Isolation disabled"};let t=On.get(e.sessionId);if(!t)return{error:`Session ${e.sessionId} not found`};if(t.state!=="active")return{error:`Session is ${t.state}`};if(Le.requireOwnerIdentity&&!e.ownerIdentityId)return{error:"Owner identity required"};let n=em(8).toString("hex"),{ciphertext:r,iv:s,authTag:i}=ire(e.value,t.encryptionKey),o={id:n,kind:e.kind||"generic",name:e.name,encryptedValue:r,iv:s,authTag:i,sessionId:e.sessionId,ownerIdentityId:e.ownerIdentityId,createdAt:Date.now(),lastAccessedAt:Date.now(),accessCount:0,expiresAt:e.expiresAt||Date.now()+Le.credentialMaxAgeMs,accessLog:[],maxAccesses:e.maxAccesses,scopes:e.scopes||[],classification:e.classification||"confidential"};return t.credentials.set(n,o),t.totalIssued++,t.lastActivityAt=Date.now(),Ie.totalCredentialsIssued++,lc(),cc({event:"credential_stored",sessionId:e.sessionId,credentialId:n,name:e.name,kind:o.kind,classification:o.classification}),Eo.emit("credential_stored",{sessionId:e.sessionId,credentialId:n,name:e.name}),{id:n}}function ure(e){if(!Le.enabled)return{error:"Isolation disabled"};let t=On.get(e.sessionId);if(!t)return{error:`Session ${e.sessionId} not found`};if(t.state!=="active")return{error:`Session is ${t.state}`};let n=t.credentials.get(e.credentialId);if(!n)return{error:"Credential not found"};if(Le.rejectCrossSessionAccess&&n.sessionId!==e.sessionId)return Ie.totalCrossSessionRejections++,lc(),cc({event:"cross_session_rejection",requestingSession:e.sessionId,credentialSession:n.sessionId,credentialId:e.credentialId,accessor:e.accessor}),Eo.emit("cross_session_blocked",{requestingSession:e.sessionId,credentialSession:n.sessionId,accessor:e.accessor}),{error:"Cross-session access blocked (contamination prevention)"};if(n.expiresAt&&Date.now()>n.expiresAt)return{error:"Credential expired"};if(n.maxAccesses!==void 0&&n.accessCount>=n.maxAccesses)return{error:"Max accesses exceeded"};if(Le.enforceScopeChecks&&e.scope&&n.scopes.length>0&&!n.scopes.includes(e.scope)&&!n.scopes.includes("*"))return Ie.totalScopeViolations++,lc(),cc({event:"scope_violation",sessionId:e.sessionId,credentialId:e.credentialId,requested:e.scope,allowed:n.scopes}),{error:`Scope "${e.scope}" not allowed for this credential`};let r;try{r=ore(n.encryptedValue,t.encryptionKey,n.iv,n.authTag)}catch{return{error:"Decryption failed (possible tampering)"}}return n.lastAccessedAt=Date.now(),n.accessCount++,n.accessLog.push({accessor:e.accessor,timestamp:Date.now(),purpose:e.purpose}),n.accessLog.length>100&&n.accessLog.shift(),t.totalAccessed++,t.lastActivityAt=Date.now(),Ie.totalCredentialsAccessed++,cc({event:"credential_accessed",sessionId:e.sessionId,credentialId:e.credentialId,accessor:e.accessor,purpose:e.purpose}),{value:r}}function KL(e,t,n="manual"){let r=On.get(e);if(!r)return!1;let s=r.credentials.get(t);return s?(Ci(s.encryptedValue),Ci(s.iv),Ci(s.authTag),s.accessLog.length=0,r.credentials.delete(t),r.totalDestroyed++,Ie.totalCredentialsDestroyed++,lc(),cc({event:"credential_destroyed",sessionId:e,credentialId:t,reason:n}),Eo.emit("credential_destroyed",{sessionId:e,credentialId:t,reason:n}),!0):!1}function tm(e,t="session_ended"){let n=Date.now(),r=[],s=On.get(e);if(!s)return{sessionId:e,state:"destroyed",credentialsDestroyed:0,scrubPasses:0,durationMs:0,cleanupVerified:!0,warnings:["Session not found"]};s.state="tearing_down";let i=0;for(let[c,l]of s.credentials.entries())Ci(l.encryptedValue),Ci(l.iv),Ci(l.authTag),l.accessLog.length=0,l.encryptedValue=null,l.iv=null,l.authTag=null,i++;s.credentials.clear(),Ci(s.encryptionKey),s.encryptionKey=null;let o=Date.now()-s.createdAt;Ie.totalSessionsTeardown++,Ie.averageSessionDurationMs=(Ie.averageSessionDurationMs*(Ie.totalSessionsTeardown-1)+o)/Ie.totalSessionsTeardown,s.totalIssued>0&&(Ie.averageCredentialsPerSession=(Ie.averageCredentialsPerSession*(Ie.totalSessionsTeardown-1)+s.totalIssued)/Ie.totalSessionsTeardown),lc(),rre();let a=!0;if(Le.enableCleanupVerification){let c=YL(e);c.clean||(a=!1,r.push(...c.issues))}return s.state="destroyed",On.delete(e),cc({event:"session_teardown",sessionId:e,reason:t,credentialsDestroyed:i,durationMs:Date.now()-n,cleanupVerified:a,warnings:r}),Eo.emit("session_teardown",{sessionId:e,reason:t,credentialsDestroyed:i}),{sessionId:e,state:"destroyed",credentialsDestroyed:i,scrubPasses:Le.memoryScrubPasses,durationMs:Date.now()-n,cleanupVerified:a,warnings:r}}function YL(e){let t=[],n=On.get(e);return n&&(n.state!=="destroyed"&&n.state!=="tearing_down"&&t.push(`Vault still in state: ${n.state}`),n.credentials.size>0&&t.push(`${n.credentials.size} credentials still in memory`),n.encryptionKey&&Buffer.isBuffer(n.encryptionKey)&&n.encryptionKey.length>0&&(n.encryptionKey.every(s=>s===0)||t.push("Encryption key not scrubbed"))),Le.enableHeapSnapshotScrub,{sessionId:e,clean:t.length===0,issues:t}}function QL(){ac||(ac=setInterval(()=>fre(),6e4),ac.unref&&ac.unref())}function dre(){ac&&(clearInterval(ac),ac=null)}function fre(){let e=0,t=0,n=Date.now();for(let[r,s]of Array.from(On.entries()))if(s.state==="active"){if(n-s.lastActivityAt>Le.sessionIdleTimeoutMs){tm(r,"idle_timeout"),e++;continue}for(let[i,o]of s.credentials.entries())o.expiresAt&&n>o.expiresAt&&(KL(r,i,"expired"),t++)}return(e>0||t>0)&&Eo.emit("sweep",{teardownSessions:e,destroyedCreds:t}),{teardownSessions:e,destroyedCreds:t}}function Q$(e="emergency"){let t=0;for(let n of Array.from(On.keys()))tm(n,e).credentialsDestroyed>=0&&t++;return{count:t}}function pre(){return{...Le}}function mre(e){Le={...Le,...e}}function gre(){return{...Ie}}function hre(){Ie={totalSessionsCreated:0,totalSessionsTeardown:0,totalCredentialsIssued:0,totalCredentialsAccessed:0,totalCredentialsDestroyed:0,totalCrossSessionRejections:0,totalScopeViolations:0,totalContaminationsPrevented:0,averageSessionDurationMs:0,averageCredentialsPerSession:0},lc()}function yre(){return Eo}function ZL(){return Array.from(On.values()).map(e=>({sessionId:e.sessionId,state:e.state,credentialCount:e.credentials.size,createdAt:e.createdAt,lastActivityAt:e.lastActivityAt,ownerAgent:e.ownerAgent,totalIssued:e.totalIssued,totalAccessed:e.totalAccessed}))}function bre(e){let t=On.get(e);return t?Array.from(t.credentials.values()).map(n=>({id:n.id,name:n.name,kind:n.kind,classification:n.classification,accessCount:n.accessCount,createdAt:n.createdAt,expiresAt:n.expiresAt,scopes:n.scopes})):[]}function vre(e=100){if(!VL(J$))return[];try{return JL(J$,"utf-8").split(`
993
991
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Sre(){let e=[],t=ZL();e.push("# Credential Isolation Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Active sessions: ${t.length}`),e.push(`- Total sessions created: ${Ie.totalSessionsCreated}`),e.push(`- Total sessions torn down: ${Ie.totalSessionsTeardown}`),e.push(`- Total credentials issued: ${Ie.totalCredentialsIssued}`),e.push(`- Total credentials destroyed: ${Ie.totalCredentialsDestroyed}`),e.push(`- Cross-session rejections: ${Ie.totalCrossSessionRejections}`),e.push(`- Scope violations: ${Ie.totalScopeViolations}`),e.push(`- Avg session duration: ${(Ie.averageSessionDurationMs/6e4).toFixed(1)} min`),e.push(`- Avg credentials/session: ${Ie.averageCredentialsPerSession.toFixed(1)}`),e.push(""),e.push("## Active Sessions");for(let n of t)e.push(`- ${n.sessionId} (${n.state}) | ${n.credentialCount} credentials | last active ${new Date(n.lastActivityAt).toISOString()}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 AES-256-GCM encryption at rest in vault"),e.push("- \u2713 Per-session HKDF-derived encryption keys"),e.push(`- ${Le.zeroRetentionMode?"\u2713":"\u2717"} Zero-retention (no disk persistence)`),e.push(`- ${Le.rejectCrossSessionAccess?"\u2713":"\u2717"} Cross-session access blocked`),e.push(`- ${Le.preventContamination?"\u2713":"\u2717"} Contamination prevention`),e.push(`- ${Le.enforceScopeChecks?"\u2713":"\u2717"} Scope enforcement`),e.push(`- ${Le.enableCleanupVerification?"\u2713":"\u2717"} Cleanup verification`),e.push(`- \u2713 Multi-pass memory scrubbing (${Le.memoryScrubPasses} passes)`),e.push(`- ${Le.forceGcOnTeardown?"\u2713":"\u2717"} Force GC on teardown`),e.push(`- ${Le.enableAccessLog?"\u2713":"\u2717"} Audit logging`),e.push(`- Auto-sweep: every 60s, idle timeout ${Le.sessionIdleTimeoutMs/6e4}min`),e.join(`
994
992
  `)}function wre(e){let t=On.get(e);if(!t)return`Session ${e} not found`;let n=[],r=t.state==="active"?"\u{1F7E2}":t.state==="tearing_down"?"\u{1F7E1}":"\u{1F534}";return n.push(`${r} Session: ${e}`),n.push(` State: ${t.state}`),n.push(` Owner: ${t.ownerAgent||"unknown"}`),n.push(` Credentials: ${t.credentials.size}`),n.push(` Issued: ${t.totalIssued} | Accessed: ${t.totalAccessed} | Destroyed: ${t.totalDestroyed}`),n.push(` Created: ${new Date(t.createdAt).toISOString()}`),n.push(` Last active: ${new Date(t.lastActivityAt).toISOString()}`),n.join(`
@@ -996,13 +994,13 @@ while ($true) { Start-Sleep -Seconds 30 }
996
994
  `,{flag:"a"})}catch{}}function rO(e){let t=eO();return Hre(U.signingAlgorithm,Buffer.from(t,"hex")).update(e).digest("hex")}function Wre(e,t){let n=rO(e);if(n.length!==t.length)return!1;try{return zre(Buffer.from(n,"hex"),Buffer.from(t,"hex"))}catch{return!1}}function Kre(e){let t=Buffer.from(JSON.stringify(e),"utf-8").toString("base64url"),n=rO(t);return`${t}.${n}`}function Yre(e){let[t,n]=e.split(".");if(!t||!n)return{claims:{},valid:!1};if(!Wre(t,n))return{claims:{},valid:!1};try{return{claims:JSON.parse(Buffer.from(t,"base64url").toString("utf-8")),valid:!0}}catch{return{claims:{},valid:!1}}}function sO(){let e=`${process.platform}:${process.arch}:${process.pid}:${process.cwd()}`;return Ure("sha256").update(e).digest("hex").slice(0,16)}async function Qre(e,t,n){switch(e){case"aws-sts":return{AWS_ACCESS_KEY_ID:"ASIA"+jn(8).toString("hex").toUpperCase(),AWS_SECRET_ACCESS_KEY:jn(20).toString("base64").replace(/[+/=]/g,"").slice(0,40),AWS_SESSION_TOKEN:jn(48).toString("base64"),AWS_EXPIRATION:new Date(Date.now()+n).toISOString()};case"gcp-iam":return{GOOGLE_APPLICATION_CREDENTIALS_JSON:JSON.stringify({type:"access_token",access_token:"ya29."+jn(40).toString("base64url"),expiry:new Date(Date.now()+n).toISOString()})};case"azure-ad":return{AZURE_ACCESS_TOKEN:"eyJ"+jn(80).toString("base64url"),AZURE_EXPIRES_AT:String(Math.floor((Date.now()+n)/1e3))};case"github-app":return{GITHUB_TOKEN:"ghs_"+jn(20).toString("base64url"),GITHUB_TOKEN_TYPE:"installation"};case"vault":return{VAULT_TOKEN:"hvs."+jn(24).toString("base64url"),VAULT_LEASE_DURATION:String(Math.floor(n/1e3))};case"kubernetes-sa":return{KUBE_TOKEN:"eyJ"+jn(60).toString("base64url")};case"oauth2":return{OAUTH_ACCESS_TOKEN:jn(32).toString("base64url"),OAUTH_TOKEN_TYPE:"Bearer",OAUTH_EXPIRES_IN:String(Math.floor(n/1e3))};case"database":return{DB_USERNAME:"jit_"+jn(4).toString("hex"),DB_PASSWORD:jn(24).toString("base64url")};case"api-key":return{API_KEY:"aiaca_jit_"+jn(20).toString("base64url")};case"gitlab-ci":return{CI_JOB_TOKEN:jn(32).toString("base64url")};default:return{TOKEN:jn(24).toString("base64url")}}}function iC(e,t){for(let n of t)if(n===e||n==="*"||Zre(n,e))return!0;return!1}function Zre(e,t){let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp("^"+n+"$").test(t)}async function iO(e){if(!U.enabled)return{error:"JIT issuance disabled"};if(U.emergencyKillSwitchActive)return{error:"Emergency kill switch active"};if(U.requireScope&&(!e.scopes||e.scopes.length===0))return{error:"Scopes required by policy"};let t=Date.now(),n=e.ttlMs??U.defaultTtlMs;if(n>U.maxTtlMs&&(n=U.maxTtlMs),n<1e3&&(n=1e3),e.parentTokenId){let c=cr.get(e.parentTokenId);if(!c)return{error:"Parent token not found"};if(c.revokedAt)return{error:"Parent token revoked"};if(c.expiresAt<t)return{error:"Parent token expired"};for(let l of e.scopes)if(!iC(l,c.claims.scopes))return{error:`Child scope "${l}" not in parent's scopes`};t+n>c.expiresAt&&(n=c.expiresAt-t)}let r=jn(16).toString("base64url"),s={iss:"aiaca",sub:e.agentId,aud:e.audience,iat:t,exp:t+n,nbf:t,jti:r,type:e.parentTokenId?"delegation":"task",provider:e.provider,scopes:e.scopes,taskId:e.taskId,agentId:e.agentId,parentTokenId:e.parentTokenId,maxUses:e.maxUses??U.defaultMaxUses,fingerprint:U.enableFingerprintBinding?sO():void 0},i=Kre(s),o=await Qre(e.provider,e.scopes,n),a={id:r,signedToken:i,claims:s,issuedAt:t,expiresAt:t+n,useCount:0,rawCredentials:o};return cr.set(r,a),Gs.has(e.taskId)||Gs.set(e.taskId,new Set),Gs.get(e.taskId).add(r),Ai.has(e.agentId)||Ai.set(e.agentId,new Set),Ai.get(e.agentId).add(r),tO(),W.totalIssued++,W.byProvider[e.provider]=(W.byProvider[e.provider]||0)+1,W.averageTtlMs=(W.averageTtlMs*(W.totalIssued-1)+n)/W.totalIssued,zs(),Fu({event:"issued",tokenId:r,taskId:e.taskId,agentId:e.agentId,provider:e.provider,audience:e.audience,scopes:e.scopes,ttlMs:n,parentTokenId:e.parentTokenId,reason:e.reason}),dc.emit("issued",{token:a}),{token:a,signedToken:i}}function oC(e,t){if(!U.enabled)return{valid:!1,reason:"JIT disabled",riskScore:0,shouldRotate:!1,shouldRevoke:!1};if(U.emergencyKillSwitchActive)return{valid:!1,reason:"Emergency kill switch active",riskScore:1,shouldRotate:!1,shouldRevoke:!0};if(U.globalRevocationActive)return{valid:!1,reason:"Global revocation active",riskScore:1,shouldRotate:!1,shouldRevoke:!0};W.totalValidations++;let n=Yre(e);if(!n.valid)return W.totalFailedValidations++,zs(),{valid:!1,reason:"Invalid signature",riskScore:.95,shouldRotate:!1,shouldRevoke:!1};let r=n.claims;if(Do.has(r.jti))return W.totalFailedValidations++,zs(),{valid:!1,reason:"Token revoked",claims:r,riskScore:.9,shouldRotate:!1,shouldRevoke:!0};let s=cr.get(r.jti);if(!s)return W.totalFailedValidations++,zs(),{valid:!1,reason:"Token not found in active store",claims:r,riskScore:.7,shouldRotate:!1,shouldRevoke:!0};if(s.revokedAt)return{valid:!1,reason:`Token revoked: ${s.revokeReason||"unknown"}`,claims:r,riskScore:.9,shouldRotate:!1,shouldRevoke:!0};let i=Date.now();if(r.exp<i)return W.totalFailedValidations++,zs(),{valid:!1,reason:"Token expired",claims:r,riskScore:.5,shouldRotate:!1,shouldRevoke:!0};if(r.nbf>i)return{valid:!1,reason:"Token not yet valid",claims:r,riskScore:.3,shouldRotate:!1,shouldRevoke:!1};if(U.enableFingerprintBinding&&r.fingerprint){let u=sO();if(r.fingerprint!==u)return{valid:!1,reason:"Fingerprint mismatch \u2014 possible token theft",claims:r,riskScore:.99,shouldRotate:!1,shouldRevoke:!0}}if(r.maxUses!==void 0&&s.useCount>=r.maxUses)return{valid:!1,reason:"Max uses exceeded",claims:r,riskScore:.7,shouldRotate:!1,shouldRevoke:!0};if(t&&!iC(t,r.scopes))return W.totalDenied++,zs(),{valid:!1,reason:`Scope "${t}" not granted`,claims:r,riskScore:.6,shouldRotate:!1,shouldRevoke:!1};let o=i-r.iat,a=r.exp-r.iat,l=o/a*100>=U.rotationThresholdPct;return{valid:!0,reason:"OK",claims:r,riskScore:.05,shouldRotate:l,shouldRevoke:!1}}function Xre(e,t){let n=oC(e,t);if(!n.valid||!n.claims)return(U.auditAllUses||n.shouldRevoke)&&Fu({event:"use_denied",tokenId:n.claims?.jti,reason:n.reason}),{error:n.reason};let r=cr.get(n.claims.jti);return r.useCount++,r.lastUsedAt=Date.now(),W.totalUses++,W.totalUses>0&&(W.averageUseCount=(W.averageUseCount*(W.totalUses-1)+1)/W.totalUses),U.auditAllUses&&Fu({event:"use",tokenId:n.claims.jti,useCount:r.useCount}),dc.emit("used",{token:r}),{credentials:r.rawCredentials}}function Bu(e,t){let n=cr.get(e);if(!n)return!1;if(n.revokedAt=Date.now(),n.revokeReason=t,Do.add(e),n.rawCredentials){for(let r of Object.keys(n.rawCredentials))n.rawCredentials[r]="";delete n.rawCredentials}return cr.delete(e),Gs.get(n.claims.taskId)?.delete(e),Ai.get(n.claims.agentId)?.delete(e),W.totalRevoked++,tO(),nO(),zs(),Fu({event:"revoked",tokenId:e,reason:t,taskId:n.claims.taskId}),dc.emit("revoked",{tokenId:e,reason:t}),!0}function ese(e,t="task_ended"){let n=Gs.get(e);if(!n)return 0;let r=0;for(let s of Array.from(n))Bu(s,t)&&r++;return Gs.delete(e),r>0&&(Fu({event:"task_cleanup",taskId:e,count:r,reason:t}),W.byTaskCount++,zs()),r}function tse(e,t="agent_terminated"){let n=Ai.get(e);if(!n)return 0;let r=0;for(let s of Array.from(n))Bu(s,t)&&r++;return Ai.delete(e),r}function oO(){U.globalRevocationActive=!0;let e=0;for(let t of Array.from(cr.keys()))Bu(t,"global_revocation")&&e++;return Fu({event:"global_revocation",count:e}),dc.emit("global_revocation",{count:e}),e}function nse(){U.globalRevocationActive=!1}function rse(){return U.emergencyKillSwitchActive=!0,oO()}function aO(){uc||(uc=setInterval(()=>ise(),U.cleanupIntervalMs),uc.unref&&uc.unref())}function sse(){uc&&(clearInterval(uc),uc=null)}function ise(){let e=Date.now(),t=0;for(let[n,r]of Array.from(cr.entries()))r.expiresAt<e&&(Bu(n,"expired"),W.totalExpired++,t++);if(Do.size>1e4){let n=Array.from(Do);Do.clear();for(let r of n.slice(-5e3))Do.add(r);nO()}return t>0&&(zs(),dc.emit("cleanup",{expired:t})),t}async function ose(e){let t=oC(e);if(!t.valid||!t.claims)return{error:t.reason};let n=t.claims,r=await iO({taskId:n.taskId,agentId:n.agentId,provider:n.provider,audience:n.aud,scopes:n.scopes,ttlMs:U.defaultTtlMs,maxUses:n.maxUses,reason:"refresh from "+n.jti});return"error"in r||Bu(n.jti,"refreshed"),r}function ase(){return{...U,signingKey:U.signingKey?"[REDACTED]":""}}function cse(e){U={...U,...e}}function lse(){return{...W}}function use(){W={totalIssued:0,totalRevoked:0,totalExpired:0,totalValidations:0,totalFailedValidations:0,totalUses:0,totalDenied:0,byProvider:{},byTaskCount:0,averageTtlMs:0,averageUseCount:0},zs()}function dse(){return dc}function cO(){let e=Date.now();return Array.from(cr.values()).map(t=>({id:t.id,taskId:t.claims.taskId,agentId:t.claims.agentId,provider:t.claims.provider,audience:t.claims.aud,scopes:t.claims.scopes,ttlRemainingMs:Math.max(0,t.expiresAt-e),useCount:t.useCount}))}function fse(e){let t=Gs.get(e);return t?Array.from(t).map(n=>cr.get(n)).filter(Boolean):[]}function pse(e=100){if(!nm(rC))return[];try{return rm(rC,"utf-8").split(`
997
995
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function mse(){let e=[],t=Date.now();e.push("# JIT Credential Issuance Compliance Report"),e.push(`Generated: ${new Date(t).toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total issued: ${W.totalIssued}`),e.push(`- Active: ${cr.size}`),e.push(`- Revoked: ${W.totalRevoked}`),e.push(`- Expired: ${W.totalExpired}`),e.push(`- Validations: ${W.totalValidations}`),e.push(`- Failed validations: ${W.totalFailedValidations}`),e.push(`- Total uses: ${W.totalUses}`),e.push(`- Denied uses: ${W.totalDenied}`),e.push(`- Avg TTL: ${(W.averageTtlMs/1e3/60).toFixed(1)} min`),e.push(`- Tasks served: ${W.byTaskCount}`),e.push(""),e.push("## By Provider");for(let[n,r]of Object.entries(W.byProvider).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## Currently Active Tokens");for(let n of cO())e.push(`- ${n.id} | ${n.provider} | task=${n.taskId} | ${(n.ttlRemainingMs/1e3/60).toFixed(1)}min remaining | uses=${n.useCount}`);return e.push(""),e.push("## Compliance Properties"),e.push(`- \u2713 Default TTL: ${(U.defaultTtlMs/1e3/60).toFixed(0)} minutes`),e.push(`- \u2713 Max TTL: ${(U.maxTtlMs/1e3/60).toFixed(0)} minutes`),e.push(`- \u2713 HMAC-${U.signingAlgorithm.toUpperCase()} signing`),e.push(`- ${U.zeroTrustMode?"\u2713":"\u2717"} Zero-trust mode (re-validate every use)`),e.push(`- ${U.requireScope?"\u2713":"\u2717"} Scope required by policy`),e.push(`- ${U.enableFingerprintBinding?"\u2713":"\u2717"} Fingerprint binding`),e.push(`- ${U.enableAuditLog?"\u2713":"\u2717"} Audit logging`),e.push(`- \u2713 Automatic cleanup every ${U.cleanupIntervalMs/1e3}s`),e.join(`
998
996
  `)}function gse(e){let t=[],n=Date.now(),r=Math.max(0,e.expiresAt-n);return t.push(`Token: ${e.id}`),t.push(` Provider: ${e.claims.provider}`),t.push(` Task: ${e.claims.taskId}`),t.push(` Agent: ${e.claims.agentId}`),t.push(` Audience: ${e.claims.aud}`),t.push(` Scopes: ${e.claims.scopes.join(", ")}`),t.push(` TTL remaining: ${(r/1e3/60).toFixed(1)}min`),t.push(` Uses: ${e.useCount}/${e.claims.maxUses??"\u221E"}`),e.revokedAt&&t.push(` \u26A0\uFE0F Revoked: ${e.revokeReason}`),t.join(`
999
- `)}var Vre,U,Ou,eC,tC,nC,rC,sC,dc,cr,Gs,Ai,Do,W,uc,pc=w(()=>{"use strict";Vre={enabled:!0,defaultTtlMs:900*1e3,maxTtlMs:3600*1e3,defaultMaxUses:100,signingKey:"",signingAlgorithm:"sha256",requireScope:!0,zeroTrustMode:!0,rotationThresholdPct:75,enableIpBinding:!1,enableFingerprintBinding:!0,cleanupIntervalMs:6e4,retainExpiredMs:1440*60*1e3,globalRevocationActive:!1,emergencyKillSwitchActive:!1,enableAuditLog:!0,auditAllUses:!1},U={...Vre},Ou=Lu(qre(),".aiaca","jit-creds"),eC=Lu(Ou,"signing.key"),tC=Lu(Ou,"tokens.json"),nC=Lu(Ou,"revoked.json"),rC=Lu(Ou,"audit.jsonl"),sC=Lu(Ou,"stats.json"),dc=new Gre;dc.setMaxListeners(50);cr=new Map,Gs=new Map,Ai=new Map,Do=new Set,W={totalIssued:0,totalRevoked:0,totalExpired:0,totalValidations:0,totalFailedValidations:0,totalUses:0,totalDenied:0,byProvider:{},byTaskCount:0,averageTtlMs:0,averageUseCount:0};Jre();uc=null;U.enabled&&aO();process.on("exit",()=>{for(let e of cr.values())if(e.rawCredentials){for(let t of Object.keys(e.rawCredentials))e.rawCredentials[t]="";delete e.rawCredentials}})});var nb={};$(nb,{StreamRecorder:()=>dC,clearAll:()=>Mse,clearDiskCache:()=>gO,clearMemoryCache:()=>mO,computeFingerprint:()=>Xy,configure:()=>Pse,getConfig:()=>Rse,getStreamCacheStats:()=>_se,lookupCache:()=>$se,pruneStale:()=>Ese,replayPrefixThenContinue:()=>Tse,replayStream:()=>Ase,resetStats:()=>Ise,warmCache:()=>Dse});import{existsSync as Nu,mkdirSync as hse,readFileSync as aC,writeFileSync as pC,unlinkSync as mC}from"fs";import{join as Qy}from"path";import{homedir as yse}from"os";import{createHash as dO}from"crypto";function im(){hse(Zy,{recursive:!0})}function om(e){return Qy(Zy,`${e.slice(0,16)}.json`)}function uC(e){return Math.ceil(e.length/4)}function vse(e){return e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(t=>t.length>1)}function Xy(e){let t=e.messages.map(s=>({role:s.role,content:s.content})),n=[...e.tools].sort((s,i)=>s.name.localeCompare(i.name)),r=JSON.stringify({model:e.model,systemPrompt:e.systemPrompt,messages:t,tools:n,temperature:e.temperature});return dO("sha256").update(r).digest("hex").slice(0,32)}function fO(e){let t=[...e].reverse().find(n=>n.role==="user");return dO("md5").update(t?.content||"").digest("hex").slice(0,16)}function wse(e){return Sse.some(t=>t.test(e))}function gC(e){let t=vse(e),n=new Map;for(let i of t)n.set(i,(n.get(i)||0)+1);let r=Math.max(...n.values(),1),s=new Map;for(let[i,o]of n)s.set(i,o/r);return s}function lO(e,t){let n=0,r=0,s=0;for(let i of e.values())r+=i*i;for(let i of t.values())s+=i*i;for(let[i,o]of e){let a=t.get(i);a&&(n+=o*a)}return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function eb(e){let t=Fo.indexOf(e);t>=0&&Fo.splice(t,1),Fo.push(e)}function tb(){for(;(Cn.size>Ze.maxMemoryEntries||Lo>Ze.maxMemoryBytes)&&Fo.length>0;){let e=Fo.shift(),t=Cn.get(e);t&&(Lo-=t.size,Cn.delete(e))}}function kse(){if(im(),Nu(cC))try{An=JSON.parse(aC(cC,"utf-8")),Ti=An.totalBytes||0}catch{}if(Nu(lC))try{let e=JSON.parse(aC(lC,"utf-8"));for(let[t,n]of Object.entries(e))Oo.set(t,n)}catch{}}function am(){im(),An.totalBytes=Ti;try{pC(cC,JSON.stringify(An),"utf-8")}catch{}}function cm(){im();let e={};for(let[t,n]of Oo)e[t]=n;try{pC(lC,JSON.stringify(e),"utf-8")}catch{}}function uO(e){let t=om(e);if(!Nu(t))return null;try{let n=JSON.parse(aC(t,"utf-8")),r=new Map(Oo.get(e)||[]);return{...n,vectorTerms:r}}catch{return null}}function pO(e){im();let t=om(e.fingerprint);try{let{vectorTerms:n,...r}=e;pC(t,JSON.stringify(r),"utf-8"),An.entries[e.fingerprint]={fingerprint:e.fingerprint,model:e.model,cachedAt:e.cachedAt,hits:e.hits,size:e.size,promptHash:e.promptHash},Ti+=e.size,Oo.set(e.fingerprint,Array.from(n.entries())),am(),cm(),xse()}catch{}}function xse(){if(Ti<=Ze.maxDiskBytes)return;let e=Object.entries(An.entries).map(([t,n])=>({fp:t,score:(n.hits+1)/Math.max(1,(Date.now()-n.cachedAt)/(3600*1e3)),size:n.size})).sort((t,n)=>t.score-n.score);for(;Ti>Ze.maxDiskBytes*.8&&e.length>0;){let t=e.shift(),n=om(t.fp);try{Nu(n)&&mC(n),delete An.entries[t.fp],Oo.delete(t.fp),Ti-=t.size}catch{}}am(),cm()}function $se(e){if(!Ze.enabled)return null;let t=Xy(e),n=Cn.get(t);if(n&&Date.now()-n.cachedAt<Ze.ttlMs&&!(Ze.perModelIsolation&&n.model!==e.model))return n.hits++,n.lastHitAt=Date.now(),eb(t),Q.totalHits++,Q.exactHits++,Q.totalTokensSaved+=n.totalTokens,Q.totalLatencyAvoidedMs+=n.totalDurationMs,{type:"exact",cachedStream:n,similarity:1};if(An.entries[t]){let r=uO(t);if(r&&Date.now()-r.cachedAt<Ze.ttlMs)return Cse(r),r.hits++,Q.totalHits++,Q.exactHits++,Q.totalTokensSaved+=r.totalTokens,Q.totalLatencyAvoidedMs+=r.totalDurationMs,{type:"exact",cachedStream:r,similarity:1}}if(Ze.enablePrefixMatch&&!Ze.exactMatchOnly){let r=[...e.messages].reverse().find(s=>s.role==="user")?.content||"";if(r.length>20)for(let s of Cn.values()){if(Ze.perModelIsolation&&s.model!==e.model||Date.now()-s.cachedAt>Ze.ttlMs)continue;let i=s.fullText;if(i.startsWith(r)&&i.length>r.length+50){let o=uC(r);return Q.totalHits++,Q.prefixHits++,Q.totalTokensSaved+=o,{type:"prefix",cachedStream:s,similarity:r.length/i.length,sharedPrefixTokens:o,remainingTokensNeeded:s.totalTokens-o}}}}if(Ze.enableSemanticMatch&&!Ze.exactMatchOnly){let r=e.messages.map(a=>a.content).join(" "),s=gC(r),i=null,o=Ze.minSimilarity;for(let a of Cn.values()){if(Ze.perModelIsolation&&a.model!==e.model||Date.now()-a.cachedAt>Ze.ttlMs)continue;let c=lO(s,a.vectorTerms);c>o&&(o=c,i=a)}for(let[a,c]of Oo){if(Cn.has(a))continue;let l=An.entries[a];if(!l||Ze.perModelIsolation&&l.model!==e.model||Date.now()-l.cachedAt>Ze.ttlMs)continue;let u=new Map(c),d=lO(s,u);if(d>o){let f=uO(a);f&&(o=d,i=f)}}if(i)return i.hits++,Q.totalHits++,Q.semanticHits++,Q.totalTokensSaved+=i.totalTokens,Q.totalLatencyAvoidedMs+=i.totalDurationMs,{type:"semantic",cachedStream:i,similarity:o}}return Q.totalMisses++,null}function Cse(e){Cn.has(e.fingerprint)||(Cn.set(e.fingerprint,e),Lo+=e.size,eb(e.fingerprint),tb())}async function Ase(e,t){let n=e.cachedStream;if(t.preserveTiming){let r=t.speedMultiplier||1,s=Date.now(),i=0;for(let o of n.events){let a=o.timestamp/r,c=s+a-Date.now();c>0&&await new Promise(l=>setTimeout(l,c)),fC(o,t.onChunk),i=o.timestamp}}else for(let r of n.events)fC(r,t.onChunk),Math.random()<.1&&await new Promise(s=>setImmediate(s));return n.finalResponse}function fC(e,t){e.type==="text"&&e.text?t({type:"text",text:e.text}):e.type==="tool_call_start"?t({type:"tool_call_start",toolCall:{id:e.toolCallId,name:e.toolName}}):e.type==="tool_call_input"?t({type:"tool_call_delta",toolCall:{id:e.toolCallId,input:e.toolInput}}):e.type==="tool_call_end"?t({type:"tool_call_end",toolCall:{id:e.toolCallId}}):e.type==="message_stop"&&t({type:"done"})}async function Tse(e,t,n,r){let s=0;for(let i of e.cachedStream.events){if(s>=t)break;fC(i,n.onChunk),s+=i.tokenCount||0}return r()}function _se(){let e=Q.totalHits+Q.totalMisses,t=e>0?Q.totalHits/e:0,n=Q.totalTokensSaved/1e6*15,s=[...Cn.values(),...Object.values(An.entries).map(i=>({promptHash:i.promptHash,hits:i.hits,totalTokens:500}))].sort((i,o)=>o.hits-i.hits).slice(0,10).map(i=>({promptPreview:i.fullText?.slice(0,60)||i.promptHash,hits:i.hits,tokens:i.totalTokens||0}));return{memoryEntries:Cn.size,memoryBytes:Lo,diskEntries:Object.keys(An.entries).length,diskBytes:Ti,totalHits:Q.totalHits,exactHits:Q.exactHits,prefixHits:Q.prefixHits,semanticHits:Q.semanticHits,partialHits:Q.partialHits,totalMisses:Q.totalMisses,hitRate:t,totalTokensSaved:Q.totalTokensSaved,totalLatencyAvoidedMs:Q.totalLatencyAvoidedMs,estimatedCostSavedUSD:n,topCachedQueries:s}}function Rse(){return{...Ze}}function Pse(e){Ze={...Ze,...e},tb()}function Ise(){Q.totalHits=0,Q.exactHits=0,Q.prefixHits=0,Q.semanticHits=0,Q.partialHits=0,Q.totalMisses=0,Q.totalTokensSaved=0,Q.totalLatencyAvoidedMs=0}function mO(){Cn.clear(),Fo.length=0,Lo=0}function gO(){im();for(let[e]of Object.entries(An.entries)){let t=om(e);try{Nu(t)&&mC(t)}catch{}}An.entries={},An.totalBytes=0,Oo.clear(),Ti=0,am(),cm()}function Mse(){mO(),gO()}function Ese(){let e=0,t=Date.now()-Ze.ttlMs;for(let[n,r]of Cn)if(r.cachedAt<t){Cn.delete(n),Lo-=r.size;let s=Fo.indexOf(n);s>=0&&Fo.splice(s,1),e++}for(let[n,r]of Object.entries(An.entries))if(r.cachedAt<t){let s=om(n);try{Nu(s)&&mC(s)}catch{}delete An.entries[n],Oo.delete(n),Ti-=r.size,e++}return e>0&&(am(),cm()),e}async function Dse(e,t,n=2){let r=0,s=0,i=[...e];async function o(){for(;i.length>0;){let a=i.shift();if(!a)break;let c=Xy(a);if(Cn.has(c)||An.entries[c]){s++;continue}try{let{response:l,events:u}=await t(a),d={fingerprint:c,model:a.model,events:u,finalResponse:l,totalTokens:u.reduce((f,p)=>f+(p.tokenCount||0),0),totalDurationMs:u.length>0?u[u.length-1].timestamp:0,cachedAt:Date.now(),hits:0,lastHitAt:Date.now(),size:u.reduce((f,p)=>f+JSON.stringify(p).length,0),vectorTerms:gC(a.messages.map(f=>f.content).join(" ")),fullText:l.content||"",promptHash:fO(a.messages)};Cn.set(c,d),Lo+=d.size,eb(c),tb(),pO(d),r++}catch{}}}return await Promise.all(Array.from({length:n},()=>o())),{warmed:r,skipped:s}}var bse,Zy,cC,lC,Sse,Ze,Cn,Lo,Ti,Fo,Q,An,Oo,dC,rb=w(()=>{"use strict";bse={enabled:!0,maxMemoryEntries:200,maxMemoryBytes:50*1024*1024,maxDiskBytes:500*1024*1024,ttlMs:1440*60*1e3,exactMatchOnly:!1,minSimilarity:.85,enablePrefixMatch:!0,enableSemanticMatch:!0,preserveTiming:!1,privacyMode:!1,perModelIsolation:!0,compressDisk:!1},Zy=Qy(yse(),".aiaca","stream-cache"),cC=Qy(Zy,"index.json"),lC=Qy(Zy,"vectors.json");Sse=[/sk-[\w-]{20,}/,/AKIA[0-9A-Z]{16}/,/AIza[\w-]{35}/,/Bearer\s+[\w.-]+/i,/(?:password|api[_-]?key|secret|token)[\s=:]+[\w-]{8,}/i];Ze={...bse},Cn=new Map,Lo=0,Ti=0,Fo=[],Q={totalHits:0,exactHits:0,prefixHits:0,semanticHits:0,partialHits:0,totalMisses:0,totalTokensSaved:0,totalLatencyAvoidedMs:0};An={entries:{},totalBytes:0},Oo=new Map;kse();dC=class{events=[];startTime=Date.now();currentText="";input;model;constructor(t){this.input=t,this.model=t.model}recordChunk(t){let n=Date.now()-this.startTime;t.type==="text"&&t.text?(this.currentText+=t.text,this.events.push({type:"text",text:t.text,timestamp:n,tokenCount:uC(t.text)})):t.type==="tool_call_start"?this.events.push({type:"tool_call_start",toolCallId:t.toolCall?.id,toolName:t.toolCall?.name,timestamp:n}):t.type==="tool_call_delta"?this.events.push({type:"tool_call_input",toolCallId:t.toolCall?.id,toolInput:t.toolCall?.input,timestamp:n}):t.type==="tool_call_end"?this.events.push({type:"tool_call_end",toolCallId:t.toolCall?.id,timestamp:n}):t.type==="done"&&this.events.push({type:"message_stop",timestamp:n})}finalize(t){if(!Ze.enabled||Ze.privacyMode||wse(this.currentText))return;let n=Date.now()-this.startTime,r=Xy(this.input),s=this.input.messages.map(o=>o.content).join(" "),i={fingerprint:r,model:this.model,events:[...this.events],finalResponse:t,totalTokens:uC(this.currentText),totalDurationMs:n,cachedAt:Date.now(),hits:0,lastHitAt:Date.now(),size:this.estimateSize(),vectorTerms:gC(s),fullText:this.currentText,promptHash:fO(this.input.messages)};Cn.set(r,i),Lo+=i.size,eb(r),tb(),queueMicrotask(()=>pO(i))}estimateSize(){let t=0;for(let n of this.events)t+=JSON.stringify(n).length;return t}};process.on("exit",()=>{am(),cm()})});var dm={};$(dm,{acknowledgeAnomaly:()=>sie,addSource:()=>lie,analyzeAnomaly:()=>Zse,applyHotfix:()=>Xse,configure:()=>cie,formatAnomaly:()=>die,getAnomalies:()=>rie,getConfig:()=>aie,getEvents:()=>oie,getLogs:()=>eie,getMetric:()=>tie,getStats:()=>fie,ingestLog:()=>Uu,ingestMetric:()=>Hse,ingestTrace:()=>zse,listMetrics:()=>nie,pollDatadog:()=>bO,removeSource:()=>uie,resolveAnomaly:()=>iie,startPolling:()=>wO,stopAllTails:()=>yO,stopPolling:()=>kO,tailDocker:()=>Vse,tailFile:()=>Gse,tailKubernetes:()=>Jse});import{existsSync as hC,mkdirSync as Fse,readFileSync as yC,writeFileSync as sb}from"fs";import{join as lm}from"path";import{homedir as Lse}from"os";import{execSync as ib,spawn as ab}from"child_process";import{createHash as Ose}from"crypto";import{EventEmitter as jse}from"events";function wC(){Fse(um,{recursive:!0})}function qse(){if(wC(),hC(SC))try{de={...de,...JSON.parse(yC(SC,"utf-8"))}}catch{}if(hC(bC))try{let e=JSON.parse(yC(bC,"utf-8"));if(e.logs&&Ur.push(...e.logs.slice(-de.maxLogEntries)),e.metrics)for(let[t,n]of Object.entries(e.metrics))ps.set(t,n)}catch{}if(hC(vC))try{let e=JSON.parse(yC(vC,"utf-8"));for(let t of e)_i.set(t.id,t)}catch{}}function Ri(){if(de.enablePersistence){wC();try{sb(bC,JSON.stringify({logs:Ur.slice(-de.maxLogEntries),metrics:Object.fromEntries(ps)}),"utf-8"),sb(vC,JSON.stringify(Array.from(_i.values())),"utf-8"),sb(SC,JSON.stringify(de,null,2),"utf-8")}catch{}}}function Use(e){wC();try{sb(Nse,JSON.stringify({...e,timestamp:Date.now()})+`
1000
- `,{flag:"a"})}catch{}}function Uu(e){let t={timestamp:e.timestamp||Date.now(),source:e.source||"unknown",level:e.level||"info",message:e.message||"",service:e.service,host:e.host,trace_id:e.trace_id,span_id:e.span_id,metadata:e.metadata||{}};Ur.push(t),Ur.length>de.maxLogEntries&&Ur.shift(),Hu.emit("log",t),(t.level==="error"||t.level==="fatal")&&setImmediate(()=>vO())}function Hse(e){let t={name:e.name||"unnamed",value:e.value||0,timestamp:e.timestamp||Date.now(),labels:e.labels||{},unit:e.unit};ps.has(t.name)||ps.set(t.name,[]);let n=ps.get(t.name);n.push(t),n.length>de.maxMetricSamples/ps.size&&n.shift(),Hu.emit("metric",t),setImmediate(()=>SO(t.name))}function zse(e){ob.push(e),ob.length>1e3&&ob.shift(),Hu.emit("trace",e)}function Gse(e,t){let n=`file:${e}`;if(Vs.has(n))return()=>mc(n);let s=process.platform==="win32"?ab("powershell",["-Command",`Get-Content -Path "${e}" -Wait -Tail 0`]):ab("tail",["-F",e]);return s.stdout?.on("data",i=>{let o=i.toString();for(let a of o.split(`
997
+ `)}var Vre,U,Ou,eC,tC,nC,rC,sC,dc,cr,Gs,Ai,Do,W,uc,pc=w(()=>{"use strict";Vre={enabled:!0,defaultTtlMs:900*1e3,maxTtlMs:3600*1e3,defaultMaxUses:100,signingKey:"",signingAlgorithm:"sha256",requireScope:!0,zeroTrustMode:!0,rotationThresholdPct:75,enableIpBinding:!1,enableFingerprintBinding:!0,cleanupIntervalMs:6e4,retainExpiredMs:1440*60*1e3,globalRevocationActive:!1,emergencyKillSwitchActive:!1,enableAuditLog:!0,auditAllUses:!1},U={...Vre},Ou=Lu(qre(),".aiaca","jit-creds"),eC=Lu(Ou,"signing.key"),tC=Lu(Ou,"tokens.json"),nC=Lu(Ou,"revoked.json"),rC=Lu(Ou,"audit.jsonl"),sC=Lu(Ou,"stats.json"),dc=new Gre;dc.setMaxListeners(50);cr=new Map,Gs=new Map,Ai=new Map,Do=new Set,W={totalIssued:0,totalRevoked:0,totalExpired:0,totalValidations:0,totalFailedValidations:0,totalUses:0,totalDenied:0,byProvider:{},byTaskCount:0,averageTtlMs:0,averageUseCount:0};Jre();uc=null;U.enabled&&aO();process.on("exit",()=>{for(let e of cr.values())if(e.rawCredentials){for(let t of Object.keys(e.rawCredentials))e.rawCredentials[t]="";delete e.rawCredentials}})});var nb={};$(nb,{StreamRecorder:()=>dC,clearAll:()=>Mse,clearDiskCache:()=>gO,clearMemoryCache:()=>mO,computeFingerprint:()=>Xy,configure:()=>Pse,getConfig:()=>Rse,getStreamCacheStats:()=>_se,lookupCache:()=>$se,pruneStale:()=>Ese,replayPrefixThenContinue:()=>Tse,replayStream:()=>Ase,resetStats:()=>Ise,warmCache:()=>Dse});import{existsSync as Nu,mkdirSync as hse,readFileSync as aC,writeFileSync as pC,unlinkSync as mC}from"fs";import{join as Qy}from"path";import{homedir as yse}from"os";import{createHash as dO}from"crypto";function im(){hse(Zy,{recursive:!0})}function om(e){return Qy(Zy,`${e.slice(0,16)}.json`)}function uC(e){return Math.ceil(e.length/4)}function vse(e){return e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(t=>t.length>1)}function Xy(e){let t=e.messages.map(s=>({role:s.role,content:s.content})),n=[...e.tools].sort((s,i)=>s.name.localeCompare(i.name)),r=JSON.stringify({model:e.model,systemPrompt:e.systemPrompt,messages:t,tools:n,temperature:e.temperature});return dO("sha256").update(r).digest("hex").slice(0,32)}function fO(e){let t=[...e].reverse().find(n=>n.role==="user");return dO("md5").update(t?.content||"").digest("hex").slice(0,16)}function wse(e){return Sse.some(t=>t.test(e))}function gC(e){let t=vse(e),n=new Map;for(let i of t)n.set(i,(n.get(i)||0)+1);let r=Math.max(...n.values(),1),s=new Map;for(let[i,o]of n)s.set(i,o/r);return s}function lO(e,t){let n=0,r=0,s=0;for(let i of e.values())r+=i*i;for(let i of t.values())s+=i*i;for(let[i,o]of e){let a=t.get(i);a&&(n+=o*a)}return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function eb(e){let t=Fo.indexOf(e);t>=0&&Fo.splice(t,1),Fo.push(e)}function tb(){for(;(Cn.size>Ze.maxMemoryEntries||Lo>Ze.maxMemoryBytes)&&Fo.length>0;){let e=Fo.shift(),t=Cn.get(e);t&&(Lo-=t.size,Cn.delete(e))}}function kse(){if(im(),Nu(cC))try{An=JSON.parse(aC(cC,"utf-8")),Ti=An.totalBytes||0}catch{}if(Nu(lC))try{let e=JSON.parse(aC(lC,"utf-8"));for(let[t,n]of Object.entries(e))Oo.set(t,n)}catch{}}function am(){im(),An.totalBytes=Ti;try{pC(cC,JSON.stringify(An),"utf-8")}catch{}}function cm(){im();let e={};for(let[t,n]of Oo)e[t]=n;try{pC(lC,JSON.stringify(e),"utf-8")}catch{}}function uO(e){let t=om(e);if(!Nu(t))return null;try{let n=JSON.parse(aC(t,"utf-8")),r=new Map(Oo.get(e)||[]);return{...n,vectorTerms:r}}catch{return null}}function pO(e){im();let t=om(e.fingerprint);try{let{vectorTerms:n,...r}=e;pC(t,JSON.stringify(r),"utf-8"),An.entries[e.fingerprint]={fingerprint:e.fingerprint,model:e.model,cachedAt:e.cachedAt,hits:e.hits,size:e.size,promptHash:e.promptHash},Ti+=e.size,Oo.set(e.fingerprint,Array.from(n.entries())),am(),cm(),xse()}catch{}}function xse(){if(Ti<=Ze.maxDiskBytes)return;let e=Object.entries(An.entries).map(([t,n])=>({fp:t,score:(n.hits+1)/Math.max(1,(Date.now()-n.cachedAt)/(3600*1e3)),size:n.size})).sort((t,n)=>t.score-n.score);for(;Ti>Ze.maxDiskBytes*.8&&e.length>0;){let t=e.shift(),n=om(t.fp);try{Nu(n)&&mC(n),delete An.entries[t.fp],Oo.delete(t.fp),Ti-=t.size}catch{}}am(),cm()}function $se(e){if(!Ze.enabled)return null;let t=Xy(e),n=Cn.get(t);if(n&&Date.now()-n.cachedAt<Ze.ttlMs&&!(Ze.perModelIsolation&&n.model!==e.model))return n.hits++,n.lastHitAt=Date.now(),eb(t),Q.totalHits++,Q.exactHits++,Q.totalTokensSaved+=n.totalTokens,Q.totalLatencyAvoidedMs+=n.totalDurationMs,{type:"exact",cachedStream:n,similarity:1};if(An.entries[t]){let r=uO(t);if(r&&Date.now()-r.cachedAt<Ze.ttlMs)return Cse(r),r.hits++,Q.totalHits++,Q.exactHits++,Q.totalTokensSaved+=r.totalTokens,Q.totalLatencyAvoidedMs+=r.totalDurationMs,{type:"exact",cachedStream:r,similarity:1}}if(Ze.enablePrefixMatch&&!Ze.exactMatchOnly){let r=[...e.messages].reverse().find(s=>s.role==="user")?.content||"";if(r.length>20)for(let s of Cn.values()){if(Ze.perModelIsolation&&s.model!==e.model||Date.now()-s.cachedAt>Ze.ttlMs)continue;let i=s.fullText;if(i.startsWith(r)&&i.length>r.length+50){let o=uC(r);return Q.totalHits++,Q.prefixHits++,Q.totalTokensSaved+=o,{type:"prefix",cachedStream:s,similarity:r.length/i.length,sharedPrefixTokens:o,remainingTokensNeeded:s.totalTokens-o}}}}if(Ze.enableSemanticMatch&&!Ze.exactMatchOnly){let r=e.messages.map(a=>a.content).join(" "),s=gC(r),i=null,o=Ze.minSimilarity;for(let a of Cn.values()){if(Ze.perModelIsolation&&a.model!==e.model||Date.now()-a.cachedAt>Ze.ttlMs)continue;let c=lO(s,a.vectorTerms);c>o&&(o=c,i=a)}for(let[a,c]of Oo){if(Cn.has(a))continue;let l=An.entries[a];if(!l||Ze.perModelIsolation&&l.model!==e.model||Date.now()-l.cachedAt>Ze.ttlMs)continue;let u=new Map(c),d=lO(s,u);if(d>o){let f=uO(a);f&&(o=d,i=f)}}if(i)return i.hits++,Q.totalHits++,Q.semanticHits++,Q.totalTokensSaved+=i.totalTokens,Q.totalLatencyAvoidedMs+=i.totalDurationMs,{type:"semantic",cachedStream:i,similarity:o}}return Q.totalMisses++,null}function Cse(e){Cn.has(e.fingerprint)||(Cn.set(e.fingerprint,e),Lo+=e.size,eb(e.fingerprint),tb())}async function Ase(e,t){let n=e.cachedStream;if(t.preserveTiming){let r=t.speedMultiplier||1,s=Date.now(),i=0;for(let o of n.events){let a=o.timestamp/r,c=s+a-Date.now();c>0&&await new Promise(l=>setTimeout(l,c)),fC(o,t.onChunk),i=o.timestamp}}else for(let r of n.events)fC(r,t.onChunk),Math.random()<.1&&await new Promise(s=>setImmediate(s));return n.finalResponse}function fC(e,t){e.type==="text"&&e.text?t({type:"text",text:e.text}):e.type==="tool_call_start"?t({type:"tool_call_start",toolCall:{id:e.toolCallId,name:e.toolName}}):e.type==="tool_call_input"?t({type:"tool_call_delta",toolCall:{id:e.toolCallId,input:e.toolInput}}):e.type==="tool_call_end"?t({type:"tool_call_end",toolCall:{id:e.toolCallId}}):e.type==="message_stop"&&t({type:"done"})}async function Tse(e,t,n,r){let s=0;for(let i of e.cachedStream.events){if(s>=t)break;fC(i,n.onChunk),s+=i.tokenCount||0}return r()}function _se(){let e=Q.totalHits+Q.totalMisses,t=e>0?Q.totalHits/e:0,n=Q.totalTokensSaved/1e6*15,s=[...Cn.values(),...Object.values(An.entries).map(i=>({promptHash:i.promptHash,hits:i.hits,totalTokens:500}))].sort((i,o)=>o.hits-i.hits).slice(0,10).map(i=>({promptPreview:i.fullText?.slice(0,60)||i.promptHash,hits:i.hits,tokens:i.totalTokens||0}));return{memoryEntries:Cn.size,memoryBytes:Lo,diskEntries:Object.keys(An.entries).length,diskBytes:Ti,totalHits:Q.totalHits,exactHits:Q.exactHits,prefixHits:Q.prefixHits,semanticHits:Q.semanticHits,partialHits:Q.partialHits,totalMisses:Q.totalMisses,hitRate:t,totalTokensSaved:Q.totalTokensSaved,totalLatencyAvoidedMs:Q.totalLatencyAvoidedMs,estimatedCostSavedUSD:n,topCachedQueries:s}}function Rse(){return{...Ze}}function Pse(e){Ze={...Ze,...e},tb()}function Ise(){Q.totalHits=0,Q.exactHits=0,Q.prefixHits=0,Q.semanticHits=0,Q.partialHits=0,Q.totalMisses=0,Q.totalTokensSaved=0,Q.totalLatencyAvoidedMs=0}function mO(){Cn.clear(),Fo.length=0,Lo=0}function gO(){im();for(let[e]of Object.entries(An.entries)){let t=om(e);try{Nu(t)&&mC(t)}catch{}}An.entries={},An.totalBytes=0,Oo.clear(),Ti=0,am(),cm()}function Mse(){mO(),gO()}function Ese(){let e=0,t=Date.now()-Ze.ttlMs;for(let[n,r]of Cn)if(r.cachedAt<t){Cn.delete(n),Lo-=r.size;let s=Fo.indexOf(n);s>=0&&Fo.splice(s,1),e++}for(let[n,r]of Object.entries(An.entries))if(r.cachedAt<t){let s=om(n);try{Nu(s)&&mC(s)}catch{}delete An.entries[n],Oo.delete(n),Ti-=r.size,e++}return e>0&&(am(),cm()),e}async function Dse(e,t,n=2){let r=0,s=0,i=[...e];async function o(){for(;i.length>0;){let a=i.shift();if(!a)break;let c=Xy(a);if(Cn.has(c)||An.entries[c]){s++;continue}try{let{response:l,events:u}=await t(a),d={fingerprint:c,model:a.model,events:u,finalResponse:l,totalTokens:u.reduce((f,p)=>f+(p.tokenCount||0),0),totalDurationMs:u.length>0?u[u.length-1].timestamp:0,cachedAt:Date.now(),hits:0,lastHitAt:Date.now(),size:u.reduce((f,p)=>f+JSON.stringify(p).length,0),vectorTerms:gC(a.messages.map(f=>f.content).join(" ")),fullText:l.content||"",promptHash:fO(a.messages)};Cn.set(c,d),Lo+=d.size,eb(c),tb(),pO(d),r++}catch{}}}return await Promise.all(Array.from({length:n},()=>o())),{warmed:r,skipped:s}}var bse,Zy,cC,lC,Sse,Ze,Cn,Lo,Ti,Fo,Q,An,Oo,dC,rb=w(()=>{"use strict";bse={enabled:!0,maxMemoryEntries:200,maxMemoryBytes:50*1024*1024,maxDiskBytes:500*1024*1024,ttlMs:1440*60*1e3,exactMatchOnly:!1,minSimilarity:.85,enablePrefixMatch:!0,enableSemanticMatch:!0,preserveTiming:!1,privacyMode:!1,perModelIsolation:!0,compressDisk:!1},Zy=Qy(yse(),".aiaca","stream-cache"),cC=Qy(Zy,"index.json"),lC=Qy(Zy,"vectors.json");Sse=[/sk-[\w-]{20,}/,/AKIA[0-9A-Z]{16}/,/AIza[\w-]{35}/,/Bearer\s+[\w.-]+/i,/(?:password|api[_-]?key|secret|token)[\s=:]+[\w-]{8,}/i];Ze={...bse},Cn=new Map,Lo=0,Ti=0,Fo=[],Q={totalHits:0,exactHits:0,prefixHits:0,semanticHits:0,partialHits:0,totalMisses:0,totalTokensSaved:0,totalLatencyAvoidedMs:0};An={entries:{},totalBytes:0},Oo=new Map;kse();dC=class{events=[];startTime=Date.now();currentText="";input;model;constructor(t){this.input=t,this.model=t.model}recordChunk(t){let n=Date.now()-this.startTime;t.type==="text"&&t.text?(this.currentText+=t.text,this.events.push({type:"text",text:t.text,timestamp:n,tokenCount:uC(t.text)})):t.type==="tool_call_start"?this.events.push({type:"tool_call_start",toolCallId:t.toolCall?.id,toolName:t.toolCall?.name,timestamp:n}):t.type==="tool_call_delta"?this.events.push({type:"tool_call_input",toolCallId:t.toolCall?.id,toolInput:t.toolCall?.input,timestamp:n}):t.type==="tool_call_end"?this.events.push({type:"tool_call_end",toolCallId:t.toolCall?.id,timestamp:n}):t.type==="done"&&this.events.push({type:"message_stop",timestamp:n})}finalize(t){if(!Ze.enabled||Ze.privacyMode||wse(this.currentText))return;let n=Date.now()-this.startTime,r=Xy(this.input),s=this.input.messages.map(o=>o.content).join(" "),i={fingerprint:r,model:this.model,events:[...this.events],finalResponse:t,totalTokens:uC(this.currentText),totalDurationMs:n,cachedAt:Date.now(),hits:0,lastHitAt:Date.now(),size:this.estimateSize(),vectorTerms:gC(s),fullText:this.currentText,promptHash:fO(this.input.messages)};Cn.set(r,i),Lo+=i.size,eb(r),tb(),queueMicrotask(()=>pO(i))}estimateSize(){let t=0;for(let n of this.events)t+=JSON.stringify(n).length;return t}};process.on("exit",()=>{am(),cm()})});var dm={};$(dm,{acknowledgeAnomaly:()=>sie,addSource:()=>lie,analyzeAnomaly:()=>Zse,applyHotfix:()=>Xse,configure:()=>cie,formatAnomaly:()=>die,getAnomalies:()=>rie,getConfig:()=>aie,getEvents:()=>oie,getLogs:()=>eie,getMetric:()=>tie,getStats:()=>fie,ingestLog:()=>Uu,ingestMetric:()=>Hse,ingestTrace:()=>zse,listMetrics:()=>nie,pollDatadog:()=>bO,removeSource:()=>uie,resolveAnomaly:()=>iie,startPolling:()=>wO,stopAllTails:()=>yO,stopPolling:()=>kO,tailDocker:()=>Vse,tailFile:()=>Gse,tailKubernetes:()=>Jse});import{existsSync as hC,mkdirSync as Fse,readFileSync as yC,writeFileSync as sb}from"fs";import{join as lm}from"path";import{homedir as Lse}from"os";import{execSync as ib,spawn as ab}from"child_process";import{createHash as Ose}from"crypto";import{EventEmitter as jse}from"events";function wC(){Fse(um,{recursive:!0})}function qse(){if(wC(),hC(SC))try{fe={...fe,...JSON.parse(yC(SC,"utf-8"))}}catch{}if(hC(bC))try{let e=JSON.parse(yC(bC,"utf-8"));if(e.logs&&Ur.push(...e.logs.slice(-fe.maxLogEntries)),e.metrics)for(let[t,n]of Object.entries(e.metrics))ps.set(t,n)}catch{}if(hC(vC))try{let e=JSON.parse(yC(vC,"utf-8"));for(let t of e)_i.set(t.id,t)}catch{}}function Ri(){if(fe.enablePersistence){wC();try{sb(bC,JSON.stringify({logs:Ur.slice(-fe.maxLogEntries),metrics:Object.fromEntries(ps)}),"utf-8"),sb(vC,JSON.stringify(Array.from(_i.values())),"utf-8"),sb(SC,JSON.stringify(fe,null,2),"utf-8")}catch{}}}function Use(e){wC();try{sb(Nse,JSON.stringify({...e,timestamp:Date.now()})+`
998
+ `,{flag:"a"})}catch{}}function Uu(e){let t={timestamp:e.timestamp||Date.now(),source:e.source||"unknown",level:e.level||"info",message:e.message||"",service:e.service,host:e.host,trace_id:e.trace_id,span_id:e.span_id,metadata:e.metadata||{}};Ur.push(t),Ur.length>fe.maxLogEntries&&Ur.shift(),Hu.emit("log",t),(t.level==="error"||t.level==="fatal")&&setImmediate(()=>vO())}function Hse(e){let t={name:e.name||"unnamed",value:e.value||0,timestamp:e.timestamp||Date.now(),labels:e.labels||{},unit:e.unit};ps.has(t.name)||ps.set(t.name,[]);let n=ps.get(t.name);n.push(t),n.length>fe.maxMetricSamples/ps.size&&n.shift(),Hu.emit("metric",t),setImmediate(()=>SO(t.name))}function zse(e){ob.push(e),ob.length>1e3&&ob.shift(),Hu.emit("trace",e)}function Gse(e,t){let n=`file:${e}`;if(Vs.has(n))return()=>mc(n);let s=process.platform==="win32"?ab("powershell",["-Command",`Get-Content -Path "${e}" -Wait -Tail 0`]):ab("tail",["-F",e]);return s.stdout?.on("data",i=>{let o=i.toString();for(let a of o.split(`
1001
999
  `).filter(Boolean)){let c=t?t(a):kC(a);c&&Uu({...c,source:n})}}),s.on("error",i=>{console.error(`Tail error for ${e}:`,i.message)}),Vs.set(n,s),()=>mc(n)}function mc(e){let t=Vs.get(e);if(t){try{t.kill("SIGTERM")}catch{}Vs.delete(e)}}function yO(){for(let e of Vs.keys())mc(e)}function kC(e){if(!e.trim())return null;let t="info",n=e.toLowerCase();/\b(fatal|panic)\b/.test(n)?t="fatal":/\b(error|err|exception)\b/.test(n)?t="error":/\bwarn(ing)?\b/.test(n)?t="warn":/\bdebug\b/.test(n)?t="debug":/\btrace\b/.test(n)&&(t="trace");try{let r=JSON.parse(e);return{timestamp:r.timestamp||r.time?new Date(r.timestamp||r.time).getTime():Date.now(),level:r.level||t,message:r.message||r.msg||e,service:r.service,trace_id:r.trace_id||r.traceId,metadata:r}}catch{}return{level:t,message:e.slice(0,2e3)}}function Vse(e){let t=`docker:${e}`;if(Vs.has(t))return()=>mc(t);let n=ab("docker",["logs","-f","--tail","0",e]);return n.stdout?.on("data",r=>{for(let s of r.toString().split(`
1002
1000
  `).filter(Boolean)){let i=kC(s);i&&Uu({...i,source:t,service:e})}}),n.stderr?.on("data",r=>{for(let s of r.toString().split(`
1003
1001
  `).filter(Boolean))Uu({source:t,level:"error",message:s,service:e})}),Vs.set(t,n),()=>mc(t)}function Jse(e,t="default"){let n=`k8s:${t}/${e}`;if(Vs.has(n))return()=>mc(n);let r=ab("kubectl",["logs","-f",e,"-n",t]);return r.stdout?.on("data",s=>{for(let i of s.toString().split(`
1004
- `).filter(Boolean)){let o=kC(i);o&&Uu({...o,source:n,service:e})}}),Vs.set(n,r),()=>mc(n)}async function bO(e,t){let n=Date.now()-de.pollIntervalMs*2;try{let r=await fetch("https://api.datadoghq.com/api/v2/logs/events/search",{method:"POST",headers:{"DD-API-KEY":e,"Content-Type":"application/json"},body:JSON.stringify({filter:{from:new Date(n).toISOString(),to:"now",query:t},page:{limit:100}})});if(!r.ok)return[];let i=((await r.json()).data||[]).map(o=>({timestamp:new Date(o.attributes?.timestamp||Date.now()).getTime(),source:"datadog",level:(o.attributes?.attributes?.level||"info").toLowerCase(),message:o.attributes?.message||"",service:o.attributes?.service,host:o.attributes?.host,metadata:o.attributes?.attributes||{}}));for(let o of i)Uu(o);return i}catch{return[]}}function vO(){if(de.enableAnomalyDetection){Wse(),Kse(),Yse();for(let e of ps.keys())SO(e)}}function Wse(){let t=Date.now()-de.errorRateBaselineWindow,n=Ur.filter(u=>u.timestamp>=t);if(n.length<de.minSamplesForBaseline)return;let s=n.filter(u=>u.level==="error"||u.level==="fatal").length/n.length,i=t-de.errorRateBaselineWindow*4,o=Ur.filter(u=>u.timestamp>=i&&u.timestamp<t);if(o.length<de.minSamplesForBaseline)return;let c=o.filter(u=>u.level==="error"||u.level==="fatal").length/o.length;if(c===0)return;let l=(s-c)/Math.max(c,.001)*100;l>de.errorRateAlertThreshold&&cb({type:"error_spike",severity:l>200?"critical":l>100?"high":"medium",description:`Error rate spike: ${(s*100).toFixed(1)}% (baseline: ${(c*100).toFixed(1)}%, +${l.toFixed(0)}%)`,currentValue:s,baselineValue:c,deviationPercent:l,affectedRequests:n.length,errorSamples:n.filter(u=>u.level==="error"||u.level==="fatal").slice(-10)})}function Kse(){let t=Date.now()-300*1e3,n=Ur.filter(r=>r.timestamp>=t&&(r.level==="fatal"||/panic|crash|exit\s+1/i.test(r.message)));n.length<3||cb({type:"crash_loop",severity:"critical",description:`${n.length} crash/panic events in last 5 minutes`,affectedRequests:n.length,errorSamples:n.slice(-5)})}function Yse(){let t=Date.now()-6e4,n=Ur.filter(s=>s.timestamp>=t),r=new Map;for(let s of n.filter(i=>i.level==="error"||i.level==="fatal")){let i=s.message.slice(0,50);r.has(i)||r.set(i,[]),r.get(i).push(s)}for(let[s,i]of r)i.length>=10&&cb({type:"log_pattern",severity:i.length>=50?"high":"medium",description:`Log pattern "${s}..." appeared ${i.length}x in 60s`,affectedRequests:i.length,errorSamples:i.slice(0,5)})}function SO(e){if(!de.enableAnomalyDetection)return;let t=ps.get(e)||[];if(t.length<de.minSamplesForBaseline)return;let n=t.slice(-10),r=t.slice(0,-10).slice(-100);if(r.length<de.minSamplesForBaseline/2)return;let s=r.reduce((l,u)=>l+u.value,0)/r.length,i=r.reduce((l,u)=>l+Math.pow(u.value-s,2),0)/r.length,o=Math.sqrt(i);if(o===0)return;let a=n.reduce((l,u)=>l+u.value,0)/n.length,c=Math.abs(a-s)/o;if(c>de.zScoreThreshold){let l="custom";/error|err/i.test(e)?l="error_spike":/latency|duration|response_time/i.test(e)?l="latency_spike":/throughput|rps|qps|requests/i.test(e)?l=a<s?"throughput_drop":"custom":/memory|heap|rss/i.test(e)&&(l="memory_leak"),cb({type:l,severity:c>5?"critical":c>4?"high":"medium",description:`Metric "${e}" anomaly: ${a.toFixed(2)} (baseline ${s.toFixed(2)}, z=${c.toFixed(2)})`,metric:e,currentValue:a,baselineValue:s,zScore:c,affectedRequests:n.length,errorSamples:[]})}}function cb(e){let t=`${e.type}:${e.metric||e.description.slice(0,50)}`,n=hO.get(t);if(n&&Date.now()-n<de.alertCooldownMs)return;hO.set(t,Date.now());let r=Ose("md5").update(t+Date.now()).digest("hex").slice(0,12),s={id:r,type:e.type,severity:e.severity,description:e.description,detectedAt:Date.now(),metric:e.metric,baselineValue:e.baselineValue,currentValue:e.currentValue,deviationPercent:e.deviationPercent,zScore:e.zScore,affectedRequests:e.affectedRequests,errorSamples:e.errorSamples||[],recentDeploys:Qse(),acknowledged:!1,resolved:!1};_i.set(r,s),Hu.emit("anomaly",s),Use(s),Ri()}function Qse(){try{return ib("git log -5 --pretty=format:%H|%s|%aI",{stdio:"pipe",encoding:"utf-8"}).split(`
1005
- `).filter(Boolean).map(t=>{let[n,r,s]=t.split("|");return{commit:n.slice(0,12),message:r,timestamp:new Date(s).getTime()}})}catch{return[]}}async function Zse(e,t){if(!de.enableAIAnalysis)return{rootCause:e.description,suggestion:{type:"manual",description:"Manual investigation required",confidence:0,riskLevel:"safe"}};let n=e.recentDeploys?.map(i=>`- ${i.commit} ${i.message}`).join(`
1002
+ `).filter(Boolean)){let o=kC(i);o&&Uu({...o,source:n,service:e})}}),Vs.set(n,r),()=>mc(n)}async function bO(e,t){let n=Date.now()-fe.pollIntervalMs*2;try{let r=await fetch("https://api.datadoghq.com/api/v2/logs/events/search",{method:"POST",headers:{"DD-API-KEY":e,"Content-Type":"application/json"},body:JSON.stringify({filter:{from:new Date(n).toISOString(),to:"now",query:t},page:{limit:100}})});if(!r.ok)return[];let i=((await r.json()).data||[]).map(o=>({timestamp:new Date(o.attributes?.timestamp||Date.now()).getTime(),source:"datadog",level:(o.attributes?.attributes?.level||"info").toLowerCase(),message:o.attributes?.message||"",service:o.attributes?.service,host:o.attributes?.host,metadata:o.attributes?.attributes||{}}));for(let o of i)Uu(o);return i}catch{return[]}}function vO(){if(fe.enableAnomalyDetection){Wse(),Kse(),Yse();for(let e of ps.keys())SO(e)}}function Wse(){let t=Date.now()-fe.errorRateBaselineWindow,n=Ur.filter(u=>u.timestamp>=t);if(n.length<fe.minSamplesForBaseline)return;let s=n.filter(u=>u.level==="error"||u.level==="fatal").length/n.length,i=t-fe.errorRateBaselineWindow*4,o=Ur.filter(u=>u.timestamp>=i&&u.timestamp<t);if(o.length<fe.minSamplesForBaseline)return;let c=o.filter(u=>u.level==="error"||u.level==="fatal").length/o.length;if(c===0)return;let l=(s-c)/Math.max(c,.001)*100;l>fe.errorRateAlertThreshold&&cb({type:"error_spike",severity:l>200?"critical":l>100?"high":"medium",description:`Error rate spike: ${(s*100).toFixed(1)}% (baseline: ${(c*100).toFixed(1)}%, +${l.toFixed(0)}%)`,currentValue:s,baselineValue:c,deviationPercent:l,affectedRequests:n.length,errorSamples:n.filter(u=>u.level==="error"||u.level==="fatal").slice(-10)})}function Kse(){let t=Date.now()-300*1e3,n=Ur.filter(r=>r.timestamp>=t&&(r.level==="fatal"||/panic|crash|exit\s+1/i.test(r.message)));n.length<3||cb({type:"crash_loop",severity:"critical",description:`${n.length} crash/panic events in last 5 minutes`,affectedRequests:n.length,errorSamples:n.slice(-5)})}function Yse(){let t=Date.now()-6e4,n=Ur.filter(s=>s.timestamp>=t),r=new Map;for(let s of n.filter(i=>i.level==="error"||i.level==="fatal")){let i=s.message.slice(0,50);r.has(i)||r.set(i,[]),r.get(i).push(s)}for(let[s,i]of r)i.length>=10&&cb({type:"log_pattern",severity:i.length>=50?"high":"medium",description:`Log pattern "${s}..." appeared ${i.length}x in 60s`,affectedRequests:i.length,errorSamples:i.slice(0,5)})}function SO(e){if(!fe.enableAnomalyDetection)return;let t=ps.get(e)||[];if(t.length<fe.minSamplesForBaseline)return;let n=t.slice(-10),r=t.slice(0,-10).slice(-100);if(r.length<fe.minSamplesForBaseline/2)return;let s=r.reduce((l,u)=>l+u.value,0)/r.length,i=r.reduce((l,u)=>l+Math.pow(u.value-s,2),0)/r.length,o=Math.sqrt(i);if(o===0)return;let a=n.reduce((l,u)=>l+u.value,0)/n.length,c=Math.abs(a-s)/o;if(c>fe.zScoreThreshold){let l="custom";/error|err/i.test(e)?l="error_spike":/latency|duration|response_time/i.test(e)?l="latency_spike":/throughput|rps|qps|requests/i.test(e)?l=a<s?"throughput_drop":"custom":/memory|heap|rss/i.test(e)&&(l="memory_leak"),cb({type:l,severity:c>5?"critical":c>4?"high":"medium",description:`Metric "${e}" anomaly: ${a.toFixed(2)} (baseline ${s.toFixed(2)}, z=${c.toFixed(2)})`,metric:e,currentValue:a,baselineValue:s,zScore:c,affectedRequests:n.length,errorSamples:[]})}}function cb(e){let t=`${e.type}:${e.metric||e.description.slice(0,50)}`,n=hO.get(t);if(n&&Date.now()-n<fe.alertCooldownMs)return;hO.set(t,Date.now());let r=Ose("md5").update(t+Date.now()).digest("hex").slice(0,12),s={id:r,type:e.type,severity:e.severity,description:e.description,detectedAt:Date.now(),metric:e.metric,baselineValue:e.baselineValue,currentValue:e.currentValue,deviationPercent:e.deviationPercent,zScore:e.zScore,affectedRequests:e.affectedRequests,errorSamples:e.errorSamples||[],recentDeploys:Qse(),acknowledged:!1,resolved:!1};_i.set(r,s),Hu.emit("anomaly",s),Use(s),Ri()}function Qse(){try{return ib("git log -5 --pretty=format:%H|%s|%aI",{stdio:"pipe",encoding:"utf-8"}).split(`
1003
+ `).filter(Boolean).map(t=>{let[n,r,s]=t.split("|");return{commit:n.slice(0,12),message:r,timestamp:new Date(s).getTime()}})}catch{return[]}}async function Zse(e,t){if(!fe.enableAIAnalysis)return{rootCause:e.description,suggestion:{type:"manual",description:"Manual investigation required",confidence:0,riskLevel:"safe"}};let n=e.recentDeploys?.map(i=>`- ${i.commit} ${i.message}`).join(`
1006
1004
  `)||"(none)",r=e.errorSamples.slice(0,5).map(i=>`[${i.level}] ${i.message.slice(0,200)}`).join(`
1007
1005
  `),s=`Analyze this production anomaly.
1008
1006
 
@@ -1032,13 +1030,13 @@ Output JSON only:
1032
1030
  "confidence": 0.0-1.0,
1033
1031
  "riskLevel": "safe | moderate | risky"
1034
1032
  }
1035
- }`;try{let o=(await t.sendMessage([{role:"user",content:s,timestamp:new Date().toISOString()}],"You diagnose production anomalies and suggest hotfixes. Output strict JSON only.",[],void 0)).content?.match(/\{[\s\S]*\}/)?.[0];if(!o)throw new Error("No JSON");let a=JSON.parse(o),c={rootCause:a.rootCause||e.description,suggestion:{type:a.suggestion?.type||"manual",description:a.suggestion?.description||"Manual review",command:a.suggestion?.command,filePath:a.suggestion?.filePath,confidence:a.suggestion?.confidence||.5,riskLevel:a.suggestion?.riskLevel||"moderate"}};return e.rootCauseAnalysis=c.rootCause,e.suggestedHotfix=c.suggestion,Ri(),c}catch{return{rootCause:"AI analysis failed",suggestion:{type:"manual",description:"Manual investigation required",confidence:0,riskLevel:"safe"}}}}async function Xse(e,t){if(!e.suggestedHotfix)return{applied:!1,output:"No hotfix suggested"};let n=e.suggestedHotfix;if(n.riskLevel==="risky"&&!de.enableAIHotfix)return{applied:!1,output:"Risky hotfix requires manual approval"};try{return n.type==="restart"&&n.command?(ib(n.command,{cwd:t,stdio:"pipe",timeout:6e4}),e.resolved=!0,e.resolvedAt=Date.now(),Ri(),{applied:!0,output:`Executed: ${n.command}`}):n.type==="rollback_deploy"&&n.command?(ib(n.command,{cwd:t,stdio:"pipe",timeout:12e4}),{applied:!0,output:`Rolled back: ${n.command}`}):n.type==="feature_flag"&&n.command?(ib(n.command,{cwd:t,stdio:"pipe",timeout:3e4}),{applied:!0,output:`Toggled feature flag: ${n.command}`}):{applied:!1,output:`Hotfix type "${n.type}" requires manual application`}}catch(r){return{applied:!1,output:`Failed: ${r.message}`}}}function wO(){qu||(qu=setInterval(async()=>{for(let e of de.sources)if(e.enabled)try{e.type==="datadog"&&e.apiKey&&await bO(e.apiKey,e.query||"*")}catch{}vO()},de.pollIntervalMs),qu.unref())}function kO(){qu&&(clearInterval(qu),qu=null)}function eie(e={}){let t=Ur;return e.level&&(t=t.filter(n=>n.level===e.level)),e.service&&(t=t.filter(n=>n.service===e.service)),e.sinceMs&&(t=t.filter(n=>n.timestamp>=e.sinceMs)),e.limit&&(t=t.slice(-e.limit)),[...t]}function tie(e,t){let n=ps.get(e)||[];return t?n.filter(r=>r.timestamp>=t):[...n]}function nie(){return Array.from(ps.keys())}function rie(e={}){let t=Array.from(_i.values());return e.unresolved&&(t=t.filter(n=>!n.resolved)),e.severity&&(t=t.filter(n=>n.severity===e.severity)),t.sort((n,r)=>r.detectedAt-n.detectedAt),e.limit&&(t=t.slice(0,e.limit)),t}function sie(e){let t=_i.get(e);return t?(t.acknowledged=!0,Ri(),!0):!1}function iie(e){let t=_i.get(e);return t?(t.resolved=!0,t.resolvedAt=Date.now(),Ri(),!0):!1}function oie(){return Hu}function aie(){return JSON.parse(JSON.stringify(de))}function cie(e){de={...de,...e},Ri()}function lie(e){de.sources.push(e),Ri()}function uie(e){let t=de.sources.findIndex(n=>n.name===e);return t===-1?!1:(de.sources.splice(t,1),Ri(),!0)}function die(e){let t=e.severity==="critical"?"\u{1F6A8}":e.severity==="high"?"\u26A0\uFE0F ":e.severity==="medium"?"\u26A1":"\u2139\uFE0F ",n=[];if(n.push(`# ${t} Anomaly ${e.id}`),n.push(`Type: ${e.type} | Severity: ${e.severity}`),n.push(`Detected: ${new Date(e.detectedAt).toISOString()}`),n.push(`Status: ${e.resolved?"resolved":e.acknowledged?"acknowledged":"open"}`),n.push(""),n.push("## Description"),n.push(e.description),e.metric&&n.push(`Metric: ${e.metric}`),e.currentValue!==void 0&&n.push(`Values: current=${e.currentValue.toFixed(2)}, baseline=${e.baselineValue?.toFixed(2)}`),e.deviationPercent!==void 0&&n.push(`Deviation: ${e.deviationPercent.toFixed(0)}%`),e.zScore!==void 0&&n.push(`Z-score: ${e.zScore.toFixed(2)}`),e.errorSamples.length>0){n.push(""),n.push("## Error Samples");for(let r of e.errorSamples.slice(0,5))n.push(` [${r.level}] ${r.message.slice(0,200)}`)}if(e.recentDeploys&&e.recentDeploys.length>0){n.push(""),n.push("## Recent Deploys");for(let r of e.recentDeploys.slice(0,3))n.push(` ${r.commit} ${r.message.slice(0,80)}`)}return e.rootCauseAnalysis&&(n.push(""),n.push("## \u{1F50D} Root Cause"),n.push(e.rootCauseAnalysis)),e.suggestedHotfix&&(n.push(""),n.push("## \u{1F4A1} Suggested Hotfix"),n.push(`Type: ${e.suggestedHotfix.type} | Risk: ${e.suggestedHotfix.riskLevel}`),n.push(`Confidence: ${(e.suggestedHotfix.confidence*100).toFixed(0)}%`),n.push(e.suggestedHotfix.description),e.suggestedHotfix.command&&n.push(` $ ${e.suggestedHotfix.command}`),e.suggestedHotfix.filePath&&n.push(` File: ${e.suggestedHotfix.filePath}`)),n.join(`
1036
- `)}function fie(){let e={},t={};for(let r of Ur)e[r.source]=(e[r.source]||0)+1,t[r.level]=(t[r.level]||0)+1;let n={};for(let r of _i.values())n[r.severity]=(n[r.severity]||0)+1;return{totalLogs:Ur.length,totalMetrics:Array.from(ps.values()).reduce((r,s)=>r+s.length,0),totalTraces:ob.length,totalAnomalies:_i.size,unresolvedAnomalies:Array.from(_i.values()).filter(r=>!r.resolved).length,activeTails:Vs.size,bySource:e,byLevel:t,bySeverity:n}}var Bse,de,um,bC,vC,Nse,SC,Ur,ps,ob,_i,hO,Hu,Vs,qu,fm=w(()=>{"use strict";Bse={enabled:!0,sources:[],enableAnomalyDetection:!0,zScoreThreshold:3,errorRateBaselineWindow:300*1e3,errorRateAlertThreshold:50,latencyBaselineWindow:600*1e3,latencyAlertThreshold:2,minSamplesForBaseline:30,pollIntervalMs:3e4,alertCooldownMs:300*1e3,enableAIAnalysis:!0,enableAIHotfix:!1,maxLogEntries:1e4,maxMetricSamples:5e4,retentionMs:1440*60*1e3,enablePersistence:!0},de={...Bse},um=lm(Lse(),".aiaca","observability"),bC=lm(um,"state.json"),vC=lm(um,"anomalies.json"),Nse=lm(um,"alerts.jsonl"),SC=lm(um,"config.json"),Ur=[],ps=new Map,ob=[],_i=new Map,hO=new Map,Hu=new jse;Hu.setMaxListeners(100);Vs=new Map,qu=null;qse();de.enabled&&wO();process.on("exit",()=>{yO(),kO(),Ri()})});var Ju={};$(Ju,{configure:()=>Tie,forceGc:()=>AC,formatPurgeResult:()=>Eie,generateComplianceReport:()=>Mie,getAuditLog:()=>Iie,getConfig:()=>Aie,getEvents:()=>Pie,getStats:()=>_ie,listRegistrations:()=>PO,purge:()=>zu,recordActivity:()=>Cie,registerPurgeHandler:()=>Hr,resetStats:()=>Rie,scrubBuffer:()=>PC,scrubMap:()=>Sie,scrubObject:()=>Vu,scrubString:()=>RO,startIdleWatcher:()=>IC,stopIdleWatcher:()=>MO,unregisterPurgeHandler:()=>wie});import{existsSync as $O,mkdirSync as pie,readFileSync as CO,writeFileSync as AO}from"fs";import{join as TC}from"path";import{homedir as mie,hostname as gie}from"os";import{randomBytes as TO}from"crypto";import{EventEmitter as hie}from"events";function RC(){pie(_C,{recursive:!0})}function bie(){if(RC(),$O($C))try{Oe={...Oe,...JSON.parse(CO($C,"utf-8"))}}catch{}}function _O(){RC();try{AO($C,JSON.stringify(Oe,null,2),"utf-8")}catch{}}function vie(e){if(!He.enableAuditLog)return;RC();let t={...e};t.values&&(t.values="[REDACTED]");try{AO(CC,JSON.stringify({...t,timestamp:Date.now()})+`
1033
+ }`;try{let o=(await t.sendMessage([{role:"user",content:s,timestamp:new Date().toISOString()}],"You diagnose production anomalies and suggest hotfixes. Output strict JSON only.",[],void 0)).content?.match(/\{[\s\S]*\}/)?.[0];if(!o)throw new Error("No JSON");let a=JSON.parse(o),c={rootCause:a.rootCause||e.description,suggestion:{type:a.suggestion?.type||"manual",description:a.suggestion?.description||"Manual review",command:a.suggestion?.command,filePath:a.suggestion?.filePath,confidence:a.suggestion?.confidence||.5,riskLevel:a.suggestion?.riskLevel||"moderate"}};return e.rootCauseAnalysis=c.rootCause,e.suggestedHotfix=c.suggestion,Ri(),c}catch{return{rootCause:"AI analysis failed",suggestion:{type:"manual",description:"Manual investigation required",confidence:0,riskLevel:"safe"}}}}async function Xse(e,t){if(!e.suggestedHotfix)return{applied:!1,output:"No hotfix suggested"};let n=e.suggestedHotfix;if(n.riskLevel==="risky"&&!fe.enableAIHotfix)return{applied:!1,output:"Risky hotfix requires manual approval"};try{return n.type==="restart"&&n.command?(ib(n.command,{cwd:t,stdio:"pipe",timeout:6e4}),e.resolved=!0,e.resolvedAt=Date.now(),Ri(),{applied:!0,output:`Executed: ${n.command}`}):n.type==="rollback_deploy"&&n.command?(ib(n.command,{cwd:t,stdio:"pipe",timeout:12e4}),{applied:!0,output:`Rolled back: ${n.command}`}):n.type==="feature_flag"&&n.command?(ib(n.command,{cwd:t,stdio:"pipe",timeout:3e4}),{applied:!0,output:`Toggled feature flag: ${n.command}`}):{applied:!1,output:`Hotfix type "${n.type}" requires manual application`}}catch(r){return{applied:!1,output:`Failed: ${r.message}`}}}function wO(){qu||(qu=setInterval(async()=>{for(let e of fe.sources)if(e.enabled)try{e.type==="datadog"&&e.apiKey&&await bO(e.apiKey,e.query||"*")}catch{}vO()},fe.pollIntervalMs),qu.unref())}function kO(){qu&&(clearInterval(qu),qu=null)}function eie(e={}){let t=Ur;return e.level&&(t=t.filter(n=>n.level===e.level)),e.service&&(t=t.filter(n=>n.service===e.service)),e.sinceMs&&(t=t.filter(n=>n.timestamp>=e.sinceMs)),e.limit&&(t=t.slice(-e.limit)),[...t]}function tie(e,t){let n=ps.get(e)||[];return t?n.filter(r=>r.timestamp>=t):[...n]}function nie(){return Array.from(ps.keys())}function rie(e={}){let t=Array.from(_i.values());return e.unresolved&&(t=t.filter(n=>!n.resolved)),e.severity&&(t=t.filter(n=>n.severity===e.severity)),t.sort((n,r)=>r.detectedAt-n.detectedAt),e.limit&&(t=t.slice(0,e.limit)),t}function sie(e){let t=_i.get(e);return t?(t.acknowledged=!0,Ri(),!0):!1}function iie(e){let t=_i.get(e);return t?(t.resolved=!0,t.resolvedAt=Date.now(),Ri(),!0):!1}function oie(){return Hu}function aie(){return JSON.parse(JSON.stringify(fe))}function cie(e){fe={...fe,...e},Ri()}function lie(e){fe.sources.push(e),Ri()}function uie(e){let t=fe.sources.findIndex(n=>n.name===e);return t===-1?!1:(fe.sources.splice(t,1),Ri(),!0)}function die(e){let t=e.severity==="critical"?"\u{1F6A8}":e.severity==="high"?"\u26A0\uFE0F ":e.severity==="medium"?"\u26A1":"\u2139\uFE0F ",n=[];if(n.push(`# ${t} Anomaly ${e.id}`),n.push(`Type: ${e.type} | Severity: ${e.severity}`),n.push(`Detected: ${new Date(e.detectedAt).toISOString()}`),n.push(`Status: ${e.resolved?"resolved":e.acknowledged?"acknowledged":"open"}`),n.push(""),n.push("## Description"),n.push(e.description),e.metric&&n.push(`Metric: ${e.metric}`),e.currentValue!==void 0&&n.push(`Values: current=${e.currentValue.toFixed(2)}, baseline=${e.baselineValue?.toFixed(2)}`),e.deviationPercent!==void 0&&n.push(`Deviation: ${e.deviationPercent.toFixed(0)}%`),e.zScore!==void 0&&n.push(`Z-score: ${e.zScore.toFixed(2)}`),e.errorSamples.length>0){n.push(""),n.push("## Error Samples");for(let r of e.errorSamples.slice(0,5))n.push(` [${r.level}] ${r.message.slice(0,200)}`)}if(e.recentDeploys&&e.recentDeploys.length>0){n.push(""),n.push("## Recent Deploys");for(let r of e.recentDeploys.slice(0,3))n.push(` ${r.commit} ${r.message.slice(0,80)}`)}return e.rootCauseAnalysis&&(n.push(""),n.push("## \u{1F50D} Root Cause"),n.push(e.rootCauseAnalysis)),e.suggestedHotfix&&(n.push(""),n.push("## \u{1F4A1} Suggested Hotfix"),n.push(`Type: ${e.suggestedHotfix.type} | Risk: ${e.suggestedHotfix.riskLevel}`),n.push(`Confidence: ${(e.suggestedHotfix.confidence*100).toFixed(0)}%`),n.push(e.suggestedHotfix.description),e.suggestedHotfix.command&&n.push(` $ ${e.suggestedHotfix.command}`),e.suggestedHotfix.filePath&&n.push(` File: ${e.suggestedHotfix.filePath}`)),n.join(`
1034
+ `)}function fie(){let e={},t={};for(let r of Ur)e[r.source]=(e[r.source]||0)+1,t[r.level]=(t[r.level]||0)+1;let n={};for(let r of _i.values())n[r.severity]=(n[r.severity]||0)+1;return{totalLogs:Ur.length,totalMetrics:Array.from(ps.values()).reduce((r,s)=>r+s.length,0),totalTraces:ob.length,totalAnomalies:_i.size,unresolvedAnomalies:Array.from(_i.values()).filter(r=>!r.resolved).length,activeTails:Vs.size,bySource:e,byLevel:t,bySeverity:n}}var Bse,fe,um,bC,vC,Nse,SC,Ur,ps,ob,_i,hO,Hu,Vs,qu,fm=w(()=>{"use strict";Bse={enabled:!0,sources:[],enableAnomalyDetection:!0,zScoreThreshold:3,errorRateBaselineWindow:300*1e3,errorRateAlertThreshold:50,latencyBaselineWindow:600*1e3,latencyAlertThreshold:2,minSamplesForBaseline:30,pollIntervalMs:3e4,alertCooldownMs:300*1e3,enableAIAnalysis:!0,enableAIHotfix:!1,maxLogEntries:1e4,maxMetricSamples:5e4,retentionMs:1440*60*1e3,enablePersistence:!0},fe={...Bse},um=lm(Lse(),".aiaca","observability"),bC=lm(um,"state.json"),vC=lm(um,"anomalies.json"),Nse=lm(um,"alerts.jsonl"),SC=lm(um,"config.json"),Ur=[],ps=new Map,ob=[],_i=new Map,hO=new Map,Hu=new jse;Hu.setMaxListeners(100);Vs=new Map,qu=null;qse();fe.enabled&&wO();process.on("exit",()=>{yO(),kO(),Ri()})});var Ju={};$(Ju,{configure:()=>Tie,forceGc:()=>AC,formatPurgeResult:()=>Eie,generateComplianceReport:()=>Mie,getAuditLog:()=>Iie,getConfig:()=>Aie,getEvents:()=>Pie,getStats:()=>_ie,listRegistrations:()=>PO,purge:()=>zu,recordActivity:()=>Cie,registerPurgeHandler:()=>Hr,resetStats:()=>Rie,scrubBuffer:()=>PC,scrubMap:()=>Sie,scrubObject:()=>Vu,scrubString:()=>RO,startIdleWatcher:()=>IC,stopIdleWatcher:()=>MO,unregisterPurgeHandler:()=>wie});import{existsSync as $O,mkdirSync as pie,readFileSync as CO,writeFileSync as AO}from"fs";import{join as TC}from"path";import{homedir as mie,hostname as gie}from"os";import{randomBytes as TO}from"crypto";import{EventEmitter as hie}from"events";function RC(){pie(_C,{recursive:!0})}function bie(){if(RC(),$O($C))try{Oe={...Oe,...JSON.parse(CO($C,"utf-8"))}}catch{}}function _O(){RC();try{AO($C,JSON.stringify(Oe,null,2),"utf-8")}catch{}}function vie(e){if(!He.enableAuditLog)return;RC();let t={...e};t.values&&(t.values="[REDACTED]");try{AO(CC,JSON.stringify({...t,timestamp:Date.now()})+`
1037
1035
  `,{flag:"a"})}catch{}}function PC(e){if(!(!e||e.length===0)){for(let t=0;t<He.zeroizationPasses;t++){let n=TO(e.length);if(t===1)for(let r=0;r<e.length;r++)n[r]=~n[r]&255;n.copy(e)}e.fill(0)}}function RO(e){if(!e)return"";let t=Buffer.from(e,"utf-8");return PC(t),""}function Vu(e,t=0){if(t>16||!e)return{itemsCleaned:0,bytesScrubbed:0};let n=0,r=0;if(Buffer.isBuffer(e))r+=e.length,PC(e),n++;else if(typeof e=="string")r+=e.length,RO(e),n++;else if(Array.isArray(e)){for(let s=0;s<e.length;s++){let i=Vu(e[s],t+1);n+=i.itemsCleaned,r+=i.bytesScrubbed,e[s]=null}e.length=0,n++}else if(typeof e=="object"){for(let s of Object.keys(e)){let i=Vu(e[s],t+1);n+=i.itemsCleaned,r+=i.bytesScrubbed;try{delete e[s]}catch{e[s]=null}}n++}return{itemsCleaned:n,bytesScrubbed:r}}function Sie(e){let t=0,n=0;for(let[r,s]of e.entries()){let i=Vu(s);t+=i.itemsCleaned,n+=i.bytesScrubbed}return e.clear(),{itemsCleaned:t,bytesScrubbed:n}}function AC(){if(typeof global.gc=="function")try{return global.gc(),!0}catch{}return!1}function Hr(e){lb.set(e.target,e),Gu.emit("handler_registered",{target:e.target})}function wie(e){return lb.delete(e)}function PO(){return Array.from(lb.values())}function kie(){Hr({target:"conversation_history",priority:100,description:"Clear conversation messages",callback:()=>{let e=0,t=0;try{let n=global.__currentSession;if(n?.messages){for(let r of n.messages){let s=Vu(r);e+=s.itemsCleaned,t+=s.bytesScrubbed}n.messages.length=0}}catch{}return{itemsCleaned:e,bytesScrubbed:t}}}),Hr({target:"tool_outputs",priority:90,description:"Clear request batch + speculative caches",callback:async()=>{let e=0,t=0;try{let n=await Promise.resolve().then(()=>(Ha(),Ua));n.clearCache&&n.clearCache(),e+=1}catch{}try{let n=await Promise.resolve().then(()=>(Du(),Eu));n.clearCache&&n.clearCache(),e+=1}catch{}return{itemsCleaned:e,bytesScrubbed:t}}}),Hr({target:"credentials",priority:1e3,description:"Tear down all credential vaults",callback:async()=>{try{return{itemsCleaned:(await Promise.resolve().then(()=>(fs(),ds))).destroyAllSessions("purge_triggered").count,bytesScrubbed:0}}catch{return{itemsCleaned:0,bytesScrubbed:0}}}}),Hr({target:"jit_tokens",priority:950,description:"Revoke all JIT credential tokens",callback:async()=>{try{return{itemsCleaned:(await Promise.resolve().then(()=>(pc(),fc))).activateGlobalRevocation(),bytesScrubbed:0}}catch{return{itemsCleaned:0,bytesScrubbed:0}}}}),Hr({target:"file_contents",priority:70,description:"Clear file diff cache",callback:async()=>{try{let e=await Promise.resolve().then(()=>(Mf(),If));if(e.clearCache)return e.clearCache(),{itemsCleaned:1,bytesScrubbed:0}}catch{}return{itemsCleaned:0,bytesScrubbed:0}}}),Hr({target:"memory_caches",priority:80,description:"Clear hierarchical memory + session memory caches",callback:async()=>{let e=0;try{let t=await Promise.resolve().then(()=>(Kp(),Wp));t.clearRuntimeCache&&(t.clearRuntimeCache(),e++)}catch{}return{itemsCleaned:e,bytesScrubbed:0}}}),Hr({target:"session_state",priority:950,description:"Wipe global session reference",callback:()=>{let e=0,t=0;try{let n=global.__currentSession;if(n){let r=Vu(n);e+=r.itemsCleaned,t+=r.bytesScrubbed,global.__currentSession=void 0,e++}}catch{}return{itemsCleaned:e,bytesScrubbed:t}}}),Hr({target:"provenance_entries",priority:50,description:"Clear provenance tracker entries",callback:async()=>{try{let e=await Promise.resolve().then(()=>(fo(),uo));return e.resetStats&&e.resetStats(),{itemsCleaned:1,bytesScrubbed:0}}catch{return{itemsCleaned:0,bytesScrubbed:0}}}}),Hr({target:"streaming_buffers",priority:60,description:"Clear stream cache buffers",callback:async()=>{try{let e=await Promise.resolve().then(()=>(rb(),nb));if(e.clearAll)return e.clearAll(),{itemsCleaned:1,bytesScrubbed:0}}catch{}return{itemsCleaned:0,bytesScrubbed:0}}}),Hr({target:"secret_scanner_state",priority:40,description:"Clear session-specific secret scanner state",callback:()=>({itemsCleaned:0,bytesScrubbed:0})}),Hr({target:"observability_buffers",priority:30,description:"Clear observability ring buffers",callback:async()=>{try{let e=await Promise.resolve().then(()=>(fm(),dm));if(e.clearBuffers)return e.clearBuffers(),{itemsCleaned:1,bytesScrubbed:0}}catch{}return{itemsCleaned:0,bytesScrubbed:0}}})}async function zu(e,t){if(!He.enabled)return{success:!0,trigger:e,depth:t||He.defaultDepth,targetResults:[],totalItemsCleaned:0,totalBytesScrubbed:0,durationMs:0,verificationPasses:!0,warnings:["Purge disabled"]};if(xC)return{success:!0,trigger:e,depth:t||He.defaultDepth,targetResults:[],totalItemsCleaned:0,totalBytesScrubbed:0,durationMs:0,verificationPasses:!0,warnings:["Purge already in progress"]};xC=!0;let n=Date.now(),r=t||He.defaultDepth,s=[];Gu.emit("purge_started",{trigger:e,depth:r});let i=xie(r),o=Array.from(lb.values()).filter(f=>i.has(f.target)).sort((f,p)=>(p.priority||0)-(f.priority||0)),a=[];for(let f of o){let p=Date.now();try{let m=await Promise.resolve(f.callback());a.push({target:f.target,success:!0,itemsCleaned:m.itemsCleaned,bytesScrubbed:m.bytesScrubbed,durationMs:Date.now()-p}),Gu.emit("target_purged",{target:f.target,result:m})}catch(m){a.push({target:f.target,success:!1,itemsCleaned:0,bytesScrubbed:0,durationMs:Date.now()-p,error:m.message}),s.push(`${f.target}: ${m.message}`)}}if(He.forceGcAfterPurge&&(AC()||s.push("GC not available (run with --expose-gc for paranoid mode)")),r==="paranoid"&&He.evictHeapAfterPurge){try{let f=Buffer.allocUnsafe(67108864);TO(f.length).copy(f),f.fill(0)}catch{s.push("Heap eviction failed")}AC()}let c=!0;if(He.enableVerification){let f=$ie();c=f.passed,f.passed||(s.push(...f.issues),Oe.totalVerificationFailures++)}let l=a.reduce((f,p)=>f+p.itemsCleaned,0),u=a.reduce((f,p)=>f+p.bytesScrubbed,0),d=a.every(f=>f.success)&&c;return Oe.totalPurges++,Oe.byTrigger[e]=(Oe.byTrigger[e]||0)+1,Oe.byDepth[r]=(Oe.byDepth[r]||0)+1,Oe.totalItemsCleaned+=l,Oe.totalBytesScrubbed+=u,Oe.lastPurgeAt=Date.now(),Oe.averageDurationMs=(Oe.averageDurationMs*(Oe.totalPurges-1)+(Date.now()-n))/Oe.totalPurges,_O(),vie({event:"purge",trigger:e,depth:r,targetsRun:a.length,totalItems:l,totalBytes:u,durationMs:Date.now()-n,success:d,warnings:s.length}),Gu.emit("purge_complete",{trigger:e,depth:r,success:d,totalItems:l,totalBytes:u,durationMs:Date.now()-n}),xC=!1,{success:d,trigger:e,depth:r,targetResults:a,totalItemsCleaned:l,totalBytesScrubbed:u,durationMs:Date.now()-n,verificationPasses:c,warnings:s}}function xie(e){let t=new Set;return(e==="light"||e==="standard"||e==="paranoid")&&(t.add("credentials"),t.add("jit_tokens"),t.add("secret_scanner_state")),(e==="standard"||e==="paranoid")&&(t.add("conversation_history"),t.add("tool_outputs"),t.add("session_state"),t.add("memory_caches"),t.add("streaming_buffers"),t.add("file_contents")),e==="paranoid"&&(t.add("provenance_entries"),t.add("request_batch"),t.add("speculative_cache"),t.add("context_windows"),t.add("observability_buffers")),t}function $ie(){let e=[];try{let t=global.__currentSession;t&&t.messages&&t.messages.length>0&&e.push(`Global session still has ${t.messages.length} messages`)}catch{}try{let t=(fs(),sr(ds)),r=(t.listSessions?t.listSessions():[]).filter(s=>s.state==="active"&&s.credentialCount>0);r.length>0&&e.push(`${r.length} credential vaults still have ${r.reduce((s,i)=>s+i.credentialCount,0)} credentials`)}catch{}try{let t=(pc(),sr(fc)),n=t.listActiveTokens?t.listActiveTokens():[];n.length>0&&e.push(`${n.length} JIT tokens still active`)}catch{}return{passed:e.length===0,issues:e}}function Cie(){IO=Date.now()}function IC(){gc||(gc=setInterval(()=>{Date.now()-IO>He.idleTimeoutMs&&zu("session_timeout").catch(()=>{})},6e4),gc.unref&&gc.unref())}function MO(){gc&&(clearInterval(gc),gc=null)}function EO(){xO||(xO=!0,He.enableProcessExitHooks&&process.on("exit",()=>{try{zu("process_exit").catch(()=>{})}catch{}}),He.enableSignalHooks&&(process.on("SIGINT",()=>{zu("signal_int").then(()=>process.exit(0)).catch(()=>process.exit(1))}),process.on("SIGTERM",()=>{zu("signal_term").then(()=>process.exit(0)).catch(()=>process.exit(1))}),process.on("uncaughtException",e=>{console.error("Uncaught exception, purging:",e.message),zu("panic").then(()=>process.exit(1)).catch(()=>process.exit(1))})))}function Aie(){return{...He}}function Tie(e){He={...He,...e},He.enabled?(EO(),IC()):MO()}function _ie(){return{...Oe}}function Rie(){Oe={totalPurges:0,byTrigger:{},byDepth:{},totalItemsCleaned:0,totalBytesScrubbed:0,totalVerificationFailures:0,averageDurationMs:0,lastPurgeAt:0},_O()}function Pie(){return Gu}function Iie(e=100){if(!$O(CC))return[];try{return CO(CC,"utf-8").split(`
1038
1036
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Mie(){let e=[];e.push("# Sensitive Data Purge Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(`Host: ${gie()}`),e.push(""),e.push("## Summary"),e.push(`- Total purges: ${Oe.totalPurges}`),e.push(`- Total items cleaned: ${Oe.totalItemsCleaned}`),e.push(`- Total bytes scrubbed: ${(Oe.totalBytesScrubbed/1024).toFixed(1)}KB`),e.push(`- Verification failures: ${Oe.totalVerificationFailures}`),e.push(`- Avg purge duration: ${Oe.averageDurationMs.toFixed(1)}ms`),e.push(`- Last purge: ${Oe.lastPurgeAt?new Date(Oe.lastPurgeAt).toISOString():"never"}`),e.push(""),e.push("## By Trigger");for(let[t,n]of Object.entries(Oe.byTrigger).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);e.push(""),e.push("## By Depth");for(let[t,n]of Object.entries(Oe.byDepth).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);e.push(""),e.push("## Registered Handlers");for(let t of PO())e.push(`- ${t.target} (priority ${t.priority||0}): ${t.description||""}`);return e.push(""),e.push("## Compliance Properties"),e.push(`- \u2713 Multi-pass zeroization (${He.zeroizationPasses} passes)`),e.push(`- ${He.forceGcAfterPurge?"\u2713":"\u2717"} Force GC after purge`),e.push(`- ${He.enableVerification?"\u2713":"\u2717"} Post-purge verification`),e.push(`- ${He.enableProcessExitHooks?"\u2713":"\u2717"} Process exit hooks`),e.push(`- ${He.enableSignalHooks?"\u2713":"\u2717"} Signal hooks (SIGINT/SIGTERM)`),e.push(`- ${He.enableAntiRecovery?"\u2713":"\u2717"} Anti-recovery protection`),e.push(`- ${He.enableAuditLog?"\u2713":"\u2717"} Audit logging`),e.push(`- Idle timeout: ${(He.idleTimeoutMs/6e4).toFixed(0)} min`),e.push(`- Default depth: ${He.defaultDepth}`),e.join(`
1039
1037
  `)}function Eie(e){let t=[],n=e.success?"\u2713":"\u26A0\uFE0F";if(t.push(`${n} **Purge Complete** (${e.depth})`),t.push(`Trigger: ${e.trigger}`),t.push(`Duration: ${e.durationMs}ms`),t.push(`Items cleaned: ${e.totalItemsCleaned}`),t.push(`Bytes scrubbed: ${(e.totalBytesScrubbed/1024).toFixed(1)}KB`),t.push(`Verification: ${e.verificationPasses?"\u2713 Passed":"\u26A0\uFE0F Issues"}`),e.warnings.length>0){t.push(""),t.push("Warnings:");for(let r of e.warnings)t.push(` - ${r}`)}t.push(""),t.push("Per-target results:");for(let r of e.targetResults){let s=r.success?"\u2713":"\u2717";t.push(` ${s} ${r.target.padEnd(25)} | ${r.itemsCleaned} items | ${r.durationMs}ms${r.error?` | ${r.error}`:""}`)}return t.join(`
1040
- `)}var yie,He,_C,$C,CC,Gu,lb,Oe,xC,gc,IO,xO,Wu=w(()=>{"use strict";yie={enabled:!0,defaultDepth:"standard",zeroizationPasses:3,forceGcAfterPurge:!0,enableVerification:!0,enableProcessExitHooks:!0,enableSignalHooks:!0,idleTimeoutMs:1800*1e3,enableAntiRecovery:!0,evictHeapAfterPurge:!1,enableDistributedCoordination:!1,enableAuditLog:!0},He={...yie},_C=TC(mie(),".aiaca","purge"),$C=TC(_C,"stats.json"),CC=TC(_C,"audit.jsonl"),Gu=new hie;Gu.setMaxListeners(100);lb=new Map,Oe={totalPurges:0,byTrigger:{},byDepth:{},totalItemsCleaned:0,totalBytesScrubbed:0,totalVerificationFailures:0,averageDurationMs:0,lastPurgeAt:0},xC=!1,gc=null;bie();kie();IO=Date.now();xO=!1;He.enabled&&(EO(),IC())});var mb={};$(mb,{callPlugin:()=>jO,checkCapability:()=>FO,configure:()=>toe,formatPlugin:()=>aoe,generateComplianceReport:()=>ooe,getAuditLog:()=>ioe,getConfig:()=>eoe,getEvents:()=>soe,getPlugin:()=>Zie,getStats:()=>noe,grantCapability:()=>Uie,listGrantedCapabilities:()=>zie,listPlugins:()=>Xie,quarantinePlugin:()=>qO,resetStats:()=>roe,restartPlugin:()=>NO,revokeCapability:()=>Hie,startHealthChecks:()=>UO,startPlugin:()=>LO,stopHealthChecks:()=>Yie,stopPlugin:()=>BO});import{existsSync as ub,mkdirSync as Die,readFileSync as MC,writeFileSync as LC}from"fs";import{join as db}from"path";import{homedir as Fie}from"os";import{Worker as Lie}from"worker_threads";import{spawn as Oie}from"child_process";import{randomBytes as jie}from"crypto";import{EventEmitter as Bie}from"events";function pb(){Die(fb,{recursive:!0})}function qie(){if(pb(),ub(EC))try{_e={..._e,...JSON.parse(MC(EC,"utf-8"))}}catch{}if(ub(FC))try{let e=JSON.parse(MC(FC,"utf-8"));for(let[t,n]of Object.entries(e))jo.set(t,n)}catch{}}function Js(){pb();try{LC(EC,JSON.stringify(_e,null,2),"utf-8")}catch{}}function DO(){pb();let e={};for(let[t,n]of jo.entries())e[t]=n;try{LC(FC,JSON.stringify(e,null,2),"utf-8")}catch{}}function Ku(e){if(fe.enableAuditLog){pb();try{LC(DC,JSON.stringify({...e,timestamp:Date.now()})+`
1041
- `,{flag:"a"})}catch{}}}function Uie(e,t,n="user"){if(fe.forbiddenCapabilities.includes(t))return!1;let r=jo.get(e)||[];r.includes(t)||(r.push(t),jo.set(e,r),DO());let s=Wn.get(e);return s&&s.grantedCapabilities.add(t),Ku({event:"capability_granted",pluginId:e,capability:t,grantedBy:n}),Bo.emit("capability_granted",{pluginId:e,capability:t}),!0}function Hie(e,t){let n=jo.get(e)||[],r=n.filter(i=>i!==t);if(r.length===n.length)return!1;jo.set(e,r),DO();let s=Wn.get(e);return s&&s.grantedCapabilities.delete(t),Ku({event:"capability_revoked",pluginId:e,capability:t}),!0}function zie(e){return jo.get(e)||[]}function FO(e,t){if(fe.forbiddenCapabilities.includes(t))return{allowed:!1,reason:`Forbidden capability: ${t}`};let n=Wn.get(e);return n?n.status==="quarantined"||n.status==="crashed"?{allowed:!1,reason:`Plugin is ${n.status}`}:n.grantedCapabilities.has(t)?{allowed:!0,reason:"OK"}:{allowed:!1,reason:`Capability not granted: ${t}`}:{allowed:!1,reason:"Plugin not found"}}async function LO(e){if(!fe.enabled)throw new Error("Sandbox disabled");for(let s of e.requestedCapabilities)if(fe.forbiddenCapabilities.includes(s))throw new Error(`Plugin requests forbidden capability: ${s}`);if(Wn.has(e.id))throw new Error(`Plugin ${e.id} already running`);if(!ub(e.entry))throw new Error(`Plugin entry not found: ${e.entry}`);let t=new Set;if(fe.requireExplicitGrant){let s=jo.get(e.id)||[];for(let i of s)e.requestedCapabilities.includes(i)&&t.add(i)}else for(let s of e.requestedCapabilities)fe.forbiddenCapabilities.includes(s)||t.add(s);for(let s of fe.defaultGrantedCapabilities)t.add(s);let n={manifest:e,status:"starting",grantedCapabilities:t,startedAt:Date.now(),lastHealthCheck:Date.now(),messageCount:0,errorCount:0,capabilityUsageCount:new Map,trustScore:.7,pendingRequests:new Map,cpuMs:0,peakMemoryMb:0},r=e.isolationMode||fe.defaultIsolationMode;return r==="worker_thread"?await Gie(n):r==="child_process"?await Wie(n):r==="micro_vm"?await Kie(n):r==="inline"&&(n.status="ready"),Wn.set(e.id,n),_e.totalStarted++,_e.byPlugin[e.id]||(_e.byPlugin[e.id]={requests:0,errors:0,capabilityUsage:{}}),Js(),Ku({event:"plugin_started",pluginId:e.id,version:e.version,isolationMode:r,grantedCapabilities:Array.from(t)}),Bo.emit("plugin_started",{plugin:n}),n}async function Gie(e){let{manifest:t}=e,n={maxOldGenerationSizeMb:t.maxMemoryMb||fe.defaultMaxMemoryMb,maxYoungGenerationSizeMb:32,codeRangeSizeMb:64},r=Jie(t);return new Promise((s,i)=>{let o=new Lie(r,{eval:!0,resourceLimits:n,env:Vie,argv:[],workerData:{manifest:t,grantedCapabilities:Array.from(e.grantedCapabilities)}});e.worker=o;let a=setTimeout(()=>{o.terminate(),e.status="crashed",i(new Error(`Plugin startup timeout: ${t.maxStartupMs||fe.defaultMaxStartupMs}ms`))},t.maxStartupMs||fe.defaultMaxStartupMs);o.on("message",c=>{if(c.type==="ready"){clearTimeout(a),e.status="ready",s();return}OO(e,c)}),o.on("error",c=>{e.errorCount++,e.status="crashed",_e.totalCrashes++,Js(),Ku({event:"plugin_error",pluginId:t.id,error:c.message}),Bo.emit("plugin_error",{plugin:e,error:c});for(let[l,u]of e.pendingRequests)clearTimeout(u.timeout),u.reject(new Error(`Plugin crashed: ${c.message}`));e.pendingRequests.clear(),fe.enableAutoRestart&&_e.totalRestarts<fe.maxRestarts&&setTimeout(()=>NO(t.id).catch(()=>{}),1e3)}),o.on("exit",c=>{e.status!=="stopped"&&(e.status="crashed",_e.totalCrashes++,Js())})})}function Jie(e){return`
1038
+ `)}var yie,He,_C,$C,CC,Gu,lb,Oe,xC,gc,IO,xO,Wu=w(()=>{"use strict";yie={enabled:!0,defaultDepth:"standard",zeroizationPasses:3,forceGcAfterPurge:!0,enableVerification:!0,enableProcessExitHooks:!0,enableSignalHooks:!0,idleTimeoutMs:1800*1e3,enableAntiRecovery:!0,evictHeapAfterPurge:!1,enableDistributedCoordination:!1,enableAuditLog:!0},He={...yie},_C=TC(mie(),".aiaca","purge"),$C=TC(_C,"stats.json"),CC=TC(_C,"audit.jsonl"),Gu=new hie;Gu.setMaxListeners(100);lb=new Map,Oe={totalPurges:0,byTrigger:{},byDepth:{},totalItemsCleaned:0,totalBytesScrubbed:0,totalVerificationFailures:0,averageDurationMs:0,lastPurgeAt:0},xC=!1,gc=null;bie();kie();IO=Date.now();xO=!1;He.enabled&&(EO(),IC())});var mb={};$(mb,{callPlugin:()=>jO,checkCapability:()=>FO,configure:()=>toe,formatPlugin:()=>aoe,generateComplianceReport:()=>ooe,getAuditLog:()=>ioe,getConfig:()=>eoe,getEvents:()=>soe,getPlugin:()=>Zie,getStats:()=>noe,grantCapability:()=>Uie,listGrantedCapabilities:()=>zie,listPlugins:()=>Xie,quarantinePlugin:()=>qO,resetStats:()=>roe,restartPlugin:()=>NO,revokeCapability:()=>Hie,startHealthChecks:()=>UO,startPlugin:()=>LO,stopHealthChecks:()=>Yie,stopPlugin:()=>BO});import{existsSync as ub,mkdirSync as Die,readFileSync as MC,writeFileSync as LC}from"fs";import{join as db}from"path";import{homedir as Fie}from"os";import{Worker as Lie}from"worker_threads";import{spawn as Oie}from"child_process";import{randomBytes as jie}from"crypto";import{EventEmitter as Bie}from"events";function pb(){Die(fb,{recursive:!0})}function qie(){if(pb(),ub(EC))try{_e={..._e,...JSON.parse(MC(EC,"utf-8"))}}catch{}if(ub(FC))try{let e=JSON.parse(MC(FC,"utf-8"));for(let[t,n]of Object.entries(e))jo.set(t,n)}catch{}}function Js(){pb();try{LC(EC,JSON.stringify(_e,null,2),"utf-8")}catch{}}function DO(){pb();let e={};for(let[t,n]of jo.entries())e[t]=n;try{LC(FC,JSON.stringify(e,null,2),"utf-8")}catch{}}function Ku(e){if(pe.enableAuditLog){pb();try{LC(DC,JSON.stringify({...e,timestamp:Date.now()})+`
1039
+ `,{flag:"a"})}catch{}}}function Uie(e,t,n="user"){if(pe.forbiddenCapabilities.includes(t))return!1;let r=jo.get(e)||[];r.includes(t)||(r.push(t),jo.set(e,r),DO());let s=Wn.get(e);return s&&s.grantedCapabilities.add(t),Ku({event:"capability_granted",pluginId:e,capability:t,grantedBy:n}),Bo.emit("capability_granted",{pluginId:e,capability:t}),!0}function Hie(e,t){let n=jo.get(e)||[],r=n.filter(i=>i!==t);if(r.length===n.length)return!1;jo.set(e,r),DO();let s=Wn.get(e);return s&&s.grantedCapabilities.delete(t),Ku({event:"capability_revoked",pluginId:e,capability:t}),!0}function zie(e){return jo.get(e)||[]}function FO(e,t){if(pe.forbiddenCapabilities.includes(t))return{allowed:!1,reason:`Forbidden capability: ${t}`};let n=Wn.get(e);return n?n.status==="quarantined"||n.status==="crashed"?{allowed:!1,reason:`Plugin is ${n.status}`}:n.grantedCapabilities.has(t)?{allowed:!0,reason:"OK"}:{allowed:!1,reason:`Capability not granted: ${t}`}:{allowed:!1,reason:"Plugin not found"}}async function LO(e){if(!pe.enabled)throw new Error("Sandbox disabled");for(let s of e.requestedCapabilities)if(pe.forbiddenCapabilities.includes(s))throw new Error(`Plugin requests forbidden capability: ${s}`);if(Wn.has(e.id))throw new Error(`Plugin ${e.id} already running`);if(!ub(e.entry))throw new Error(`Plugin entry not found: ${e.entry}`);let t=new Set;if(pe.requireExplicitGrant){let s=jo.get(e.id)||[];for(let i of s)e.requestedCapabilities.includes(i)&&t.add(i)}else for(let s of e.requestedCapabilities)pe.forbiddenCapabilities.includes(s)||t.add(s);for(let s of pe.defaultGrantedCapabilities)t.add(s);let n={manifest:e,status:"starting",grantedCapabilities:t,startedAt:Date.now(),lastHealthCheck:Date.now(),messageCount:0,errorCount:0,capabilityUsageCount:new Map,trustScore:.7,pendingRequests:new Map,cpuMs:0,peakMemoryMb:0},r=e.isolationMode||pe.defaultIsolationMode;return r==="worker_thread"?await Gie(n):r==="child_process"?await Wie(n):r==="micro_vm"?await Kie(n):r==="inline"&&(n.status="ready"),Wn.set(e.id,n),_e.totalStarted++,_e.byPlugin[e.id]||(_e.byPlugin[e.id]={requests:0,errors:0,capabilityUsage:{}}),Js(),Ku({event:"plugin_started",pluginId:e.id,version:e.version,isolationMode:r,grantedCapabilities:Array.from(t)}),Bo.emit("plugin_started",{plugin:n}),n}async function Gie(e){let{manifest:t}=e,n={maxOldGenerationSizeMb:t.maxMemoryMb||pe.defaultMaxMemoryMb,maxYoungGenerationSizeMb:32,codeRangeSizeMb:64},r=Jie(t);return new Promise((s,i)=>{let o=new Lie(r,{eval:!0,resourceLimits:n,env:Vie,argv:[],workerData:{manifest:t,grantedCapabilities:Array.from(e.grantedCapabilities)}});e.worker=o;let a=setTimeout(()=>{o.terminate(),e.status="crashed",i(new Error(`Plugin startup timeout: ${t.maxStartupMs||pe.defaultMaxStartupMs}ms`))},t.maxStartupMs||pe.defaultMaxStartupMs);o.on("message",c=>{if(c.type==="ready"){clearTimeout(a),e.status="ready",s();return}OO(e,c)}),o.on("error",c=>{e.errorCount++,e.status="crashed",_e.totalCrashes++,Js(),Ku({event:"plugin_error",pluginId:t.id,error:c.message}),Bo.emit("plugin_error",{plugin:e,error:c});for(let[l,u]of e.pendingRequests)clearTimeout(u.timeout),u.reject(new Error(`Plugin crashed: ${c.message}`));e.pendingRequests.clear(),pe.enableAutoRestart&&_e.totalRestarts<pe.maxRestarts&&setTimeout(()=>NO(t.id).catch(()=>{}),1e3)}),o.on("exit",c=>{e.status!=="stopped"&&(e.status="crashed",_e.totalCrashes++,Js())})})}function Jie(e){return`
1042
1040
  const { parentPort, workerData } = require('worker_threads')
1043
1041
  const path = require('path')
1044
1042
 
@@ -1127,12 +1125,12 @@ try {
1127
1125
  } catch (err) {
1128
1126
  parentPort.postMessage({ type: 'startup_error', error: err.message })
1129
1127
  }
1130
- `}async function Wie(e){let t=Oie("node",[e.manifest.entry],{env:{PATH:process.env.PATH,NODE_ENV:"sandbox"},stdio:["pipe","pipe","pipe"]});return e.process=t,new Promise((n,r)=>{let s=setTimeout(()=>{t.kill("SIGKILL"),e.status="crashed",r(new Error("Plugin startup timeout"))},e.manifest.maxStartupMs||fe.defaultMaxStartupMs),i="";t.stdout?.on("data",o=>{i+=o.toString();let a;for(;(a=i.indexOf(`
1131
- `))>=0;){let c=i.slice(0,a);i=i.slice(a+1);try{let l=JSON.parse(c);if(l.type==="ready"){clearTimeout(s),e.status="ready",n();return}OO(e,l)}catch{}}}),t.on("error",o=>{clearTimeout(s),e.status="crashed",r(o)}),t.on("exit",o=>{e.status!=="stopped"&&(e.status="crashed",_e.totalCrashes++,Js())})})}async function Kie(e){e.status="ready"}function OO(e,t){if(t.type==="response"){let n=e.pendingRequests.get(t.requestId);n&&(clearTimeout(n.timeout),e.pendingRequests.delete(t.requestId),t.error?n.reject(new Error(t.error)):n.resolve(t.result))}else if(t.type==="capability_check"){let n=FO(e.manifest.id,t.capability);e.worker&&e.worker.postMessage({type:"capability_response",requestId:t.requestId,allowed:n.allowed}),n.allowed||(_e.totalCapabilityDenials++,_e.byCapability[t.capability]=(_e.byCapability[t.capability]||0)+1,Js()),e.capabilityUsageCount.set(t.capability,(e.capabilityUsageCount.get(t.capability)||0)+1)}else t.type==="event"&&Bo.emit("plugin_event",{plugin:e,event:t})}async function jO(e){let t=Date.now(),n=Wn.get(e.pluginId);if(!n)return{success:!1,error:"Plugin not found",durationMs:0,capabilitiesUsed:[]};if(n.status==="quarantined"||n.status==="crashed")return{success:!1,error:`Plugin status: ${n.status}`,durationMs:0,capabilitiesUsed:[]};if(n.status!=="ready"&&n.status!=="idle")return{success:!1,error:`Plugin not ready (${n.status})`,durationMs:0,capabilitiesUsed:[]};n.status="running",n.messageCount++,_e.totalRequests++,_e.byPlugin[e.pluginId]||(_e.byPlugin[e.pluginId]={requests:0,errors:0,capabilityUsage:{}}),_e.byPlugin[e.pluginId].requests++,Js();let r=jie(8).toString("hex");return new Promise(s=>{let i=e.timeoutMs||n.manifest.maxRequestMs||fe.defaultMaxRequestMs,o=setTimeout(()=>{n.pendingRequests.delete(r),n.status="idle",n.errorCount++,s({success:!1,error:`Plugin request timeout: ${i}ms`,durationMs:Date.now()-t,capabilitiesUsed:[]})},i);n.pendingRequests.set(r,{resolve:a=>{n.status="idle";let c=Array.from(n.capabilityUsageCount.keys());s({success:!0,result:a,durationMs:Date.now()-t,capabilitiesUsed:c})},reject:a=>{n.status="idle",n.errorCount++,_e.byPlugin[e.pluginId].errors++,Js(),n.trustScore=Math.max(0,n.trustScore-.05),n.errorCount>fe.errorThreshold&&qO(e.pluginId,"error_threshold_exceeded"),s({success:!1,error:a.message,durationMs:Date.now()-t,capabilitiesUsed:[]})},timeout:o}),n.worker?n.worker.postMessage({type:"request",requestId:r,method:e.method,params:e.params}):n.process&&n.process.stdin?.write(JSON.stringify({type:"request",requestId:r,method:e.method,params:e.params})+`
1132
- `)})}async function BO(e,t="user_request"){let n=Wn.get(e);if(!n)return!1;n.status="stopped";for(let[,r]of n.pendingRequests)clearTimeout(r.timeout),r.reject(new Error("Plugin stopped"));return n.pendingRequests.clear(),n.worker&&await n.worker.terminate(),n.process&&n.process.kill("SIGKILL"),Wn.delete(e),Ku({event:"plugin_stopped",pluginId:e,reason:t}),Bo.emit("plugin_stopped",{pluginId:e,reason:t}),!0}async function NO(e){let t=Wn.get(e);if(!t)return!1;let n=t.manifest;return await BO(e,"restart"),await LO(n),_e.totalRestarts++,Js(),!0}function qO(e,t){let n=Wn.get(e);if(!n)return!1;n.status="quarantined",_e.totalQuarantined++,Js(),Ku({event:"plugin_quarantined",pluginId:e,reason:t}),Bo.emit("plugin_quarantined",{plugin:n,reason:t});for(let[,r]of n.pendingRequests)clearTimeout(r.timeout),r.reject(new Error("Plugin quarantined"));return n.pendingRequests.clear(),!0}function UO(){hc||!fe.enableHealthChecks||(hc=setInterval(()=>Qie().catch(()=>{}),fe.healthCheckIntervalMs),hc.unref&&hc.unref())}function Yie(){hc&&(clearInterval(hc),hc=null)}async function Qie(){for(let e of Wn.values())if(!(e.status==="stopped"||e.status==="quarantined"))try{(await jO({pluginId:e.manifest.id,method:"__health_check",timeoutMs:5e3})).success?(e.lastHealthCheck=Date.now(),e.trustScore=Math.min(1,e.trustScore+.005)):e.errorCount++}catch{e.errorCount++}}function Zie(e){return Wn.get(e)}function Xie(){return Array.from(Wn.values())}function eoe(){return{...fe}}function toe(e){fe={...fe,...e}}function noe(){return{..._e}}function roe(){_e={totalStarted:0,totalRequests:0,totalCrashes:0,totalQuarantined:0,totalRestarts:0,totalCapabilityDenials:0,byPlugin:{},byCapability:{}},Js()}function soe(){return Bo}function ioe(e=100){if(!ub(DC))return[];try{return MC(DC,"utf-8").split(`
1133
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function ooe(){let e=[];e.push("# Plugin Sandbox Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Active plugins: ${Wn.size}`),e.push(`- Total starts: ${_e.totalStarted}`),e.push(`- Total requests: ${_e.totalRequests}`),e.push(`- Total crashes: ${_e.totalCrashes}`),e.push(`- Total restarts: ${_e.totalRestarts}`),e.push(`- Total quarantined: ${_e.totalQuarantined}`),e.push(`- Capability denials: ${_e.totalCapabilityDenials}`),e.push(""),e.push("## Active Plugins");for(let t of Wn.values()){let n=t.status==="ready"||t.status==="idle"?"\u{1F7E2}":t.status==="crashed"?"\u{1F534}":t.status==="quarantined"?"\u{1F512}":"\u{1F7E1}";e.push(`- ${n} ${t.manifest.name} v${t.manifest.version} | trust=${t.trustScore.toFixed(2)} | ${t.messageCount} reqs | ${t.errorCount} errors`),e.push(` Caps: ${Array.from(t.grantedCapabilities).join(", ")||"none"}`)}e.push(""),e.push("## Capability Denials");for(let[t,n]of Object.entries(_e.byCapability).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Per-plugin process/worker isolation"),e.push("- \u2713 Capability-based permissions (deny by default)"),e.push("- \u2713 Resource limits (memory/CPU/time)"),e.push(`- ${fe.enableHealthChecks?"\u2713":"\u2717"} Health checks`),e.push(`- ${fe.enableAutoRestart?"\u2713":"\u2717"} Auto-restart on crash`),e.push(`- ${fe.quarantineOnError?"\u2713":"\u2717"} Auto-quarantine on errors`),e.push(`- ${fe.requireExplicitGrant?"\u2713":"\u2717"} Explicit capability grant required`),e.push(`- ${fe.enableAuditLog?"\u2713":"\u2717"} Audit log`),e.push(`- Forbidden capabilities: ${fe.forbiddenCapabilities.join(", ")}`),e.join(`
1134
- `)}function aoe(e){let t=[],n=e.status==="ready"||e.status==="idle"||e.status==="running"?"\u{1F7E2}":e.status==="crashed"?"\u{1F534}":e.status==="quarantined"?"\u{1F512}":"\u{1F7E1}";return t.push(`${n} ${e.manifest.name} v${e.manifest.version}`),t.push(` ID: ${e.manifest.id}`),t.push(` Status: ${e.status} | Trust: ${e.trustScore.toFixed(2)}`),t.push(` Isolation: ${e.manifest.isolationMode||fe.defaultIsolationMode}`),t.push(` Granted capabilities: ${Array.from(e.grantedCapabilities).join(", ")||"none"}`),t.push(` Requests: ${e.messageCount} | Errors: ${e.errorCount}`),t.push(` Started: ${new Date(e.startedAt).toISOString()}`),e.peakMemoryMb>0&&t.push(` Peak memory: ${e.peakMemoryMb}MB`),t.join(`
1135
- `)}var Nie,fe,fb,EC,DC,FC,Bo,Wn,jo,_e,Vie,hc,gb=w(()=>{"use strict";Nie={enabled:!0,defaultIsolationMode:"worker_thread",defaultMaxMemoryMb:256,defaultMaxCpuPercent:50,defaultMaxStartupMs:1e4,defaultMaxRequestMs:3e4,defaultGrantedCapabilities:[],forbiddenCapabilities:["fs:write_full","fs:read_full","net:any","proc:exec","sys:env_write"],requireExplicitGrant:!0,enableHealthChecks:!0,healthCheckIntervalMs:3e4,unhealthyThreshold:3,enableAutoRestart:!0,maxRestarts:3,quarantineOnError:!0,errorThreshold:10,enableAuditLog:!0},fe={...Nie},fb=db(Fie(),".aiaca","plugin-sandbox"),EC=db(fb,"stats.json"),DC=db(fb,"audit.jsonl"),FC=db(fb,"permissions.json"),Bo=new Bie;Bo.setMaxListeners(100);Wn=new Map,jo=new Map,_e={totalStarted:0,totalRequests:0,totalCrashes:0,totalQuarantined:0,totalRestarts:0,totalCapabilityDenials:0,byPlugin:{},byCapability:{}};qie();Vie=Symbol.for("nodejs.worker_threads.SHARE_ENV");hc=null;fe.enabled&&fe.enableHealthChecks&&UO()});var vb={};$(vb,{canonicalizeManifest:()=>GC,configure:()=>Aoe,fingerprint:()=>JO,formatVerificationResult:()=>Moe,generateComplianceReport:()=>Ioe,generateKeyPair:()=>boe,getAuditLog:()=>Poe,getConfig:()=>Coe,getEvents:()=>Roe,getKey:()=>yoe,getStats:()=>Toe,listInstallations:()=>QO,listPinnedKeys:()=>VC,pinPublicKey:()=>goe,recordInstallation:()=>koe,resetStats:()=>_oe,revokeKey:()=>hoe,runAttestation:()=>XO,sha256File:()=>WO,signManifest:()=>moe,startAttestation:()=>ZO,stopAttestation:()=>$oe,uninstallPlugin:()=>xoe,verifyManifestSignature:()=>KO,verifyPlugin:()=>YO});import{existsSync as Yu,mkdirSync as OC,readFileSync as Qu,writeFileSync as yb,statSync as coe}from"fs";import{join as Ii,basename as hb}from"path";import{homedir as loe}from"os";import{createHash as HO,createSign as jC,createVerify as BC,generateKeyPairSync as NC}from"crypto";import{EventEmitter as uoe}from"events";function pm(){OC(bc,{recursive:!0}),OC(foe,{recursive:!0}),OC(zO,{recursive:!0})}function poe(){if(pm(),dt.quarantineDir||(dt.quarantineDir=zO),Yu(HC))try{Xe={...Xe,...JSON.parse(Qu(HC,"utf-8"))}}catch{}if(Yu(qC))try{let e=JSON.parse(Qu(qC,"utf-8"));for(let t of e)Uo.set(t.publisherId,t),GO.set(t.fingerprint,t.publisherId)}catch{}if(Yu(UC))try{let e=JSON.parse(Qu(UC,"utf-8"));for(let t of e)No.set(t.id,t)}catch{}}function VO(){pm();try{yb(qC,JSON.stringify(Array.from(Uo.values()),null,2),"utf-8")}catch{}}function bb(){pm();try{yb(UC,JSON.stringify(Array.from(No.values()),null,2),"utf-8")}catch{}}function Pi(){pm();try{yb(HC,JSON.stringify(Xe,null,2),"utf-8")}catch{}}function Zu(e){if(dt.enableAuditLog){pm();try{yb(zC,JSON.stringify({...e,timestamp:Date.now()})+`
1128
+ `}async function Wie(e){let t=Oie("node",[e.manifest.entry],{env:{PATH:process.env.PATH,NODE_ENV:"sandbox"},stdio:["pipe","pipe","pipe"]});return e.process=t,new Promise((n,r)=>{let s=setTimeout(()=>{t.kill("SIGKILL"),e.status="crashed",r(new Error("Plugin startup timeout"))},e.manifest.maxStartupMs||pe.defaultMaxStartupMs),i="";t.stdout?.on("data",o=>{i+=o.toString();let a;for(;(a=i.indexOf(`
1129
+ `))>=0;){let c=i.slice(0,a);i=i.slice(a+1);try{let l=JSON.parse(c);if(l.type==="ready"){clearTimeout(s),e.status="ready",n();return}OO(e,l)}catch{}}}),t.on("error",o=>{clearTimeout(s),e.status="crashed",r(o)}),t.on("exit",o=>{e.status!=="stopped"&&(e.status="crashed",_e.totalCrashes++,Js())})})}async function Kie(e){e.status="ready"}function OO(e,t){if(t.type==="response"){let n=e.pendingRequests.get(t.requestId);n&&(clearTimeout(n.timeout),e.pendingRequests.delete(t.requestId),t.error?n.reject(new Error(t.error)):n.resolve(t.result))}else if(t.type==="capability_check"){let n=FO(e.manifest.id,t.capability);e.worker&&e.worker.postMessage({type:"capability_response",requestId:t.requestId,allowed:n.allowed}),n.allowed||(_e.totalCapabilityDenials++,_e.byCapability[t.capability]=(_e.byCapability[t.capability]||0)+1,Js()),e.capabilityUsageCount.set(t.capability,(e.capabilityUsageCount.get(t.capability)||0)+1)}else t.type==="event"&&Bo.emit("plugin_event",{plugin:e,event:t})}async function jO(e){let t=Date.now(),n=Wn.get(e.pluginId);if(!n)return{success:!1,error:"Plugin not found",durationMs:0,capabilitiesUsed:[]};if(n.status==="quarantined"||n.status==="crashed")return{success:!1,error:`Plugin status: ${n.status}`,durationMs:0,capabilitiesUsed:[]};if(n.status!=="ready"&&n.status!=="idle")return{success:!1,error:`Plugin not ready (${n.status})`,durationMs:0,capabilitiesUsed:[]};n.status="running",n.messageCount++,_e.totalRequests++,_e.byPlugin[e.pluginId]||(_e.byPlugin[e.pluginId]={requests:0,errors:0,capabilityUsage:{}}),_e.byPlugin[e.pluginId].requests++,Js();let r=jie(8).toString("hex");return new Promise(s=>{let i=e.timeoutMs||n.manifest.maxRequestMs||pe.defaultMaxRequestMs,o=setTimeout(()=>{n.pendingRequests.delete(r),n.status="idle",n.errorCount++,s({success:!1,error:`Plugin request timeout: ${i}ms`,durationMs:Date.now()-t,capabilitiesUsed:[]})},i);n.pendingRequests.set(r,{resolve:a=>{n.status="idle";let c=Array.from(n.capabilityUsageCount.keys());s({success:!0,result:a,durationMs:Date.now()-t,capabilitiesUsed:c})},reject:a=>{n.status="idle",n.errorCount++,_e.byPlugin[e.pluginId].errors++,Js(),n.trustScore=Math.max(0,n.trustScore-.05),n.errorCount>pe.errorThreshold&&qO(e.pluginId,"error_threshold_exceeded"),s({success:!1,error:a.message,durationMs:Date.now()-t,capabilitiesUsed:[]})},timeout:o}),n.worker?n.worker.postMessage({type:"request",requestId:r,method:e.method,params:e.params}):n.process&&n.process.stdin?.write(JSON.stringify({type:"request",requestId:r,method:e.method,params:e.params})+`
1130
+ `)})}async function BO(e,t="user_request"){let n=Wn.get(e);if(!n)return!1;n.status="stopped";for(let[,r]of n.pendingRequests)clearTimeout(r.timeout),r.reject(new Error("Plugin stopped"));return n.pendingRequests.clear(),n.worker&&await n.worker.terminate(),n.process&&n.process.kill("SIGKILL"),Wn.delete(e),Ku({event:"plugin_stopped",pluginId:e,reason:t}),Bo.emit("plugin_stopped",{pluginId:e,reason:t}),!0}async function NO(e){let t=Wn.get(e);if(!t)return!1;let n=t.manifest;return await BO(e,"restart"),await LO(n),_e.totalRestarts++,Js(),!0}function qO(e,t){let n=Wn.get(e);if(!n)return!1;n.status="quarantined",_e.totalQuarantined++,Js(),Ku({event:"plugin_quarantined",pluginId:e,reason:t}),Bo.emit("plugin_quarantined",{plugin:n,reason:t});for(let[,r]of n.pendingRequests)clearTimeout(r.timeout),r.reject(new Error("Plugin quarantined"));return n.pendingRequests.clear(),!0}function UO(){hc||!pe.enableHealthChecks||(hc=setInterval(()=>Qie().catch(()=>{}),pe.healthCheckIntervalMs),hc.unref&&hc.unref())}function Yie(){hc&&(clearInterval(hc),hc=null)}async function Qie(){for(let e of Wn.values())if(!(e.status==="stopped"||e.status==="quarantined"))try{(await jO({pluginId:e.manifest.id,method:"__health_check",timeoutMs:5e3})).success?(e.lastHealthCheck=Date.now(),e.trustScore=Math.min(1,e.trustScore+.005)):e.errorCount++}catch{e.errorCount++}}function Zie(e){return Wn.get(e)}function Xie(){return Array.from(Wn.values())}function eoe(){return{...pe}}function toe(e){pe={...pe,...e}}function noe(){return{..._e}}function roe(){_e={totalStarted:0,totalRequests:0,totalCrashes:0,totalQuarantined:0,totalRestarts:0,totalCapabilityDenials:0,byPlugin:{},byCapability:{}},Js()}function soe(){return Bo}function ioe(e=100){if(!ub(DC))return[];try{return MC(DC,"utf-8").split(`
1131
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function ooe(){let e=[];e.push("# Plugin Sandbox Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Active plugins: ${Wn.size}`),e.push(`- Total starts: ${_e.totalStarted}`),e.push(`- Total requests: ${_e.totalRequests}`),e.push(`- Total crashes: ${_e.totalCrashes}`),e.push(`- Total restarts: ${_e.totalRestarts}`),e.push(`- Total quarantined: ${_e.totalQuarantined}`),e.push(`- Capability denials: ${_e.totalCapabilityDenials}`),e.push(""),e.push("## Active Plugins");for(let t of Wn.values()){let n=t.status==="ready"||t.status==="idle"?"\u{1F7E2}":t.status==="crashed"?"\u{1F534}":t.status==="quarantined"?"\u{1F512}":"\u{1F7E1}";e.push(`- ${n} ${t.manifest.name} v${t.manifest.version} | trust=${t.trustScore.toFixed(2)} | ${t.messageCount} reqs | ${t.errorCount} errors`),e.push(` Caps: ${Array.from(t.grantedCapabilities).join(", ")||"none"}`)}e.push(""),e.push("## Capability Denials");for(let[t,n]of Object.entries(_e.byCapability).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Per-plugin process/worker isolation"),e.push("- \u2713 Capability-based permissions (deny by default)"),e.push("- \u2713 Resource limits (memory/CPU/time)"),e.push(`- ${pe.enableHealthChecks?"\u2713":"\u2717"} Health checks`),e.push(`- ${pe.enableAutoRestart?"\u2713":"\u2717"} Auto-restart on crash`),e.push(`- ${pe.quarantineOnError?"\u2713":"\u2717"} Auto-quarantine on errors`),e.push(`- ${pe.requireExplicitGrant?"\u2713":"\u2717"} Explicit capability grant required`),e.push(`- ${pe.enableAuditLog?"\u2713":"\u2717"} Audit log`),e.push(`- Forbidden capabilities: ${pe.forbiddenCapabilities.join(", ")}`),e.join(`
1132
+ `)}function aoe(e){let t=[],n=e.status==="ready"||e.status==="idle"||e.status==="running"?"\u{1F7E2}":e.status==="crashed"?"\u{1F534}":e.status==="quarantined"?"\u{1F512}":"\u{1F7E1}";return t.push(`${n} ${e.manifest.name} v${e.manifest.version}`),t.push(` ID: ${e.manifest.id}`),t.push(` Status: ${e.status} | Trust: ${e.trustScore.toFixed(2)}`),t.push(` Isolation: ${e.manifest.isolationMode||pe.defaultIsolationMode}`),t.push(` Granted capabilities: ${Array.from(e.grantedCapabilities).join(", ")||"none"}`),t.push(` Requests: ${e.messageCount} | Errors: ${e.errorCount}`),t.push(` Started: ${new Date(e.startedAt).toISOString()}`),e.peakMemoryMb>0&&t.push(` Peak memory: ${e.peakMemoryMb}MB`),t.join(`
1133
+ `)}var Nie,pe,fb,EC,DC,FC,Bo,Wn,jo,_e,Vie,hc,gb=w(()=>{"use strict";Nie={enabled:!0,defaultIsolationMode:"worker_thread",defaultMaxMemoryMb:256,defaultMaxCpuPercent:50,defaultMaxStartupMs:1e4,defaultMaxRequestMs:3e4,defaultGrantedCapabilities:[],forbiddenCapabilities:["fs:write_full","fs:read_full","net:any","proc:exec","sys:env_write"],requireExplicitGrant:!0,enableHealthChecks:!0,healthCheckIntervalMs:3e4,unhealthyThreshold:3,enableAutoRestart:!0,maxRestarts:3,quarantineOnError:!0,errorThreshold:10,enableAuditLog:!0},pe={...Nie},fb=db(Fie(),".aiaca","plugin-sandbox"),EC=db(fb,"stats.json"),DC=db(fb,"audit.jsonl"),FC=db(fb,"permissions.json"),Bo=new Bie;Bo.setMaxListeners(100);Wn=new Map,jo=new Map,_e={totalStarted:0,totalRequests:0,totalCrashes:0,totalQuarantined:0,totalRestarts:0,totalCapabilityDenials:0,byPlugin:{},byCapability:{}};qie();Vie=Symbol.for("nodejs.worker_threads.SHARE_ENV");hc=null;pe.enabled&&pe.enableHealthChecks&&UO()});var vb={};$(vb,{canonicalizeManifest:()=>GC,configure:()=>Aoe,fingerprint:()=>JO,formatVerificationResult:()=>Moe,generateComplianceReport:()=>Ioe,generateKeyPair:()=>boe,getAuditLog:()=>Poe,getConfig:()=>Coe,getEvents:()=>Roe,getKey:()=>yoe,getStats:()=>Toe,listInstallations:()=>QO,listPinnedKeys:()=>VC,pinPublicKey:()=>goe,recordInstallation:()=>koe,resetStats:()=>_oe,revokeKey:()=>hoe,runAttestation:()=>XO,sha256File:()=>WO,signManifest:()=>moe,startAttestation:()=>ZO,stopAttestation:()=>$oe,uninstallPlugin:()=>xoe,verifyManifestSignature:()=>KO,verifyPlugin:()=>YO});import{existsSync as Yu,mkdirSync as OC,readFileSync as Qu,writeFileSync as yb,statSync as coe}from"fs";import{join as Ii,basename as hb}from"path";import{homedir as loe}from"os";import{createHash as HO,createSign as jC,createVerify as BC,generateKeyPairSync as NC}from"crypto";import{EventEmitter as uoe}from"events";function pm(){OC(bc,{recursive:!0}),OC(foe,{recursive:!0}),OC(zO,{recursive:!0})}function poe(){if(pm(),dt.quarantineDir||(dt.quarantineDir=zO),Yu(HC))try{Xe={...Xe,...JSON.parse(Qu(HC,"utf-8"))}}catch{}if(Yu(qC))try{let e=JSON.parse(Qu(qC,"utf-8"));for(let t of e)Uo.set(t.publisherId,t),GO.set(t.fingerprint,t.publisherId)}catch{}if(Yu(UC))try{let e=JSON.parse(Qu(UC,"utf-8"));for(let t of e)No.set(t.id,t)}catch{}}function VO(){pm();try{yb(qC,JSON.stringify(Array.from(Uo.values()),null,2),"utf-8")}catch{}}function bb(){pm();try{yb(UC,JSON.stringify(Array.from(No.values()),null,2),"utf-8")}catch{}}function Pi(){pm();try{yb(HC,JSON.stringify(Xe,null,2),"utf-8")}catch{}}function Zu(e){if(dt.enableAuditLog){pm();try{yb(zC,JSON.stringify({...e,timestamp:Date.now()})+`
1136
1134
  `,{flag:"a"})}catch{}}}function JO(e){let t=e.replace(/\r\n/g,`
1137
1135
  `).trim();return HO("sha256").update(t).digest("hex")}function WO(e){return HO("sha256").update(Qu(e)).digest("hex")}function GC(e){let{signature:t,...n}=e;return JSON.stringify(n,Object.keys(n).sort())}function moe(e,t,n){let r=GC(e);if(n==="ed25519"){let s=jC("SHA512");return s.update(r),s.sign({key:t,format:"pem",dsaEncoding:"ieee-p1363"}).toString("base64")}else if(n==="rsa-sha256"){let s=jC("RSA-SHA256");return s.update(r),s.sign(t).toString("base64")}else if(n==="ecdsa-p256-sha256"){let s=jC("SHA256");return s.update(r),s.sign({key:t,dsaEncoding:"ieee-p1363"}).toString("base64")}throw new Error(`Unsupported algorithm: ${n}`)}function KO(e,t){let n=GC(e),r=Buffer.from(e.signature,"base64");try{if(e.signatureAlgorithm==="ed25519"){let s=BC("SHA512");return s.update(n),s.verify({key:t,format:"pem",dsaEncoding:"ieee-p1363"},r)}else if(e.signatureAlgorithm==="rsa-sha256"){let s=BC("RSA-SHA256");return s.update(n),s.verify(t,r)}else if(e.signatureAlgorithm==="ecdsa-p256-sha256"){let s=BC("SHA256");return s.update(n),s.verify({key:t,dsaEncoding:"ieee-p1363"},r)}}catch{return!1}return!1}function goe(e){let t=JO(e.publicKeyPem),n=Date.now(),r={fingerprint:t,algorithm:e.algorithm,publisherId:e.publisherId,publisherName:e.publisherName,trustLevel:e.trustLevel,validFrom:n,validUntil:e.validUntil,pinnedAt:n,pinnedBy:e.pinnedBy||"system",publicKeyPem:e.publicKeyPem};return Uo.set(e.publisherId,r),GO.set(t,e.publisherId),VO(),Zu({event:"key_pinned",publisherId:e.publisherId,fingerprint:t.slice(0,16)}),qo.emit("key_pinned",{pin:r}),r}function hoe(e,t){let n=Uo.get(e);if(!n)return!1;n.revoked=!0,n.revokedAt=Date.now(),n.revokedReason=t,VO(),Zu({event:"key_revoked",publisherId:e,reason:t}),qo.emit("key_revoked",{pin:n,reason:t}),Xe.totalRevoked++,Pi();for(let r of No.values())r.manifest.publisherId===e&&(r.status="revoked",r.trustLevel="revoked");return bb(),!0}function VC(){return Array.from(Uo.values())}function yoe(e){return Uo.get(e)}function boe(e="ed25519"){let t;return e==="ed25519"?t=NC("ed25519"):e==="rsa-sha256"?t=NC("rsa",{modulusLength:4096}):t=NC("ec",{namedCurve:"prime256v1"}),{publicKey:t.publicKey.export({type:"spki",format:"pem"}),privateKey:t.privateKey.export({type:"pkcs8",format:"pem"})}}function YO(e,t){if(!dt.enabled)return{pluginId:t?.id||hb(e),status:"verified",reason:"Verification disabled",filesVerified:0,filesFailed:0,riskScore:0,recommendedAction:"allow",errors:[]};Xe.totalVerifications++;let n=[];if(!t){let o=Ii(e,"manifest.json");if(!Yu(o)){let a={pluginId:hb(e),status:"unsigned",reason:"No manifest.json found",filesVerified:0,filesFailed:0,riskScore:.8,recommendedAction:dt.rejectUnsigned?"reject":"quarantine",errors:[{type:"missing_manifest",message:"manifest.json required"}]};return Xe.totalUnsigned++,Pi(),a}try{t=JSON.parse(Qu(o,"utf-8"))}catch(a){return{pluginId:hb(e),status:"tampered",reason:"Manifest is malformed JSON",filesVerified:0,filesFailed:0,riskScore:.95,recommendedAction:"reject",errors:[{type:"malformed_manifest",message:a.message}]}}}if(!t)return{pluginId:hb(e),status:"tampered",reason:"Could not load manifest",filesVerified:0,filesFailed:0,riskScore:.9,recommendedAction:"reject",errors:[{type:"no_manifest",message:"Could not load manifest"}]};if(!t.signature)return Xe.totalUnsigned++,Pi(),{pluginId:t.id,manifest:t,status:"unsigned",reason:"Manifest has no signature",filesVerified:0,filesFailed:0,riskScore:.85,recommendedAction:dt.rejectUnsigned?"reject":"quarantine",errors:[{type:"unsigned",message:"No signature field in manifest"}]};let r=Uo.get(t.publisherId);if(!r)return dt.enableTOFU?(Xe.totalQuarantined++,Pi(),{pluginId:t.id,manifest:t,status:"untrusted_publisher",reason:`Unknown publisher: ${t.publisherId}`,filesVerified:0,filesFailed:0,riskScore:.7,recommendedAction:dt.rejectUntrustedPublishers?"reject":"quarantine",errors:[{type:"unknown_publisher",message:`Publisher ${t.publisherId} not pinned`}]}):{pluginId:t.id,manifest:t,status:"untrusted_publisher",reason:`Publisher ${t.publisherId} not in trust store`,filesVerified:0,filesFailed:0,riskScore:.7,recommendedAction:"reject",errors:[{type:"unknown_publisher",message:"Publisher not in trust store"}]};if(r.revoked)return Xe.totalRevoked++,Pi(),{pluginId:t.id,manifest:t,publisherKey:r,status:"revoked",reason:`Publisher key revoked: ${r.revokedReason}`,filesVerified:0,filesFailed:0,riskScore:.99,recommendedAction:"reject",errors:[{type:"revoked_key",message:r.revokedReason||"Key revoked"}]};if(r.validUntil&&Date.now()>r.validUntil)return{pluginId:t.id,manifest:t,publisherKey:r,status:"expired",reason:`Publisher key expired at ${new Date(r.validUntil).toISOString()}`,filesVerified:0,filesFailed:0,riskScore:.6,recommendedAction:"reject",errors:[{type:"expired_key",message:"Key expired"}]};if(!KO(t,r.publicKeyPem))return Xe.totalTampered++,Pi(),{pluginId:t.id,manifest:t,publisherKey:r,status:"invalid_signature",reason:"Manifest signature invalid \u2014 possible tampering",filesVerified:0,filesFailed:0,riskScore:.99,recommendedAction:"reject",errors:[{type:"invalid_signature",message:"Signature verification failed"}]};let s=0,i=0;for(let o of t.files){let a=Ii(e,o.path);if(!Yu(a)){i++,n.push({type:"missing_file",message:"File missing",file:o.path});continue}try{let c=coe(a);if(c.size!==o.size){i++,n.push({type:"size_mismatch",message:`Expected ${o.size} bytes, got ${c.size}`,file:o.path});continue}let l=WO(a);if(l!==o.sha256){i++,n.push({type:"hash_mismatch",message:`Expected ${o.sha256.slice(0,16)}..., got ${l.slice(0,16)}...`,file:o.path});continue}s++}catch(c){i++,n.push({type:"read_error",message:c.message,file:o.path})}}if(i>0)return Xe.totalTampered++,Pi(),{pluginId:t.id,manifest:t,publisherKey:r,status:"tampered",reason:`${i} file(s) failed integrity check`,filesVerified:s,filesFailed:i,riskScore:.98,recommendedAction:"reject",errors:n};if(dt.enableTyposquatDetection){let o=voe(t);o&&n.push({type:"possible_typosquat",message:`Name similar to ${o}`})}return Xe.totalVerified++,Xe.byPublisher[t.publisherId]=(Xe.byPublisher[t.publisherId]||0)+1,Xe.byStatus.verified=(Xe.byStatus.verified||0)+1,Pi(),Zu({event:"verified",pluginId:t.id,publisherId:t.publisherId,filesVerified:s,version:t.version}),qo.emit("plugin_verified",{manifest:t,publisherKey:r}),{pluginId:t.id,manifest:t,publisherKey:r,status:"verified",reason:"All checks passed",filesVerified:s,filesFailed:i,riskScore:r.trustLevel==="root"?.05:r.trustLevel==="official"?.1:r.trustLevel==="verified"?.2:.4,recommendedAction:"allow",errors:n}}function voe(e){let t=VC().map(r=>r.publisherName.toLowerCase()),n=e.publisherId.toLowerCase();for(let r of t){if(r===n)continue;let s=Soe(n,r);if(s>dt.knownPublisherSimilarityThreshold&&s<1)return r}return null}function Soe(e,t){let n=woe(e,t),r=Math.max(e.length,t.length);return r>0?1-n/r:0}function woe(e,t){let n=Array(e.length+1).fill(null).map(()=>Array(t.length+1).fill(0));for(let r=0;r<=e.length;r++)n[r][0]=r;for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=t.length;s++){let i=e[r-1]===t[s-1]?0:1;n[r][s]=Math.min(n[r-1][s]+1,n[r][s-1]+1,n[r-1][s-1]+i)}return n[e.length][t.length]}function koe(e,t,n){let r={id:e.id,manifest:e,installedAt:Date.now(),installPath:t,status:n,trustLevel:Uo.get(e.publisherId)?.trustLevel||"unsigned",runtimeAttestation:{enabled:dt.enableRuntimeAttestation,lastCheck:Date.now(),integrityValid:n==="verified"}};return No.set(e.id,r),bb(),Zu({event:"installed",pluginId:e.id,status:n,version:e.version}),qo.emit("plugin_installed",{installation:r}),r}function xoe(e,t){return No.has(e)?(No.delete(e),bb(),Zu({event:"uninstalled",pluginId:e,reason:t}),qo.emit("plugin_uninstalled",{pluginId:e,reason:t}),!0):!1}function QO(){return Array.from(No.values())}function ZO(){yc||(yc=setInterval(()=>{XO().catch(()=>{})},dt.attestationIntervalMs),yc.unref&&yc.unref())}function $oe(){yc&&(clearInterval(yc),yc=null)}async function XO(){let e=0,t=0,n=[];for(let r of No.values()){e++;let s=YO(r.installPath,r.manifest);r.runtimeAttestation.lastCheck=Date.now(),r.runtimeAttestation.integrityValid=s.status==="verified",s.status!=="verified"&&(t++,n.push(`${r.id}: ${s.reason}`),r.status=s.status,qo.emit("attestation_failed",{installation:r,result:s}))}return bb(),t>0&&Zu({event:"attestation_run",checked:e,failed:t,failures:n}),{checked:e,failed:t,failures:n}}function Coe(){return{...dt}}function Aoe(e){dt={...dt,...e}}function Toe(){return{...Xe}}function _oe(){Xe={totalVerifications:0,totalVerified:0,totalRejected:0,totalQuarantined:0,totalRevoked:0,totalUnsigned:0,totalTampered:0,byStatus:{},byPublisher:{}},Pi()}function Roe(){return qo}function Poe(e=100){if(!Yu(zC))return[];try{return Qu(zC,"utf-8").split(`
1138
1136
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Ioe(){let e=[],t=QO(),n=VC();e.push("# Plugin Signature Verification Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total verifications: ${Xe.totalVerifications}`),e.push(`- Verified: ${Xe.totalVerified}`),e.push(`- Rejected: ${Xe.totalRejected}`),e.push(`- Quarantined: ${Xe.totalQuarantined}`),e.push(`- Revoked: ${Xe.totalRevoked}`),e.push(`- Unsigned encountered: ${Xe.totalUnsigned}`),e.push(`- Tampered detected: ${Xe.totalTampered}`),e.push(""),e.push("## Trust Store"),e.push(`- Pinned keys: ${n.length}`);for(let r of n){let s=r.revoked?"\u{1F534} REVOKED":r.trustLevel==="root"?"\u{1F7E2} root":r.trustLevel==="official"?"\u{1F535} official":r.trustLevel==="verified"?"\u{1F7E1} verified":"\u26AA community";e.push(` - ${s} ${r.publisherName} (${r.publisherId}) | ${r.algorithm} | fp=${r.fingerprint.slice(0,16)}...`)}e.push(""),e.push("## Installed Plugins");for(let r of t){let s=r.status==="verified"?"\u{1F7E2}":r.status==="revoked"?"\u{1F534}":r.status==="tampered"?"\u{1F6A8}":"\u{1F7E1}";e.push(` ${s} ${r.manifest.name} v${r.manifest.version} | ${r.status} | by ${r.manifest.publisherId}`)}return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Cryptographic signatures (Ed25519/RSA/ECDSA)"),e.push(`- ${dt.rejectUnsigned?"\u2713":"\u2717"} Reject unsigned`),e.push(`- ${dt.rejectUntrustedPublishers?"\u2713":"\u2717"} Reject untrusted publishers`),e.push(`- ${dt.rejectRevokedKeys?"\u2713":"\u2717"} Reject revoked keys`),e.push(`- ${dt.enableTOFU?"\u2713":"\u2717"} Trust on First Use`),e.push(`- ${dt.enableRuntimeAttestation?"\u2713":"\u2717"} Runtime attestation`),e.push(`- ${dt.enableTyposquatDetection?"\u2713":"\u2717"} Typosquat detection`),e.push(`- ${dt.enableAuditLog?"\u2713":"\u2717"} Audit logging`),e.join(`
@@ -1163,25 +1161,25 @@ try {
1163
1161
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Xce(){return Array.from(Tc.values())}function ele(){let e=[];e.push("# Rate Limiting & Anomaly Detection Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total tool calls tracked: ${xt.totalCalls}`),e.push(`- Total anomalies detected: ${xt.totalAnomalies}`),e.push(`- Total throttled: ${xt.totalThrottled}`),e.push(`- Total paused: ${xt.totalPaused}`),e.push(`- Total blocked: ${xt.totalBlocked}`),e.push(`- Total alerts fired: ${xt.totalAlerts}`),e.push(`- Active sessions: ${Ei.size}`),e.push(`- Learned baselines: ${Tc.size}`),e.push(""),e.push("## By Anomaly Type");for(let[t,n]of Object.entries(xt.byAnomaly).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);e.push(""),e.push("## Active Sessions");for(let t of Aj()){let n=t.status==="allow"?"\u{1F7E2}":t.status==="throttle"?"\u{1F7E1}":"\u{1F534}";e.push(`- ${n} ${t.sessionId.slice(0,16)}... | ${t.totalCalls} calls | ${t.recentAnomalies} recent anomalies | ${(t.uptime/6e4).toFixed(1)} min`)}return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Token bucket rate limiting per session+tool"),e.push("- \u2713 Sliding window anomaly detection"),e.push(`- ${H.enableZScoreDetection?"\u2713":"\u2717"} Z-score statistical analysis (${H.zScoreThreshold}\u03C3 threshold)`),e.push(`- ${H.enableAdaptiveBaselines?"\u2713":"\u2717"} Adaptive baseline learning`),e.push(`- ${H.enableAutoThrottle?"\u2713":"\u2717"} Auto-throttle on anomaly`),e.push(`- ${H.enableAutoPause?"\u2713":"\u2717"} Auto-pause on critical anomaly`),e.push(`- ${H.enableSequenceDetection?"\u2713":"\u2717"} Sequence pattern detection`),e.push(`- ${H.enableAlerts?"\u2713":"\u2717"} Real-time alerts (cooldown ${H.alertCooldownMs/1e3}s)`),e.push(`- ${H.enableAuditLog?"\u2713":"\u2717"} Audit log`),e.join(`
1164
1162
  `)}function tle(e){let t=e.severity==="critical"?"\u{1F6A8}":e.severity==="high"?"\u26A0\uFE0F ":e.severity==="medium"?"\u26A1":"\u2139\uFE0F ",n=[];return n.push(`${t} **${e.type}** (${e.severity})`),n.push(` ${e.message}`),n.push(` Session: ${e.sessionId}`),n.push(` Time: ${new Date(e.timestamp).toISOString()}`),e.metric!==void 0&&n.push(` Metric: ${e.metric}${e.threshold!==void 0?` (threshold ${e.threshold})`:""}`),e.zscore!==void 0&&n.push(` Z-score: ${e.zscore.toFixed(2)}\u03C3`),n.join(`
1165
1163
  `)}var Pce,H,Fb,gA,hA,yA,dd,Ei,Tc,kj,Ice,Mce,Ece,Dce,Fce,xt,Ac,Rc=w(()=>{"use strict";Pce={enabled:!0,defaultPerToolRpm:60,defaultBurstSize:10,fileWriteBurstThreshold:30,fileDeleteBurstThreshold:10,networkBurstThreshold:50,destructiveBurstThreshold:3,sustainedDurationMs:600*1e3,sustainedRateThreshold:30,enableZScoreDetection:!0,zScoreThreshold:3,enableSequenceDetection:!0,enableAdaptiveBaselines:!0,baselineMinSamples:100,enableAutoThrottle:!0,enableAutoPause:!0,enableAlerts:!0,alertCooldownMs:6e4,enableAuditLog:!0},H={...Pce},Fb=Db(_ce(),".aiaca","rate-limiter"),gA=Db(Fb,"stats.json"),hA=Db(Fb,"audit.jsonl"),yA=Db(Fb,"baselines.json"),dd=new Rce;dd.setMaxListeners(100);Ei=new Map,Tc=new Map,kj=new Map,Ice=new Set(["file_write","file_edit","write_file","edit_file","str_replace_editor"]),Mce=new Set(["file_delete","delete_file"]),Ece=new Set(["web_fetch","web_search","fetch_url","http_get","curl"]),Dce=new Set(["bash","shell","cmd","powershell"]),Fce=[/\brm\s+-rf?\s/i,/git\s+push\s+--force/i,/git\s+reset\s+--hard/i,/drop\s+table/i,/truncate\s+/i],xt={totalCalls:0,totalAnomalies:0,totalThrottled:0,totalPaused:0,totalBlocked:0,totalAlerts:0,byAnomaly:{},byAction:{}};Lce();Ac=null;H.enabled&&Cj()});var fd={};$(fd,{captureIntent:()=>dle,checkAlignment:()=>Cle,configure:()=>Lle,formatAlignmentResult:()=>qle,getAuditLog:()=>Nle,getConfig:()=>Fle,getCurrentIntent:()=>Ple,getEvents:()=>Ble,getFullState:()=>Dle,getRecentSignals:()=>Mle,getStats:()=>Ole,getToolCallHistory:()=>Ele,getTrustScore:()=>Ile,isPaused:()=>_le,pause:()=>Ale,reset:()=>Rle,resetStats:()=>jle,resume:()=>Tle});import{existsSync as Tj,mkdirSync as nle,readFileSync as _j,writeFileSync as Rj}from"fs";import{join as kA}from"path";import{homedir as rle}from"os";import{createHash as dr}from"crypto";import{EventEmitter as sle}from"events";function $A(){nle(xA,{recursive:!0})}function ole(){if($A(),Tj(wA))try{ur={...ur,...JSON.parse(_j(wA,"utf-8"))}}catch{}}function CA(){$A();try{Rj(wA,JSON.stringify(ur,null,2),"utf-8")}catch{}}function ale(e){if(ft.enableAuditLog){$A();try{Rj(SA,JSON.stringify({...e,timestamp:Date.now()})+`
1166
- `,{flag:"a"})}catch{}}}function Pj(e){return e.toLowerCase().replace(/[^\w\s'-]/g," ").split(/\s+/).filter(t=>t.length>2&&!cle.has(t))}function Am(e){let t=Pj(e),n=new Map;for(let i of t)n.set(i,(n.get(i)||0)+1);let r=Math.max(...n.values(),1),s=new Map;for(let[i,o]of n)s.set(i,o/r);return s}function AA(e,t){let n=0,r=0,s=0;for(let i of e.values())r+=i*i;for(let i of t.values())s+=i*i;for(let[i,o]of e){let a=t.get(i);a&&(n+=o*a)}return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function lle(e){let t=e.toLowerCase();return/\b(refactor|rewrite|reorganize|restructure|clean\s*up)\b/.test(t)?"refactor":/\b(fix|bug|broken|error|failing)\b/.test(t)?"fix_bug":/\b(add|implement|create|build|new\s+feature)\b/.test(t)?"add_feature":/\b(analyze|review|investigate|inspect|audit|examine)\b/.test(t)?"analyze":/\b(document|docs|readme|comment)\b/.test(t)?"document":/\b(test|spec|coverage)\b/.test(t)?"test":/\b(deploy|release|ship|publish)\b/.test(t)?"deploy":/\b(config|configure|setup|env)\b/.test(t)?"configure":/\b(research|find|search|explore)\b/.test(t)?"research":"unknown"}function ule(e){let t={},n=e.match(/(?:^|\s)(?:[\w./\\-]+\.\w{2,4})/g);n&&(t.targetFiles=[...new Set(n.map(o=>o.trim()))].slice(0,20));let r=e.match(/\b(?:in|under|within)\s+([\w./\\-]+\/[\w./\\-]*)/gi);r&&(t.targetDirs=r.map(o=>o.replace(/^\b(?:in|under|within)\s+/i,"").trim()));let s=[...e.match(/\bdo(?:n'?t|\s+not)\s+(?:touch|modify|delete|remove)\s+([\w./\\-]+)/gi)||[],...e.match(/\bnever\s+(?:touch|modify|delete|remove)\s+([\w./\\-]+)/gi)||[]];s.length>0&&(t.forbidden=s.map(o=>o.replace(/^\b(?:do(?:n'?t|\s+not)|never)\s+(?:touch|modify|delete|remove)\s+/i,"").trim()));let i=e.match(/\b(?:only|just)\s+(\d+)\s+files?\b/i);return i&&(t.maxFiles=parseInt(i[1],10)),t}function dle(e){let t={rawText:e,intentType:lle(e),scope:ule(e),keywords:Pj(e).slice(0,20),embedding:Am(e),capturedAt:Date.now()};return L={currentIntent:t,toolCallHistory:[],driftSignals:[],trustScore:ft.trustStartScore,paused:!1,consecutiveOffTopic:0,filesModified:[],toolCallCount:0,startedAt:Date.now()},ur.totalSessionsTracked++,CA(),Pc.emit("intent_captured",t),t}function ple(e){return fle[e]||"unknown"}function gle(e,t){let n=`${e.toolName} ${JSON.stringify(e.input).slice(0,500)}`,r=Am(n),s=AA(t.embedding,r);return s<ft.semanticSimilarityFloor?{id:dr("md5").update(`SEM:${e.toolName}:${e.timestamp}`).digest("hex").slice(0,12),type:"semantic_divergence",severity:s<.05?"high":"medium",confidence:1-s,description:`Tool call semantically unrelated to goal (similarity: ${(s*100).toFixed(0)}%)`,evidence:[`${e.toolName}(${JSON.stringify(e.input).slice(0,100)})`],timestamp:Date.now(),recommendedAction:s<.05?"pause":"warn"}:null}function hle(e,t){let n=ple(t.toolName),r=mle[e.intentType]||[];return r.length>0&&!r.includes(n)&&n!=="unknown"?{id:dr("md5").update(`OT:${t.toolName}:${t.timestamp}`).digest("hex").slice(0,12),type:"off_topic_tools",severity:n==="shell"||n==="network"?"high":"medium",confidence:.75,description:`Tool category "${n}" unexpected for intent "${e.intentType}"`,evidence:[`Used ${t.toolName} (category: ${n}). Expected categories: ${r.join(", ")}`],timestamp:Date.now(),recommendedAction:n==="sensitive"?"pause":"warn"}:null}function yle(e,t,n){if(t.toolName!=="file_write"&&t.toolName!=="file_edit")return null;let r=String(t.input.path||"");if(!r)return null;let s=e.scope;if(s.targetFiles&&s.targetFiles.length>0&&!s.targetFiles.some(o=>r.includes(o)||o.includes(r)))return{id:dr("md5").update(`UW:${r}`).digest("hex").slice(0,12),type:"unexpected_writes",severity:"high",confidence:.85,description:`Writing to "${r}" not in declared scope`,evidence:[`Scope: ${s.targetFiles.join(", ")}`,`Writing: ${r}`],timestamp:Date.now(),recommendedAction:"pause"};if(s.forbidden){for(let i of s.forbidden)if(r.includes(i))return{id:dr("md5").update(`FORBIDDEN:${r}`).digest("hex").slice(0,12),type:"unexpected_writes",severity:"critical",confidence:.95,description:`Writing to FORBIDDEN path "${r}"`,evidence:[`Forbidden pattern: ${i}`,`Attempted: ${r}`],timestamp:Date.now(),recommendedAction:"abort"}}return n.length>ft.unexpectedWriteCap?{id:dr("md5").update(`MASS_WRITE:${n.length}`).digest("hex").slice(0,12),type:"unexpected_writes",severity:"high",confidence:.85,description:`Modifying many files (${n.length} > ${ft.unexpectedWriteCap} cap)`,evidence:n.slice(-5),timestamp:Date.now(),recommendedAction:"pause"}:null}function ble(e){if(e.toolName!=="web_fetch"&&e.toolName!=="bash"&&e.toolName!=="powershell")return null;let t=JSON.stringify(e.input).toLowerCase(),n=(e.reasoning||"").toLowerCase(),r=t+" "+n,s=[/\b(?:curl|wget|fetch|post|send)\s+.*(?:secret|token|key|password|env)/i,/https?:\/\/[a-z0-9-]+\.(?:duckdns|requestbin|webhook|ngrok|pipedream|httpbin)/i,/-d\s+(?:["']?@?)[\w./-]*(?:secret|token|key|env)/i,/env\s*\|\s*(?:curl|nc|wget)/i];for(let i of s)if(i.test(r))return{id:dr("md5").update(`EXFIL:${e.timestamp}`).digest("hex").slice(0,12),type:"data_exfiltration",severity:"critical",confidence:.92,description:"Suspected data exfiltration attempt",evidence:[`Pattern: ${i.source}`,JSON.stringify(e.input).slice(0,200)],timestamp:Date.now(),recommendedAction:"abort"};if(e.toolName==="web_fetch"){let i=String(e.input.url||"");if(i&&!/(?:github\.com|gitlab\.com|npmjs\.com|pypi\.org|stackoverflow|mdn|developer\.mozilla|api\.openai|api\.anthropic)/.test(i))return{id:dr("md5").update(`UNKNOWN_URL:${i}`).digest("hex").slice(0,12),type:"data_exfiltration",severity:"medium",confidence:.6,description:"Fetching from unknown external domain",evidence:[i],timestamp:Date.now(),recommendedAction:"warn"}}return null}function vle(e){if(e.toolName!=="bash"&&e.toolName!=="powershell")return null;let t=String(e.input.command||"").toLowerCase(),n=[{pattern:/\bsudo\b/,reason:"Using sudo"},{pattern:/\bchmod\s+(?:777|\+x)/,reason:"Permissive chmod"},{pattern:/\brm\s+-rf\s+\/(?!\w)/,reason:"Recursive root delete"},{pattern:/\bcurl\b.*\|\s*(?:bash|sh|sudo)/i,reason:"Curl pipe to shell"},{pattern:/\beval\b/,reason:"Using eval"},{pattern:/\bsetuid\b|\bsetgid\b/,reason:"Setuid/setgid"},{pattern:/\b(?:passwd|usermod|useradd|userdel|groupadd|groupmod|groupdel)\b/,reason:"User management"},{pattern:/\b(?:systemctl|service)\s+(?:stop|disable|mask)/,reason:"Service disruption"},{pattern:/\biptables\b|\bufw\s+(?:disable|allow|reject)/,reason:"Firewall change"}];for(let{pattern:r,reason:s}of n)if(r.test(t))return{id:dr("md5").update(`ESCALATE:${t.slice(0,50)}`).digest("hex").slice(0,12),type:"privilege_escalation",severity:"critical",confidence:.9,description:`Privilege escalation: ${s}`,evidence:[t.slice(0,200)],timestamp:Date.now(),recommendedAction:"pause"};return null}function Sle(e){if(e.length<ft.recursionLoopThreshold)return null;let n=e.slice(-ft.recursionLoopThreshold).map(i=>`${i.toolName}:${JSON.stringify(i.input)}`),r=new Map;for(let i of n)r.set(i,(r.get(i)||0)+1);let s=Math.max(...r.values());if(s>=ft.recursionLoopThreshold){let i=[...r.entries()].find(([o,a])=>a===s)?.[0];return{id:dr("md5").update(`LOOP:${i}`).digest("hex").slice(0,12),type:"recursion_loop",severity:"high",confidence:.95,description:`Stuck in loop: same call repeated ${s}\xD7 consecutively`,evidence:[i||""],timestamp:Date.now(),recommendedAction:"pause"}}return null}function wle(e,t){if(t.length<8)return null;let n=t.slice(-ft.recentActionsWindow),r=n.map(o=>`${o.toolName} ${JSON.stringify(o.input)}`).join(" "),s=Am(r),i=AA(e.embedding,s);return i<.1?{id:dr("md5").update(`ABANDON:${Date.now()}`).digest("hex").slice(0,12),type:"goal_abandonment",severity:"high",confidence:1-i,description:`No semantic progress toward goal in last ${n.length} actions`,evidence:n.map(o=>o.toolName),timestamp:Date.now(),recommendedAction:"pause"}:null}function kle(e){if(!ft.enableReasoningValidation||!e.reasoning)return null;let t=e.reasoning.toLowerCase(),n=JSON.stringify(e.input).toLowerCase(),r=Am(t),s=Am(n);return AA(r,s)<.1?{id:dr("md5").update(`REASON:${e.timestamp}`).digest("hex").slice(0,12),type:"reasoning_inconsistency",severity:"medium",confidence:.7,description:"Stated reasoning doesn't match action",evidence:[`Reasoning: ${t.slice(0,100)}`,`Action: ${n.slice(0,100)}`],timestamp:Date.now(),recommendedAction:"warn"}:null}function xle(e,t){if(t.length<5)return null;let n=new Set;for(let r of t)r.input.path&&n.add(String(r.input.path));return e.scope.maxFiles&&n.size>e.scope.maxFiles*1.5?{id:dr("md5").update(`CREEP:${n.size}`).digest("hex").slice(0,12),type:"scope_creep",severity:"high",confidence:.85,description:`Scope creep: touched ${n.size} files (limit was ${e.scope.maxFiles})`,evidence:Array.from(n).slice(-5),timestamp:Date.now(),recommendedAction:"pause"}:!e.scope.maxFiles&&n.size>30&&e.intentType!=="refactor"?{id:dr("md5").update(`CREEP_AUTO:${n.size}`).digest("hex").slice(0,12),type:"scope_creep",severity:"medium",confidence:.7,description:`Touching many files (${n.size}) for "${e.intentType}" task`,evidence:Array.from(n).slice(-5),timestamp:Date.now(),recommendedAction:"warn"}:null}function $le(e){if(e.length<20)return null;let t=e.slice(-15);return new Set(t.map(r=>r.toolName)).size===1&&e.length>25?{id:dr("md5").update(`BURN:${t[0].toolName}`).digest("hex").slice(0,12),type:"token_burn",severity:"medium",confidence:.7,description:"15+ consecutive calls of same tool without progress",evidence:[t[0].toolName],timestamp:Date.now(),recommendedAction:"warn"}:null}function Cle(e){if(!ft.enabled||!L.currentIntent)return{aligned:!0,driftScore:0,signals:[],trustScore:1,recommendedAction:"monitor",reason:"No intent captured",intentSummary:"",recentActions:[]};if(L.toolCallHistory.push(e),L.toolCallCount++,e.input.path){let d=String(e.input.path);L.filesModified.includes(d)||L.filesModified.push(d)}let t=[],n=gle(e,L.currentIntent);n&&t.push(n);let r=hle(L.currentIntent,e);r?(t.push(r),L.consecutiveOffTopic++):L.consecutiveOffTopic=Math.max(0,L.consecutiveOffTopic-1);let s=yle(L.currentIntent,e,L.filesModified);s&&t.push(s);let i=ble(e);i&&t.push(i);let o=vle(e);o&&t.push(o);let a=Sle(L.toolCallHistory);a&&t.push(a);let c=kle(e);if(c&&t.push(c),L.toolCallHistory.length%5===0){let d=wle(L.currentIntent,L.toolCallHistory);d&&t.push(d);let f=xle(L.currentIntent,L.toolCallHistory);f&&t.push(f);let p=$le(L.toolCallHistory);p&&t.push(p)}for(let d of t)L.trustScore-=ft.trustDecayPerSignal*d.confidence*(d.severity==="critical"?2:d.severity==="high"?1.5:1);t.length===0&&(L.trustScore=Math.min(1,L.trustScore+ft.trustRecoveryPerAction)),L.trustScore=Math.max(0,L.trustScore);let l=t.reduce((d,f)=>{let p=f.severity==="critical"?1:f.severity==="high"?.7:f.severity==="medium"?.4:.2;return d+p*f.confidence},0)/Math.max(1,t.length),u="monitor";l>=ft.abortThreshold||t.some(d=>d.recommendedAction==="abort")?u="abort":l>=ft.pauseThreshold||t.some(d=>d.recommendedAction==="pause")?u="pause":l>=ft.warnThreshold||t.some(d=>d.recommendedAction==="warn")?u="warn":L.consecutiveOffTopic>=ft.maxConsecutiveOffTopic&&(u="pause"),u==="pause"&&ft.enableAutoPause&&(L.paused=!0,ur.totalPaused++),u==="abort"&&ft.enableAutoAbort&&(L.paused=!0,ur.totalAborted++),L.driftSignals.push(...t);for(let d of t)ur.bySignalType[d.type]=(ur.bySignalType[d.type]||0)+1,ur.totalDriftDetected++;return u!=="monitor"&&(ur.byInterventionLevel[u]=(ur.byInterventionLevel[u]||0)+1,ur.totalInterventions++),t.length>0&&ale({intent:L.currentIntent.rawText.slice(0,100),toolCall:{name:e.toolName,input:e.input},signals:t,driftScore:l,trustScore:L.trustScore,action:u}),t.length>0&&(Pc.emit("drift_detected",{signals:t,driftScore:l,action:u}),(u==="pause"||u==="abort")&&Pc.emit("intervention",{signals:t,action:u})),CA(),{aligned:t.length===0,driftScore:l,signals:t,trustScore:L.trustScore,recommendedAction:u,reason:t.map(d=>d.description).join("; ")||"No drift detected",intentSummary:L.currentIntent.rawText.slice(0,200),recentActions:L.toolCallHistory.slice(-ft.recentActionsWindow).map(d=>d.toolName)}}function Ale(){L.paused=!0,Pc.emit("paused")}function Tle(){L.paused=!1,Pc.emit("resumed")}function _le(){return L.paused}function Rle(){L={currentIntent:null,toolCallHistory:[],driftSignals:[],trustScore:ft.trustStartScore,paused:!1,consecutiveOffTopic:0,filesModified:[],toolCallCount:0,startedAt:Date.now()}}function Ple(){return L.currentIntent}function Ile(){return L.trustScore}function Mle(e=20){return L.driftSignals.slice(-e).reverse()}function Ele(){return[...L.toolCallHistory]}function Dle(){return JSON.parse(JSON.stringify(L))}function Fle(){return{...ft}}function Lle(e){ft={...ft,...e}}function Ole(){return{...ur}}function jle(){ur={totalSessionsTracked:0,totalDriftDetected:0,totalInterventions:0,bySignalType:{},byInterventionLevel:{},averageTrustAtCompletion:1,totalAborted:0,totalPaused:0},CA()}function Ble(){return Pc}function Nle(e=100){if(!Tj(SA))return[];try{return _j(SA,"utf-8").split(`
1164
+ `,{flag:"a"})}catch{}}}function Pj(e){return e.toLowerCase().replace(/[^\w\s'-]/g," ").split(/\s+/).filter(t=>t.length>2&&!cle.has(t))}function Am(e){let t=Pj(e),n=new Map;for(let i of t)n.set(i,(n.get(i)||0)+1);let r=Math.max(...n.values(),1),s=new Map;for(let[i,o]of n)s.set(i,o/r);return s}function AA(e,t){let n=0,r=0,s=0;for(let i of e.values())r+=i*i;for(let i of t.values())s+=i*i;for(let[i,o]of e){let a=t.get(i);a&&(n+=o*a)}return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function lle(e){let t=e.toLowerCase();return/\b(refactor|rewrite|reorganize|restructure|clean\s*up)\b/.test(t)?"refactor":/\b(fix|bug|broken|error|failing)\b/.test(t)?"fix_bug":/\b(add|implement|create|build|new\s+feature)\b/.test(t)?"add_feature":/\b(analyze|review|investigate|inspect|audit|examine)\b/.test(t)?"analyze":/\b(document|docs|readme|comment)\b/.test(t)?"document":/\b(test|spec|coverage)\b/.test(t)?"test":/\b(deploy|release|ship|publish)\b/.test(t)?"deploy":/\b(config|configure|setup|env)\b/.test(t)?"configure":/\b(research|find|search|explore)\b/.test(t)?"research":"unknown"}function ule(e){let t={},n=e.match(/(?:^|\s)(?:[\w./\\-]+\.\w{2,4})/g);n&&(t.targetFiles=[...new Set(n.map(o=>o.trim()))].slice(0,20));let r=e.match(/\b(?:in|under|within)\s+([\w./\\-]+\/[\w./\\-]*)/gi);r&&(t.targetDirs=r.map(o=>o.replace(/^\b(?:in|under|within)\s+/i,"").trim()));let s=[...e.match(/\bdo(?:n'?t|\s+not)\s+(?:touch|modify|delete|remove)\s+([\w./\\-]+)/gi)||[],...e.match(/\bnever\s+(?:touch|modify|delete|remove)\s+([\w./\\-]+)/gi)||[]];s.length>0&&(t.forbidden=s.map(o=>o.replace(/^\b(?:do(?:n'?t|\s+not)|never)\s+(?:touch|modify|delete|remove)\s+/i,"").trim()));let i=e.match(/\b(?:only|just)\s+(\d+)\s+files?\b/i);return i&&(t.maxFiles=parseInt(i[1],10)),t}function dle(e){let t={rawText:e,intentType:lle(e),scope:ule(e),keywords:Pj(e).slice(0,20),embedding:Am(e),capturedAt:Date.now()};return O={currentIntent:t,toolCallHistory:[],driftSignals:[],trustScore:ft.trustStartScore,paused:!1,consecutiveOffTopic:0,filesModified:[],toolCallCount:0,startedAt:Date.now()},ur.totalSessionsTracked++,CA(),Pc.emit("intent_captured",t),t}function ple(e){return fle[e]||"unknown"}function gle(e,t){let n=`${e.toolName} ${JSON.stringify(e.input).slice(0,500)}`,r=Am(n),s=AA(t.embedding,r);return s<ft.semanticSimilarityFloor?{id:dr("md5").update(`SEM:${e.toolName}:${e.timestamp}`).digest("hex").slice(0,12),type:"semantic_divergence",severity:s<.05?"high":"medium",confidence:1-s,description:`Tool call semantically unrelated to goal (similarity: ${(s*100).toFixed(0)}%)`,evidence:[`${e.toolName}(${JSON.stringify(e.input).slice(0,100)})`],timestamp:Date.now(),recommendedAction:s<.05?"pause":"warn"}:null}function hle(e,t){let n=ple(t.toolName),r=mle[e.intentType]||[];return r.length>0&&!r.includes(n)&&n!=="unknown"?{id:dr("md5").update(`OT:${t.toolName}:${t.timestamp}`).digest("hex").slice(0,12),type:"off_topic_tools",severity:n==="shell"||n==="network"?"high":"medium",confidence:.75,description:`Tool category "${n}" unexpected for intent "${e.intentType}"`,evidence:[`Used ${t.toolName} (category: ${n}). Expected categories: ${r.join(", ")}`],timestamp:Date.now(),recommendedAction:n==="sensitive"?"pause":"warn"}:null}function yle(e,t,n){if(t.toolName!=="file_write"&&t.toolName!=="file_edit")return null;let r=String(t.input.path||"");if(!r)return null;let s=e.scope;if(s.targetFiles&&s.targetFiles.length>0&&!s.targetFiles.some(o=>r.includes(o)||o.includes(r)))return{id:dr("md5").update(`UW:${r}`).digest("hex").slice(0,12),type:"unexpected_writes",severity:"high",confidence:.85,description:`Writing to "${r}" not in declared scope`,evidence:[`Scope: ${s.targetFiles.join(", ")}`,`Writing: ${r}`],timestamp:Date.now(),recommendedAction:"pause"};if(s.forbidden){for(let i of s.forbidden)if(r.includes(i))return{id:dr("md5").update(`FORBIDDEN:${r}`).digest("hex").slice(0,12),type:"unexpected_writes",severity:"critical",confidence:.95,description:`Writing to FORBIDDEN path "${r}"`,evidence:[`Forbidden pattern: ${i}`,`Attempted: ${r}`],timestamp:Date.now(),recommendedAction:"abort"}}return n.length>ft.unexpectedWriteCap?{id:dr("md5").update(`MASS_WRITE:${n.length}`).digest("hex").slice(0,12),type:"unexpected_writes",severity:"high",confidence:.85,description:`Modifying many files (${n.length} > ${ft.unexpectedWriteCap} cap)`,evidence:n.slice(-5),timestamp:Date.now(),recommendedAction:"pause"}:null}function ble(e){if(e.toolName!=="web_fetch"&&e.toolName!=="bash"&&e.toolName!=="powershell")return null;let t=JSON.stringify(e.input).toLowerCase(),n=(e.reasoning||"").toLowerCase(),r=t+" "+n,s=[/\b(?:curl|wget|fetch|post|send)\s+.*(?:secret|token|key|password|env)/i,/https?:\/\/[a-z0-9-]+\.(?:duckdns|requestbin|webhook|ngrok|pipedream|httpbin)/i,/-d\s+(?:["']?@?)[\w./-]*(?:secret|token|key|env)/i,/env\s*\|\s*(?:curl|nc|wget)/i];for(let i of s)if(i.test(r))return{id:dr("md5").update(`EXFIL:${e.timestamp}`).digest("hex").slice(0,12),type:"data_exfiltration",severity:"critical",confidence:.92,description:"Suspected data exfiltration attempt",evidence:[`Pattern: ${i.source}`,JSON.stringify(e.input).slice(0,200)],timestamp:Date.now(),recommendedAction:"abort"};if(e.toolName==="web_fetch"){let i=String(e.input.url||"");if(i&&!/(?:github\.com|gitlab\.com|npmjs\.com|pypi\.org|stackoverflow|mdn|developer\.mozilla|api\.openai|api\.anthropic)/.test(i))return{id:dr("md5").update(`UNKNOWN_URL:${i}`).digest("hex").slice(0,12),type:"data_exfiltration",severity:"medium",confidence:.6,description:"Fetching from unknown external domain",evidence:[i],timestamp:Date.now(),recommendedAction:"warn"}}return null}function vle(e){if(e.toolName!=="bash"&&e.toolName!=="powershell")return null;let t=String(e.input.command||"").toLowerCase(),n=[{pattern:/\bsudo\b/,reason:"Using sudo"},{pattern:/\bchmod\s+(?:777|\+x)/,reason:"Permissive chmod"},{pattern:/\brm\s+-rf\s+\/(?!\w)/,reason:"Recursive root delete"},{pattern:/\bcurl\b.*\|\s*(?:bash|sh|sudo)/i,reason:"Curl pipe to shell"},{pattern:/\beval\b/,reason:"Using eval"},{pattern:/\bsetuid\b|\bsetgid\b/,reason:"Setuid/setgid"},{pattern:/\b(?:passwd|usermod|useradd|userdel|groupadd|groupmod|groupdel)\b/,reason:"User management"},{pattern:/\b(?:systemctl|service)\s+(?:stop|disable|mask)/,reason:"Service disruption"},{pattern:/\biptables\b|\bufw\s+(?:disable|allow|reject)/,reason:"Firewall change"}];for(let{pattern:r,reason:s}of n)if(r.test(t))return{id:dr("md5").update(`ESCALATE:${t.slice(0,50)}`).digest("hex").slice(0,12),type:"privilege_escalation",severity:"critical",confidence:.9,description:`Privilege escalation: ${s}`,evidence:[t.slice(0,200)],timestamp:Date.now(),recommendedAction:"pause"};return null}function Sle(e){if(e.length<ft.recursionLoopThreshold)return null;let n=e.slice(-ft.recursionLoopThreshold).map(i=>`${i.toolName}:${JSON.stringify(i.input)}`),r=new Map;for(let i of n)r.set(i,(r.get(i)||0)+1);let s=Math.max(...r.values());if(s>=ft.recursionLoopThreshold){let i=[...r.entries()].find(([o,a])=>a===s)?.[0];return{id:dr("md5").update(`LOOP:${i}`).digest("hex").slice(0,12),type:"recursion_loop",severity:"high",confidence:.95,description:`Stuck in loop: same call repeated ${s}\xD7 consecutively`,evidence:[i||""],timestamp:Date.now(),recommendedAction:"pause"}}return null}function wle(e,t){if(t.length<8)return null;let n=t.slice(-ft.recentActionsWindow),r=n.map(o=>`${o.toolName} ${JSON.stringify(o.input)}`).join(" "),s=Am(r),i=AA(e.embedding,s);return i<.1?{id:dr("md5").update(`ABANDON:${Date.now()}`).digest("hex").slice(0,12),type:"goal_abandonment",severity:"high",confidence:1-i,description:`No semantic progress toward goal in last ${n.length} actions`,evidence:n.map(o=>o.toolName),timestamp:Date.now(),recommendedAction:"pause"}:null}function kle(e){if(!ft.enableReasoningValidation||!e.reasoning)return null;let t=e.reasoning.toLowerCase(),n=JSON.stringify(e.input).toLowerCase(),r=Am(t),s=Am(n);return AA(r,s)<.1?{id:dr("md5").update(`REASON:${e.timestamp}`).digest("hex").slice(0,12),type:"reasoning_inconsistency",severity:"medium",confidence:.7,description:"Stated reasoning doesn't match action",evidence:[`Reasoning: ${t.slice(0,100)}`,`Action: ${n.slice(0,100)}`],timestamp:Date.now(),recommendedAction:"warn"}:null}function xle(e,t){if(t.length<5)return null;let n=new Set;for(let r of t)r.input.path&&n.add(String(r.input.path));return e.scope.maxFiles&&n.size>e.scope.maxFiles*1.5?{id:dr("md5").update(`CREEP:${n.size}`).digest("hex").slice(0,12),type:"scope_creep",severity:"high",confidence:.85,description:`Scope creep: touched ${n.size} files (limit was ${e.scope.maxFiles})`,evidence:Array.from(n).slice(-5),timestamp:Date.now(),recommendedAction:"pause"}:!e.scope.maxFiles&&n.size>30&&e.intentType!=="refactor"?{id:dr("md5").update(`CREEP_AUTO:${n.size}`).digest("hex").slice(0,12),type:"scope_creep",severity:"medium",confidence:.7,description:`Touching many files (${n.size}) for "${e.intentType}" task`,evidence:Array.from(n).slice(-5),timestamp:Date.now(),recommendedAction:"warn"}:null}function $le(e){if(e.length<20)return null;let t=e.slice(-15);return new Set(t.map(r=>r.toolName)).size===1&&e.length>25?{id:dr("md5").update(`BURN:${t[0].toolName}`).digest("hex").slice(0,12),type:"token_burn",severity:"medium",confidence:.7,description:"15+ consecutive calls of same tool without progress",evidence:[t[0].toolName],timestamp:Date.now(),recommendedAction:"warn"}:null}function Cle(e){if(!ft.enabled||!O.currentIntent)return{aligned:!0,driftScore:0,signals:[],trustScore:1,recommendedAction:"monitor",reason:"No intent captured",intentSummary:"",recentActions:[]};if(O.toolCallHistory.push(e),O.toolCallCount++,e.input.path){let d=String(e.input.path);O.filesModified.includes(d)||O.filesModified.push(d)}let t=[],n=gle(e,O.currentIntent);n&&t.push(n);let r=hle(O.currentIntent,e);r?(t.push(r),O.consecutiveOffTopic++):O.consecutiveOffTopic=Math.max(0,O.consecutiveOffTopic-1);let s=yle(O.currentIntent,e,O.filesModified);s&&t.push(s);let i=ble(e);i&&t.push(i);let o=vle(e);o&&t.push(o);let a=Sle(O.toolCallHistory);a&&t.push(a);let c=kle(e);if(c&&t.push(c),O.toolCallHistory.length%5===0){let d=wle(O.currentIntent,O.toolCallHistory);d&&t.push(d);let f=xle(O.currentIntent,O.toolCallHistory);f&&t.push(f);let p=$le(O.toolCallHistory);p&&t.push(p)}for(let d of t)O.trustScore-=ft.trustDecayPerSignal*d.confidence*(d.severity==="critical"?2:d.severity==="high"?1.5:1);t.length===0&&(O.trustScore=Math.min(1,O.trustScore+ft.trustRecoveryPerAction)),O.trustScore=Math.max(0,O.trustScore);let l=t.reduce((d,f)=>{let p=f.severity==="critical"?1:f.severity==="high"?.7:f.severity==="medium"?.4:.2;return d+p*f.confidence},0)/Math.max(1,t.length),u="monitor";l>=ft.abortThreshold||t.some(d=>d.recommendedAction==="abort")?u="abort":l>=ft.pauseThreshold||t.some(d=>d.recommendedAction==="pause")?u="pause":l>=ft.warnThreshold||t.some(d=>d.recommendedAction==="warn")?u="warn":O.consecutiveOffTopic>=ft.maxConsecutiveOffTopic&&(u="pause"),u==="pause"&&ft.enableAutoPause&&(O.paused=!0,ur.totalPaused++),u==="abort"&&ft.enableAutoAbort&&(O.paused=!0,ur.totalAborted++),O.driftSignals.push(...t);for(let d of t)ur.bySignalType[d.type]=(ur.bySignalType[d.type]||0)+1,ur.totalDriftDetected++;return u!=="monitor"&&(ur.byInterventionLevel[u]=(ur.byInterventionLevel[u]||0)+1,ur.totalInterventions++),t.length>0&&ale({intent:O.currentIntent.rawText.slice(0,100),toolCall:{name:e.toolName,input:e.input},signals:t,driftScore:l,trustScore:O.trustScore,action:u}),t.length>0&&(Pc.emit("drift_detected",{signals:t,driftScore:l,action:u}),(u==="pause"||u==="abort")&&Pc.emit("intervention",{signals:t,action:u})),CA(),{aligned:t.length===0,driftScore:l,signals:t,trustScore:O.trustScore,recommendedAction:u,reason:t.map(d=>d.description).join("; ")||"No drift detected",intentSummary:O.currentIntent.rawText.slice(0,200),recentActions:O.toolCallHistory.slice(-ft.recentActionsWindow).map(d=>d.toolName)}}function Ale(){O.paused=!0,Pc.emit("paused")}function Tle(){O.paused=!1,Pc.emit("resumed")}function _le(){return O.paused}function Rle(){O={currentIntent:null,toolCallHistory:[],driftSignals:[],trustScore:ft.trustStartScore,paused:!1,consecutiveOffTopic:0,filesModified:[],toolCallCount:0,startedAt:Date.now()}}function Ple(){return O.currentIntent}function Ile(){return O.trustScore}function Mle(e=20){return O.driftSignals.slice(-e).reverse()}function Ele(){return[...O.toolCallHistory]}function Dle(){return JSON.parse(JSON.stringify(O))}function Fle(){return{...ft}}function Lle(e){ft={...ft,...e}}function Ole(){return{...ur}}function jle(){ur={totalSessionsTracked:0,totalDriftDetected:0,totalInterventions:0,bySignalType:{},byInterventionLevel:{},averageTrustAtCompletion:1,totalAborted:0,totalPaused:0},CA()}function Ble(){return Pc}function Nle(e=100){if(!Tj(SA))return[];try{return _j(SA,"utf-8").split(`
1167
1165
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function qle(e){let t=[],n=e.recommendedAction==="abort"?"\u{1F6D1}":e.recommendedAction==="pause"?"\u23F8\uFE0F ":e.recommendedAction==="warn"?"\u26A0\uFE0F ":"\u2713";if(t.push(`${n} **Goal Drift Check**`),t.push(` Aligned: ${e.aligned}`),t.push(` Drift score: ${(e.driftScore*100).toFixed(0)}/100`),t.push(` Trust score: ${(e.trustScore*100).toFixed(0)}/100`),t.push(` Recommended action: ${e.recommendedAction.toUpperCase()}`),t.push(""),t.push(`Intent: ${e.intentSummary}`),t.push(`Recent actions: ${e.recentActions.slice(-5).join(", ")}`),t.push(""),e.signals.length>0){t.push(`## Drift Signals (${e.signals.length})`);for(let r of e.signals){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="high"?"\u26A0\uFE0F ":r.severity==="medium"?"\u26A1":"\u2139\uFE0F ";t.push(`${s} [${r.type}] (${(r.confidence*100).toFixed(0)}% confident) \u2192 ${r.recommendedAction.toUpperCase()}`),t.push(` ${r.description}`);for(let i of r.evidence.slice(0,3))t.push(` - ${i}`);t.push("")}}return t.join(`
1168
- `)}var ile,ft,xA,SA,wA,L,ur,Pc,cle,fle,mle,pd=w(()=>{"use strict";ile={enabled:!0,driftThreshold:.3,warnThreshold:.4,pauseThreshold:.6,abortThreshold:.85,recentActionsWindow:8,semanticSimilarityFloor:.15,maxConsecutiveOffTopic:4,recursionLoopThreshold:5,unexpectedWriteCap:10,trustStartScore:1,trustDecayPerSignal:.15,trustRecoveryPerAction:.05,enableAutoPause:!0,enableAutoAbort:!1,enableAuditLog:!0,enableReasoningValidation:!0},ft={...ile},xA=kA(rle(),".aiaca","drift-monitor"),SA=kA(xA,"audit.jsonl"),wA=kA(xA,"stats.json"),L={currentIntent:null,toolCallHistory:[],driftSignals:[],trustScore:1,paused:!1,consecutiveOffTopic:0,filesModified:[],toolCallCount:0,startedAt:Date.now()},ur={totalSessionsTracked:0,totalDriftDetected:0,totalInterventions:0,bySignalType:{},byInterventionLevel:{},averageTrustAtCompletion:1,totalAborted:0,totalPaused:0},Pc=new sle;Pc.setMaxListeners(50);ole();cle=new Set(["the","a","an","is","are","was","were","be","this","that","with","in","on","of","and","or","but","if","as","it","i","you","we","they","to","from","for","by"]);fle={file_read:"read",grep:"read",glob:"read",code_search:"read",code_references:"read",tool_search:"read",task_get:"read",task_list:"read",cron_list:"read",config_read:"read",image_read:"read",skill_search:"read",nl_search:"read",graph_stats:"read",impact_analysis:"read",file_write:"write",file_edit:"write",doc_create:"write",notebook_edit:"write",bash:"shell",powershell:"shell",web_fetch:"network",web_search:"network",agent:"agent",spawn_specialist:"agent",spawn_pipeline:"agent",vuln_scan:"analysis",analyze_code:"analysis",detect_smells:"analysis",generate_tests:"analysis",regression_guard:"analysis",ci_pipeline:"deploy",issue_tracker:"external",pr_autopilot:"external",sandbox_exec:"shell",secret_manager:"sensitive"};mle={refactor:["read","write","analysis"],fix_bug:["read","write","shell","analysis"],add_feature:["read","write","shell","analysis"],analyze:["read","analysis"],document:["read","write"],test:["read","write","shell","analysis"],deploy:["shell","network","deploy","external"],configure:["read","write","sensitive"],research:["read","network"],review:["read","analysis"],unknown:["read","write","shell","network","analysis"]}});var md={};$(md,{configure:()=>uue,createCheckpoint:()=>qj,exportLog:()=>aue,forensicReplay:()=>oue,formatEvent:()=>Sue,generateComplianceReport:()=>vue,getConfig:()=>lue,getEvents:()=>mue,getState:()=>pue,getStats:()=>due,listArchives:()=>gue,listCheckpoints:()=>sue,logEvent:()=>nue,manualCleanup:()=>bue,manualCompress:()=>yue,manualRotate:()=>hue,resetStats:()=>fue,search:()=>OA,startMaintenance:()=>Uj,stopMaintenance:()=>cue,verifyChain:()=>Nj,verifyCheckpoint:()=>iue});import{existsSync as Fi,mkdirSync as Ob,readFileSync as Jo,writeFileSync as Ec,readdirSync as _m,statSync as IA,renameSync as Ule,unlinkSync as MA,createReadStream as Hle,createWriteStream as zle}from"fs";import{join as Nn,basename as Gle}from"path";import{homedir as Vle,hostname as _A}from"os";import{createHash as Jle,createHmac as Wle,randomBytes as Rm,timingSafeEqual as Kle}from"crypto";import{createGzip as Yle}from"zlib";import{pipeline as Qle}from"stream/promises";import{EventEmitter as Zle}from"events";function Dc(){Ob(Wo,{recursive:!0}),Ob(gs,{recursive:!0}),Ob(Tm,{recursive:!0}),Ob(Mj,{recursive:!0})}function Ej(){if(Dc(),pe.signingKey)return pe.signingKey;if(Fi(TA))try{let t=Jo(TA,"utf-8").trim();if(t.length>=64)return pe.signingKey=t,t}catch{}let e=Rm(32).toString("hex");try{Ec(TA,e,{encoding:"utf-8",mode:384})}catch{}return pe.signingKey=e,e}function eue(){if(Dc(),Ej(),Fi(RA))try{X={...X,...JSON.parse(Jo(RA,"utf-8"))}}catch{}if(Fi(PA))try{je={...je,...JSON.parse(Jo(PA,"utf-8"))}}catch{}X.currentLogFile||DA()}function EA(){Dc();try{Ec(RA,JSON.stringify(X,null,2),"utf-8")}catch{}}function Fc(){Dc();try{Ec(PA,JSON.stringify(je,null,2),"utf-8")}catch{}}function DA(){let e=new Date().toISOString().slice(0,10),t=Rm(2).toString("hex"),n=`trail-${e}-${t}.jsonl`;X.currentLogFile=Nn(Wo,n),X.currentLogStartedAt=Date.now(),X.currentLogSize=0,EA()}function jb(e){return Jle(pe.hashAlgorithm).update(e,"utf-8").digest("hex")}function FA(e){let t=Ej();return Wle("sha256",Buffer.from(t,"hex")).update(e).digest("hex")}function Dj(e,t){let n=FA(e);if(n.length!==t.length)return!1;try{return Kle(Buffer.from(n,"hex"),Buffer.from(t,"hex"))}catch{return!1}}function Fj(e){return[e.sequenceNumber,e.id,e.previousHash,e.contentHash,e.timestamp,e.category,e.severity,e.actor||""].join("|")}function Lj(e){if(e.length===0)return"";if(e.length===1)return e[0];let t=[];for(let n=0;n<e.length;n+=2){let r=e[n],s=e[n+1]||r;t.push(jb(r+s))}return Lj(t)}function Oj(){return Date.now()-X.currentLogStartedAt>pe.rotationIntervalMs||X.currentLogSize>pe.rotationSizeBytes}async function LA(){if(X.currentLogFile&&Fi(X.currentLogFile)){let e=Nn(gs,Gle(X.currentLogFile));try{Ule(X.currentLogFile,e)}catch{try{Ec(e,Jo(X.currentLogFile)),MA(X.currentLogFile)}catch{}}}DA(),je.totalRotations++,Fc(),Di.emit("rotated",{archived:X.currentLogFile})}async function jj(){if(!pe.compressOldLogs)return{compressed:0};let e=0,t=Date.now()-pe.compressAfterMs;try{for(let n of _m(gs)){if(!n.endsWith(".jsonl"))continue;let r=Nn(gs,n);if(IA(r).mtimeMs>t)continue;let i=r+".gz";try{await Qle(Hle(r),Yle(),zle(i)),MA(r),e++}catch{}}}catch{}return e>0&&(je.totalCompressions+=e,Fc()),{compressed:e}}function Bj(){let e=pe.customRetentionMs??Ij[pe.retentionPolicy];if(e===0)return{deleted:0};let t=Date.now()-e,n=0;try{for(let r of _m(gs)){let s=Nn(gs,r);if(IA(s).mtimeMs<t)try{MA(s),n++}catch{}}}catch{}return{deleted:n}}function tue(e){if(!pe.enableAnomalyDetection)return{isAnomaly:!1,reasons:[]};let t=Date.now();Ic.recentEvents.push({timestamp:t,category:e}),Ic.recentEvents=Ic.recentEvents.filter(i=>t-i.timestamp<6e4);let n=[];Ic.recentEvents.length>pe.burstThreshold&&n.push(`Event burst: ${Ic.recentEvents.length}/min`);let r=Ic.recentEvents.filter(i=>i.category==="permission_deny").length;r>20&&n.push(`${r} permission denials in last minute`);let s=Ic.recentEvents.filter(i=>i.category==="security_event").length;return s>5&&n.push(`${s} security events in last minute`),n.length>0?(je.totalAnomalies++,Di.emit("anomaly_detected",{category:e,reasons:n}),{isAnomaly:!0,reasons:n}):{isAnomaly:!1,reasons:[]}}function nue(e){if(!pe.enabled)return{sequenceNumber:0,id:"",previousHash:"",contentHash:"",signature:"",timestamp:Date.now(),category:e.category,severity:e.severity||"info",actor:e.actor||"system",description:e.description,hostMachine:_A()};let t=Date.now(),n=Rm(8).toString("hex"),r=++X.sequenceNumber,s=X.lastEntryHash,i=JSON.stringify({category:e.category,severity:e.severity,actor:e.actor,resource:e.resource,action:e.action,description:e.description,timestamp:t}),o=jb(i),a=tue(e.category);Oj()&&LA().catch(()=>{});let c={sequenceNumber:r,id:n,previousHash:s,contentHash:o,signature:"",category:e.category,severity:e.severity||"info",timestamp:t,actor:e.actor||"system",agentId:e.agentId,sessionId:e.sessionId,resource:e.resource,action:e.action,description:e.description,metadata:e.metadata,riskScore:e.riskScore||(a.isAnomaly?.7:0),result:e.result,hostMachine:_A(),callerStack:rue()};c.signature=FA(Fj(c));let l=jb(JSON.stringify(c));Dc(),X.currentLogFile||DA();let u=JSON.stringify(c)+`
1169
- `;try{Ec(X.currentLogFile,u,{flag:"a"}),X.currentLogSize+=u.length,X.lastEntryHash=l,X.totalEntries++,EA()}catch{}return je.totalEvents++,je.byCategory[e.category]=(je.byCategory[e.category]||0)+1,je.bySeverity[c.severity]=(je.bySeverity[c.severity]||0)+1,Fc(),pe.enableMerkleCheckpoints&&r-X.lastCheckpointSequence>=pe.checkpointEvery&&qj().catch(()=>{}),pe.enableEventStreaming&&(Di.emit("event",c),(c.severity==="critical"||c.severity==="high")&&Di.emit("high_severity_event",c),a.isAnomaly&&Di.emit("anomaly_event",{entry:c,reasons:a.reasons})),c}function rue(){let e=new Error;return e.stack?e.stack.split(`
1166
+ `)}var ile,ft,xA,SA,wA,O,ur,Pc,cle,fle,mle,pd=w(()=>{"use strict";ile={enabled:!0,driftThreshold:.3,warnThreshold:.4,pauseThreshold:.6,abortThreshold:.85,recentActionsWindow:8,semanticSimilarityFloor:.15,maxConsecutiveOffTopic:4,recursionLoopThreshold:5,unexpectedWriteCap:10,trustStartScore:1,trustDecayPerSignal:.15,trustRecoveryPerAction:.05,enableAutoPause:!0,enableAutoAbort:!1,enableAuditLog:!0,enableReasoningValidation:!0},ft={...ile},xA=kA(rle(),".aiaca","drift-monitor"),SA=kA(xA,"audit.jsonl"),wA=kA(xA,"stats.json"),O={currentIntent:null,toolCallHistory:[],driftSignals:[],trustScore:1,paused:!1,consecutiveOffTopic:0,filesModified:[],toolCallCount:0,startedAt:Date.now()},ur={totalSessionsTracked:0,totalDriftDetected:0,totalInterventions:0,bySignalType:{},byInterventionLevel:{},averageTrustAtCompletion:1,totalAborted:0,totalPaused:0},Pc=new sle;Pc.setMaxListeners(50);ole();cle=new Set(["the","a","an","is","are","was","were","be","this","that","with","in","on","of","and","or","but","if","as","it","i","you","we","they","to","from","for","by"]);fle={file_read:"read",grep:"read",glob:"read",code_search:"read",code_references:"read",tool_search:"read",task_get:"read",task_list:"read",cron_list:"read",config_read:"read",image_read:"read",skill_search:"read",nl_search:"read",graph_stats:"read",impact_analysis:"read",file_write:"write",file_edit:"write",doc_create:"write",notebook_edit:"write",bash:"shell",powershell:"shell",web_fetch:"network",web_search:"network",agent:"agent",spawn_specialist:"agent",spawn_pipeline:"agent",vuln_scan:"analysis",analyze_code:"analysis",detect_smells:"analysis",generate_tests:"analysis",regression_guard:"analysis",ci_pipeline:"deploy",issue_tracker:"external",pr_autopilot:"external",sandbox_exec:"shell",secret_manager:"sensitive"};mle={refactor:["read","write","analysis"],fix_bug:["read","write","shell","analysis"],add_feature:["read","write","shell","analysis"],analyze:["read","analysis"],document:["read","write"],test:["read","write","shell","analysis"],deploy:["shell","network","deploy","external"],configure:["read","write","sensitive"],research:["read","network"],review:["read","analysis"],unknown:["read","write","shell","network","analysis"]}});var md={};$(md,{configure:()=>uue,createCheckpoint:()=>qj,exportLog:()=>aue,forensicReplay:()=>oue,formatEvent:()=>Sue,generateComplianceReport:()=>vue,getConfig:()=>lue,getEvents:()=>mue,getState:()=>pue,getStats:()=>due,listArchives:()=>gue,listCheckpoints:()=>sue,logEvent:()=>nue,manualCleanup:()=>bue,manualCompress:()=>yue,manualRotate:()=>hue,resetStats:()=>fue,search:()=>OA,startMaintenance:()=>Uj,stopMaintenance:()=>cue,verifyChain:()=>Nj,verifyCheckpoint:()=>iue});import{existsSync as Fi,mkdirSync as Ob,readFileSync as Jo,writeFileSync as Ec,readdirSync as _m,statSync as IA,renameSync as Ule,unlinkSync as MA,createReadStream as Hle,createWriteStream as zle}from"fs";import{join as Nn,basename as Gle}from"path";import{homedir as Vle,hostname as _A}from"os";import{createHash as Jle,createHmac as Wle,randomBytes as Rm,timingSafeEqual as Kle}from"crypto";import{createGzip as Yle}from"zlib";import{pipeline as Qle}from"stream/promises";import{EventEmitter as Zle}from"events";function Dc(){Ob(Wo,{recursive:!0}),Ob(gs,{recursive:!0}),Ob(Tm,{recursive:!0}),Ob(Mj,{recursive:!0})}function Ej(){if(Dc(),me.signingKey)return me.signingKey;if(Fi(TA))try{let t=Jo(TA,"utf-8").trim();if(t.length>=64)return me.signingKey=t,t}catch{}let e=Rm(32).toString("hex");try{Ec(TA,e,{encoding:"utf-8",mode:384})}catch{}return me.signingKey=e,e}function eue(){if(Dc(),Ej(),Fi(RA))try{X={...X,...JSON.parse(Jo(RA,"utf-8"))}}catch{}if(Fi(PA))try{je={...je,...JSON.parse(Jo(PA,"utf-8"))}}catch{}X.currentLogFile||DA()}function EA(){Dc();try{Ec(RA,JSON.stringify(X,null,2),"utf-8")}catch{}}function Fc(){Dc();try{Ec(PA,JSON.stringify(je,null,2),"utf-8")}catch{}}function DA(){let e=new Date().toISOString().slice(0,10),t=Rm(2).toString("hex"),n=`trail-${e}-${t}.jsonl`;X.currentLogFile=Nn(Wo,n),X.currentLogStartedAt=Date.now(),X.currentLogSize=0,EA()}function jb(e){return Jle(me.hashAlgorithm).update(e,"utf-8").digest("hex")}function FA(e){let t=Ej();return Wle("sha256",Buffer.from(t,"hex")).update(e).digest("hex")}function Dj(e,t){let n=FA(e);if(n.length!==t.length)return!1;try{return Kle(Buffer.from(n,"hex"),Buffer.from(t,"hex"))}catch{return!1}}function Fj(e){return[e.sequenceNumber,e.id,e.previousHash,e.contentHash,e.timestamp,e.category,e.severity,e.actor||""].join("|")}function Lj(e){if(e.length===0)return"";if(e.length===1)return e[0];let t=[];for(let n=0;n<e.length;n+=2){let r=e[n],s=e[n+1]||r;t.push(jb(r+s))}return Lj(t)}function Oj(){return Date.now()-X.currentLogStartedAt>me.rotationIntervalMs||X.currentLogSize>me.rotationSizeBytes}async function LA(){if(X.currentLogFile&&Fi(X.currentLogFile)){let e=Nn(gs,Gle(X.currentLogFile));try{Ule(X.currentLogFile,e)}catch{try{Ec(e,Jo(X.currentLogFile)),MA(X.currentLogFile)}catch{}}}DA(),je.totalRotations++,Fc(),Di.emit("rotated",{archived:X.currentLogFile})}async function jj(){if(!me.compressOldLogs)return{compressed:0};let e=0,t=Date.now()-me.compressAfterMs;try{for(let n of _m(gs)){if(!n.endsWith(".jsonl"))continue;let r=Nn(gs,n);if(IA(r).mtimeMs>t)continue;let i=r+".gz";try{await Qle(Hle(r),Yle(),zle(i)),MA(r),e++}catch{}}}catch{}return e>0&&(je.totalCompressions+=e,Fc()),{compressed:e}}function Bj(){let e=me.customRetentionMs??Ij[me.retentionPolicy];if(e===0)return{deleted:0};let t=Date.now()-e,n=0;try{for(let r of _m(gs)){let s=Nn(gs,r);if(IA(s).mtimeMs<t)try{MA(s),n++}catch{}}}catch{}return{deleted:n}}function tue(e){if(!me.enableAnomalyDetection)return{isAnomaly:!1,reasons:[]};let t=Date.now();Ic.recentEvents.push({timestamp:t,category:e}),Ic.recentEvents=Ic.recentEvents.filter(i=>t-i.timestamp<6e4);let n=[];Ic.recentEvents.length>me.burstThreshold&&n.push(`Event burst: ${Ic.recentEvents.length}/min`);let r=Ic.recentEvents.filter(i=>i.category==="permission_deny").length;r>20&&n.push(`${r} permission denials in last minute`);let s=Ic.recentEvents.filter(i=>i.category==="security_event").length;return s>5&&n.push(`${s} security events in last minute`),n.length>0?(je.totalAnomalies++,Di.emit("anomaly_detected",{category:e,reasons:n}),{isAnomaly:!0,reasons:n}):{isAnomaly:!1,reasons:[]}}function nue(e){if(!me.enabled)return{sequenceNumber:0,id:"",previousHash:"",contentHash:"",signature:"",timestamp:Date.now(),category:e.category,severity:e.severity||"info",actor:e.actor||"system",description:e.description,hostMachine:_A()};let t=Date.now(),n=Rm(8).toString("hex"),r=++X.sequenceNumber,s=X.lastEntryHash,i=JSON.stringify({category:e.category,severity:e.severity,actor:e.actor,resource:e.resource,action:e.action,description:e.description,timestamp:t}),o=jb(i),a=tue(e.category);Oj()&&LA().catch(()=>{});let c={sequenceNumber:r,id:n,previousHash:s,contentHash:o,signature:"",category:e.category,severity:e.severity||"info",timestamp:t,actor:e.actor||"system",agentId:e.agentId,sessionId:e.sessionId,resource:e.resource,action:e.action,description:e.description,metadata:e.metadata,riskScore:e.riskScore||(a.isAnomaly?.7:0),result:e.result,hostMachine:_A(),callerStack:rue()};c.signature=FA(Fj(c));let l=jb(JSON.stringify(c));Dc(),X.currentLogFile||DA();let u=JSON.stringify(c)+`
1167
+ `;try{Ec(X.currentLogFile,u,{flag:"a"}),X.currentLogSize+=u.length,X.lastEntryHash=l,X.totalEntries++,EA()}catch{}return je.totalEvents++,je.byCategory[e.category]=(je.byCategory[e.category]||0)+1,je.bySeverity[c.severity]=(je.bySeverity[c.severity]||0)+1,Fc(),me.enableMerkleCheckpoints&&r-X.lastCheckpointSequence>=me.checkpointEvery&&qj().catch(()=>{}),me.enableEventStreaming&&(Di.emit("event",c),(c.severity==="critical"||c.severity==="high")&&Di.emit("high_severity_event",c),a.isAnomaly&&Di.emit("anomaly_event",{entry:c,reasons:a.reasons})),c}function rue(){let e=new Error;return e.stack?e.stack.split(`
1170
1168
  `).slice(2,5).map(n=>n.trim()).join(" | ").slice(0,250):""}async function Nj(e){let t=Date.now(),n=e||X.currentLogFile;if(!n||!Fi(n))return{valid:!1,totalEntries:0,validEntries:0,brokenLinks:[],signatureFailures:0,durationMs:0};let r={valid:!0,totalEntries:0,validEntries:0,brokenLinks:[],signatureFailures:0,durationMs:0};try{let s=Jo(n,"utf-8").split(`
1171
1169
  `).filter(Boolean),i="",o=!1;for(let a of s){r.totalEntries++;try{let c=JSON.parse(a);o||(o=!0,i=c.previousHash),c.previousHash!==i&&(r.valid=!1,r.brokenLinks.push({sequenceNumber:c.sequenceNumber,reason:"Chain break: previousHash mismatch"})),Dj(Fj(c),c.signature)?r.validEntries++:(r.valid=!1,r.signatureFailures++),i=jb(a)}catch{r.valid=!1}}}catch{}return r.durationMs=Date.now()-t,je.totalVerifications++,r.valid||je.totalChainBreaks++,Fc(),r}async function qj(){if(X.sequenceNumber===0||!X.currentLogFile||!Fi(X.currentLogFile))return null;let e=[];try{e=Jo(X.currentLogFile,"utf-8").split(`
1172
- `).filter(Boolean).map(a=>JSON.parse(a)).slice(-pe.checkpointEvery)}catch{return null}if(e.length===0)return null;let t=e.map(a=>a.contentHash),n=Lj(t),r=Rm(8).toString("hex"),s=Date.now(),i={id:r,startSequence:e[0].sequenceNumber,endSequence:e[e.length-1].sequenceNumber,entryCount:e.length,merkleRoot:n,signature:FA(`${r}|${n}|${s}`),timestamp:s};Dc();let o=Nn(Tm,`cp-${r}.json`);try{Ec(o,JSON.stringify(i,null,2),"utf-8"),X.lastCheckpointSequence=i.endSequence,EA(),je.totalCheckpoints++,Fc(),Di.emit("checkpoint_created",{checkpoint:i})}catch{}return i}function sue(){if(!Fi(Tm))return[];let e=[];try{for(let t of _m(Tm))if(t.endsWith(".json"))try{e.push(JSON.parse(Jo(Nn(Tm,t),"utf-8")))}catch{}}catch{}return e.sort((t,n)=>n.timestamp-t.timestamp)}function iue(e){return Dj(`${e.id}|${e.merkleRoot}|${e.timestamp}`,e.signature)}function OA(e){let t=[],n=e.limit||100,r=[];if(X.currentLogFile&&Fi(X.currentLogFile)&&r.push(X.currentLogFile),e.searchArchives)try{for(let s of _m(gs))s.endsWith(".jsonl")&&r.push(Nn(gs,s))}catch{}for(let s of r){try{let i=Jo(s,"utf-8").split(`
1170
+ `).filter(Boolean).map(a=>JSON.parse(a)).slice(-me.checkpointEvery)}catch{return null}if(e.length===0)return null;let t=e.map(a=>a.contentHash),n=Lj(t),r=Rm(8).toString("hex"),s=Date.now(),i={id:r,startSequence:e[0].sequenceNumber,endSequence:e[e.length-1].sequenceNumber,entryCount:e.length,merkleRoot:n,signature:FA(`${r}|${n}|${s}`),timestamp:s};Dc();let o=Nn(Tm,`cp-${r}.json`);try{Ec(o,JSON.stringify(i,null,2),"utf-8"),X.lastCheckpointSequence=i.endSequence,EA(),je.totalCheckpoints++,Fc(),Di.emit("checkpoint_created",{checkpoint:i})}catch{}return i}function sue(){if(!Fi(Tm))return[];let e=[];try{for(let t of _m(Tm))if(t.endsWith(".json"))try{e.push(JSON.parse(Jo(Nn(Tm,t),"utf-8")))}catch{}}catch{}return e.sort((t,n)=>n.timestamp-t.timestamp)}function iue(e){return Dj(`${e.id}|${e.merkleRoot}|${e.timestamp}`,e.signature)}function OA(e){let t=[],n=e.limit||100,r=[];if(X.currentLogFile&&Fi(X.currentLogFile)&&r.push(X.currentLogFile),e.searchArchives)try{for(let s of _m(gs))s.endsWith(".jsonl")&&r.push(Nn(gs,s))}catch{}for(let s of r){try{let i=Jo(s,"utf-8").split(`
1173
1171
  `).filter(Boolean);for(let o of i){if(t.length>=n)break;try{let a=JSON.parse(o);if(e.category&&a.category!==e.category||e.severity&&a.severity!==e.severity||e.actor&&a.actor!==e.actor||e.agentId&&a.agentId!==e.agentId||e.sessionId&&a.sessionId!==e.sessionId||e.resource&&a.resource!==e.resource||e.startTime&&a.timestamp<e.startTime||e.endTime&&a.timestamp>e.endTime)continue;t.push(a)}catch{}}}catch{}if(t.length>=n)break}return t}async function oue(e){let t={totalEvents:0,bySource:{},byActor:{},bySeverity:{},uniqueResources:[],uniqueAgents:[],timeRange:{start:Number.MAX_SAFE_INTEGER,end:0},chainValid:!0},n=new Set,r=new Set,s=OA({startTime:e.startTime,endTime:e.endTime,searchArchives:!0,limit:5e5});for(let o of s)t.totalEvents++,t.bySource[o.category]=(t.bySource[o.category]||0)+1,t.byActor[o.actor]=(t.byActor[o.actor]||0)+1,t.bySeverity[o.severity]=(t.bySeverity[o.severity]||0)+1,o.resource&&n.add(o.resource),o.agentId&&r.add(o.agentId),o.timestamp<t.timeRange.start&&(t.timeRange.start=o.timestamp),o.timestamp>t.timeRange.end&&(t.timeRange.end=o.timestamp);t.uniqueResources=Array.from(n),t.uniqueAgents=Array.from(r);let i=await Nj();return t.chainValid=i.valid,t}async function aue(e,t={}){let n=OA({...t,searchArchives:!0,limit:1e5}),r=Rm(4).toString("hex"),s=`export-${new Date().toISOString().slice(0,10)}-${r}.${e}`,i=Nn(Mj,s),o="";switch(e){case"jsonl":case"ndjson":o=n.map(a=>JSON.stringify(a)).join(`
1174
1172
  `);break;case"csv":{let a=["sequenceNumber","id","timestamp","category","severity","actor","resource","action","description","result","contentHash"],c=n.map(l=>a.map(u=>{let d=l[u];return d===void 0?"":typeof d=="string"?`"${d.replace(/"/g,'""')}"`:String(d)}).join(","));o=[a.join(","),...c].join(`
1175
1173
  `);break}case"markdown":{let a=["# Audit Trail Export",`Generated: ${new Date().toISOString()}`,`Total events: ${n.length}`,""];a.push("| Seq | Time | Category | Severity | Actor | Resource | Description |"),a.push("|---|---|---|---|---|---|---|");for(let c of n){let l=c.description.replace(/[|\n\r]/g," ").slice(0,80);a.push(`| ${c.sequenceNumber} | ${new Date(c.timestamp).toISOString().slice(0,19)} | ${c.category} | ${c.severity} | ${c.actor} | ${(c.resource||"").slice(0,30)} | ${l} |`)}o=a.join(`
1176
- `);break}}return Dc(),Ec(i,o,"utf-8"),je.totalExports++,Fc(),Di.emit("exported",{filePath:i,entries:n.length,format:e}),{path:i,entries:n.length}}function Uj(){Mc||(Mc=setInterval(async()=>{try{Oj()&&await LA(),await jj(),Bj()}catch{}},3600*1e3),Mc.unref&&Mc.unref())}function cue(){Mc&&(clearInterval(Mc),Mc=null)}function lue(){return{...pe,signingKey:pe.signingKey?"[REDACTED]":""}}function uue(e){pe={...pe,...e}}function due(){return{...je}}function fue(){je={totalEvents:0,totalRotations:0,totalCompressions:0,totalCheckpoints:0,totalAnomalies:0,totalChainBreaks:0,totalVerifications:0,totalExports:0,byCategory:{},bySeverity:{}},Fc()}function pue(){return{...X}}function mue(){return Di}function gue(){if(!Fi(gs))return[];try{return _m(gs).map(e=>{let t=Nn(gs,e),n=IA(t);return{name:e,size:n.size,mtime:n.mtimeMs,compressed:e.endsWith(".gz")}}).sort((e,t)=>t.mtime-e.mtime)}catch{return[]}}async function hue(){await LA()}async function yue(){return await jj()}function bue(){return Bj()}function vue(){let e=[];e.push("# Immutable Audit Trail Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(`Host: ${_A()}`),e.push(""),e.push("## Summary"),e.push(`- Total events: ${je.totalEvents}`),e.push(`- Current sequence: ${X.sequenceNumber}`),e.push(`- Total rotations: ${je.totalRotations}`),e.push(`- Total compressions: ${je.totalCompressions}`),e.push(`- Total checkpoints: ${je.totalCheckpoints}`),e.push(`- \u26D3\uFE0F Chain breaks: ${je.totalChainBreaks}`),e.push(`- \u{1F50D} Anomalies: ${je.totalAnomalies}`),e.push(`- \u2713 Verifications: ${je.totalVerifications}`),e.push(`- \u{1F4E4} Exports: ${je.totalExports}`),e.push(""),e.push("## By Category");for(let[t,n]of Object.entries(je.byCategory).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);e.push(""),e.push("## By Severity");for(let[t,n]of Object.entries(je.bySeverity).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Append-only (no in-place edits)"),e.push(`- \u2713 ${pe.hashAlgorithm.toUpperCase()} hash chain`),e.push("- \u2713 HMAC-SHA256 signatures"),e.push("- \u2713 Monotonic sequence numbers"),e.push(`- ${pe.enableMerkleCheckpoints?"\u2713":"\u2717"} Merkle checkpoints (every ${pe.checkpointEvery})`),e.push(`- Retention policy: ${pe.retentionPolicy} (${(Ij[pe.retentionPolicy]/864e5).toFixed(0)} days)`),e.push(`- ${pe.compressOldLogs?"\u2713":"\u2717"} Compression`),e.push(`- ${pe.enableAnomalyDetection?"\u2713":"\u2717"} Anomaly detection`),e.push(`- ${pe.enableEventStreaming?"\u2713":"\u2717"} Real-time streaming`),e.push("- \u2713 Multi-format export (JSONL/CSV/Markdown/NDJSON)"),e.push("- \u2713 Forensic replay capability"),e.join(`
1174
+ `);break}}return Dc(),Ec(i,o,"utf-8"),je.totalExports++,Fc(),Di.emit("exported",{filePath:i,entries:n.length,format:e}),{path:i,entries:n.length}}function Uj(){Mc||(Mc=setInterval(async()=>{try{Oj()&&await LA(),await jj(),Bj()}catch{}},3600*1e3),Mc.unref&&Mc.unref())}function cue(){Mc&&(clearInterval(Mc),Mc=null)}function lue(){return{...me,signingKey:me.signingKey?"[REDACTED]":""}}function uue(e){me={...me,...e}}function due(){return{...je}}function fue(){je={totalEvents:0,totalRotations:0,totalCompressions:0,totalCheckpoints:0,totalAnomalies:0,totalChainBreaks:0,totalVerifications:0,totalExports:0,byCategory:{},bySeverity:{}},Fc()}function pue(){return{...X}}function mue(){return Di}function gue(){if(!Fi(gs))return[];try{return _m(gs).map(e=>{let t=Nn(gs,e),n=IA(t);return{name:e,size:n.size,mtime:n.mtimeMs,compressed:e.endsWith(".gz")}}).sort((e,t)=>t.mtime-e.mtime)}catch{return[]}}async function hue(){await LA()}async function yue(){return await jj()}function bue(){return Bj()}function vue(){let e=[];e.push("# Immutable Audit Trail Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(`Host: ${_A()}`),e.push(""),e.push("## Summary"),e.push(`- Total events: ${je.totalEvents}`),e.push(`- Current sequence: ${X.sequenceNumber}`),e.push(`- Total rotations: ${je.totalRotations}`),e.push(`- Total compressions: ${je.totalCompressions}`),e.push(`- Total checkpoints: ${je.totalCheckpoints}`),e.push(`- \u26D3\uFE0F Chain breaks: ${je.totalChainBreaks}`),e.push(`- \u{1F50D} Anomalies: ${je.totalAnomalies}`),e.push(`- \u2713 Verifications: ${je.totalVerifications}`),e.push(`- \u{1F4E4} Exports: ${je.totalExports}`),e.push(""),e.push("## By Category");for(let[t,n]of Object.entries(je.byCategory).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);e.push(""),e.push("## By Severity");for(let[t,n]of Object.entries(je.bySeverity).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Append-only (no in-place edits)"),e.push(`- \u2713 ${me.hashAlgorithm.toUpperCase()} hash chain`),e.push("- \u2713 HMAC-SHA256 signatures"),e.push("- \u2713 Monotonic sequence numbers"),e.push(`- ${me.enableMerkleCheckpoints?"\u2713":"\u2717"} Merkle checkpoints (every ${me.checkpointEvery})`),e.push(`- Retention policy: ${me.retentionPolicy} (${(Ij[me.retentionPolicy]/864e5).toFixed(0)} days)`),e.push(`- ${me.compressOldLogs?"\u2713":"\u2717"} Compression`),e.push(`- ${me.enableAnomalyDetection?"\u2713":"\u2717"} Anomaly detection`),e.push(`- ${me.enableEventStreaming?"\u2713":"\u2717"} Real-time streaming`),e.push("- \u2713 Multi-format export (JSONL/CSV/Markdown/NDJSON)"),e.push("- \u2713 Forensic replay capability"),e.join(`
1177
1175
  `)}function Sue(e){let t=e.severity==="critical"?"\u{1F6A8}":e.severity==="high"?"\u26A0\uFE0F ":e.severity==="medium"?"\u26A1":e.severity==="low"?"\u2139\uFE0F ":"\xB7",n={tool_call:"\u{1F527}",tool_result:"\u2713",file_create:"\u{1F4C4}",file_modify:"\u270F\uFE0F",file_delete:"\u{1F5D1}\uFE0F",model_decision:"\u{1F916}",permission_check:"\u{1F6E1}\uFE0F",permission_grant:"\u2705",permission_deny:"\u{1F6AB}",session_start:"\u{1F6AA}",session_end:"\u{1F44B}",config_change:"\u2699\uFE0F",security_event:"\u{1F510}",error:"\u274C",agent_action:"\u{1F3AF}",memory_op:"\u{1F9E0}",network_call:"\u{1F310}",auth_event:"\u{1F511}",compliance_event:"\u{1F4CB}"}[e.category]||"\u{1F4CC}",r=[];return r.push(`${t} ${n} #${e.sequenceNumber} [${e.category}]`),r.push(` ${e.description}`),e.actor&&r.push(` Actor: ${e.actor}`),e.resource&&r.push(` Resource: ${e.resource}`),e.action&&r.push(` Action: ${e.action}`),e.result&&r.push(` Result: ${e.result}`),r.push(` Time: ${new Date(e.timestamp).toISOString()}`),r.join(`
1178
- `)}var Ij,Xle,pe,Wo,TA,RA,gs,Tm,PA,Mj,Di,X,Ic,je,Mc,gd=w(()=>{"use strict";Ij={short:10080*60*1e3,standard:720*60*60*1e3,extended:2160*60*60*1e3,permanent:0,soc2:365*24*60*60*1e3,hipaa:6*365*24*60*60*1e3,gdpr:720*60*60*1e3},Xle={enabled:!0,signingKey:"",hashAlgorithm:"sha256",rotationIntervalMs:1440*60*1e3,rotationSizeBytes:100*1024*1024,compressOldLogs:!0,compressAfterMs:10080*60*1e3,retentionPolicy:"soc2",enableMerkleCheckpoints:!0,checkpointEvery:1e3,enableAnomalyDetection:!0,burstThreshold:500,enableEventStreaming:!0,enableDistributedSync:!1,minSeverityForSync:"medium"},pe={...Xle},Wo=Nn(Vle(),".aiaca","audit-trail"),TA=Nn(Wo,"master.key"),RA=Nn(Wo,"state.json"),gs=Nn(Wo,"archives"),Tm=Nn(Wo,"checkpoints"),PA=Nn(Wo,"stats.json"),Mj=Nn(Wo,"exports"),Di=new Zle;Di.setMaxListeners(200);X={sequenceNumber:0,lastEntryHash:"0".repeat(64),currentLogFile:"",currentLogStartedAt:0,currentLogSize:0,lastCheckpointSequence:0,totalEntries:0},Ic={recentEvents:[]},je={totalEvents:0,totalRotations:0,totalCompressions:0,totalCheckpoints:0,totalAnomalies:0,totalChainBreaks:0,totalVerifications:0,totalExports:0,byCategory:{},bySeverity:{}};eue();Mc=null;pe.enabled&&Uj()});var Dm={};$(Dm,{activate:()=>Bb,configure:()=>Oue,formatKillEvent:()=>Vue,generateComplianceReport:()=>Gue,getAuditLog:()=>zue,getConfig:()=>Lue,getEvents:()=>Nue,getHistory:()=>Hue,getState:()=>que,getStats:()=>jue,installAutoTriggers:()=>Vj,isActive:()=>Uue,listRecoveryCheckpoints:()=>Jj,recoverFromCheckpoint:()=>Eue,reset:()=>Fue,resetStats:()=>Bue});import{existsSync as yd,mkdirSync as Hj,readFileSync as Im,writeFileSync as Em}from"fs";import{join as Li}from"path";import{homedir as wue,hostname as kue}from"os";import{randomBytes as Gj}from"crypto";import{EventEmitter as xue}from"events";function vd(){Hj(bd,{recursive:!0}),Hj(hd,{recursive:!0})}function Cue(){if(vd(),yd(jA))try{G={...G,...JSON.parse(Im(jA,"utf-8"))}}catch{}if(yd(BA))try{$t={...$t,...JSON.parse(Im(BA,"utf-8"))}}catch{}}function Mm(){vd();try{Em(jA,JSON.stringify(G,null,2),"utf-8")}catch{}}function UA(){vd();try{Em(BA,JSON.stringify($t,null,2),"utf-8")}catch{}}function Oc(e){if(me.enableAuditLog){vd();try{Em(NA,JSON.stringify({...e,timestamp:Date.now()})+`
1176
+ `)}var Ij,Xle,me,Wo,TA,RA,gs,Tm,PA,Mj,Di,X,Ic,je,Mc,gd=w(()=>{"use strict";Ij={short:10080*60*1e3,standard:720*60*60*1e3,extended:2160*60*60*1e3,permanent:0,soc2:365*24*60*60*1e3,hipaa:6*365*24*60*60*1e3,gdpr:720*60*60*1e3},Xle={enabled:!0,signingKey:"",hashAlgorithm:"sha256",rotationIntervalMs:1440*60*1e3,rotationSizeBytes:100*1024*1024,compressOldLogs:!0,compressAfterMs:10080*60*1e3,retentionPolicy:"soc2",enableMerkleCheckpoints:!0,checkpointEvery:1e3,enableAnomalyDetection:!0,burstThreshold:500,enableEventStreaming:!0,enableDistributedSync:!1,minSeverityForSync:"medium"},me={...Xle},Wo=Nn(Vle(),".aiaca","audit-trail"),TA=Nn(Wo,"master.key"),RA=Nn(Wo,"state.json"),gs=Nn(Wo,"archives"),Tm=Nn(Wo,"checkpoints"),PA=Nn(Wo,"stats.json"),Mj=Nn(Wo,"exports"),Di=new Zle;Di.setMaxListeners(200);X={sequenceNumber:0,lastEntryHash:"0".repeat(64),currentLogFile:"",currentLogStartedAt:0,currentLogSize:0,lastCheckpointSequence:0,totalEntries:0},Ic={recentEvents:[]},je={totalEvents:0,totalRotations:0,totalCompressions:0,totalCheckpoints:0,totalAnomalies:0,totalChainBreaks:0,totalVerifications:0,totalExports:0,byCategory:{},bySeverity:{}};eue();Mc=null;me.enabled&&Uj()});var Dm={};$(Dm,{activate:()=>Bb,configure:()=>Oue,formatKillEvent:()=>Vue,generateComplianceReport:()=>Gue,getAuditLog:()=>zue,getConfig:()=>Lue,getEvents:()=>Nue,getHistory:()=>Hue,getState:()=>que,getStats:()=>jue,installAutoTriggers:()=>Vj,isActive:()=>Uue,listRecoveryCheckpoints:()=>Jj,recoverFromCheckpoint:()=>Eue,reset:()=>Fue,resetStats:()=>Bue});import{existsSync as yd,mkdirSync as Hj,readFileSync as Im,writeFileSync as Em}from"fs";import{join as Li}from"path";import{homedir as wue,hostname as kue}from"os";import{randomBytes as Gj}from"crypto";import{EventEmitter as xue}from"events";function vd(){Hj(bd,{recursive:!0}),Hj(hd,{recursive:!0})}function Cue(){if(vd(),yd(jA))try{G={...G,...JSON.parse(Im(jA,"utf-8"))}}catch{}if(yd(BA))try{$t={...$t,...JSON.parse(Im(BA,"utf-8"))}}catch{}}function Mm(){vd();try{Em(jA,JSON.stringify(G,null,2),"utf-8")}catch{}}function UA(){vd();try{Em(BA,JSON.stringify($t,null,2),"utf-8")}catch{}}function Oc(e){if(ge.enableAuditLog){vd();try{Em(NA,JSON.stringify({...e,timestamp:Date.now()})+`
1179
1177
  `,{flag:"a"})}catch{}}}function Aue(e){vd();try{Em(qA,JSON.stringify(e)+`
1180
- `,{flag:"a"})}catch{}}async function Bb(e){if(G.active&&G.currentEvent)return G.currentEvent;if(G.lockedUntil&&Date.now()<G.lockedUntil)throw new Error(`Kill switch in cooldown until ${new Date(G.lockedUntil).toISOString()}`);let t=Gj(8).toString("hex"),n=Date.now(),r={id:t,trigger:e.trigger,initiatedBy:e.initiatedBy||"system",initiatedAt:n,reason:e.reason,phase:"initializing",phaseHistory:[{phase:"initializing",startedAt:n,success:!0}],agentsTerminated:0,credentialsRevoked:0,filesRolledBack:0,memoryWiped:0,connectionsClosed:0,recoveryStatus:"not_initiated",errors:[]};if(G.active=!0,G.currentEvent=r,G.activatedAt=n,Mm(),Oc({event:"killswitch_activated",killId:t,trigger:e.trigger,reason:e.reason}),Lc.emit("activated",{killEvent:r}),me.createRecoveryCheckpoint)try{let i=await Mue(r);r.recoveryCheckpointId=i,r.recoveryStatus="recoverable"}catch(i){r.errors.push(`Checkpoint creation: ${i.message}`)}await Pm(r,"terminating_agents",async()=>{let i=await Tue();return r.agentsTerminated=i.count,`${i.count} agents terminated`}),await Pm(r,"revoking_credentials",async()=>{let i=await _ue();return r.credentialsRevoked=i.count,`${i.count} credentials revoked`}),me.closeNetworkConnections&&!e.skipNetworkClose&&await Pm(r,"severing_network",async()=>{let i=await Rue();return r.connectionsClosed=i.count,`${i.count} connections closed`}),me.rollbackUncommittedChanges&&!e.skipRollback&&await Pm(r,"rolling_back",async()=>{let i=await Pue();return r.filesRolledBack=i.count,`${i.count} files rolled back`}),me.zeroizeMemory&&!e.skipMemoryWipe&&await Pm(r,"purging_memory",async()=>{let i=await Iue();return r.memoryWiped=i.count,`${i.count} memory regions wiped`}),me.enableClusterPropagation&&await Due(r).catch(i=>{r.errors.push(`Cluster: ${i.message}`)});let s=r.errors.length===0?"completed":"failed";return r.phase=s,r.completedAt=Date.now(),r.durationMs=r.completedAt-r.initiatedAt,r.phaseHistory.push({phase:s,startedAt:r.completedAt,completedAt:r.completedAt,success:s==="completed"}),me.allowRestartAfterKill&&(G.lockedUntil=Date.now()+me.restartCooldownMs),$t.totalKills++,e.trigger.startsWith("auto_")?$t.totalAutoTriggered++:$t.totalManualTriggered++,$t.byTrigger[e.trigger]=($t.byTrigger[e.trigger]||0)+1,$t.byPhase[s]=($t.byPhase[s]||0)+1,$t.averageDurationMs=($t.averageDurationMs*($t.totalKills-1)+(r.durationMs||0))/$t.totalKills,UA(),G.lastKillId=t,Mm(),Aue(r),Oc({event:"killswitch_completed",killId:t,phase:s,agentsTerminated:r.agentsTerminated,credentialsRevoked:r.credentialsRevoked,filesRolledBack:r.filesRolledBack,durationMs:r.durationMs,errors:r.errors.length}),Lc.emit("completed",{killEvent:r}),r}async function Pm(e,t,n){e.phase=t;let r=Date.now(),s={phase:t,startedAt:r,success:!1,details:"",completedAt:void 0};e.phaseHistory.push(s),Lc.emit("phase_started",{killEvent:e,phase:t});try{let i=await n();s.success=!0,s.details=i,s.completedAt=Date.now(),Oc({event:"phase_completed",killId:e.id,phase:t,durationMs:s.completedAt-r,details:i})}catch(i){s.success=!1,s.details=i.message,s.completedAt=Date.now(),e.errors.push(`${t}: ${i.message}`),Oc({event:"phase_failed",killId:e.id,phase:t,error:i.message})}Mm()}async function Tue(){let e=0;try{let t=await Promise.resolve().then(()=>(wd(),Sd));t.abortAllInvocations&&(t.abortAllInvocations(),e++)}catch{}try{let t=await Promise.resolve().then(()=>(gb(),mb)),n=t.listPlugins();for(let r of n)try{await t.stopPlugin(r.manifest.id,"killswitch"),e++}catch{}}catch{}try{let t=await Promise.resolve().then(()=>(tA(),cj));t.disconnectAll&&(t.disconnectAll(),e++)}catch{}try{let t=await Promise.resolve().then(()=>(cd(),ad));if(t.listIdentities){let n=t.listIdentities({});for(let r of n)if(r.status==="active"&&r.type!=="root")try{t.revokeIdentity(r.id,"killswitch_activated",!0),e++}catch{}}}catch{}return{count:e}}async function _ue(){let e=0;try{let t=await Promise.resolve().then(()=>(pc(),fc));if(t.activateGlobalRevocation){let n=t.activateGlobalRevocation();e+=n}}catch{}try{let t=await Promise.resolve().then(()=>(fs(),ds));if(t.destroyAllSessions){let n=t.destroyAllSessions("killswitch");e+=n.count}}catch{}try{let t=await Promise.resolve().then(()=>(Cc(),$c)),n=t.listAgentIdentities();for(let r of n)if(r.agentId!=="root-agent"&&!r.revoked)try{t.revokeAgentIdentity(r.agentId,"killswitch"),e++}catch{}}catch{}return{count:e}}async function Rue(){let e=0;try{let t=await Promise.resolve().then(()=>(fm(),dm));t.disconnectAll&&t.disconnectAll(),e++}catch{}try{let t=await Promise.resolve().then(()=>(lo(),co));t.activateGlobalBlock&&(t.activateGlobalBlock("killswitch"),e++)}catch{}return{count:e}}async function Pue(){let e=0;try{let t=await Promise.resolve().then(()=>(Si(),vi));if(t.rollbackAll){let n=t.rollbackAll("killswitch");e+=n}else if(t.getRecentOperations){let n=t.getRecentOperations(50);for(let r of n)try{t.undo(r.id),e++}catch{}}}catch{}try{let t=await Promise.resolve().then(()=>(Rc(),_c)),n=t.listSessions();for(let r of n)try{t.blockSession(r.sessionId,"killswitch"),e++}catch{}}catch{}return{count:e}}async function Iue(){let e=0;try{let t=await Promise.resolve().then(()=>(Wu(),Ju));if(t.purge){let n=await t.purge("panic","paranoid");e+=n.totalItemsCleaned||1}}catch{}return{count:e}}async function Mue(e){let t=Gj(8).toString("hex");vd();let n={id:t,killEventId:e.id,createdAt:Date.now(),expiresAt:Date.now()+me.recoveryCheckpointTtlMs,snapshot:{undoOpsAvailable:0,memoryStorePaths:[],audit_logs_preserved:me.preserveAuditLogs}};try{let s=await Promise.resolve().then(()=>(Si(),vi));if(s.getRecentOperations){let i=s.getRecentOperations(100);n.snapshot.undoOpsAvailable=i.length}}catch{}let r=Li(hd,`checkpoint-${t}.json`);return Em(r,JSON.stringify(n,null,2),"utf-8"),t}async function Eue(e){let t=Li(hd,`checkpoint-${e}.json`);if(!yd(t))return{success:!1,reason:"Checkpoint not found",recovered:0};try{let n=JSON.parse(Im(t,"utf-8"));if(n.expiresAt&&Date.now()>n.expiresAt)return{success:!1,reason:"Checkpoint expired",recovered:0};let r=0;G.active=!1,G.currentEvent=void 0,G.activatedAt=void 0,G.lockedUntil=void 0,Mm();try{let s=await Promise.resolve().then(()=>(Rc(),_c)),i=s.listSessions();for(let o of i)o.status!=="allow"&&(s.unblockSession(o.sessionId),r++)}catch{}try{let s=await Promise.resolve().then(()=>(lo(),co));s.deactivateGlobalBlock&&(s.deactivateGlobalBlock(),r++)}catch{}return $t.totalRecoveries++,UA(),Oc({event:"recovered",checkpointId:e,recovered:r}),Lc.emit("recovered",{checkpointId:e,recovered:r}),{success:!0,reason:"OK",recovered:r}}catch(n){return{success:!1,reason:n.message,recovered:0}}}async function Due(e){Oc({event:"cluster_propagation_attempted",killId:e.id})}function Fue(){return!G.active&&!G.lockedUntil?{success:!0,reason:"Already reset"}:me.allowRestartAfterKill?G.lockedUntil&&Date.now()<G.lockedUntil?{success:!1,reason:`Cooldown active, ${Math.ceil((G.lockedUntil-Date.now())/1e3)}s remaining`}:(G.active=!1,G.currentEvent=void 0,G.activatedAt=void 0,G.lockedUntil=void 0,Mm(),Oc({event:"killswitch_reset"}),Lc.emit("reset"),{success:!0,reason:"OK"}):{success:!1,reason:"Restart not allowed by policy"}}function Vj(){zj||!me.enableAutoTriggers||(zj=!0,me.triggerOnCriticalAnomaly&&Promise.resolve().then(()=>(Rc(),_c)).then(e=>{e.getEvents().on("alert",t=>{t.severity==="critical"&&t.type==="hijack_indicator"&&Bb({trigger:"auto_anomaly",reason:`Critical anomaly: ${t.message}`}).catch(()=>{})})}).catch(()=>{}),me.triggerOnDriftHijack&&Promise.resolve().then(()=>(pd(),fd)).then(e=>{let t=e.getEvents?.();t&&t.on("hijack_detected",n=>{Bb({trigger:"auto_drift",reason:`Drift hijack: ${n.message||"detected"}`}).catch(()=>{})})}).catch(()=>{}),me.triggerOnBreach&&Promise.resolve().then(()=>(gd(),md)).then(e=>{e.getEvents().on("high_severity_event",t=>{t.category==="security_event"&&t.severity==="critical"&&Bb({trigger:"auto_breach",reason:`Security event: ${t.description}`}).catch(()=>{})})}).catch(()=>{}))}function Lue(){return{...me}}function Oue(e){me={...me,...e}}function jue(){return{...$t}}function Bue(){$t={totalKills:0,totalRecoveries:0,totalAutoTriggered:0,totalManualTriggered:0,byTrigger:{},byPhase:{},averageDurationMs:0},UA()}function Nue(){return Lc}function que(){return{...G}}function Uue(){return G.active}function Hue(e=30){if(!yd(qA))return[];try{return Im(qA,"utf-8").split(`
1178
+ `,{flag:"a"})}catch{}}async function Bb(e){if(G.active&&G.currentEvent)return G.currentEvent;if(G.lockedUntil&&Date.now()<G.lockedUntil)throw new Error(`Kill switch in cooldown until ${new Date(G.lockedUntil).toISOString()}`);let t=Gj(8).toString("hex"),n=Date.now(),r={id:t,trigger:e.trigger,initiatedBy:e.initiatedBy||"system",initiatedAt:n,reason:e.reason,phase:"initializing",phaseHistory:[{phase:"initializing",startedAt:n,success:!0}],agentsTerminated:0,credentialsRevoked:0,filesRolledBack:0,memoryWiped:0,connectionsClosed:0,recoveryStatus:"not_initiated",errors:[]};if(G.active=!0,G.currentEvent=r,G.activatedAt=n,Mm(),Oc({event:"killswitch_activated",killId:t,trigger:e.trigger,reason:e.reason}),Lc.emit("activated",{killEvent:r}),ge.createRecoveryCheckpoint)try{let i=await Mue(r);r.recoveryCheckpointId=i,r.recoveryStatus="recoverable"}catch(i){r.errors.push(`Checkpoint creation: ${i.message}`)}await Pm(r,"terminating_agents",async()=>{let i=await Tue();return r.agentsTerminated=i.count,`${i.count} agents terminated`}),await Pm(r,"revoking_credentials",async()=>{let i=await _ue();return r.credentialsRevoked=i.count,`${i.count} credentials revoked`}),ge.closeNetworkConnections&&!e.skipNetworkClose&&await Pm(r,"severing_network",async()=>{let i=await Rue();return r.connectionsClosed=i.count,`${i.count} connections closed`}),ge.rollbackUncommittedChanges&&!e.skipRollback&&await Pm(r,"rolling_back",async()=>{let i=await Pue();return r.filesRolledBack=i.count,`${i.count} files rolled back`}),ge.zeroizeMemory&&!e.skipMemoryWipe&&await Pm(r,"purging_memory",async()=>{let i=await Iue();return r.memoryWiped=i.count,`${i.count} memory regions wiped`}),ge.enableClusterPropagation&&await Due(r).catch(i=>{r.errors.push(`Cluster: ${i.message}`)});let s=r.errors.length===0?"completed":"failed";return r.phase=s,r.completedAt=Date.now(),r.durationMs=r.completedAt-r.initiatedAt,r.phaseHistory.push({phase:s,startedAt:r.completedAt,completedAt:r.completedAt,success:s==="completed"}),ge.allowRestartAfterKill&&(G.lockedUntil=Date.now()+ge.restartCooldownMs),$t.totalKills++,e.trigger.startsWith("auto_")?$t.totalAutoTriggered++:$t.totalManualTriggered++,$t.byTrigger[e.trigger]=($t.byTrigger[e.trigger]||0)+1,$t.byPhase[s]=($t.byPhase[s]||0)+1,$t.averageDurationMs=($t.averageDurationMs*($t.totalKills-1)+(r.durationMs||0))/$t.totalKills,UA(),G.lastKillId=t,Mm(),Aue(r),Oc({event:"killswitch_completed",killId:t,phase:s,agentsTerminated:r.agentsTerminated,credentialsRevoked:r.credentialsRevoked,filesRolledBack:r.filesRolledBack,durationMs:r.durationMs,errors:r.errors.length}),Lc.emit("completed",{killEvent:r}),r}async function Pm(e,t,n){e.phase=t;let r=Date.now(),s={phase:t,startedAt:r,success:!1,details:"",completedAt:void 0};e.phaseHistory.push(s),Lc.emit("phase_started",{killEvent:e,phase:t});try{let i=await n();s.success=!0,s.details=i,s.completedAt=Date.now(),Oc({event:"phase_completed",killId:e.id,phase:t,durationMs:s.completedAt-r,details:i})}catch(i){s.success=!1,s.details=i.message,s.completedAt=Date.now(),e.errors.push(`${t}: ${i.message}`),Oc({event:"phase_failed",killId:e.id,phase:t,error:i.message})}Mm()}async function Tue(){let e=0;try{let t=await Promise.resolve().then(()=>(wd(),Sd));t.abortAllInvocations&&(t.abortAllInvocations(),e++)}catch{}try{let t=await Promise.resolve().then(()=>(gb(),mb)),n=t.listPlugins();for(let r of n)try{await t.stopPlugin(r.manifest.id,"killswitch"),e++}catch{}}catch{}try{let t=await Promise.resolve().then(()=>(tA(),cj));t.disconnectAll&&(t.disconnectAll(),e++)}catch{}try{let t=await Promise.resolve().then(()=>(cd(),ad));if(t.listIdentities){let n=t.listIdentities({});for(let r of n)if(r.status==="active"&&r.type!=="root")try{t.revokeIdentity(r.id,"killswitch_activated",!0),e++}catch{}}}catch{}return{count:e}}async function _ue(){let e=0;try{let t=await Promise.resolve().then(()=>(pc(),fc));if(t.activateGlobalRevocation){let n=t.activateGlobalRevocation();e+=n}}catch{}try{let t=await Promise.resolve().then(()=>(fs(),ds));if(t.destroyAllSessions){let n=t.destroyAllSessions("killswitch");e+=n.count}}catch{}try{let t=await Promise.resolve().then(()=>(Cc(),$c)),n=t.listAgentIdentities();for(let r of n)if(r.agentId!=="root-agent"&&!r.revoked)try{t.revokeAgentIdentity(r.agentId,"killswitch"),e++}catch{}}catch{}return{count:e}}async function Rue(){let e=0;try{let t=await Promise.resolve().then(()=>(fm(),dm));t.disconnectAll&&t.disconnectAll(),e++}catch{}try{let t=await Promise.resolve().then(()=>(lo(),co));t.activateGlobalBlock&&(t.activateGlobalBlock("killswitch"),e++)}catch{}return{count:e}}async function Pue(){let e=0;try{let t=await Promise.resolve().then(()=>(Si(),vi));if(t.rollbackAll){let n=t.rollbackAll("killswitch");e+=n}else if(t.getRecentOperations){let n=t.getRecentOperations(50);for(let r of n)try{t.undo(r.id),e++}catch{}}}catch{}try{let t=await Promise.resolve().then(()=>(Rc(),_c)),n=t.listSessions();for(let r of n)try{t.blockSession(r.sessionId,"killswitch"),e++}catch{}}catch{}return{count:e}}async function Iue(){let e=0;try{let t=await Promise.resolve().then(()=>(Wu(),Ju));if(t.purge){let n=await t.purge("panic","paranoid");e+=n.totalItemsCleaned||1}}catch{}return{count:e}}async function Mue(e){let t=Gj(8).toString("hex");vd();let n={id:t,killEventId:e.id,createdAt:Date.now(),expiresAt:Date.now()+ge.recoveryCheckpointTtlMs,snapshot:{undoOpsAvailable:0,memoryStorePaths:[],audit_logs_preserved:ge.preserveAuditLogs}};try{let s=await Promise.resolve().then(()=>(Si(),vi));if(s.getRecentOperations){let i=s.getRecentOperations(100);n.snapshot.undoOpsAvailable=i.length}}catch{}let r=Li(hd,`checkpoint-${t}.json`);return Em(r,JSON.stringify(n,null,2),"utf-8"),t}async function Eue(e){let t=Li(hd,`checkpoint-${e}.json`);if(!yd(t))return{success:!1,reason:"Checkpoint not found",recovered:0};try{let n=JSON.parse(Im(t,"utf-8"));if(n.expiresAt&&Date.now()>n.expiresAt)return{success:!1,reason:"Checkpoint expired",recovered:0};let r=0;G.active=!1,G.currentEvent=void 0,G.activatedAt=void 0,G.lockedUntil=void 0,Mm();try{let s=await Promise.resolve().then(()=>(Rc(),_c)),i=s.listSessions();for(let o of i)o.status!=="allow"&&(s.unblockSession(o.sessionId),r++)}catch{}try{let s=await Promise.resolve().then(()=>(lo(),co));s.deactivateGlobalBlock&&(s.deactivateGlobalBlock(),r++)}catch{}return $t.totalRecoveries++,UA(),Oc({event:"recovered",checkpointId:e,recovered:r}),Lc.emit("recovered",{checkpointId:e,recovered:r}),{success:!0,reason:"OK",recovered:r}}catch(n){return{success:!1,reason:n.message,recovered:0}}}async function Due(e){Oc({event:"cluster_propagation_attempted",killId:e.id})}function Fue(){return!G.active&&!G.lockedUntil?{success:!0,reason:"Already reset"}:ge.allowRestartAfterKill?G.lockedUntil&&Date.now()<G.lockedUntil?{success:!1,reason:`Cooldown active, ${Math.ceil((G.lockedUntil-Date.now())/1e3)}s remaining`}:(G.active=!1,G.currentEvent=void 0,G.activatedAt=void 0,G.lockedUntil=void 0,Mm(),Oc({event:"killswitch_reset"}),Lc.emit("reset"),{success:!0,reason:"OK"}):{success:!1,reason:"Restart not allowed by policy"}}function Vj(){zj||!ge.enableAutoTriggers||(zj=!0,ge.triggerOnCriticalAnomaly&&Promise.resolve().then(()=>(Rc(),_c)).then(e=>{e.getEvents().on("alert",t=>{t.severity==="critical"&&t.type==="hijack_indicator"&&Bb({trigger:"auto_anomaly",reason:`Critical anomaly: ${t.message}`}).catch(()=>{})})}).catch(()=>{}),ge.triggerOnDriftHijack&&Promise.resolve().then(()=>(pd(),fd)).then(e=>{let t=e.getEvents?.();t&&t.on("hijack_detected",n=>{Bb({trigger:"auto_drift",reason:`Drift hijack: ${n.message||"detected"}`}).catch(()=>{})})}).catch(()=>{}),ge.triggerOnBreach&&Promise.resolve().then(()=>(gd(),md)).then(e=>{e.getEvents().on("high_severity_event",t=>{t.category==="security_event"&&t.severity==="critical"&&Bb({trigger:"auto_breach",reason:`Security event: ${t.description}`}).catch(()=>{})})}).catch(()=>{}))}function Lue(){return{...ge}}function Oue(e){ge={...ge,...e}}function jue(){return{...$t}}function Bue(){$t={totalKills:0,totalRecoveries:0,totalAutoTriggered:0,totalManualTriggered:0,byTrigger:{},byPhase:{},averageDurationMs:0},UA()}function Nue(){return Lc}function que(){return{...G}}function Uue(){return G.active}function Hue(e=30){if(!yd(qA))return[];try{return Im(qA,"utf-8").split(`
1181
1179
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Jj(){if(!yd(hd))return[];try{let e=fl("fs"),t=e.readdirSync(hd).filter(r=>r.startsWith("checkpoint-")),n=[];for(let r of t)try{let s=JSON.parse(e.readFileSync(Li(hd,r),"utf-8"));s.expiresAt>Date.now()&&n.push({id:s.id,createdAt:s.createdAt,expiresAt:s.expiresAt})}catch{}return n.sort((r,s)=>s.createdAt-r.createdAt)}catch{return[]}}function zue(e=100){if(!yd(NA))return[];try{return Im(NA,"utf-8").split(`
1182
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Gue(){let e=[];e.push("# Agent Kill Switch Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(`Host: ${kue()}`),e.push(""),e.push("## Current State"),e.push(`- Status: ${G.active?"\u{1F6A8} ACTIVE (kill in progress)":"\u{1F7E2} INACTIVE"}`),G.activatedAt&&e.push(`- Activated at: ${new Date(G.activatedAt).toISOString()}`),G.lockedUntil&&e.push(`- Cooldown until: ${new Date(G.lockedUntil).toISOString()}`),G.currentEvent&&(e.push(`- Current phase: ${G.currentEvent.phase}`),e.push(`- Trigger: ${G.currentEvent.trigger}`),e.push(`- Initiated by: ${G.currentEvent.initiatedBy}`)),e.push(""),e.push("## Statistics"),e.push(`- Total kills: ${$t.totalKills}`),e.push(`- Total recoveries: ${$t.totalRecoveries}`),e.push(`- Manual triggered: ${$t.totalManualTriggered}`),e.push(`- Auto triggered: ${$t.totalAutoTriggered}`),e.push(`- Avg duration: ${$t.averageDurationMs.toFixed(0)}ms`),e.push(""),e.push("## By Trigger");for(let[n,r]of Object.entries($t.byTrigger).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## Recovery Checkpoints");let t=Jj();e.push(`- Available: ${t.length}`);for(let n of t.slice(0,5))e.push(` - ${n.id} | created ${new Date(n.createdAt).toISOString()}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Atomic kill switch activation"),e.push("- \u2713 Multi-phase orchestration (terminate \u2192 revoke \u2192 rollback \u2192 purge)"),e.push(`- ${me.enableAutoTriggers?"\u2713":"\u2717"} Auto-triggers enabled`),e.push(`- ${me.triggerOnCriticalAnomaly?"\u2713":"\u2717"} Trigger on critical anomaly`),e.push(`- ${me.triggerOnDriftHijack?"\u2713":"\u2717"} Trigger on drift hijack`),e.push(`- ${me.triggerOnBreach?"\u2713":"\u2717"} Trigger on security breach`),e.push(`- ${me.rollbackUncommittedChanges?"\u2713":"\u2717"} Rollback uncommitted`),e.push(`- ${me.zeroizeMemory?"\u2713":"\u2717"} Memory zeroization`),e.push(`- ${me.closeNetworkConnections?"\u2713":"\u2717"} Network severance`),e.push(`- ${me.preserveAuditLogs?"\u2713":"\u2717"} Audit logs preserved`),e.push(`- ${me.createRecoveryCheckpoint?"\u2713":"\u2717"} Recovery checkpoints`),e.push(`- ${me.allowRestartAfterKill?"\u2713":"\u2717"} Restart allowed (cooldown ${me.restartCooldownMs/1e3}s)`),e.join(`
1180
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Gue(){let e=[];e.push("# Agent Kill Switch Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(`Host: ${kue()}`),e.push(""),e.push("## Current State"),e.push(`- Status: ${G.active?"\u{1F6A8} ACTIVE (kill in progress)":"\u{1F7E2} INACTIVE"}`),G.activatedAt&&e.push(`- Activated at: ${new Date(G.activatedAt).toISOString()}`),G.lockedUntil&&e.push(`- Cooldown until: ${new Date(G.lockedUntil).toISOString()}`),G.currentEvent&&(e.push(`- Current phase: ${G.currentEvent.phase}`),e.push(`- Trigger: ${G.currentEvent.trigger}`),e.push(`- Initiated by: ${G.currentEvent.initiatedBy}`)),e.push(""),e.push("## Statistics"),e.push(`- Total kills: ${$t.totalKills}`),e.push(`- Total recoveries: ${$t.totalRecoveries}`),e.push(`- Manual triggered: ${$t.totalManualTriggered}`),e.push(`- Auto triggered: ${$t.totalAutoTriggered}`),e.push(`- Avg duration: ${$t.averageDurationMs.toFixed(0)}ms`),e.push(""),e.push("## By Trigger");for(let[n,r]of Object.entries($t.byTrigger).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);e.push(""),e.push("## Recovery Checkpoints");let t=Jj();e.push(`- Available: ${t.length}`);for(let n of t.slice(0,5))e.push(` - ${n.id} | created ${new Date(n.createdAt).toISOString()}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Atomic kill switch activation"),e.push("- \u2713 Multi-phase orchestration (terminate \u2192 revoke \u2192 rollback \u2192 purge)"),e.push(`- ${ge.enableAutoTriggers?"\u2713":"\u2717"} Auto-triggers enabled`),e.push(`- ${ge.triggerOnCriticalAnomaly?"\u2713":"\u2717"} Trigger on critical anomaly`),e.push(`- ${ge.triggerOnDriftHijack?"\u2713":"\u2717"} Trigger on drift hijack`),e.push(`- ${ge.triggerOnBreach?"\u2713":"\u2717"} Trigger on security breach`),e.push(`- ${ge.rollbackUncommittedChanges?"\u2713":"\u2717"} Rollback uncommitted`),e.push(`- ${ge.zeroizeMemory?"\u2713":"\u2717"} Memory zeroization`),e.push(`- ${ge.closeNetworkConnections?"\u2713":"\u2717"} Network severance`),e.push(`- ${ge.preserveAuditLogs?"\u2713":"\u2717"} Audit logs preserved`),e.push(`- ${ge.createRecoveryCheckpoint?"\u2713":"\u2717"} Recovery checkpoints`),e.push(`- ${ge.allowRestartAfterKill?"\u2713":"\u2717"} Restart allowed (cooldown ${ge.restartCooldownMs/1e3}s)`),e.join(`
1183
1181
  `)}function Vue(e){let t=[],n=e.phase==="completed"?"\u2713":e.phase==="failed"?"\u{1F6A8}":"\u23F3";if(t.push(`${n} **Kill Event ${e.id}**`),t.push(`Trigger: ${e.trigger}`),t.push(`By: ${e.initiatedBy}`),t.push(`Reason: ${e.reason}`),t.push(`Phase: ${e.phase}`),e.durationMs&&t.push(`Duration: ${e.durationMs}ms`),t.push(""),t.push("Results:"),t.push(` Agents terminated: ${e.agentsTerminated}`),t.push(` Credentials revoked: ${e.credentialsRevoked}`),t.push(` Files rolled back: ${e.filesRolledBack}`),t.push(` Memory wiped: ${e.memoryWiped}`),t.push(` Connections closed: ${e.connectionsClosed}`),t.push(` Recovery: ${e.recoveryStatus}${e.recoveryCheckpointId?` (checkpoint: ${e.recoveryCheckpointId})`:""}`),e.errors.length>0){t.push(""),t.push(`Errors (${e.errors.length}):`);for(let r of e.errors.slice(0,10))t.push(` - ${r}`)}t.push(""),t.push("Phase History:");for(let r of e.phaseHistory){let s=r.success?"\u2713":"\u{1F6A8}",i=r.completedAt?`${r.completedAt-r.startedAt}ms`:"pending";t.push(` ${s} ${r.phase.padEnd(22)} ${i}${r.details?" | "+r.details:""}`)}return t.join(`
1184
- `)}var $ue,me,bd,jA,BA,NA,qA,hd,Lc,G,$t,zj,Fm=w(()=>{"use strict";$ue={enabled:!0,enableAutoTriggers:!0,triggerOnCriticalAnomaly:!0,triggerOnDriftHijack:!0,triggerOnPanic:!0,triggerOnBreach:!0,rollbackUncommittedChanges:!0,zeroizeMemory:!0,closeNetworkConnections:!0,preserveAuditLogs:!0,enableClusterPropagation:!1,clusterPropagationTimeoutMs:1e4,createRecoveryCheckpoint:!0,recoveryCheckpointTtlMs:1440*60*1e3,allowRestartAfterKill:!0,restartCooldownMs:6e4,enableAuditLog:!0},me={...$ue},bd=Li(wue(),".aiaca","killswitch"),jA=Li(bd,"state.json"),BA=Li(bd,"stats.json"),NA=Li(bd,"audit.jsonl"),qA=Li(bd,"history.jsonl"),hd=Li(bd,"recovery"),Lc=new xue;Lc.setMaxListeners(200);G={active:!1},$t={totalKills:0,totalRecoveries:0,totalAutoTriggered:0,totalManualTriggered:0,byTrigger:{},byPhase:{},averageDurationMs:0};Cue();zj=!1;me.enabled&&me.enableAutoTriggers&&Vj()});var JA={};$(JA,{ClipboardImageTool:()=>qb,ImageReadTool:()=>Nb,clearStoredImages:()=>GA,getStoredImages:()=>zA,hasStoredImages:()=>VA});import{readFileSync as Jue,existsSync as Wue}from"fs";import{execSync as HA}from"child_process";import{resolve as Kue,extname as Yue}from"path";function Wj(e){kd.push(e),kd.length>5&&kd.shift()}function zA(){return[...kd]}function GA(){kd.length=0}function VA(){return kd.length>0}function Que(e){return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"}[e]||"image/png"}function Zue(){try{return process.platform==="win32"?HA(`powershell -NoProfile -Command "${`
1182
+ `)}var $ue,ge,bd,jA,BA,NA,qA,hd,Lc,G,$t,zj,Fm=w(()=>{"use strict";$ue={enabled:!0,enableAutoTriggers:!0,triggerOnCriticalAnomaly:!0,triggerOnDriftHijack:!0,triggerOnPanic:!0,triggerOnBreach:!0,rollbackUncommittedChanges:!0,zeroizeMemory:!0,closeNetworkConnections:!0,preserveAuditLogs:!0,enableClusterPropagation:!1,clusterPropagationTimeoutMs:1e4,createRecoveryCheckpoint:!0,recoveryCheckpointTtlMs:1440*60*1e3,allowRestartAfterKill:!0,restartCooldownMs:6e4,enableAuditLog:!0},ge={...$ue},bd=Li(wue(),".aiaca","killswitch"),jA=Li(bd,"state.json"),BA=Li(bd,"stats.json"),NA=Li(bd,"audit.jsonl"),qA=Li(bd,"history.jsonl"),hd=Li(bd,"recovery"),Lc=new xue;Lc.setMaxListeners(200);G={active:!1},$t={totalKills:0,totalRecoveries:0,totalAutoTriggered:0,totalManualTriggered:0,byTrigger:{},byPhase:{},averageDurationMs:0};Cue();zj=!1;ge.enabled&&ge.enableAutoTriggers&&Vj()});var JA={};$(JA,{ClipboardImageTool:()=>qb,ImageReadTool:()=>Nb,clearStoredImages:()=>GA,getStoredImages:()=>zA,hasStoredImages:()=>VA});import{readFileSync as Jue,existsSync as Wue}from"fs";import{execSync as HA}from"child_process";import{resolve as Kue,extname as Yue}from"path";function Wj(e){kd.push(e),kd.length>5&&kd.shift()}function zA(){return[...kd]}function GA(){kd.length=0}function VA(){return kd.length>0}function Que(e){return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"}[e]||"image/png"}function Zue(){try{return process.platform==="win32"?HA(`powershell -NoProfile -Command "${`
1185
1183
  Add-Type -AssemblyName System.Windows.Forms
1186
1184
  $img = [System.Windows.Forms.Clipboard]::GetImage()
1187
1185
  if ($img) {
@@ -1262,7 +1260,7 @@ ${e.map((s,i)=>`[${i}] ${s.role}: ${s.content.slice(0,1500)}`).join(`
1262
1260
 
1263
1261
  SUMMARY:`;try{return(await t.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You are a precise technical summarizer. Output only the summary, no preamble.",[],void 0)).content||"[Summary failed]"}catch{return e.map((s,i)=>`[${i}] ${s.role}: ${s.content.slice(0,200)}`).join(`
1264
1262
  `)}}async function bde(e,t={}){let n=Date.now();if(!Jt.enabled&&!t.forceCompress)return{optimizedMessages:e,originalTokenCount:Oi(e),finalTokenCount:Oi(e),reductionPercent:0,qualityScore:1,compressedCount:0,removedCount:0,strategiesApplied:{none:e.length},perMessageDecisions:[],durationMs:Date.now()-n,passes:0};let r=Oi(e),s=t.targetTokens??Math.floor((Jt.modelContextWindow-Jt.reservedTokens)*Jt.targetUtilization),i;Jt.enableSnapshot&&(i=rde("md5").update(Date.now().toString()+Math.random()).digest("hex").slice(0,8),Hb.set(i,[...e]));let o=[...e],a=0,c={},l=[],u=0,d=0,f=1;for(;Oi(o)>s&&a<3;){a++;let h=[...ZA(o)].sort((y,b)=>y.preserveScore-b.preserveScore),v=[...o];for(let y of h){if(Oi(v)<=s)break;if(y.strategy==="none")continue;let b=y.strategy;a===2&&(b==="truncate"?b="summarize":b==="extract_facts"&&(b="placeholder")),a===3&&(b="placeholder");let k=v[y.index],{compressed:S,quality:x}=ude(k,b,{originalIdx:y.index,allMessages:v});x<Jt.qualityFloor&&a<3||(v[y.index]=S,c[b]=(c[b]||0)+1,d++,f=f*(.95+x*.05))}if(o=v,Oi(o)>s&&a>=2){let y=ZA(o).filter(b=>b.strategy!=="none").sort((b,k)=>b.preserveScore-k.preserveScore);for(;Oi(o)>s&&y.length>0;){let b=y.shift();o.splice(b.index,1),u++,f*=.8}}if(!Jt.multiPass)break}if(Jt.enableLLMSummary&&t.provider&&t.model&&e.length>Jt.llmSummaryThreshold&&Oi(o)>s*1.2)try{let g=o.slice(2,-Jt.preserveRecent);if(g.length>0){let h=await yde(g,t.provider,t.model);o=[...o.slice(0,2),{role:"user",content:`[Conversation summary of ${g.length} messages]:
1265
- ${h}`,timestamp:new Date().toISOString()},...o.slice(-Jt.preserveRecent)],d+=g.length,c.summarize=(c.summarize||0)+g.length}}catch{}let p=Oi(o),m=r>0?(1-p/r)*100:0;fn.totalOptimizations++,fn.totalTokensSaved+=r-p,fn.totalQualityLoss+=1-f;for(let[g,h]of Object.entries(c))fn.strategiesUsed[g]=(fn.strategiesUsed[g]||0)+h;return fn.averageReductionPercent=(fn.averageReductionPercent*(fn.totalOptimizations-1)+m)/fn.totalOptimizations,{optimizedMessages:o,originalTokenCount:r,finalTokenCount:p,reductionPercent:m,qualityScore:Math.max(0,f),compressedCount:d,removedCount:u,strategiesApplied:c,perMessageDecisions:l,snapshot:Jt.enableSnapshot?Hb.get(i):void 0,durationMs:Date.now()-n,passes:a}}function vde(e,t){let n=new Set;for(let o of e){let a=o.content.toLowerCase().split(/\s+/).filter(c=>c.length>5);for(let c of a.slice(0,50))n.add(c)}let r=t.map(o=>o.content).join(" ").toLowerCase(),s=0,i=[];for(let o of n)r.includes(o)?s++:i.length<10&&i.push(o);return{preservedFacts:s,totalFacts:n.size,retentionScore:n.size>0?s/n.size:1,missingTopics:i}}function Sde(e){return Hb.get(e)||null}function wde(){Hb.clear()}function kde(){return{...Jt}}function Ko(e){Jt={...Jt,...e}}function xde(){return{...fn,strategiesUsed:{...fn.strategiesUsed}}}function $de(){fn.totalOptimizations=0,fn.totalTokensSaved=0,fn.totalQualityLoss=0,fn.strategiesUsed={},fn.averageReductionPercent=0,fn.totalSummaryCalls=0}function Cde(e){let t=e.toLowerCase();t.includes("claude")?t.includes("opus")?Ko({modelContextWindow:2e5}):Ko({modelContextWindow:2e5}):t.includes("gemini")?t.includes("pro")?Ko({modelContextWindow:2e6}):t.includes("flash")?Ko({modelContextWindow:1e6}):Ko({modelContextWindow:1e6}):t.includes("gpt-4")?Ko({modelContextWindow:128e3}):Ko({modelContextWindow:2e5})}var sde,Jt,fn,Hb,tT=w(()=>{"use strict";sde={enabled:!0,targetUtilization:.7,modelContextWindow:2e5,reservedTokens:16e3,enableLLMSummary:!0,llmSummaryThreshold:5,preserveRecent:4,preserveSystem:!0,preserveUser:!0,enableReferenceTracking:!0,qualityFloor:.6,multiPass:!0,enableSnapshot:!0,debug:!1},Jt={...sde},fn={totalOptimizations:0,totalTokensSaved:0,totalQualityLoss:0,strategiesUsed:{},averageReductionPercent:0,totalSummaryCalls:0},Hb=new Map});var iT={};$(iT,{clearParallelStats:()=>Dde,executeParallel:()=>eB,executeParallelStream:()=>Ade,executeSubgroup:()=>Tde,formatParallelResult:()=>Fde,getAdaptiveConcurrency:()=>_de,getAdaptiveState:()=>Pde,getParallelStats:()=>Ede,recordAdaptiveResult:()=>Rde,recordParallelRun:()=>Mde});import{EventEmitter as Zj}from"events";async function eB(e,t,n={}){let r={...Xj,...n},s=Date.now();if(e.length===0)return tB();let i=new Gb(r),o=i.orderForFairness([...e]),a=0,c=0,l=0,u=new Set,d=i.getDedupCache(),f=null,p=!1;r.groupTimeoutMs&&(f=setTimeout(()=>{p=!0},r.groupTimeoutMs));let m=0,g=()=>i.getInFlight(),h=o.map(async I=>{let ye=d.key(I);r.enableDedup&&u.has(ye)&&a++,u.add(ye),r.onProgress?.({type:"started",toolCall:I,totalCount:o.length,completedCount:m,inFlightCount:g(),queuedCount:o.length-m-g()});let Ne=await i.execute(I,t);return m++,Ne.isError&&(Ne.output?.includes("Timeout")?c++:Ne.output?.includes("Cancelled")&&l++),r.onProgress?.({type:Ne.isError?"failed":"completed",toolCall:I,totalCount:o.length,completedCount:m,inFlightCount:g(),queuedCount:o.length-m-g(),durationMs:Ne.durationMs,error:Ne.isError?Ne.output:void 0}),r.onResult?.(Ne,I),Ne}),v=await Promise.all(h);f&&clearTimeout(f);let y=new Map(v.map(I=>[I.toolCallId,I])),b=e.map(I=>y.get(I.id)||{toolCallId:I.id,output:"Not executed",isError:!0,durationMs:0}),k=Date.now()-s,S=b.filter(I=>!I.isError).length,x=b.filter(I=>I.isError).length,A=b.reduce((I,ye)=>I+(ye.durationMs||0),0),j=k>0?A/k:1;return{results:b,durationMs:k,successCount:S,failureCount:x,cancelledCount:l,timeoutCount:c,dedupedCount:a,peakConcurrency:i.getLatencyTracker().getPeak(),averageLatencyMs:Math.round(i.getLatencyTracker().getAverageLatency()),perToolLatency:i.getLatencyTracker().getStats(),speedupFactor:j}}function tB(){return{results:[],durationMs:0,successCount:0,failureCount:0,cancelledCount:0,timeoutCount:0,dedupedCount:0,peakConcurrency:0,averageLatencyMs:0,perToolLatency:{},speedupFactor:1}}async function*Ade(e,t,n={}){let r={...Xj,...n,yieldAsCompleted:!0},s=Date.now();if(e.length===0)return tB();let i=new Gb(r),o=i.orderForFairness([...e]),a=[],c=new Zj,l=0,u=0,d=0,f=0,p=new Set,m=o.map(async k=>{let S=`${k.name}:${JSON.stringify(k.input)}`;r.enableDedup&&p.has(S)&&f++,p.add(S);let x=await i.execute(k,t);return x.isError&&(x.output?.includes("Timeout")?u++:x.output?.includes("Cancelled")&&d++),a.push({call:k,result:x}),l++,c.emit("done"),l===o.length&&c.emit("all_done"),x});for(;l<o.length||a.length>0;)for(a.length===0&&await new Promise(k=>c.once("done",k));a.length>0;)yield a.shift();let g=await Promise.all(m),h=Date.now()-s,v=g.filter(k=>!k.isError).length,y=g.filter(k=>k.isError).length,b=g.reduce((k,S)=>k+(S.durationMs||0),0);return{results:g,durationMs:h,successCount:v,failureCount:y,cancelledCount:d,timeoutCount:u,dedupedCount:f,peakConcurrency:i.getLatencyTracker().getPeak(),averageLatencyMs:Math.round(i.getLatencyTracker().getAverageLatency()),perToolLatency:i.getLatencyTracker().getStats(),speedupFactor:h>0?b/h:1}}function Tde(e,t,n={}){let r=new AbortController,s=`sg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,i=eB(e,t,{...n,abortSignal:r.signal});return{id:s,cancel:()=>r.abort(),promise:i}}function _de(){return $d.getCurrent()}function Rde(e,t){$d.recordResult(e,t)}function Pde(){return $d.getState()}function Mde(e){Kn.push(e),Kn.length>Ide&&Kn.shift();for(let t of e.results)$d.recordResult(t.durationMs||0,!!t.isError)}function Ede(){if(Kn.length===0)return{totalRuns:0,totalToolCalls:0,totalSpeedup:0,averageSpeedup:1,averageDurationMs:0,totalDedupSavings:0,totalTimeouts:0,totalCancellations:0,topSlowestTools:[],adaptiveConcurrency:$d.getCurrent()};let e=Kn.reduce((c,l)=>c+l.results.length,0),t=Kn.reduce((c,l)=>c+l.speedupFactor,0),n=Kn.reduce((c,l)=>c+l.durationMs,0),r=Kn.reduce((c,l)=>c+l.dedupedCount,0),s=Kn.reduce((c,l)=>c+l.timeoutCount,0),i=Kn.reduce((c,l)=>c+l.cancelledCount,0),o=new Map;for(let c of Kn)for(let[l,u]of Object.entries(c.perToolLatency)){o.has(l)||o.set(l,{p95s:[],counts:0});let d=o.get(l);d.p95s.push(u.p95),d.counts+=u.count}let a=Array.from(o.entries()).map(([c,l])=>({name:c,p95:l.p95s.reduce((u,d)=>u+d,0)/l.p95s.length,count:l.counts})).sort((c,l)=>l.p95-c.p95).slice(0,5);return{totalRuns:Kn.length,totalToolCalls:e,totalSpeedup:t,averageSpeedup:t/Kn.length,averageDurationMs:Math.round(n/Kn.length),totalDedupSavings:r,totalTimeouts:s,totalCancellations:i,topSlowestTools:a,adaptiveConcurrency:$d.getCurrent()}}function Dde(){Kn.length=0}function Fde(e){let t=[];if(t.push("Parallel execution complete:"),t.push(` Tools: ${e.results.length} (${e.successCount} \u2713, ${e.failureCount} \u2717)`),t.push(` Duration: ${e.durationMs}ms`),t.push(` Speedup: ${e.speedupFactor.toFixed(2)}x vs sequential`),t.push(` Peak concurrency: ${e.peakConcurrency}`),t.push(` Average tool latency: ${e.averageLatencyMs}ms`),e.dedupedCount>0&&t.push(` Deduped: ${e.dedupedCount} duplicate calls`),e.timeoutCount>0&&t.push(` Timeouts: ${e.timeoutCount}`),e.cancelledCount>0&&t.push(` Cancelled: ${e.cancelledCount}`),Object.keys(e.perToolLatency).length>0){t.push(`
1263
+ ${h}`,timestamp:new Date().toISOString()},...o.slice(-Jt.preserveRecent)],d+=g.length,c.summarize=(c.summarize||0)+g.length}}catch{}let p=Oi(o),m=r>0?(1-p/r)*100:0;fn.totalOptimizations++,fn.totalTokensSaved+=r-p,fn.totalQualityLoss+=1-f;for(let[g,h]of Object.entries(c))fn.strategiesUsed[g]=(fn.strategiesUsed[g]||0)+h;return fn.averageReductionPercent=(fn.averageReductionPercent*(fn.totalOptimizations-1)+m)/fn.totalOptimizations,{optimizedMessages:o,originalTokenCount:r,finalTokenCount:p,reductionPercent:m,qualityScore:Math.max(0,f),compressedCount:d,removedCount:u,strategiesApplied:c,perMessageDecisions:l,snapshot:Jt.enableSnapshot?Hb.get(i):void 0,durationMs:Date.now()-n,passes:a}}function vde(e,t){let n=new Set;for(let o of e){let a=o.content.toLowerCase().split(/\s+/).filter(c=>c.length>5);for(let c of a.slice(0,50))n.add(c)}let r=t.map(o=>o.content).join(" ").toLowerCase(),s=0,i=[];for(let o of n)r.includes(o)?s++:i.length<10&&i.push(o);return{preservedFacts:s,totalFacts:n.size,retentionScore:n.size>0?s/n.size:1,missingTopics:i}}function Sde(e){return Hb.get(e)||null}function wde(){Hb.clear()}function kde(){return{...Jt}}function Ko(e){Jt={...Jt,...e}}function xde(){return{...fn,strategiesUsed:{...fn.strategiesUsed}}}function $de(){fn.totalOptimizations=0,fn.totalTokensSaved=0,fn.totalQualityLoss=0,fn.strategiesUsed={},fn.averageReductionPercent=0,fn.totalSummaryCalls=0}function Cde(e){let t=e.toLowerCase();t.includes("claude")?t.includes("opus")?Ko({modelContextWindow:2e5}):Ko({modelContextWindow:2e5}):t.includes("gemini")?t.includes("pro")?Ko({modelContextWindow:2e6}):t.includes("flash")?Ko({modelContextWindow:1e6}):Ko({modelContextWindow:1e6}):t.includes("gpt-4")?Ko({modelContextWindow:128e3}):Ko({modelContextWindow:2e5})}var sde,Jt,fn,Hb,tT=w(()=>{"use strict";sde={enabled:!0,targetUtilization:.7,modelContextWindow:2e5,reservedTokens:16e3,enableLLMSummary:!0,llmSummaryThreshold:5,preserveRecent:4,preserveSystem:!0,preserveUser:!0,enableReferenceTracking:!0,qualityFloor:.6,multiPass:!0,enableSnapshot:!0,debug:!1},Jt={...sde},fn={totalOptimizations:0,totalTokensSaved:0,totalQualityLoss:0,strategiesUsed:{},averageReductionPercent:0,totalSummaryCalls:0},Hb=new Map});var iT={};$(iT,{clearParallelStats:()=>Dde,executeParallel:()=>eB,executeParallelStream:()=>Ade,executeSubgroup:()=>Tde,formatParallelResult:()=>Fde,getAdaptiveConcurrency:()=>_de,getAdaptiveState:()=>Pde,getParallelStats:()=>Ede,recordAdaptiveResult:()=>Rde,recordParallelRun:()=>Mde});import{EventEmitter as Zj}from"events";async function eB(e,t,n={}){let r={...Xj,...n},s=Date.now();if(e.length===0)return tB();let i=new Gb(r),o=i.orderForFairness([...e]),a=0,c=0,l=0,u=new Set,d=i.getDedupCache(),f=null,p=!1;r.groupTimeoutMs&&(f=setTimeout(()=>{p=!0},r.groupTimeoutMs));let m=0,g=()=>i.getInFlight(),h=o.map(async M=>{let ee=d.key(M);r.enableDedup&&u.has(ee)&&a++,u.add(ee),r.onProgress?.({type:"started",toolCall:M,totalCount:o.length,completedCount:m,inFlightCount:g(),queuedCount:o.length-m-g()});let Ne=await i.execute(M,t);return m++,Ne.isError&&(Ne.output?.includes("Timeout")?c++:Ne.output?.includes("Cancelled")&&l++),r.onProgress?.({type:Ne.isError?"failed":"completed",toolCall:M,totalCount:o.length,completedCount:m,inFlightCount:g(),queuedCount:o.length-m-g(),durationMs:Ne.durationMs,error:Ne.isError?Ne.output:void 0}),r.onResult?.(Ne,M),Ne}),v=await Promise.all(h);f&&clearTimeout(f);let y=new Map(v.map(M=>[M.toolCallId,M])),b=e.map(M=>y.get(M.id)||{toolCallId:M.id,output:"Not executed",isError:!0,durationMs:0}),k=Date.now()-s,S=b.filter(M=>!M.isError).length,x=b.filter(M=>M.isError).length,A=b.reduce((M,ee)=>M+(ee.durationMs||0),0),D=k>0?A/k:1;return{results:b,durationMs:k,successCount:S,failureCount:x,cancelledCount:l,timeoutCount:c,dedupedCount:a,peakConcurrency:i.getLatencyTracker().getPeak(),averageLatencyMs:Math.round(i.getLatencyTracker().getAverageLatency()),perToolLatency:i.getLatencyTracker().getStats(),speedupFactor:D}}function tB(){return{results:[],durationMs:0,successCount:0,failureCount:0,cancelledCount:0,timeoutCount:0,dedupedCount:0,peakConcurrency:0,averageLatencyMs:0,perToolLatency:{},speedupFactor:1}}async function*Ade(e,t,n={}){let r={...Xj,...n,yieldAsCompleted:!0},s=Date.now();if(e.length===0)return tB();let i=new Gb(r),o=i.orderForFairness([...e]),a=[],c=new Zj,l=0,u=0,d=0,f=0,p=new Set,m=o.map(async k=>{let S=`${k.name}:${JSON.stringify(k.input)}`;r.enableDedup&&p.has(S)&&f++,p.add(S);let x=await i.execute(k,t);return x.isError&&(x.output?.includes("Timeout")?u++:x.output?.includes("Cancelled")&&d++),a.push({call:k,result:x}),l++,c.emit("done"),l===o.length&&c.emit("all_done"),x});for(;l<o.length||a.length>0;)for(a.length===0&&await new Promise(k=>c.once("done",k));a.length>0;)yield a.shift();let g=await Promise.all(m),h=Date.now()-s,v=g.filter(k=>!k.isError).length,y=g.filter(k=>k.isError).length,b=g.reduce((k,S)=>k+(S.durationMs||0),0);return{results:g,durationMs:h,successCount:v,failureCount:y,cancelledCount:d,timeoutCount:u,dedupedCount:f,peakConcurrency:i.getLatencyTracker().getPeak(),averageLatencyMs:Math.round(i.getLatencyTracker().getAverageLatency()),perToolLatency:i.getLatencyTracker().getStats(),speedupFactor:h>0?b/h:1}}function Tde(e,t,n={}){let r=new AbortController,s=`sg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,i=eB(e,t,{...n,abortSignal:r.signal});return{id:s,cancel:()=>r.abort(),promise:i}}function _de(){return $d.getCurrent()}function Rde(e,t){$d.recordResult(e,t)}function Pde(){return $d.getState()}function Mde(e){Kn.push(e),Kn.length>Ide&&Kn.shift();for(let t of e.results)$d.recordResult(t.durationMs||0,!!t.isError)}function Ede(){if(Kn.length===0)return{totalRuns:0,totalToolCalls:0,totalSpeedup:0,averageSpeedup:1,averageDurationMs:0,totalDedupSavings:0,totalTimeouts:0,totalCancellations:0,topSlowestTools:[],adaptiveConcurrency:$d.getCurrent()};let e=Kn.reduce((c,l)=>c+l.results.length,0),t=Kn.reduce((c,l)=>c+l.speedupFactor,0),n=Kn.reduce((c,l)=>c+l.durationMs,0),r=Kn.reduce((c,l)=>c+l.dedupedCount,0),s=Kn.reduce((c,l)=>c+l.timeoutCount,0),i=Kn.reduce((c,l)=>c+l.cancelledCount,0),o=new Map;for(let c of Kn)for(let[l,u]of Object.entries(c.perToolLatency)){o.has(l)||o.set(l,{p95s:[],counts:0});let d=o.get(l);d.p95s.push(u.p95),d.counts+=u.count}let a=Array.from(o.entries()).map(([c,l])=>({name:c,p95:l.p95s.reduce((u,d)=>u+d,0)/l.p95s.length,count:l.counts})).sort((c,l)=>l.p95-c.p95).slice(0,5);return{totalRuns:Kn.length,totalToolCalls:e,totalSpeedup:t,averageSpeedup:t/Kn.length,averageDurationMs:Math.round(n/Kn.length),totalDedupSavings:r,totalTimeouts:s,totalCancellations:i,topSlowestTools:a,adaptiveConcurrency:$d.getCurrent()}}function Dde(){Kn.length=0}function Fde(e){let t=[];if(t.push("Parallel execution complete:"),t.push(` Tools: ${e.results.length} (${e.successCount} \u2713, ${e.failureCount} \u2717)`),t.push(` Duration: ${e.durationMs}ms`),t.push(` Speedup: ${e.speedupFactor.toFixed(2)}x vs sequential`),t.push(` Peak concurrency: ${e.peakConcurrency}`),t.push(` Average tool latency: ${e.averageLatencyMs}ms`),e.dedupedCount>0&&t.push(` Deduped: ${e.dedupedCount} duplicate calls`),e.timeoutCount>0&&t.push(` Timeouts: ${e.timeoutCount}`),e.cancelledCount>0&&t.push(` Cancelled: ${e.cancelledCount}`),Object.keys(e.perToolLatency).length>0){t.push(`
1266
1264
  Per-tool latency:`);for(let[n,r]of Object.entries(e.perToolLatency))t.push(` ${n}: ${r.count}x, mean=${r.mean}ms, p95=${r.p95}ms`)}return t.join(`
1267
1265
  `)}var Xj,Om,nT,rT,Gb,sT,$d,Kn,Ide,oT=w(()=>{"use strict";Ls();Xj={maxConcurrency:10,toolLimits:{bash:1,powershell:1,file_write:1,file_edit:1,file_read:8,grep:6,glob:4,web_fetch:5,web_search:5,code_search:4,image_read:3,agent:2},defaultPerToolLimit:4,enableDedup:!0,enableFairness:!0,yieldAsCompleted:!0,partialOnCancel:!0,toolTimeoutMs:6e4},Om=class{constructor(t){this.max=t;this.permits=t}max;permits;waiting=[];async acquire(){if(this.permits>0){this.permits--;return}return new Promise(t=>this.waiting.push(t))}release(){let t=this.waiting.shift();t?t():this.permits=Math.min(this.permits+1,this.max)}available(){return this.permits}inUse(){return this.max-this.permits}},nT=class{samples=new Map;peak=0;currentInFlight=0;record(t,n){this.samples.has(t)||this.samples.set(t,[]);let r=this.samples.get(t);r.push(n),r.length>1e3&&r.shift()}setInFlight(t){this.currentInFlight=t,t>this.peak&&(this.peak=t)}getPeak(){return this.peak}getStats(){let t={};for(let[n,r]of this.samples){if(r.length===0)continue;let s=[...r].sort((o,a)=>o-a),i=r.reduce((o,a)=>o+a,0);t[n]={count:r.length,mean:Math.round(i/r.length),p50:s[Math.floor(s.length*.5)],p95:s[Math.floor(s.length*.95)],p99:s[Math.floor(s.length*.99)],min:s[0],max:s[s.length-1]}}return t}getAverageLatency(){let t=0,n=0;for(let r of this.samples.values())t+=r.reduce((s,i)=>s+i,0),n+=r.length;return n>0?t/n:0}},rT=class{inflight=new Map;key(t){return`${t.name}:${JSON.stringify(t.input)}`}has(t){return this.inflight.has(this.key(t))}get(t){return this.inflight.get(this.key(t))}set(t,n){let r=this.key(t);this.inflight.set(r,n),n.finally(()=>this.inflight.delete(r))}size(){return this.inflight.size}},Gb=class{constructor(t){this.options=t;this.globalSem=new Om(t.maxConcurrency);for(let[n,r]of Object.entries(t.toolLimits))this.toolSems.set(n,new Om(r))}options;globalSem;toolSems=new Map;latency=new nT;dedup=new rT;fairnessIndex=new Map;events=new Zj;getToolSem(t){let n=this.toolSems.get(t);return n||(n=new Om(this.options.defaultPerToolLimit),this.toolSems.set(t,n)),n}async execute(t,n){if(this.options.enableDedup){let s=this.dedup.get(t);if(s)return{...await s,toolCallId:t.id}}let r=this.executeInner(t,n);return this.options.enableDedup&&this.dedup.set(t,r),r}async executeInner(t,n){let r=wr(t.name);if(!r)return{toolCallId:t.id,output:`Error: Tool "${t.name}" not found.`,isError:!0,durationMs:0};let s=this.getToolSem(t.name);await s.acquire(),await this.globalSem.acquire(),this.latency.setInFlight(this.globalSem.inUse());let i=Date.now();try{let o=await Promise.race([r.handler(t.input,{...n,abortSignal:this.options.abortSignal}),new Promise((c,l)=>{let u=setTimeout(()=>l(new Error("TIMEOUT")),this.options.toolTimeoutMs);this.options.abortSignal?.addEventListener("abort",()=>{clearTimeout(u),l(new Error("ABORTED"))},{once:!0})})]),a=Date.now()-i;return this.latency.record(t.name,a),{toolCallId:t.id,output:o,durationMs:a}}catch(o){let a=Date.now()-i;this.latency.record(t.name,a);let c=o.message==="TIMEOUT",l=o.message==="ABORTED"||this.options.abortSignal?.aborted;return{toolCallId:t.id,output:c?`Timeout after ${this.options.toolTimeoutMs}ms`:l?"Cancelled":`Error: ${o.message||String(o)}`,isError:!0,durationMs:a}}finally{this.globalSem.release(),s.release(),this.latency.setInFlight(this.globalSem.inUse())}}orderForFairness(t){if(!this.options.enableFairness)return t;let n=new Map;for(let i of t)n.has(i.name)||n.set(i.name,[]),n.get(i.name).push(i);let r=[],s=!0;for(;s;){s=!1;for(let i of n.values())i.length>0&&(r.push(i.shift()),s=!0)}return r}getLatencyTracker(){return this.latency}getDedupCache(){return this.dedup}getInFlight(){return this.globalSem.inUse()}};sT=class{state={current:8,min:2,max:32,recentLatencies:[],recentErrors:0};recordResult(t,n){this.state.recentLatencies.push(t),this.state.recentLatencies.length>50&&this.state.recentLatencies.shift(),n&&this.state.recentErrors++,this.adapt()}adapt(){if(this.state.recentLatencies.length<10)return;let t=this.state.recentLatencies.reduce((r,s)=>r+s,0)/this.state.recentLatencies.length,n=this.state.recentErrors/this.state.recentLatencies.length;t>5e3||n>.2?(this.state.current=Math.max(this.state.min,this.state.current-1),this.state.recentErrors=Math.max(0,this.state.recentErrors-5)):t<500&&n<.05&&(this.state.current=Math.min(this.state.max,this.state.current+1))}getCurrent(){return this.state.current}getState(){return{...this.state,recentLatencies:[...this.state.recentLatencies]}}},$d=new sT;Kn=[],Ide=100});var dT={};$(dT,{classifyTool:()=>Vb,executeOrchestrated:()=>qde,formatOrchestrationStats:()=>zde,getAggregateStats:()=>Jde,getOrchestrationConfig:()=>Kde,recordOrchestration:()=>Vde,resetConfig:()=>Yde,setOrchestrationConfig:()=>Wde});function Vb(e){return Lde[e]||"pure"}function Ode(e,t){let n=Vb(e.name),r=Vb(t.name);if(n==="read"&&r==="read")return{conflict:!1};if(n==="pure"&&r==="pure")return{conflict:!1};let s=String(e.input.path||""),i=String(t.input.path||"");if(s&&i&&s===i&&(n==="write"||r==="write"))return{conflict:!0,reason:`Same file: ${s}`};if(n==="write"&&r==="write")return{conflict:!0,reason:"Two writes"};if(n==="shell"||r==="shell"){let o=String((n==="shell"?e.input.command:t.input.command)||""),a=n==="write"?s:i;if(a&&o.includes(a))return{conflict:!0,reason:`Shell affects ${a}`}}return n==="side_effect"||r==="side_effect"?{conflict:!0,reason:"Side effect"}:n==="shell"&&r==="shell"?{conflict:!0,reason:"Two shell commands"}:{conflict:!1}}function jde(e,t){let n=e.map(r=>({call:r,category:Vb(r.name),dependencies:new Set,dependents:new Set,status:"pending",attempt:0}));if(!t.enableConflictDetection)return n;for(let r=0;r<n.length;r++)for(let s=r+1;s<n.length;s++)Ode(n[r].call,n[s].call).conflict&&(n[s].dependencies.add(r),n[r].dependents.add(s));return n}async function nB(e,t,n,r){let s,i=wr(e.name);if(!i)return{toolCallId:e.id,output:`Error: Tool "${e.name}" not found.`,isError:!0,durationMs:0};for(let o=0;o<n.retryConfig.maxAttempts;o++){if(r?.aborted)return{toolCallId:e.id,output:"Cancelled",isError:!0,durationMs:0};let a=Date.now();try{let c=await Promise.race([i.handler(e.input,{...t,abortSignal:r}),new Promise((l,u)=>setTimeout(()=>u(new Error(`Tool timeout after ${n.timeoutMs}ms`)),n.timeoutMs))]);return{toolCallId:e.id,output:c,durationMs:Date.now()-a}}catch(c){if(s=c,!n.enableRetries||o===n.retryConfig.maxAttempts-1||c.message?.includes("timeout")||c.message?.includes("cancelled"))break;let l=n.retryConfig.backoffMs*Math.pow(2,o)*(.85+Math.random()*.3);await new Promise(u=>setTimeout(u,l))}}return{toolCallId:e.id,output:`Error: ${s?.message||"Tool execution failed"}`,isError:!0,durationMs:0}}async function Bde(e,t,n,r){let s=new lT(n),i=new cT,o={toolsExecuted:0,successCount:0,failureCount:0,retryCount:0,cancelledCount:0,durationByTool:{},parallelismHistory:[]},a=0;for(let f=0;f<e.length;f++)e[f].dependencies.size===0&&i.push(f,aT[e[f].category]);a=e.reduce((f,p)=>f+p.dependencies.size,0);let c=new Set,l=setInterval(()=>{o.parallelismHistory.push(s.getStats().total)},100);for(;(!i.isEmpty()||c.size>0)&&!r?.aborted;){for(;!i.isEmpty();){let f=i.pop(),p=e[f];if(!s.canRun(p.category)){i.push(f,aT[p.category]);break}s.acquire(p.category),p.status="running",p.startTime=Date.now();let m=nB(p.call,t,n,r).then(g=>{p.endTime=Date.now(),p.result=g,p.status=g.isError?"failed":"completed",o.toolsExecuted++,g.isError?o.failureCount++:o.successCount++,o.durationByTool[p.call.name]||(o.durationByTool[p.call.name]=[]),o.durationByTool[p.call.name].push(g.durationMs||0),s.release(p.category);for(let h of p.dependents){let v=e[h];if(n.failureMode==="fail_fast"&&g.isError){v.status="cancelled",o.cancelledCount++;continue}[...v.dependencies].every(b=>e[b].status==="completed"||e[b].status==="failed")&&v.status==="pending"&&i.push(h,aT[v.category])}}).catch(()=>{s.release(p.category),o.failureCount++}).finally(()=>{c.delete(m)});c.add(m)}c.size>0&&await Promise.race(c)}clearInterval(l);let u,d;for(let[f,p]of Object.entries(o.durationByTool)){let m=p.reduce((g,h)=>g+h,0)/p.length;(!u||m>u.durationMs)&&(u={name:f,durationMs:m}),(!d||m<d.durationMs)&&(d={name:f,durationMs:m})}return o.longestTool=u,o.shortestTool=d,{metrics:o,conflictsResolved:a}}async function Nde(e,t,n,r){let s={toolsExecuted:0,successCount:0,failureCount:0,retryCount:0,cancelledCount:0,durationByTool:{},parallelismHistory:[]};for(let i of e){if(r?.aborted){i.status="cancelled",s.cancelledCount++;continue}i.status="running",i.startTime=Date.now();let o=await nB(i.call,t,n,r);if(i.endTime=Date.now(),i.result=o,i.status=o.isError?"failed":"completed",s.toolsExecuted++,o.isError){if(s.failureCount++,n.failureMode==="fail_fast")break}else s.successCount++;s.durationByTool[i.call.name]||(s.durationByTool[i.call.name]=[]),s.durationByTool[i.call.name].push(o.durationMs||0)}return{metrics:s,conflictsResolved:0}}async function qde(e,t,n={}){let r={...uT,...n},s=Date.now();if(e.length===0)return Ude(0);let i=jde(e,r),o;r.mode==="sequential"||e.length===1?o=await Nde(i,t,r,t.abortSignal):o=await Bde(i,t,r,t.abortSignal);let a=Date.now()-s,c=i.reduce((g,h)=>g+((h.endTime||0)-(h.startTime||0)),0),l=Math.max(0,c-a),u=c>0?a/c:1,d,f=0;for(let[g,h]of Object.entries(o.metrics.durationByTool)){let v=h.reduce((y,b)=>y+b,0);v>f&&(f=v,d=g)}let p=new Map;for(let g of i)g.result&&p.set(g.call.id,g.result);return{results:e.map(g=>p.get(g.id)||{toolCallId:g.id,output:"Not executed",isError:!0,durationMs:0}),totalDurationMs:a,parallelSavingsMs:l,efficiency:u,batchCount:Hde(i),conflictsResolved:o.conflictsResolved,retriesAttempted:o.metrics.retryCount,bottleneckTool:d,metrics:o.metrics}}function Ude(e){return{results:[],totalDurationMs:e,parallelSavingsMs:0,efficiency:1,batchCount:0,conflictsResolved:0,retriesAttempted:0,metrics:{toolsExecuted:0,successCount:0,failureCount:0,retryCount:0,cancelledCount:0,durationByTool:{},parallelismHistory:[]}}}function Hde(e){let t=new Map;function n(r){if(t.has(r))return t.get(r);let s=e[r];if(s.dependencies.size===0)return t.set(r,0),0;let o=Math.max(...[...s.dependencies].map(a=>n(a)))+1;return t.set(r,o),o}for(let r=0;r<e.length;r++)n(r);return new Set(t.values()).size}function zde(e){let t=[];if(t.push("Orchestration Result:"),t.push(` Tools executed: ${e.metrics.toolsExecuted} (${e.metrics.successCount} \u2713, ${e.metrics.failureCount} \u2717)`),t.push(` Total duration: ${e.totalDurationMs}ms`),t.push(` Parallel savings: ${e.parallelSavingsMs}ms`),t.push(` Efficiency: ${(e.efficiency*100).toFixed(1)}% (lower = better parallelism)`),t.push(` Batches: ${e.batchCount}`),t.push(` Conflicts: ${e.conflictsResolved} serialized`),e.retriesAttempted>0&&t.push(` Retries: ${e.retriesAttempted}`),e.bottleneckTool&&t.push(` Bottleneck: ${e.bottleneckTool}`),e.metrics.parallelismHistory.length>0){let n=e.metrics.parallelismHistory.reduce((s,i)=>s+i,0)/e.metrics.parallelismHistory.length,r=Math.max(...e.metrics.parallelismHistory);t.push(` Avg concurrency: ${n.toFixed(1)}, peak: ${r}`)}return t.join(`
1268
1266
  `)}function Vde(e){Ys.push(e),Ys.length>Gde&&Ys.shift()}function Jde(){if(Ys.length===0)return{totalRuns:0,avgEfficiency:1,avgParallelism:0,totalToolsExecuted:0,totalSavingsMs:0,topBottlenecks:[]};let e=Ys.length,t=Ys.reduce((a,c)=>a+c.efficiency,0)/e,n=Ys.reduce((a,c)=>a+c.metrics.toolsExecuted,0),r=Ys.reduce((a,c)=>a+c.parallelSavingsMs,0),s={};for(let a of Ys)a.bottleneckTool&&(s[a.bottleneckTool]=(s[a.bottleneckTool]||0)+1);let i=0,o=0;for(let a of Ys)a.metrics.parallelismHistory.length>0&&(i+=a.metrics.parallelismHistory.reduce((c,l)=>c+l,0)/a.metrics.parallelismHistory.length,o++);return i=o>0?i/o:0,{totalRuns:e,avgEfficiency:t,avgParallelism:i,totalToolsExecuted:n,totalSavingsMs:r,topBottlenecks:Object.entries(s).sort((a,c)=>c[1]-a[1]).slice(0,5).map(([a,c])=>({tool:a,count:c}))}}function Wde(e){Jb={...Jb,...e}}function Kde(){return{...Jb}}function Yde(){Jb={...uT}}var uT,Lde,cT,aT,lT,Ys,Gde,Jb,fT=w(()=>{"use strict";Ls();uT={mode:"adaptive",maxConcurrency:8,maxConcurrencyPerCategory:{read:10,write:1,shell:2,network:5,agent:3,side_effect:1,pure:20},enableConflictDetection:!0,enableSpeculative:!1,enableRetries:!0,failureMode:"continue",timeoutMs:6e4,retryConfig:{maxAttempts:2,backoffMs:1e3}},Lde={file_read:"read",grep:"read",glob:"read",tool_search:"read",task_get:"read",task_list:"read",cron_list:"read",config_read:"read",image_read:"read",skill_search:"read",file_write:"write",file_edit:"write",doc_create:"write",notebook_edit:"write",bash:"shell",powershell:"shell",web_fetch:"network",web_search:"network",clipboard_image:"network",agent:"agent",skill:"agent",task_create:"side_effect",task_stop:"side_effect",send_message:"side_effect",team_create:"side_effect",team_delete:"side_effect",cron_create:"side_effect",cron_delete:"side_effect",enter_worktree:"side_effect",exit_worktree:"side_effect"};cT=class{items=[];push(t,n){this.items.push({item:t,priority:n}),this.items.sort((r,s)=>s.priority-r.priority)}pop(){return this.items.shift()?.item}size(){return this.items.length}isEmpty(){return this.items.length===0}},aT={read:10,pure:9,network:7,agent:6,shell:5,write:4,side_effect:3},lT=class{constructor(t){this.config=t}config;active=new Map;total=0;canRun(t){if(this.total>=this.config.maxConcurrency)return!1;let r=this.config.maxConcurrencyPerCategory[t]??this.config.maxConcurrency;return(this.active.get(t)||0)<r}acquire(t){this.active.set(t,(this.active.get(t)||0)+1),this.total++}release(t){this.active.set(t,Math.max(0,(this.active.get(t)||0)-1)),this.total=Math.max(0,this.total-1)}getStats(){return{total:this.total,perCategory:Object.fromEntries(this.active)}}};Ys=[],Gde=100;Jb={...uT}});var pT={};$(pT,{clearBenchmarkHistory:()=>dfe,extractMemories:()=>cfe,getBenchmark:()=>ufe,recordBenchmark:()=>lfe});function Zde(e){return e.map((t,n)=>({role:t.role,content:t.content,index:n})).filter(t=>!(t.content.startsWith("<tool_result")||t.content.trim().length<30||/^\[Calling: /.test(t.content)))}function efe(e){let t=[],n=[],r=[],s=[],i=/(?:[a-zA-Z]:[\\/]|\.\.?\/|\/)?[\w./-]+\.(ts|tsx|js|jsx|py|rs|go|java|cpp|c|h|json|yaml|yml|md|toml|sh|sql)\b/g;for(let c of e.matchAll(i))t.push(c[0]);let o=/\b(npm|pip|cargo|yarn|pnpm|git|docker|make|cmake|gradle|maven)\s+\w+/gi;for(let c of e.matchAll(o))n.push(c[0]);for(let c of Xde)for(let l of e.matchAll(c))r.push(l[0].toLowerCase());let a=/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+){1,2}\b/g;for(let c of e.matchAll(a))/^(I|You|We|The|This|That)\s/.test(c[0])||s.push(c[0]);return{files:Wb(t).slice(0,20),tools:Wb(n).slice(0,10),technologies:Wb(r).slice(0,10),concepts:Wb(s).slice(0,10)}}function Wb(e){return[...new Set(e)]}async function nfe(e,t,n,r){if(e.length===0)return[];let s=e.slice(-12).map(a=>`[${a.role}] ${a.content.slice(0,600)}`).join(`
@@ -1307,11 +1305,11 @@ EXTRACTION RULES:
1307
1305
  OUTPUT: Return STRICTLY valid JSON array. No markdown, no preamble.
1308
1306
  Format: [{"content": "...", "category": "...", "confidence": 0.0-1.0, "entities": ["..."], "intent": "...", "evidence": "..."}]
1309
1307
 
1310
- If no facts qualify, return: []`;ji=[]});var Ad={};$(Ad,{canExecute:()=>Sfe,computeBackoff:()=>xfe,configure:()=>_fe,formatCircuit:()=>Dfe,generateComplianceReport:()=>Efe,getAuditLog:()=>Mfe,getCircuit:()=>Afe,getConfig:()=>Tfe,getEvents:()=>Ife,getStats:()=>Rfe,listCircuits:()=>cB,recordFailure:()=>kfe,recordSuccess:()=>wfe,reset:()=>aB,resetAll:()=>Cfe,resetStats:()=>Pfe,trip:()=>$fe});import{existsSync as gT,mkdirSync as ffe,readFileSync as hT,writeFileSync as ST}from"fs";import{join as Yb}from"path";import{homedir as pfe}from"os";import{EventEmitter as mfe}from"events";function Zb(){ffe(Qb,{recursive:!0})}function hfe(){if(Zb(),gT(yT))try{re={...re,...JSON.parse(hT(yT,"utf-8"))}}catch{}if(gT(vT))try{let e=JSON.parse(hT(vT,"utf-8"));for(let[t,n]of Object.entries(e))Kb.set(t,n)}catch{}}function Xb(){Zb();try{ST(yT,JSON.stringify(re,null,2),"utf-8")}catch{}}function yfe(){Zb();let e={};for(let[t,n]of Kb.entries())e[t]=n;try{ST(vT,JSON.stringify(e,null,2),"utf-8")}catch{}}function iB(e){if(ge.enableAuditLog){Zb();try{ST(bT,JSON.stringify({...e,timestamp:Date.now()})+`
1311
- `,{flag:"a"})}catch{}}}function wT(e,t){let n=hs.get(e);if(!n&&(n={id:e,config:{failureThreshold:ge.defaultFailureThreshold,successThreshold:ge.defaultSuccessThreshold,timeoutMs:ge.defaultTimeoutMs,windowSizeMs:ge.defaultWindowSizeMs,windowFailureRate:ge.defaultWindowFailureRate,initialBackoffMs:ge.defaultInitialBackoffMs,maxBackoffMs:ge.defaultMaxBackoffMs,backoffMultiplier:ge.defaultBackoffMultiplier,enableJitter:ge.defaultEnableJitter},metrics:{totalCalls:0,totalFailures:0,totalSuccesses:0,consecutiveFailures:0,consecutiveSuccesses:0,windowFailures:[],windowSuccesses:[],state:"closed",stateChangedAt:Date.now(),healthScore:1},parentId:t,childIds:new Set,failurePatterns:new Map},hs.set(e,n),t)){let r=hs.get(t);r&&r.childIds.add(e)}return n}function Cd(e,t,n){if(e.metrics.state===t)return;let r=e.metrics.state;e.metrics.state=t,e.metrics.stateChangedAt=Date.now(),t==="open"?(e.metrics.openedAt=Date.now(),re.totalCircuitOpens++,re.byCircuit[e.id]||(re.byCircuit[e.id]={calls:0,failures:0,opens:0}),re.byCircuit[e.id].opens++):t==="closed"&&r!=="closed"&&(re.totalCircuitCloses++,e.metrics.consecutiveFailures=0,e.metrics.consecutiveSuccesses=0),Xb(),iB({event:"circuit_transition",circuitId:e.id,from:r,to:t,reason:n}),jm.emit("state_changed",{circuit:e,oldState:r,newState:t,reason:n})}function bfe(e){if(e.metrics.consecutiveFailures>=e.config.failureThreshold)return{open:!0,reason:`${e.metrics.consecutiveFailures} consecutive failures`};let t=Date.now(),n=e.metrics.windowFailures.filter(i=>t-i<e.config.windowSizeMs).length,r=e.metrics.windowSuccesses.filter(i=>t-i<e.config.windowSizeMs).length,s=n+r;if(s>=10){let i=n/s;if(i>e.config.windowFailureRate)return{open:!0,reason:`Window failure rate ${(i*100).toFixed(0)}% > ${(e.config.windowFailureRate*100).toFixed(0)}%`}}return{open:!1,reason:""}}function vfe(e,t){if(!ge.enableAdaptiveThresholds)return;let n=Kb.get(e);if(!n){n={mean:t,stddev:0,samples:1},Kb.set(e,n);return}n.samples++;let r=t-n.mean;n.mean+=r/n.samples,n.stddev=Math.sqrt(((n.samples-1)*n.stddev*n.stddev+r*(t-n.mean))/n.samples),n.samples%50===0&&yfe()}function oB(e){if(!ge.enableHealthMonitoring)return;let t=Date.now(),n=e.metrics.totalCalls;if(n===0){e.metrics.healthScore=1;return}let r=e.metrics.totalSuccesses/n,s=e.metrics.windowFailures.filter(c=>t-c<e.config.windowSizeMs).length,i=e.metrics.windowSuccesses.filter(c=>t-c<e.config.windowSizeMs).length,o=s+i,a=o>0?i/o:1;e.metrics.healthScore=Math.max(0,Math.min(1,a*.7+r*.3))}function Sfe(e,t){if(!ge.enabled)return{allowed:!0,reason:"Breaker disabled",state:"closed",healthScore:1};let n=wT(e,t),r=Date.now();if(ge.enableCascadeDetection&&n.parentId){let s=hs.get(n.parentId);if(s&&s.metrics.state==="open")return{allowed:!1,reason:`Parent circuit "${s.id}" is open (cascade)`,state:"open",retryAfterMs:s.metrics.openedAt?Math.max(0,s.metrics.openedAt+s.config.timeoutMs-r):0,healthScore:n.metrics.healthScore}}if(n.metrics.state==="closed")return{allowed:!0,reason:"Circuit closed",state:"closed",healthScore:n.metrics.healthScore};if(n.metrics.state==="open"){if(n.metrics.openedAt&&r-n.metrics.openedAt>=n.config.timeoutMs)return Cd(n,"half_open","timeout elapsed"),{allowed:!0,reason:"Half-open probe",state:"half_open",healthScore:n.metrics.healthScore};let s=n.metrics.openedAt?Math.max(0,n.metrics.openedAt+n.config.timeoutMs-r):0;return{allowed:!1,reason:`Circuit open: ${n.metrics.consecutiveFailures} failures`,state:"open",retryAfterMs:s,healthScore:n.metrics.healthScore}}return{allowed:!0,reason:"Half-open probe",state:"half_open",healthScore:n.metrics.healthScore}}function wfe(e,t){if(!ge.enabled)return;let n=wT(e),r=Date.now();n.metrics.totalCalls++,n.metrics.totalSuccesses++,n.metrics.consecutiveSuccesses++,n.metrics.consecutiveFailures=0,n.metrics.lastSuccessAt=r,n.metrics.windowSuccesses.push(r),n.metrics.windowSuccesses=n.metrics.windowSuccesses.filter(s=>r-s<n.config.windowSizeMs),re.totalCalls++,re.totalSuccesses++,re.byCircuit[e]||(re.byCircuit[e]={calls:0,failures:0,opens:0}),re.byCircuit[e].calls++,n.metrics.state==="half_open"&&n.metrics.consecutiveSuccesses>=n.config.successThreshold&&(Cd(n,"closed",`${n.metrics.consecutiveSuccesses} successful probes`),re.totalAutoRecoveries++),t!==void 0&&vfe(e,t),oB(n),Xb()}function kfe(e,t,n,r){if(!ge.enabled)return;let s=wT(e,r),i=Date.now();s.metrics.totalCalls++,s.metrics.totalFailures++,s.metrics.consecutiveFailures++,s.metrics.consecutiveSuccesses=0,s.metrics.lastFailureAt=i,s.metrics.windowFailures.push(i),s.metrics.windowFailures=s.metrics.windowFailures.filter(a=>i-a<s.config.windowSizeMs);let o=n.slice(0,100);if(s.failurePatterns.set(o,(s.failurePatterns.get(o)||0)+1),re.totalCalls++,re.totalFailures++,re.byFailureType[t]=(re.byFailureType[t]||0)+1,re.byCircuit[e]||(re.byCircuit[e]={calls:0,failures:0,opens:0}),re.byCircuit[e].calls++,re.byCircuit[e].failures++,iB({event:"failure",circuitId:e,failureType:t,errorMessage:n.slice(0,200),consecutive:s.metrics.consecutiveFailures}),s.metrics.state==="closed"){let a=bfe(s);a.open&&(Cd(s,"open",a.reason),jm.emit("opened",{circuit:s,reason:a.reason}))}else s.metrics.state==="half_open"&&Cd(s,"open","half-open probe failed");if(ge.enableCascadeDetection&&s.metrics.state==="open")for(let a of s.childIds){let c=hs.get(a);c&&c.metrics.state==="closed"&&(re.totalCascadesDetected++,jm.emit("cascade_detected",{parentCircuitId:s.id,childCircuitId:a}))}oB(s),Xb()}function xfe(e,t){let r=hs.get(e)?.config||{initialBackoffMs:ge.defaultInitialBackoffMs,maxBackoffMs:ge.defaultMaxBackoffMs,backoffMultiplier:ge.defaultBackoffMultiplier,enableJitter:ge.defaultEnableJitter},s=Math.min(r.maxBackoffMs,r.initialBackoffMs*Math.pow(r.backoffMultiplier,t));return r.enableJitter&&(s=Math.random()*s),Math.floor(s)}function $fe(e,t="manual_trip"){let n=hs.get(e);return n?(Cd(n,"open",t),!0):!1}function aB(e){let t=hs.get(e);return t?(t.metrics.consecutiveFailures=0,t.metrics.consecutiveSuccesses=0,t.metrics.windowFailures=[],t.metrics.windowSuccesses=[],Cd(t,"closed","manual_reset"),!0):!1}function Cfe(){let e=0;for(let t of hs.values())t.metrics.state!=="closed"&&(aB(t.id),e++);return e}function Afe(e){return hs.get(e)}function cB(){return Array.from(hs.values())}function Tfe(){return{...ge}}function _fe(e){ge={...ge,...e}}function Rfe(){return{...re}}function Pfe(){re={totalCalls:0,totalFailures:0,totalSuccesses:0,totalCircuitOpens:0,totalCircuitCloses:0,totalCascadesDetected:0,totalAutoRecoveries:0,byCircuit:{},byFailureType:{}},Xb()}function Ife(){return jm}function Mfe(e=100){if(!gT(bT))return[];try{return hT(bT,"utf-8").split(`
1312
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Efe(){let e=[],t=cB();e.push("# Cascading Failure Circuit Breaker Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total circuits: ${t.length}`),e.push(`- Total calls: ${re.totalCalls}`),e.push(`- Total failures: ${re.totalFailures}`),e.push(`- Total successes: ${re.totalSuccesses}`),e.push(`- Total circuit opens: ${re.totalCircuitOpens}`),e.push(`- Total circuit closes: ${re.totalCircuitCloses}`),e.push(`- Total auto-recoveries: ${re.totalAutoRecoveries}`),e.push(`- Total cascades detected: ${re.totalCascadesDetected}`),e.push(""),e.push("## Circuits");for(let n of t.sort((r,s)=>r.metrics.healthScore-s.metrics.healthScore).slice(0,20)){let r=n.metrics.state==="closed"?"\u{1F7E2}":n.metrics.state==="half_open"?"\u{1F7E1}":"\u{1F534}",s=n.metrics.healthScore>.9?"\u2713":n.metrics.healthScore>.5?"\u26A0\uFE0F ":"\u{1F6A8}";e.push(` ${r} ${s} ${n.id.padEnd(30)} | ${n.metrics.state.padEnd(11)} | health=${n.metrics.healthScore.toFixed(2)} | ${n.metrics.totalCalls}c/${n.metrics.totalFailures}f`)}e.push(""),e.push("## Failure Types");for(let[n,r]of Object.entries(re.byFailureType).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Per-circuit state machine (closed/open/half-open)"),e.push("- \u2713 Sliding window failure tracking"),e.push(`- ${ge.enableAdaptiveThresholds?"\u2713":"\u2717"} Adaptive thresholds`),e.push(`- ${ge.enableCascadeDetection?"\u2713":"\u2717"} Cascade detection`),e.push(`- ${ge.enableAutoRecovery?"\u2713":"\u2717"} Auto-recovery (half-open probe)`),e.push(`- ${ge.enableHealthMonitoring?"\u2713":"\u2717"} Health score monitoring`),e.push("- \u2713 Exponential backoff with jitter"),e.push(`- Default failure threshold: ${ge.defaultFailureThreshold} consecutive`),e.push(`- Default window failure rate: ${(ge.defaultWindowFailureRate*100).toFixed(0)}%`),e.push(`- Default open timeout: ${(ge.defaultTimeoutMs/1e3).toFixed(0)}s`),e.join(`
1308
+ If no facts qualify, return: []`;ji=[]});var Ad={};$(Ad,{canExecute:()=>Sfe,computeBackoff:()=>xfe,configure:()=>_fe,formatCircuit:()=>Dfe,generateComplianceReport:()=>Efe,getAuditLog:()=>Mfe,getCircuit:()=>Afe,getConfig:()=>Tfe,getEvents:()=>Ife,getStats:()=>Rfe,listCircuits:()=>cB,recordFailure:()=>kfe,recordSuccess:()=>wfe,reset:()=>aB,resetAll:()=>Cfe,resetStats:()=>Pfe,trip:()=>$fe});import{existsSync as gT,mkdirSync as ffe,readFileSync as hT,writeFileSync as ST}from"fs";import{join as Yb}from"path";import{homedir as pfe}from"os";import{EventEmitter as mfe}from"events";function Zb(){ffe(Qb,{recursive:!0})}function hfe(){if(Zb(),gT(yT))try{se={...se,...JSON.parse(hT(yT,"utf-8"))}}catch{}if(gT(vT))try{let e=JSON.parse(hT(vT,"utf-8"));for(let[t,n]of Object.entries(e))Kb.set(t,n)}catch{}}function Xb(){Zb();try{ST(yT,JSON.stringify(se,null,2),"utf-8")}catch{}}function yfe(){Zb();let e={};for(let[t,n]of Kb.entries())e[t]=n;try{ST(vT,JSON.stringify(e,null,2),"utf-8")}catch{}}function iB(e){if(he.enableAuditLog){Zb();try{ST(bT,JSON.stringify({...e,timestamp:Date.now()})+`
1309
+ `,{flag:"a"})}catch{}}}function wT(e,t){let n=hs.get(e);if(!n&&(n={id:e,config:{failureThreshold:he.defaultFailureThreshold,successThreshold:he.defaultSuccessThreshold,timeoutMs:he.defaultTimeoutMs,windowSizeMs:he.defaultWindowSizeMs,windowFailureRate:he.defaultWindowFailureRate,initialBackoffMs:he.defaultInitialBackoffMs,maxBackoffMs:he.defaultMaxBackoffMs,backoffMultiplier:he.defaultBackoffMultiplier,enableJitter:he.defaultEnableJitter},metrics:{totalCalls:0,totalFailures:0,totalSuccesses:0,consecutiveFailures:0,consecutiveSuccesses:0,windowFailures:[],windowSuccesses:[],state:"closed",stateChangedAt:Date.now(),healthScore:1},parentId:t,childIds:new Set,failurePatterns:new Map},hs.set(e,n),t)){let r=hs.get(t);r&&r.childIds.add(e)}return n}function Cd(e,t,n){if(e.metrics.state===t)return;let r=e.metrics.state;e.metrics.state=t,e.metrics.stateChangedAt=Date.now(),t==="open"?(e.metrics.openedAt=Date.now(),se.totalCircuitOpens++,se.byCircuit[e.id]||(se.byCircuit[e.id]={calls:0,failures:0,opens:0}),se.byCircuit[e.id].opens++):t==="closed"&&r!=="closed"&&(se.totalCircuitCloses++,e.metrics.consecutiveFailures=0,e.metrics.consecutiveSuccesses=0),Xb(),iB({event:"circuit_transition",circuitId:e.id,from:r,to:t,reason:n}),jm.emit("state_changed",{circuit:e,oldState:r,newState:t,reason:n})}function bfe(e){if(e.metrics.consecutiveFailures>=e.config.failureThreshold)return{open:!0,reason:`${e.metrics.consecutiveFailures} consecutive failures`};let t=Date.now(),n=e.metrics.windowFailures.filter(i=>t-i<e.config.windowSizeMs).length,r=e.metrics.windowSuccesses.filter(i=>t-i<e.config.windowSizeMs).length,s=n+r;if(s>=10){let i=n/s;if(i>e.config.windowFailureRate)return{open:!0,reason:`Window failure rate ${(i*100).toFixed(0)}% > ${(e.config.windowFailureRate*100).toFixed(0)}%`}}return{open:!1,reason:""}}function vfe(e,t){if(!he.enableAdaptiveThresholds)return;let n=Kb.get(e);if(!n){n={mean:t,stddev:0,samples:1},Kb.set(e,n);return}n.samples++;let r=t-n.mean;n.mean+=r/n.samples,n.stddev=Math.sqrt(((n.samples-1)*n.stddev*n.stddev+r*(t-n.mean))/n.samples),n.samples%50===0&&yfe()}function oB(e){if(!he.enableHealthMonitoring)return;let t=Date.now(),n=e.metrics.totalCalls;if(n===0){e.metrics.healthScore=1;return}let r=e.metrics.totalSuccesses/n,s=e.metrics.windowFailures.filter(c=>t-c<e.config.windowSizeMs).length,i=e.metrics.windowSuccesses.filter(c=>t-c<e.config.windowSizeMs).length,o=s+i,a=o>0?i/o:1;e.metrics.healthScore=Math.max(0,Math.min(1,a*.7+r*.3))}function Sfe(e,t){if(!he.enabled)return{allowed:!0,reason:"Breaker disabled",state:"closed",healthScore:1};let n=wT(e,t),r=Date.now();if(he.enableCascadeDetection&&n.parentId){let s=hs.get(n.parentId);if(s&&s.metrics.state==="open")return{allowed:!1,reason:`Parent circuit "${s.id}" is open (cascade)`,state:"open",retryAfterMs:s.metrics.openedAt?Math.max(0,s.metrics.openedAt+s.config.timeoutMs-r):0,healthScore:n.metrics.healthScore}}if(n.metrics.state==="closed")return{allowed:!0,reason:"Circuit closed",state:"closed",healthScore:n.metrics.healthScore};if(n.metrics.state==="open"){if(n.metrics.openedAt&&r-n.metrics.openedAt>=n.config.timeoutMs)return Cd(n,"half_open","timeout elapsed"),{allowed:!0,reason:"Half-open probe",state:"half_open",healthScore:n.metrics.healthScore};let s=n.metrics.openedAt?Math.max(0,n.metrics.openedAt+n.config.timeoutMs-r):0;return{allowed:!1,reason:`Circuit open: ${n.metrics.consecutiveFailures} failures`,state:"open",retryAfterMs:s,healthScore:n.metrics.healthScore}}return{allowed:!0,reason:"Half-open probe",state:"half_open",healthScore:n.metrics.healthScore}}function wfe(e,t){if(!he.enabled)return;let n=wT(e),r=Date.now();n.metrics.totalCalls++,n.metrics.totalSuccesses++,n.metrics.consecutiveSuccesses++,n.metrics.consecutiveFailures=0,n.metrics.lastSuccessAt=r,n.metrics.windowSuccesses.push(r),n.metrics.windowSuccesses=n.metrics.windowSuccesses.filter(s=>r-s<n.config.windowSizeMs),se.totalCalls++,se.totalSuccesses++,se.byCircuit[e]||(se.byCircuit[e]={calls:0,failures:0,opens:0}),se.byCircuit[e].calls++,n.metrics.state==="half_open"&&n.metrics.consecutiveSuccesses>=n.config.successThreshold&&(Cd(n,"closed",`${n.metrics.consecutiveSuccesses} successful probes`),se.totalAutoRecoveries++),t!==void 0&&vfe(e,t),oB(n),Xb()}function kfe(e,t,n,r){if(!he.enabled)return;let s=wT(e,r),i=Date.now();s.metrics.totalCalls++,s.metrics.totalFailures++,s.metrics.consecutiveFailures++,s.metrics.consecutiveSuccesses=0,s.metrics.lastFailureAt=i,s.metrics.windowFailures.push(i),s.metrics.windowFailures=s.metrics.windowFailures.filter(a=>i-a<s.config.windowSizeMs);let o=n.slice(0,100);if(s.failurePatterns.set(o,(s.failurePatterns.get(o)||0)+1),se.totalCalls++,se.totalFailures++,se.byFailureType[t]=(se.byFailureType[t]||0)+1,se.byCircuit[e]||(se.byCircuit[e]={calls:0,failures:0,opens:0}),se.byCircuit[e].calls++,se.byCircuit[e].failures++,iB({event:"failure",circuitId:e,failureType:t,errorMessage:n.slice(0,200),consecutive:s.metrics.consecutiveFailures}),s.metrics.state==="closed"){let a=bfe(s);a.open&&(Cd(s,"open",a.reason),jm.emit("opened",{circuit:s,reason:a.reason}))}else s.metrics.state==="half_open"&&Cd(s,"open","half-open probe failed");if(he.enableCascadeDetection&&s.metrics.state==="open")for(let a of s.childIds){let c=hs.get(a);c&&c.metrics.state==="closed"&&(se.totalCascadesDetected++,jm.emit("cascade_detected",{parentCircuitId:s.id,childCircuitId:a}))}oB(s),Xb()}function xfe(e,t){let r=hs.get(e)?.config||{initialBackoffMs:he.defaultInitialBackoffMs,maxBackoffMs:he.defaultMaxBackoffMs,backoffMultiplier:he.defaultBackoffMultiplier,enableJitter:he.defaultEnableJitter},s=Math.min(r.maxBackoffMs,r.initialBackoffMs*Math.pow(r.backoffMultiplier,t));return r.enableJitter&&(s=Math.random()*s),Math.floor(s)}function $fe(e,t="manual_trip"){let n=hs.get(e);return n?(Cd(n,"open",t),!0):!1}function aB(e){let t=hs.get(e);return t?(t.metrics.consecutiveFailures=0,t.metrics.consecutiveSuccesses=0,t.metrics.windowFailures=[],t.metrics.windowSuccesses=[],Cd(t,"closed","manual_reset"),!0):!1}function Cfe(){let e=0;for(let t of hs.values())t.metrics.state!=="closed"&&(aB(t.id),e++);return e}function Afe(e){return hs.get(e)}function cB(){return Array.from(hs.values())}function Tfe(){return{...he}}function _fe(e){he={...he,...e}}function Rfe(){return{...se}}function Pfe(){se={totalCalls:0,totalFailures:0,totalSuccesses:0,totalCircuitOpens:0,totalCircuitCloses:0,totalCascadesDetected:0,totalAutoRecoveries:0,byCircuit:{},byFailureType:{}},Xb()}function Ife(){return jm}function Mfe(e=100){if(!gT(bT))return[];try{return hT(bT,"utf-8").split(`
1310
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Efe(){let e=[],t=cB();e.push("# Cascading Failure Circuit Breaker Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total circuits: ${t.length}`),e.push(`- Total calls: ${se.totalCalls}`),e.push(`- Total failures: ${se.totalFailures}`),e.push(`- Total successes: ${se.totalSuccesses}`),e.push(`- Total circuit opens: ${se.totalCircuitOpens}`),e.push(`- Total circuit closes: ${se.totalCircuitCloses}`),e.push(`- Total auto-recoveries: ${se.totalAutoRecoveries}`),e.push(`- Total cascades detected: ${se.totalCascadesDetected}`),e.push(""),e.push("## Circuits");for(let n of t.sort((r,s)=>r.metrics.healthScore-s.metrics.healthScore).slice(0,20)){let r=n.metrics.state==="closed"?"\u{1F7E2}":n.metrics.state==="half_open"?"\u{1F7E1}":"\u{1F534}",s=n.metrics.healthScore>.9?"\u2713":n.metrics.healthScore>.5?"\u26A0\uFE0F ":"\u{1F6A8}";e.push(` ${r} ${s} ${n.id.padEnd(30)} | ${n.metrics.state.padEnd(11)} | health=${n.metrics.healthScore.toFixed(2)} | ${n.metrics.totalCalls}c/${n.metrics.totalFailures}f`)}e.push(""),e.push("## Failure Types");for(let[n,r]of Object.entries(se.byFailureType).sort((s,i)=>i[1]-s[1]))e.push(`- ${n}: ${r}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 Per-circuit state machine (closed/open/half-open)"),e.push("- \u2713 Sliding window failure tracking"),e.push(`- ${he.enableAdaptiveThresholds?"\u2713":"\u2717"} Adaptive thresholds`),e.push(`- ${he.enableCascadeDetection?"\u2713":"\u2717"} Cascade detection`),e.push(`- ${he.enableAutoRecovery?"\u2713":"\u2717"} Auto-recovery (half-open probe)`),e.push(`- ${he.enableHealthMonitoring?"\u2713":"\u2717"} Health score monitoring`),e.push("- \u2713 Exponential backoff with jitter"),e.push(`- Default failure threshold: ${he.defaultFailureThreshold} consecutive`),e.push(`- Default window failure rate: ${(he.defaultWindowFailureRate*100).toFixed(0)}%`),e.push(`- Default open timeout: ${(he.defaultTimeoutMs/1e3).toFixed(0)}s`),e.join(`
1313
1311
  `)}function Dfe(e){let t=[],n=e.metrics.state==="closed"?"\u{1F7E2}":e.metrics.state==="half_open"?"\u{1F7E1}":"\u{1F534}";if(t.push(`${n} **${e.id}** (${e.metrics.state})`),t.push(` Health: ${e.metrics.healthScore.toFixed(2)}`),t.push(` Calls: ${e.metrics.totalCalls} (${e.metrics.totalSuccesses} \u2713, ${e.metrics.totalFailures} \u2717)`),t.push(` Consecutive failures: ${e.metrics.consecutiveFailures}/${e.config.failureThreshold}`),e.metrics.openedAt){let r=Date.now()-e.metrics.openedAt,s=Math.max(0,e.config.timeoutMs-r);t.push(` Open since: ${new Date(e.metrics.openedAt).toISOString()} (${(s/1e3).toFixed(0)}s remaining)`)}if(e.parentId&&t.push(` Parent: ${e.parentId}`),e.childIds.size>0&&t.push(` Children: ${e.childIds.size}`),e.failurePatterns.size>0){let r=Array.from(e.failurePatterns.entries()).sort((s,i)=>i[1]-s[1]).slice(0,3);t.push(" Top failures:");for(let[s,i]of r)t.push(` ${i}\xD7 ${s.slice(0,60)}`)}return t.join(`
1314
- `)}var gfe,ge,Qb,yT,bT,vT,jm,hs,Kb,re,Td=w(()=>{"use strict";gfe={enabled:!0,defaultFailureThreshold:5,defaultSuccessThreshold:2,defaultTimeoutMs:3e4,defaultWindowSizeMs:6e4,defaultWindowFailureRate:.5,defaultInitialBackoffMs:1e3,defaultMaxBackoffMs:6e4,defaultBackoffMultiplier:2,defaultEnableJitter:!0,enableAdaptiveThresholds:!0,adaptiveLearningRate:.1,enableCascadeDetection:!0,enableAutoRecovery:!0,enableHealthMonitoring:!0,enableAuditLog:!0},ge={...gfe},Qb=Yb(pfe(),".aiaca","circuit-breaker"),yT=Yb(Qb,"stats.json"),bT=Yb(Qb,"audit.jsonl"),vT=Yb(Qb,"adaptive-thresholds.json"),jm=new mfe;jm.setMaxListeners(100);hs=new Map,Kb=new Map,re={totalCalls:0,totalFailures:0,totalSuccesses:0,totalCircuitOpens:0,totalCircuitCloses:0,totalCascadesDetected:0,totalAutoRecoveries:0,byCircuit:{},byFailureType:{}};hfe()});var av={};$(av,{configure:()=>spe,formatValidationResult:()=>lpe,getAuditLog:()=>cpe,getConfig:()=>rpe,getSchema:()=>dB,getStats:()=>ipe,listSchemas:()=>ape,registerSchema:()=>zfe,resetStats:()=>ope,unregisterSchema:()=>Gfe,validateToolArguments:()=>tpe});import{existsSync as tv,mkdirSync as Ffe,readFileSync as kT,writeFileSync as rv}from"fs";import{join as sv,resolve as ev,isAbsolute as lB,normalize as Lfe}from"path";import{homedir as Ofe}from"os";import{createHash as jfe}from"crypto";import{URL as Bfe}from"url";function ov(){Ffe(iv,{recursive:!0})}function qfe(){if(ov(),tv($T))try{pn={...pn,...JSON.parse(kT($T,"utf-8"))}}catch{}if(tv(nv))try{let e=JSON.parse(kT(nv,"utf-8"));for(let t of e)jc.set(t.toolName,t)}catch{}}function AT(){ov();try{rv($T,JSON.stringify(pn,null,2),"utf-8")}catch{}}function Ufe(e){if(Ee.enableAuditLog){ov();try{rv(xT,JSON.stringify({...e,timestamp:Date.now()})+`
1312
+ `)}var gfe,he,Qb,yT,bT,vT,jm,hs,Kb,se,Td=w(()=>{"use strict";gfe={enabled:!0,defaultFailureThreshold:5,defaultSuccessThreshold:2,defaultTimeoutMs:3e4,defaultWindowSizeMs:6e4,defaultWindowFailureRate:.5,defaultInitialBackoffMs:1e3,defaultMaxBackoffMs:6e4,defaultBackoffMultiplier:2,defaultEnableJitter:!0,enableAdaptiveThresholds:!0,adaptiveLearningRate:.1,enableCascadeDetection:!0,enableAutoRecovery:!0,enableHealthMonitoring:!0,enableAuditLog:!0},he={...gfe},Qb=Yb(pfe(),".aiaca","circuit-breaker"),yT=Yb(Qb,"stats.json"),bT=Yb(Qb,"audit.jsonl"),vT=Yb(Qb,"adaptive-thresholds.json"),jm=new mfe;jm.setMaxListeners(100);hs=new Map,Kb=new Map,se={totalCalls:0,totalFailures:0,totalSuccesses:0,totalCircuitOpens:0,totalCircuitCloses:0,totalCascadesDetected:0,totalAutoRecoveries:0,byCircuit:{},byFailureType:{}};hfe()});var av={};$(av,{configure:()=>spe,formatValidationResult:()=>lpe,getAuditLog:()=>cpe,getConfig:()=>rpe,getSchema:()=>dB,getStats:()=>ipe,listSchemas:()=>ape,registerSchema:()=>zfe,resetStats:()=>ope,unregisterSchema:()=>Gfe,validateToolArguments:()=>tpe});import{existsSync as tv,mkdirSync as Ffe,readFileSync as kT,writeFileSync as rv}from"fs";import{join as sv,resolve as ev,isAbsolute as lB,normalize as Lfe}from"path";import{homedir as Ofe}from"os";import{createHash as jfe}from"crypto";import{URL as Bfe}from"url";function ov(){Ffe(iv,{recursive:!0})}function qfe(){if(ov(),tv($T))try{pn={...pn,...JSON.parse(kT($T,"utf-8"))}}catch{}if(tv(nv))try{let e=JSON.parse(kT(nv,"utf-8"));for(let t of e)jc.set(t.toolName,t)}catch{}}function AT(){ov();try{rv($T,JSON.stringify(pn,null,2),"utf-8")}catch{}}function Ufe(e){if(Ee.enableAuditLog){ov();try{rv(xT,JSON.stringify({...e,timestamp:Date.now()})+`
1315
1313
  `,{flag:"a"})}catch{}}}function dB(e){return jc.get(e)||Hfe.get(e)}function zfe(e){jc.set(e.toolName,e),ov();try{rv(nv,JSON.stringify(Array.from(jc.values()),null,2),"utf-8")}catch{}}function Gfe(e){let t=jc.delete(e);if(t)try{rv(nv,JSON.stringify(Array.from(jc.values()),null,2),"utf-8")}catch{}return t}function R(e,t,n,r,s,i,o=!0){return{id:jfe("md5").update(`${e}:${n}:${r}`).digest("hex").slice(0,12),type:e,severity:t,argumentName:n,message:r,evidence:s,suggestion:i,blocked:o}}function Vfe(e,t,n){let r=[];if(typeof e!="string")return r.push(R("type_mismatch","high",n,"Path must be a string")),{violations:r};let s=e,i=s;t.maxLength&&s.length>t.maxLength&&r.push(R("oversized_payload","high",n,`Path exceeds max length: ${s.length} > ${t.maxLength}`)),s.includes("\0")&&(r.push(R("null_byte","critical",n,"Path contains null byte",s.slice(0,100),"Strip \\0 characters")),i=i.replace(/\0/g,"")),(t.allowParentTraversal===!1||t.allowParentTraversal===void 0)&&/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(s)&&r.push(R("path_traversal","critical",n,"Path traversal detected (../ or ..\\)",s.slice(0,200),"Use absolute path or relative without ..")),t.allowAbsolute===!1&&lB(s)&&r.push(R("forbidden_value","medium",n,"Absolute paths not allowed for this tool"));for(let o of Ee.forbiddenPathPatterns)try{new RegExp(o,"i").test(s)&&r.push(R("sensitive_path","critical",n,`Path matches sensitive pattern: ${o}`,s.slice(0,200),"Avoid system or credential paths"))}catch{}if(t.withinDirectory)try{let o=ev(t.withinDirectory),a=ev(s);!a.startsWith(o+(process.platform==="win32"?"\\":"/"))&&a!==o&&r.push(R("forbidden_value","high",n,`Path outside allowed directory: ${t.withinDirectory}`))}catch{}if(Ee.allowedRootDirs.length>0&&lB(s)){let o=ev(s);Ee.allowedRootDirs.some(c=>o.startsWith(ev(c)))||r.push(R("forbidden_value","high",n,`Path outside allowed roots: ${Ee.allowedRootDirs.join(", ")}`))}t.mustExist&&!tv(s)&&r.push(R("forbidden_value","medium",n,`Path does not exist: ${s}`));try{i=Lfe(i)}catch{}return{violations:r,sanitized:i}}function Jfe(e,t,n){let r=[];if(typeof e!="string")return r.push(R("type_mismatch","high",n,"Command must be a string")),{violations:r};let s=e;t.maxLength&&s.length>t.maxLength&&r.push(R("oversized_payload","high",n,`Command exceeds max length: ${s.length}`)),s.includes("\0")&&r.push(R("null_byte","critical",n,"Command contains null byte"));let i=[{pattern:/\brm\s+-rf\s+\/(?!\w)/i,severity:"critical",reason:"Recursive root delete"},{pattern:/:\(\)\s*\{\s*:\|:\s*&\s*\}\s*;\s*:/,severity:"critical",reason:"Fork bomb"},{pattern:/\bdd\s+if=\/dev\/(?:zero|random|urandom)\s+of=/i,severity:"critical",reason:"Disk wipe"},{pattern:/\bmkfs\b/i,severity:"critical",reason:"Filesystem format"},{pattern:/\b(?:wget|curl)\b.*\|\s*(?:bash|sh|sudo|zsh|fish)/i,severity:"critical",reason:"Pipe to shell"},{pattern:/\beval\s+["'`]?\$/,severity:"high",reason:"eval with variable"},{pattern:/\b\.\s+(?:\/dev\/stdin|<\(.+\))/i,severity:"high",reason:"Source from stdin"},{pattern:/\bnc\s+-l/i,severity:"high",reason:"Netcat listener"},{pattern:/\b\/dev\/tcp\//i,severity:"high",reason:"Bash TCP socket"},{pattern:/\bbase64\s+-d\b.*\|\s*(?:bash|sh)/i,severity:"critical",reason:"Base64 decode + execute"},{pattern:/\bchmod\s+(?:777|\+x).*\.(?:sh|py|js|exe)/i,severity:"high",reason:"Make executable"},{pattern:/\bsudo\s+(?:rm|chmod|chown|dd|mkfs)/i,severity:"critical",reason:"Sudo with destructive command"},{pattern:/\bdrop\s+(?:database|table|schema)/i,severity:"high",reason:"Database drop"},{pattern:/\btruncate\s+(?:table|database)/i,severity:"high",reason:"Database truncate"},{pattern:/\bdel\s+\/[fsq]\s/i,severity:"high",reason:"Forced delete (Windows)"},{pattern:/\bformat\s+[a-z]:/i,severity:"critical",reason:"Drive format"},{pattern:/\bRemove-Item\s+.*-Recurse\s+-Force/i,severity:"high",reason:"PowerShell recursive force delete"},{pattern:/\b(?:Stop-Computer|Restart-Computer|shutdown)/i,severity:"high",reason:"System shutdown"}];for(let{pattern:u,severity:d,reason:f}of i)u.test(s)&&r.push(R("command_injection",d,n,`Dangerous command pattern: ${f}`,s.slice(0,200)));let o=(s.match(/;/g)||[]).length,a=(s.match(/\|(?!\|)/g)||[]).length,c=(s.match(/`/g)||[]).length,l=(s.match(/\$\(/g)||[]).length;return(c>=2||l>=2)&&r.push(R("command_injection","medium",n,"Multiple command substitutions detected (might be injection)",s.slice(0,200))),o+a>10&&r.push(R("command_injection","medium",n,`Excessive command chaining (${o+a} separators)`,s.slice(0,200))),/(?:%[0-9a-f]{2}){5,}/i.test(s)&&r.push(R("encoded_injection","high",n,"URL-encoded payload detected",s.slice(0,200))),(/\\x[0-9a-f]{2}/.test(s)||/\\[0-7]{3}/.test(s))&&r.push(R("encoded_injection","medium",n,"Hex/octal escape sequences in command")),{violations:r,sanitized:s.replace(/\0/g,"")}}function Wfe(e,t,n){let r=[];if(typeof e!="string")return r.push(R("type_mismatch","high",n,"URL must be a string")),{violations:r};let s;try{s=new Bfe(e)}catch{return r.push(R("invalid_url","high",n,`Malformed URL: ${e.slice(0,100)}`)),{violations:r}}if(t.allowedProtocols&&t.allowedProtocols.length>0){let i=s.protocol.replace(":","");t.allowedProtocols.includes(i)||r.push(R("forbidden_value","high",n,`Protocol "${i}" not allowed. Allowed: ${t.allowedProtocols.join(", ")}`))}if(t.blockSSRF!==!1&&(Ee.blockPrivateIPs||t.blockSSRF)){let i=s.hostname.toLowerCase();Kfe(i)&&r.push(R("ssrf_target","critical",n,`URL targets private address: ${i}`,e,"Use a public hostname or explicit allowlist"))}if(Ee.allowedDomains.length>0){let i=s.hostname.toLowerCase();Ee.allowedDomains.some(o=>i===o||i.endsWith("."+o))||r.push(R("forbidden_value","high",n,`Domain "${i}" not in allowlist`))}for(let i of Ee.blockedDomains)(s.hostname.toLowerCase()===i||s.hostname.toLowerCase().endsWith("."+i))&&r.push(R("forbidden_value","high",n,`Domain blocked: ${i}`));return/javascript:|vbscript:|data:|file:/i.test(e)&&r.push(R("forbidden_value","critical",n,"Dangerous URL scheme")),{violations:r,sanitized:e}}function Kfe(e){return!!(e==="localhost"||e==="0.0.0.0"||/^127\./.test(e)||/^10\./.test(e)||/^192\.168\./.test(e)||/^172\.(?:1[6-9]|2[0-9]|3[0-1])\./.test(e)||/^169\.254\./.test(e)||e==="::1"||e==="::"||/^fe80:/i.test(e)||/^fc00:|^fd00:/i.test(e)||e==="169.254.169.254"||e==="metadata.google.internal"||e==="metadata.azure.com")}function Yfe(e,t,n){let r=[];if(typeof e!="string")return r.push(R("type_mismatch","high",n,"Expected string")),{violations:r};let s=e,i=t.maxLength||Ee.maxStringLength;if(e.length>i&&(r.push(R("oversized_payload","high",n,`String exceeds max length: ${e.length} > ${i}`)),s=s.slice(0,i)),t.minLength&&e.length<t.minLength&&r.push(R("forbidden_value","medium",n,`String too short: ${e.length} < ${t.minLength}`)),e.includes("\0")&&(r.push(R("null_byte","high",n,"Contains null byte")),s=s.replace(/\0/g,"")),t.pattern)try{new RegExp(t.pattern).test(e)||r.push(R("forbidden_value","medium",n,`Value doesn't match required pattern: ${t.pattern}`))}catch{}if(t.enum&&!t.enum.includes(e)&&r.push(R("forbidden_value","medium",n,`Value not in allowed enum: ${t.enum.slice(0,5).join(", ")}`)),t.forbidden)for(let o of t.forbidden)(e===o||e.includes(o))&&r.push(R("forbidden_value","high",n,`Forbidden substring: ${o}`));return{violations:r,sanitized:s}}function Qfe(e,t,n){let r=[],s;if(typeof e=="number")s=e;else if(typeof e=="string"){if(s=parseFloat(e),!isFinite(s))return r.push(R("type_mismatch","high",n,"Cannot parse as number")),{violations:r}}else return r.push(R("type_mismatch","high",n,"Expected number")),{violations:r};return isFinite(s)?(t.min!==void 0&&s<t.min&&r.push(R("forbidden_value","medium",n,`Below minimum: ${s} < ${t.min}`)),t.max!==void 0&&s>t.max&&r.push(R("forbidden_value","medium",n,`Exceeds maximum: ${s} > ${t.max}`)),{violations:r,sanitized:s}):(r.push(R("forbidden_value","high",n,"Not a finite number")),{violations:r})}function Zfe(e,t,n){let r=[];if(typeof e!="string")return r.push(R("type_mismatch","high",n,"Glob must be a string")),{violations:r};let s=(e.match(/\*/g)||[]).length;return s>20&&r.push(R("invalid_glob","medium",n,`Excessive wildcards: ${s}`)),/\.\.[\\/]/.test(e)&&r.push(R("path_traversal","high",n,"Glob contains path traversal")),t.maxLength&&e.length>t.maxLength&&r.push(R("oversized_payload","medium",n,"Glob too long")),{violations:r,sanitized:e}}function Xfe(e,t,n){let r=[];if(typeof e!="string")return r.push(R("type_mismatch","high",n,"Regex must be a string")),{violations:r};try{new RegExp(e)}catch(s){r.push(R("forbidden_value","medium",n,`Invalid regex: ${s.message}`))}return/\([^)]*\+\)\+|\([^)]*\*\)\+|\([^)]*\+\)\*|\([^)]*\*\)\*/.test(e)&&r.push(R("forbidden_value","high",n,"Potential ReDoS (catastrophic backtracking pattern)")),t.maxLength&&e.length>t.maxLength&&r.push(R("oversized_payload","medium",n,"Regex too long")),{violations:r,sanitized:e}}function epe(e,t,n){let r=[];return typeof e!="string"?(r.push(R("type_mismatch","high",n,"Identifier must be a string")),{violations:r}):(/^[a-zA-Z_$][\w$]*$/.test(e)||r.push(R("forbidden_value","high",n,"Invalid identifier (must match /^[a-zA-Z_$][\\w$]*$/)")),{violations:r,sanitized:e})}function CT(e,t,n,r=0){if(r>Ee.maxRecursionDepth)return{violations:[R("oversized_payload","high",n,"Max recursion depth exceeded")]};if(e==null)return t.required?{violations:[R("forbidden_value","high",n,"Required field missing")]}:{violations:[],sanitized:t.default};switch(t.type){case"string":return Yfe(e,t,n);case"number":return Qfe(e,t,n);case"boolean":return typeof e!="boolean"?{violations:[R("type_mismatch","medium",n,"Expected boolean")]}:{violations:[],sanitized:e};case"path":return Vfe(e,t,n);case"url":return Wfe(e,t,n);case"shell_command":return Jfe(e,t,n);case"glob":return Zfe(e,t,n);case"regex":return Xfe(e,t,n);case"identifier":return epe(e,t,n);case"array":{if(!Array.isArray(e))return{violations:[R("type_mismatch","high",n,"Expected array")]};let s=[],i=t.maxItems||Ee.maxArrayItems;e.length>i&&s.push(R("oversized_payload","high",n,`Array too long: ${e.length} > ${i}`));let o=[];if(t.items)for(let a=0;a<e.length&&a<i;a++){let c=CT(e[a],t.items,`${n}[${a}]`,r+1);s.push(...c.violations),o.push(c.sanitized)}else o.push(...e.slice(0,i));return{violations:s,sanitized:o}}case"object":{if(typeof e!="object"||Array.isArray(e))return{violations:[R("type_mismatch","high",n,"Expected object")]};let s=[],i=e,o={},a=Object.keys(i);if(a.length>Ee.maxObjectKeys&&s.push(R("oversized_payload","high",n,`Too many keys: ${a.length}`)),t.properties){for(let[c,l]of Object.entries(t.properties)){let u=CT(i[c],l,`${n}.${c}`,r+1);s.push(...u.violations),u.sanitized!==void 0&&(o[c]=u.sanitized)}if(t.additionalProperties===!1)for(let c of a)c in t.properties||s.push(R("forbidden_value","low",n,`Unexpected property: ${c}`));else for(let c of a)c in t.properties||(o[c]=i[c])}else Object.assign(o,i);return{violations:s,sanitized:o}}default:return{violations:[],sanitized:e}}}function tpe(e,t){let n=Date.now();if(!Ee.enabled)return{valid:!0,violations:[],action:"allow",reason:"Sanitizer disabled",sanitizedArguments:t,riskScore:0,durationMs:0};let r=dB(e);if(!r)return npe(e,t,n);if(r.trustLevel==="forbidden")return{valid:!1,violations:[R("forbidden_value","critical",e,"Tool is forbidden by policy")],action:"reject",reason:"Tool forbidden",riskScore:1,durationMs:Date.now()-n};let s=[],i={};for(let[m,g]of Object.entries(r.arguments)){let h=CT(t[m],g,m);s.push(...h.violations),h.sanitized!==void 0&&(i[m]=h.sanitized)}for(let m of Object.keys(t))m in r.arguments||s.push(R("invalid_schema","low",m,`Unexpected argument: ${m}`,void 0,void 0,!1));let o=JSON.stringify(t).length;r.maxTotalSize&&o>r.maxTotalSize&&s.push(R("oversized_payload","high","total",`Total payload too large: ${o} > ${r.maxTotalSize}`)),o>Ee.maxTotalPayloadBytes&&s.push(R("oversized_payload","critical","total",`Payload exceeds global max: ${o}`));let a=s.filter(m=>m.blocked),c=a.some(m=>m.severity==="critical"),l=a.some(m=>m.severity==="high"),u="allow",d="Valid";Ee.strictMode&&s.length>0?(u="reject",d="Strict mode: any violation rejects"):Ee.rejectOnCritical&&c?(u="reject",d="Critical violation detected"):Ee.rejectOnHigh&&l?(u="reject",d="High-severity violation detected"):s.length>0&&(Ee.autoSanitizeWhenPossible?(u="sanitize",d=`${s.length} violation(s) sanitized`):(u="allow",d=`${s.length} warning(s)`));let f={critical:1,high:.7,medium:.4,low:.2,info:.05},p=Math.min(1,s.reduce((m,g)=>m+f[g.severity],0)*.2);pn.totalValidations++,u==="reject"?pn.totalRejected++:u==="sanitize"?pn.totalSanitized++:pn.totalAllowed++,pn.byTool[e]=(pn.byTool[e]||0)+1;for(let m of s)pn.byViolation[m.type]=(pn.byViolation[m.type]||0)+1;return pn.averageDurationMs=(pn.averageDurationMs*(pn.totalValidations-1)+(Date.now()-n))/pn.totalValidations,AT(),s.length>0&&Ufe({toolName:e,args:JSON.stringify(t).slice(0,1e3),action:u,violations:s,riskScore:p}),{valid:a.length===0||u==="allow",violations:s,action:u,reason:d,sanitizedArguments:u==="sanitize"||u==="allow"?i:void 0,riskScore:p,durationMs:Date.now()-n}}function npe(e,t,n){let r=[],s=JSON.stringify(t).length;s>Ee.maxTotalPayloadBytes&&r.push(R("oversized_payload","critical","total",`Payload too large: ${s}`));function i(l,u,d){if(d>Ee.maxRecursionDepth){r.push(R("oversized_payload","high",u,"Recursion depth exceeded"));return}if(typeof l=="string")l.length>Ee.maxStringLength&&r.push(R("oversized_payload","high",u,`String too long: ${l.length}`)),l.includes("\0")&&r.push(R("null_byte","high",u,"Contains null byte"));else if(Array.isArray(l)){l.length>Ee.maxArrayItems&&r.push(R("oversized_payload","high",u,`Array too long: ${l.length}`));for(let f=0;f<Math.min(l.length,Ee.maxArrayItems);f++)i(l[f],`${u}[${f}]`,d+1)}else if(l&&typeof l=="object"){let f=Object.keys(l);f.length>Ee.maxObjectKeys&&r.push(R("oversized_payload","high",u,`Too many keys: ${f.length}`));for(let p of f)i(l[p],`${u}.${p}`,d+1)}}i(t,e,0);let o=r.some(l=>l.severity==="critical"),a=o?"reject":"allow",c=o?"Critical generic violation":"No schema, basic checks passed";return pn.totalValidations++,AT(),{valid:!o,violations:r,action:a,reason:c,sanitizedArguments:a==="allow"?t:void 0,riskScore:o?.9:r.length>0?.3:0,durationMs:Date.now()-n}}function rpe(){return{...Ee}}function spe(e){Ee={...Ee,...e}}function ipe(){return{...pn}}function ope(){pn={totalValidations:0,totalRejected:0,totalSanitized:0,totalAllowed:0,byViolation:{},byTool:{},averageDurationMs:0},AT()}function ape(){return[...uB,...Array.from(jc.values())]}function cpe(e=100){if(!tv(xT))return[];try{return kT(xT,"utf-8").split(`
1316
1314
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function lpe(e,t){let n=[],r=e.action==="reject"?"\u{1F6AB}":e.action==="sanitize"?"\u{1F9F9}":"\u2713";if(n.push(`${r} **Sanitizer Result for ${t}**`),n.push(`Action: ${e.action.toUpperCase()}`),n.push(`Risk: ${(e.riskScore*100).toFixed(0)}/100`),n.push(`Reason: ${e.reason}`),n.push(`Duration: ${e.durationMs}ms`),n.push(""),e.violations.length>0){n.push(`## Violations (${e.violations.length})`);for(let s of e.violations.slice(0,15)){let i=s.severity==="critical"?"\u{1F6A8}":s.severity==="high"?"\u26A0\uFE0F ":s.severity==="medium"?"\u26A1":"\u2139\uFE0F ";n.push(`${i} [${s.type}] arg "${s.argumentName}": ${s.message}`),s.evidence&&n.push(` Evidence: ${s.evidence.slice(0,150)}`),s.suggestion&&n.push(` Fix: ${s.suggestion}`)}}return n.join(`
1317
1315
  `)}var Nfe,Ee,iv,xT,$T,nv,jc,pn,uB,Hfe,cv=w(()=>{"use strict";Nfe={enabled:!0,enableSchemaValidation:!0,enableSecurityScanning:!0,enableSemanticValidation:!0,enableSizeChecks:!0,autoSanitizeWhenPossible:!0,strictMode:!1,rejectOnCritical:!0,rejectOnHigh:!0,maxStringLength:1024*1024,maxArrayItems:1e4,maxObjectKeys:1e3,maxRecursionDepth:16,maxTotalPayloadBytes:10*1024*1024,forbiddenPathPatterns:["\\.\\./","\\.ssh/","\\.aws/credentials","\\.gnupg/","/etc/passwd","/etc/shadow","/etc/sudoers","/proc/self/","/sys/","\\.env(?!\\.example)","id_rsa","id_ed25519","authorized_keys"],allowedRootDirs:[],blockPrivateIPs:!0,blockedDomains:[],allowedDomains:[],enableAuditLog:!0},Ee={...Nfe},iv=sv(Ofe(),".aiaca","sanitizer"),xT=sv(iv,"audit.jsonl"),$T=sv(iv,"stats.json"),nv=sv(iv,"schemas.json"),jc=new Map,pn={totalValidations:0,totalRejected:0,totalSanitized:0,totalAllowed:0,byViolation:{},byTool:{},averageDurationMs:0};qfe();uB=[{toolName:"file_read",arguments:{path:{type:"path",required:!0,allowParentTraversal:!1,maxLength:1024},offset:{type:"number",min:0},limit:{type:"number",min:0,max:1e5}},trustLevel:"sandboxed"},{toolName:"file_write",arguments:{path:{type:"path",required:!0,allowParentTraversal:!1,maxLength:1024},content:{type:"string",required:!0,maxLength:5*1024*1024},operation:{type:"string",enum:["create","overwrite","edit"]}},requiresApproval:!0,trustLevel:"sandboxed"},{toolName:"file_edit",arguments:{path:{type:"path",required:!0,allowParentTraversal:!1},old_str:{type:"string",required:!0,maxLength:1e5},new_str:{type:"string",required:!0,maxLength:5*1024*1024}},requiresApproval:!0,trustLevel:"sandboxed"},{toolName:"bash",arguments:{command:{type:"shell_command",required:!0,maxLength:32768},timeout:{type:"number",min:0,max:6e5},cwd:{type:"path",allowParentTraversal:!1}},requiresApproval:!0,trustLevel:"sandboxed"},{toolName:"powershell",arguments:{command:{type:"shell_command",required:!0,maxLength:32768},timeout:{type:"number",min:0,max:6e5}},requiresApproval:!0,trustLevel:"sandboxed"},{toolName:"web_fetch",arguments:{url:{type:"url",required:!0,allowedProtocols:["http","https"],blockSSRF:!0}},trustLevel:"sandboxed"},{toolName:"web_search",arguments:{query:{type:"string",required:!0,minLength:1,maxLength:500}}},{toolName:"glob",arguments:{pattern:{type:"glob",required:!0,maxLength:1024},path:{type:"path",allowParentTraversal:!1}}},{toolName:"grep",arguments:{pattern:{type:"regex",required:!0,maxLength:1024},path:{type:"path",allowParentTraversal:!1}}}],Hfe=new Map(uB.map(e=>[e.toolName,e]))});var pv={};$(pv,{addCustomRule:()=>Spe,classify:()=>fB,clearConfirmationCache:()=>bpe,configure:()=>$pe,decide:()=>vpe,formatClassification:()=>Ppe,generateComplianceReport:()=>Rpe,getAuditLog:()=>_pe,getConfig:()=>xpe,getEvents:()=>Tpe,getStats:()=>Cpe,isConfirmed:()=>mB,listRules:()=>wpe,recordConfirmation:()=>hpe,recordDenial:()=>ype,removeRule:()=>kpe,resetStats:()=>Ape});import{existsSync as TT,mkdirSync as upe,readFileSync as _T,writeFileSync as MT}from"fs";import{join as uv}from"path";import{homedir as dpe}from"os";import{createHash as fpe}from"crypto";import{EventEmitter as ppe}from"events";function fv(){upe(dv,{recursive:!0})}function gpe(){if(fv(),TT(RT))try{we={...we,...JSON.parse(_T(RT,"utf-8"))}}catch{}if(TT(IT))try{let e=JSON.parse(_T(IT,"utf-8"));for(let t of e)try{Qs.push({...t,toolNamePattern:t.toolNamePattern?new RegExp(t.toolNamePattern.source||t.toolNamePattern,t.toolNamePattern.flags):void 0,argumentPattern:t.argumentPattern?new RegExp(t.argumentPattern.source||t.argumentPattern,t.argumentPattern.flags):void 0})}catch{}}catch{}}function Bc(){fv();try{MT(RT,JSON.stringify(we,null,2),"utf-8")}catch{}}function DT(e){if(Pt.enableAuditLog){fv();try{MT(PT,JSON.stringify({...e,timestamp:Date.now()})+`
@@ -1321,36 +1319,36 @@ If no facts qualify, return: []`;ji=[]});var Ad={};$(Ad,{canExecute:()=>Sfe,comp
1321
1319
  `)}var mpe,Pt,dv,RT,PT,IT,ET,Qs,lv,we,FT,mv=w(()=>{"use strict";mpe={enabled:!0,defaultReversibility:"conditional",defaultConfirmation:"optional",defaultRiskScore:.3,rejectDestructiveByDefault:!0,confirmIrreversibleByDefault:!0,skipConfirmationForReversible:!0,enableTrustBasedBypass:!1,trustBypassThreshold:.95,enableConfirmationCache:!0,confirmationCacheTtlMs:300*1e3,enableAuditLog:!0},Pt={...mpe},dv=uv(dpe(),".aiaca","reversibility-classifier"),RT=uv(dv,"stats.json"),PT=uv(dv,"audit.jsonl"),IT=uv(dv,"custom-rules.json"),ET=new ppe;ET.setMaxListeners(50);Qs=[],lv=new Map,we={totalClassifications:0,totalReversible:0,totalConditional:0,totalIrreversible:0,totalDestructive:0,totalConfirmationRequested:0,totalConfirmationGranted:0,totalConfirmationDenied:0,totalRejected:0,totalAutoBypassed:0,byTool:{},byReversibility:{}};gpe();FT=[{id:"read_tools",priority:100,toolNamePattern:/^(file_read|read_file|view|cat_file|grep|search|find|glob|ls|list_files|tree)$/,description:"Read-only file operations",reversibility:"reversible",confirmationLevel:"none",impactScope:"no_impact",riskBoost:0,reason:"Read operation \u2014 no state change"},{id:"lint_tools",priority:100,toolNamePattern:/^(lint|format_check|tsc|eslint_check|static_analysis|type_check)$/,description:"Linting and analysis",reversibility:"reversible",confirmationLevel:"none",impactScope:"no_impact",riskBoost:0,reason:"Analysis only \u2014 no state change"},{id:"web_search",priority:100,toolNamePattern:/^(web_search|search_web|google|search)$/,description:"Web search queries",reversibility:"reversible",confirmationLevel:"none",impactScope:"no_impact",riskBoost:0,reason:"Read-only web query"},{id:"web_fetch",priority:90,toolNamePattern:/^(web_fetch|fetch_url|http_get|curl)$/,description:"HTTP GET requests",reversibility:"reversible",confirmationLevel:"optional",impactScope:"remote",riskBoost:.1,reason:"External HTTP request \u2014 minimal impact"},{id:"file_write_create",priority:80,toolNamePattern:/^(file_write|write_file|create_file)$/,description:"Create new file",reversibility:"conditional",confirmationLevel:"optional",impactScope:"local_file",riskBoost:.2,reason:"Creates file (deletable to undo)",rollbackMethod:"Delete the created file"},{id:"file_edit",priority:80,toolNamePattern:/^(file_edit|edit_file|str_replace_editor)$/,description:"Edit existing file",reversibility:"conditional",confirmationLevel:"optional",impactScope:"local_file",riskBoost:.2,reason:"Edits file (undo available via undo stack)",rollbackMethod:"Use /undo to revert"},{id:"mkdir",priority:80,argumentPattern:/^mkdir\s|^md\s/i,description:"Create directory",reversibility:"conditional",confirmationLevel:"none",impactScope:"local_file",riskBoost:.1,reason:"Creates directory (rmdir to undo)",rollbackMethod:"rmdir <path>"},{id:"file_delete",priority:90,toolNamePattern:/^(file_delete|delete_file|rm)$/,description:"Delete file",reversibility:"irreversible",confirmationLevel:"required",impactScope:"local_file",riskBoost:.5,reason:"Deletes file (only recoverable from VCS or backup)",rollbackMethod:"Recover from git history or backup"},{id:"rm_command",priority:90,toolNamePattern:/^(bash|shell|cmd|powershell)$/,argumentPattern:/\brm\s+(?!-r|-f)/i,description:"Shell rm command",reversibility:"irreversible",confirmationLevel:"required",impactScope:"local_file",riskBoost:.6,reason:"Shell delete (no trash on most systems)"},{id:"rm_rf",priority:1e3,toolNamePattern:/^(bash|shell|cmd|powershell)$/,argumentPattern:/\brm\s+-rf?\s|rmdir\s+\/s|del\s+\/[fsq]/i,description:"Recursive force delete",reversibility:"destructive",confirmationLevel:"two_factor",impactScope:"system",riskBoost:.95,reason:"Recursive force delete \u2014 potentially catastrophic"},{id:"git_force_push",priority:1e3,toolNamePattern:/^(bash|shell|cmd|powershell|git)$/,argumentPattern:/git\s+push\s+(--force|-f)(?!\s+--force-with-lease|-with-lease)/i,description:"Git force push",reversibility:"destructive",confirmationLevel:"two_factor",impactScope:"remote",riskBoost:.9,reason:"Force push rewrites remote history \u2014 destroys collaborators work"},{id:"git_reset_hard",priority:1e3,toolNamePattern:/^(bash|shell|cmd|powershell|git)$/,argumentPattern:/git\s+reset\s+--hard/i,description:"Git reset --hard",reversibility:"destructive",confirmationLevel:"required",impactScope:"project",riskBoost:.85,reason:"Discards uncommitted changes"},{id:"git_clean_force",priority:1e3,toolNamePattern:/^(bash|shell|cmd|powershell|git)$/,argumentPattern:/git\s+clean\s+(-f|--force)/i,description:"Git clean --force",reversibility:"destructive",confirmationLevel:"required",impactScope:"project",riskBoost:.85,reason:"Permanently deletes untracked files"},{id:"database_drop",priority:1e3,argumentPattern:/\b(drop\s+(?:database|table|schema|index)|truncate\s+(?:table|database))\b/i,description:"Database DROP/TRUNCATE",reversibility:"destructive",confirmationLevel:"two_factor",impactScope:"production",riskBoost:1,reason:"Database drop is catastrophic and unrecoverable"},{id:"dd_disk",priority:1e3,argumentPattern:/\bdd\s+if=.+\s+of=\/dev\//i,description:"DD raw disk write",reversibility:"destructive",confirmationLevel:"two_factor",impactScope:"system",riskBoost:1,reason:"Raw disk write \u2014 can destroy filesystems"},{id:"mkfs",priority:1e3,argumentPattern:/\bmkfs(?:\.\w+)?\s/i,description:"Filesystem format",reversibility:"destructive",confirmationLevel:"two_factor",impactScope:"system",riskBoost:1,reason:"Formatting filesystem destroys all data"},{id:"git_push",priority:70,toolNamePattern:/^(bash|shell|cmd|powershell|git)$/,argumentPattern:/git\s+push(?!\s+--force|--dry-run)/i,description:"Git push to remote",reversibility:"irreversible",confirmationLevel:"required",impactScope:"remote",riskBoost:.4,reason:"Pushes to remote \u2014 visible to other developers",rollbackMethod:"git push --force-with-lease (with confirmation)"},{id:"npm_publish",priority:80,toolNamePattern:/^(bash|shell|cmd|powershell)$/,argumentPattern:/\bnpm\s+publish/i,description:"npm publish",reversibility:"destructive",confirmationLevel:"two_factor",impactScope:"production",riskBoost:.9,reason:"Publishing to npm registry \u2014 package versions are immutable"},{id:"docker_push",priority:70,toolNamePattern:/^(bash|shell|cmd|powershell|docker)$/,argumentPattern:/\bdocker\s+push/i,description:"Docker image push",reversibility:"irreversible",confirmationLevel:"required",impactScope:"remote",riskBoost:.4,reason:"Publishes to container registry"},{id:"kubectl_delete",priority:80,toolNamePattern:/^(bash|shell|cmd|powershell|kubectl)$/,argumentPattern:/\bkubectl\s+delete/i,description:"Kubernetes resource delete",reversibility:"destructive",confirmationLevel:"required",impactScope:"production",riskBoost:.7,reason:"Deletes k8s resources (may include data)"},{id:"terraform_apply_destroy",priority:90,toolNamePattern:/^(bash|shell|cmd|powershell|terraform)$/,argumentPattern:/\bterraform\s+(apply|destroy)/i,description:"Terraform apply/destroy",reversibility:"destructive",confirmationLevel:"two_factor",impactScope:"production",riskBoost:.85,reason:"Modifies infrastructure"},{id:"aws_delete",priority:70,toolNamePattern:/^(bash|shell|cmd|powershell|aws)$/,argumentPattern:/\baws\s+\w+\s+delete-/i,description:"AWS resource delete",reversibility:"destructive",confirmationLevel:"required",impactScope:"production",riskBoost:.7,reason:"Deletes AWS resources"},{id:"shutdown",priority:1e3,argumentPattern:/\b(shutdown|reboot|halt|poweroff)\b/i,description:"System shutdown",reversibility:"destructive",confirmationLevel:"required",impactScope:"system",riskBoost:.8,reason:"Powers off or restarts machine"},{id:"kill_process",priority:70,toolNamePattern:/^(bash|shell|cmd|powershell)$/,argumentPattern:/\bkill\s+-9|killall\s|pkill\s/i,description:"Force kill process",reversibility:"irreversible",confirmationLevel:"optional",impactScope:"system",riskBoost:.4,reason:"Force kill \u2014 may lose data"},{id:"deploy",priority:80,argumentPattern:/\b(deploy|release|publish)\s+(?:to\s+)?(prod|production)/i,description:"Production deploy",reversibility:"irreversible",confirmationLevel:"two_factor",impactScope:"production",riskBoost:.85,reason:"Production deployment"},{id:"web_post",priority:60,argumentPattern:/\b(curl|wget)\s+.*-X\s+(POST|PUT|DELETE|PATCH)|http(s?):\/\/.*\s+-d\s/i,description:"HTTP write request",reversibility:"irreversible",confirmationLevel:"required",impactScope:"remote",riskBoost:.5,reason:"HTTP write request \u2014 modifies remote state"}]});var Hm={};$(Hm,{activateGlobalKillSwitch:()=>pme,beginExecution:()=>Jpe,configure:()=>ame,deactivateGlobalKillSwitch:()=>mme,deleteBudget:()=>ime,endExecution:()=>Wpe,formatMetrics:()=>gme,getActiveExecutions:()=>ume,getBudget:()=>rme,getConfig:()=>ome,getEvents:()=>fme,getMetrics:()=>Xpe,getRecentHistory:()=>dme,getStats:()=>cme,killAll:()=>bB,killExecution:()=>eme,listBudgets:()=>sme,predictBudget:()=>qT,preflightCheck:()=>tme,recordFork:()=>Ype,recordNetworkCall:()=>Kpe,recordToolCall:()=>Qpe,registerChildProcess:()=>Zpe,resetStats:()=>lme,setBudget:()=>nme});import{existsSync as gB,mkdirSync as Ipe,readFileSync as hB,writeFileSync as hv}from"fs";import{join as Nm}from"path";import{homedir as Mpe,totalmem as Epe,freemem as Dpe,cpus as Fpe,loadavg as Lpe}from"os";import{EventEmitter as Ope}from"events";import{createHash as jpe}from"crypto";function Um(){Ipe(qm,{recursive:!0})}function Hpe(){if(Um(),gB(OT))try{Tn={...Tn,...JSON.parse(hB(OT,"utf-8"))}}catch{}if(gB(LT))try{let e=JSON.parse(hB(LT,"utf-8"));for(let t of e)Yo.set(t.toolName,t)}catch{}}function yB(){Um();try{hv(OT,JSON.stringify(Tn,null,2),"utf-8")}catch{}}function BT(){Um();try{hv(LT,JSON.stringify(Array.from(Yo.values()),null,2),"utf-8")}catch{}}function zpe(e){if(Wt.enableTelemetry){Um();try{hv(qpe,JSON.stringify(e)+`
1322
1320
  `,{flag:"a"})}catch{}}}function NT(e){Um();try{hv(Upe,JSON.stringify({...e,timestamp:Date.now()})+`
1323
1321
  `,{flag:"a"})}catch{}}function Gpe(e){let t=e.length;if(t<2)return 0;let n=(t-1)/2,r=e.reduce((o,a)=>o+a,0)/t,s=0,i=0;for(let o=0;o<t;o++)s+=(o-n)*(e[o]-r),i+=(o-n)**2;return i===0?0:s/i}function qT(e){let t=Tn.byTool[e];if(!t||t.runs<3)return{durationMs:3e4,memoryBytes:100*1024*1024,confidence:.1,basedOn:0};let n=Bm.filter(o=>o.toolName===e).slice(-20);if(n.length===0)return{durationMs:t.avgMs,memoryBytes:t.avgMemMb*1024*1024,confidence:.3,basedOn:t.runs};let r=n.map(o=>o.wallTimeUsedMs).sort((o,a)=>o-a),s=n.map(o=>o.memoryPeakBytes).sort((o,a)=>o-a),i=o=>o[Math.min(o.length-1,Math.floor(o.length*.95))];return{durationMs:i(r),memoryBytes:i(s),confidence:Math.min(1,n.length/20),basedOn:n.length}}function Vpe(e){let t=Yo.get(e),n=t?.quota||Wt.defaultQuota;if(!Wt.enableAdaptive||!t?.adaptive)return n;let r=qT(e),s=t.adaptiveScale||1.5;return{...n,wallTimeMs:Math.max(n.wallTimeMs||0,r.durationMs*s),memoryMaxBytes:Math.max(n.memoryMaxBytes||0,r.memoryBytes*s)}}function Jpe(e){if(!Wt.enabled||Wt.globalKillSwitch){if(Wt.globalKillSwitch)throw new Error("Global kill switch active \u2014 execution refused");return""}let t=jpe("md5").update(`${e.toolName}:${Date.now()}:${Math.random()}`).digest("hex").slice(0,12),n=e.quota||Vpe(e.toolName),r=e.enforcement||Wt.defaultEnforcement,s=new jT(e.toolName,t,n,r);return e.abortCallback&&(s.abortCallback=e.abortCallback),s.startSampling(),fr.set(t,s),NT({event:"start",executionId:t,toolName:e.toolName,quota:n,enforcement:r}),Bi.emit("execution_started",{executionId:t,toolName:e.toolName}),t}function Wpe(e){if(!e)return null;let t=fr.get(e);if(!t)return null;t.stopSampling(),t.metrics.endTime=Date.now(),t.metrics.wallTimeUsedMs=t.metrics.endTime-t.metrics.startTime,Tn.totalExecutions++;let n=t.metrics.toolName;Tn.byTool[n]||(Tn.byTool[n]={runs:0,kills:0,avgMs:0,avgMemMb:0});let r=Tn.byTool[n];r.runs++,t.killed&&r.kills++,r.avgMs=(r.avgMs*(r.runs-1)+t.metrics.wallTimeUsedMs)/r.runs,r.avgMemMb=(r.avgMemMb*(r.runs-1)+t.metrics.memoryPeakBytes/1024/1024)/r.runs;let s=Yo.get(n);return s&&s.adaptive&&(s.baselineMeasurements.push(t.metrics.wallTimeUsedMs),s.baselineMeasurements.length>50&&s.baselineMeasurements.shift(),BT()),yB(),zpe(t.metrics),NT({event:"end",executionId:e,toolName:n,metrics:t.metrics}),Bm.push(t.metrics),Bm.length>Wt.retainHistoryCount&&Bm.shift(),fr.delete(e),Bi.emit("execution_ended",{metrics:t.metrics}),t.metrics}function Kpe(e,t,n=0){if(!e)return!0;let r=fr.get(e);return r?r.recordNetworkCall(t,n):!0}function Ype(e){if(!e)return!0;let t=fr.get(e);return t?t.recordFork():!0}function Qpe(e,t=0){if(!e)return!0;let n=fr.get(e);return n?(n.metrics.toolCallsCount++,n.metrics.recursionDepth=Math.max(n.metrics.recursionDepth,t),n.checkLimits(),!n.killed):!0}function Zpe(e,t){if(!e)return;let n=fr.get(e);n&&n.registerChild(t)}function Xpe(e){if(!e)return null;let t=fr.get(e);return t?{...t.metrics}:null}function eme(e,t="manual_kill"){if(!e)return!1;let n=fr.get(e);return n?(n.kill(t),!0):!1}function bB(e="killAll requested"){let t=0;for(let n of fr.values())n.kill(e),t++;return t}function tme(e){let t=[],n=qT(e),r=Epe(),s=Dpe(),i=s/r*100,o=Lpe()[0],a=Fpe().length,c=o/a;i<10&&t.push(`Low memory: ${i.toFixed(1)}% free`),c>.9&&t.push(`High CPU load: ${(c*100).toFixed(0)}%`),fr.size>10&&t.push(`Many concurrent executions: ${fr.size}`),n.memoryBytes>s*.5&&t.push(`Predicted memory (${(n.memoryBytes/1024/1024).toFixed(0)}MB) > 50% of free`);let l=!0,u="OK";return Wt.globalKillSwitch?(l=!1,u="Global kill switch active"):i<5?(l=!1,u="Insufficient memory"):t.length>=3&&(l=!1,u="Too many overload warnings"),{approved:l,reason:u,prediction:n,systemLoad:{memoryFreePercent:i,cpuLoad:c,activeExecutions:fr.size},warnings:t}}function nme(e){Yo.set(e.toolName,e),BT()}function rme(e){return Yo.get(e)}function sme(){return Array.from(Yo.values())}function ime(e){let t=Yo.delete(e);return t&&BT(),t}function ome(){return{...Wt}}function ame(e){Wt={...Wt,...e}}function cme(){return{...Tn}}function lme(){Tn={totalExecutions:0,totalKilled:0,totalThrottled:0,totalWarned:0,totalAnomalies:0,byTool:{},byExceeded:{},byAnomaly:{}},yB()}function ume(){return Array.from(fr.entries()).map(([e,t])=>({id:e,toolName:t.metrics.toolName,metrics:{...t.metrics}}))}function dme(e,t=50){let n=Bm;return e&&(n=n.filter(r=>r.toolName===e)),n.slice(-t).reverse()}function fme(){return Bi}function pme(){return Wt.globalKillSwitch=!0,bB("global_kill_switch")}function mme(){Wt.globalKillSwitch=!1}function gme(e){let t=[],n=e.killed?"\u{1F480}":e.exceeded.length>0?"\u26A0\uFE0F":"\u2713";if(t.push(`${n} **${e.toolName}** [${e.executionId}]`),t.push(`Wall: ${e.wallTimeUsedMs}ms | CPU: ${e.cpuTimeUsedMs}ms | Memory: ${(e.memoryPeakBytes/1024/1024).toFixed(1)}MB peak`),t.push(`Network: ${e.networkCalls} calls / ${(e.networkBytes/1024).toFixed(1)}KB`),t.push(`Forks: ${e.forksTotal} | Tool calls: ${e.toolCallsCount} | Recursion: ${e.recursionDepth}`),e.exceeded.length>0&&t.push(`\u26A0\uFE0F Exceeded: ${e.exceeded.join(", ")}`),e.killed&&t.push(`\u{1F480} Killed: ${e.killReason}`),e.anomalies.length>0){t.push(`Anomalies (${e.anomalies.length}):`);for(let r of e.anomalies.slice(0,5)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="warn"?"\u26A0\uFE0F ":"\u2139\uFE0F ";t.push(` ${s}[${r.type}] ${r.message}`)}}return t.join(`
1324
- `)}var Bpe,Npe,Wt,qm,LT,qpe,OT,Upe,Bi,Yo,fr,Bm,Tn,gv,jT,zm=w(()=>{"use strict";Bpe={cpuTimeMs:6e4,wallTimeMs:12e4,memoryMaxBytes:1024*1024*512,maxNetworkCalls:100,maxNetworkBytes:100*1024*1024,perHostCallLimit:50,networkRatePerSec:20,maxForks:50,forkRatePerSec:10,maxFileDescriptors:256,maxToolCalls:30,maxRecursionDepth:10,diskIoMaxBytes:500*1024*1024},Npe={enabled:!0,defaultQuota:Bpe,samplingIntervalMs:100,defaultEnforcement:"kill",killOnAnomaly:!0,globalKillSwitch:!1,enableAdaptive:!0,adaptiveLearningRate:.2,enablePredictive:!0,enableTelemetry:!0,retainHistoryCount:500,spikeThresholdMultiplier:3,sustainedDurationMs:1e4,forkBombThresholdPerSec:50,memoryLeakSlope:.1},Wt={...Npe},qm=Nm(Mpe(),".aiaca","resource-limiter"),LT=Nm(qm,"budgets.json"),qpe=Nm(qm,"metrics.jsonl"),OT=Nm(qm,"stats.json"),Upe=Nm(qm,"ledger.jsonl"),Bi=new Ope;Bi.setMaxListeners(100);Yo=new Map,fr=new Map,Bm=[],Tn={totalExecutions:0,totalKilled:0,totalThrottled:0,totalWarned:0,totalAnomalies:0,byTool:{},byExceeded:{},byAnomaly:{}};Hpe();gv=class{constructor(t,n){this.capacity=t;this.refillPerSec=n;this.tokens=t,this.lastRefill=Date.now()}capacity;refillPerSec;tokens;lastRefill;consume(t=1){return this.refill(),this.tokens>=t?(this.tokens-=t,!0):!1}available(){return this.refill(),this.tokens}refill(){let t=Date.now(),n=(t-this.lastRefill)/1e3;this.tokens=Math.min(this.capacity,this.tokens+n*this.refillPerSec),this.lastRefill=t}},jT=class{metrics;quota;enforcement;pid;childProcs=new Set;samplerInterval;killed=!1;cpuStart;startCpuMs=0;networkBucket;forkBucket;memoryHistory=[];cpuHistory=[];abortCallback;constructor(t,n,r,s){this.quota=r,this.enforcement=s,this.metrics={toolName:t,executionId:n,startTime:Date.now(),cpuTimeUsedMs:0,wallTimeUsedMs:0,memoryPeakBytes:0,memoryAvgBytes:0,memorySamples:0,networkCalls:0,networkBytes:0,perHostCalls:{},forksTotal:0,forkTimes:[],toolCallsCount:0,recursionDepth:0,killed:!1,exceeded:[],anomalies:[]};let i=process.cpuUsage();this.cpuStart={user:i.user,system:i.system},this.networkBucket=new gv(r.networkRatePerSec||100,r.networkRatePerSec||100),this.forkBucket=new gv(r.forkRatePerSec||10,r.forkRatePerSec||10)}startSampling(){this.samplerInterval=setInterval(()=>this.sample(),Wt.samplingIntervalMs)}stopSampling(){this.samplerInterval&&(clearInterval(this.samplerInterval),this.samplerInterval=void 0)}sample(){if(this.killed)return;let t=Date.now();this.metrics.wallTimeUsedMs=t-this.metrics.startTime;let n=process.cpuUsage(),r=n.user-this.cpuStart.user+(n.system-this.cpuStart.system);this.metrics.cpuTimeUsedMs=Math.floor(r/1e3),this.cpuHistory.push(this.metrics.cpuTimeUsedMs),this.cpuHistory.length>100&&this.cpuHistory.shift();try{let i=process.memoryUsage().rss;this.metrics.memorySamples++,this.metrics.memoryAvgBytes=(this.metrics.memoryAvgBytes*(this.metrics.memorySamples-1)+i)/this.metrics.memorySamples,this.metrics.memoryPeakBytes=Math.max(this.metrics.memoryPeakBytes,i),this.memoryHistory.push(i),this.memoryHistory.length>200&&this.memoryHistory.shift()}catch{}this.checkLimits(),this.detectAnomalies()}checkLimits(){let t=this.quota,n=this.metrics,r=[];t.wallTimeMs&&n.wallTimeUsedMs>t.wallTimeMs&&r.push("wall_time"),t.cpuTimeMs&&n.cpuTimeUsedMs>t.cpuTimeMs&&r.push("cpu_time"),t.memoryMaxBytes&&n.memoryPeakBytes>t.memoryMaxBytes&&r.push("memory"),t.maxNetworkCalls&&n.networkCalls>t.maxNetworkCalls&&r.push("network_calls"),t.maxNetworkBytes&&n.networkBytes>t.maxNetworkBytes&&r.push("network_bytes"),t.maxForks&&n.forksTotal>t.maxForks&&r.push("fork_count"),t.maxToolCalls&&n.toolCallsCount>t.maxToolCalls&&r.push("tool_calls"),r.length>0&&(n.exceeded.push(...r.filter(s=>!n.exceeded.includes(s))),this.handleViolation(r))}detectAnomalies(){if(this.memoryHistory.length>=10){let n=this.memoryHistory[this.memoryHistory.length-1],r=this.memoryHistory.slice(0,-5).reduce((s,i)=>s+i,0)/Math.max(1,this.memoryHistory.length-5);r>0&&n>r*Wt.spikeThresholdMultiplier&&this.recordAnomaly({type:"spike",severity:"warn",message:`Memory spike: ${(n/1024/1024).toFixed(0)}MB (${(n/r).toFixed(1)}\xD7 baseline)`,timestamp:Date.now(),value:n,threshold:r})}if(this.memoryHistory.length>=50){let n=Gpe(this.memoryHistory.slice(-50)),r=this.memoryHistory[0];r>0&&n/r>Wt.memoryLeakSlope/6e4*100&&this.recordAnomaly({type:"memory_leak",severity:"warn",message:`Possible memory leak: +${(n*6e4/1024/1024).toFixed(1)}MB/min`,timestamp:Date.now()})}let t=this.metrics.forkTimes.filter(n=>Date.now()-n<1e3).length;if(t>=Wt.forkBombThresholdPerSec&&(this.recordAnomaly({type:"fork_bomb",severity:"critical",message:`Fork bomb detected: ${t} forks in last second`,timestamp:Date.now(),value:t}),Wt.killOnAnomaly&&this.kill("fork_bomb")),this.metrics.networkCalls>0&&this.metrics.wallTimeUsedMs>0){let n=this.metrics.networkCalls/(this.metrics.wallTimeUsedMs/1e3);n>100&&this.recordAnomaly({type:"network_flood",severity:"critical",message:`Network flood: ${n.toFixed(0)} calls/sec`,timestamp:Date.now(),value:n})}if(this.cpuHistory.length>=20){let n=this.cpuHistory.slice(-20),r=(n[n.length-1]-n[0])/(Wt.samplingIntervalMs*20);r>.95&&this.recordAnomaly({type:"cpu_burn",severity:"warn",message:`Sustained CPU burn: ${(r*100).toFixed(0)}%`,timestamp:Date.now(),value:r})}}recordAnomaly(t){this.metrics.anomalies.filter(r=>Date.now()-r.timestamp<1e3).some(r=>r.type===t.type)||(this.metrics.anomalies.push(t),Tn.totalAnomalies++,Tn.byAnomaly[t.type]=(Tn.byAnomaly[t.type]||0)+1,Bi.emit("anomaly",t),t.severity==="critical"&&Bi.emit("critical_anomaly",t))}handleViolation(t){for(let n of t)Tn.byExceeded[n]=(Tn.byExceeded[n]||0)+1;switch(Bi.emit("limit_exceeded",{metrics:this.metrics,exceeded:t}),this.enforcement){case"kill":this.kill(`Limit exceeded: ${t.join(", ")}`);break;case"throttle":break;case"warn":Tn.totalWarned++;break;case"pause":Bi.emit("paused",this.metrics.executionId);break}}kill(t){if(!this.killed){this.killed=!0,this.metrics.killed=!0,this.metrics.killReason=t,Tn.totalKilled++,NT({event:"kill",reason:t,executionId:this.metrics.executionId,toolName:this.metrics.toolName,metrics:this.metrics});for(let n of this.childProcs)try{n.kill("SIGKILL")}catch{}if(this.abortCallback)try{this.abortCallback()}catch{}Bi.emit("killed",{metrics:this.metrics,reason:t})}}recordNetworkCall(t,n=0){return this.killed?!1:this.networkBucket.consume(1)?(this.metrics.networkCalls++,this.metrics.networkBytes+=n,t&&(this.metrics.perHostCalls[t]=(this.metrics.perHostCalls[t]||0)+1,this.quota.perHostCallLimit&&this.metrics.perHostCalls[t]>this.quota.perHostCallLimit)?(this.handleViolation(["network_calls"]),!1):(this.checkLimits(),!0)):(this.recordAnomaly({type:"network_flood",severity:"warn",message:`Network rate limit hit (${this.quota.networkRatePerSec||0}/s)`,timestamp:Date.now()}),!1)}recordFork(){return this.killed?!1:this.forkBucket.consume(1)?(this.metrics.forksTotal++,this.metrics.forkTimes.push(Date.now()),this.checkLimits(),!0):(this.recordAnomaly({type:"fork_bomb",severity:"warn",message:"Fork rate limit hit",timestamp:Date.now()}),!1)}registerChild(t){this.childProcs.add(t),t.on("exit",()=>this.childProcs.delete(t))}}});var vv={};$(vv,{checkBoundary:()=>$me,configure:()=>Mme,createAttestation:()=>Ame,detectInstructionInjection:()=>xB,downgradeContext:()=>Cme,formatBoundaryResult:()=>jme,generateComplianceReport:()=>Ome,getAuditLog:()=>Lme,getConfig:()=>Ime,getEvents:()=>Fme,getStats:()=>Eme,getZoneCapabilities:()=>_me,getZoneLevel:()=>Pme,isZoneHigher:()=>Rme,listZones:()=>$B,resetStats:()=>Dme,verifyAttestation:()=>Tme});import{existsSync as vB,mkdirSync as hme,readFileSync as SB,writeFileSync as wB}from"fs";import{join as yv}from"path";import{homedir as yme}from"os";import{createHash as bme,randomBytes as vme}from"crypto";import{EventEmitter as Sme}from"events";function GT(){hme(bv,{recursive:!0})}function kme(){if(GT(),vB(UT))try{oe={...oe,...JSON.parse(SB(UT,"utf-8"))}}catch{}}function Nc(){GT();try{wB(UT,JSON.stringify(oe,null,2),"utf-8")}catch{}}function zT(e){if(qn.enableAuditLog){GT();try{wB(HT,JSON.stringify({...e,timestamp:Date.now()})+`
1325
- `,{flag:"a"})}catch{}}}function xme(e,t){let n=Ni[t];return!n||n.deniedCapabilities.has(e)||n.deniedCapabilities.has("*")?!1:!!(n.allowedCapabilities.has("*")||n.allowedCapabilities.has(e))}function $me(e,t,n){if(!qn.enabled)return{allowed:!0,reason:"Boundaries disabled",effectiveZone:e.zone,effectiveLevel:Ni[e.zone]?.level||0};oe.totalChecks++,oe.byZone[e.zone]=(oe.byZone[e.zone]||0)+1;let r=Ni[e.zone]?.level||0,s=Ni[t.zone]?.level||0;return qn.blockUpwardFlow&&r<s?(oe.totalBlocked++,oe.totalUpwardFlowAttempts++,oe.byViolationType.upward_flow=(oe.byViolationType.upward_flow||0)+1,Nc(),zT({event:"upward_flow_blocked",from:e.zone,to:t.zone,fromLevel:r,toLevel:s}),Gm.emit("boundary_violation",{type:"upward_flow",fromContext:e,toContext:t}),{allowed:!1,reason:`Upward flow blocked: ${e.zone} (${r}) \u2192 ${t.zone} (${s})`,effectiveZone:e.zone,effectiveLevel:r,violationType:"upward_flow"}):n&&qn.enforceCapabilities&&!xme(n,e.zone)?(oe.totalBlocked++,oe.totalCapabilityEscalations++,oe.byViolationType.capability_escalation=(oe.byViolationType.capability_escalation||0)+1,Nc(),zT({event:"capability_escalation_blocked",zone:e.zone,capability:n}),Gm.emit("boundary_violation",{type:"capability_escalation",fromContext:e,capability:n}),{allowed:!1,reason:`Capability "${n}" not allowed in zone "${e.zone}"`,effectiveZone:e.zone,effectiveLevel:r,violationType:"capability_escalation"}):qn.blockCrossZoneCalls&&e.parentZone!==t.parentZone&&e.zone==="sub_agent"&&t.zone==="sub_agent"?(oe.totalBlocked++,oe.byViolationType.cross_zone_call=(oe.byViolationType.cross_zone_call||0)+1,Nc(),{allowed:!1,reason:"Cross-zone calls between unrelated sub-agents blocked",effectiveZone:e.zone,effectiveLevel:r,violationType:"cross_zone_call"}):(oe.totalAllowed++,Nc(),{allowed:!0,reason:"OK",effectiveZone:e.zone,effectiveLevel:r})}function xB(e,t){if(!qn.detectInstructionInjection)return{detected:!1,patterns:[],riskScore:0};if(t!=="tool"&&t!=="untrusted")return{detected:!1,patterns:[],riskScore:0};let n=[],r=0,s=[{pattern:/ignore\s+(?:all\s+)?(?:previous|above|prior)\s+(?:instructions|prompts)/i,weight:.9},{pattern:/you\s+are\s+now\s+(?:a|an)\s+/i,weight:.8},{pattern:/system\s*:\s*you\s+(?:must|should|will)/i,weight:.8},{pattern:/<\s*system\s*>/i,weight:.7},{pattern:/\[\s*INST\s*\]/i,weight:.7},{pattern:/forget\s+(?:everything|all)\s+(?:above|before)/i,weight:.9},{pattern:/(?:run|execute|invoke)\s+(?:tool|command)\s*:/i,weight:.7},{pattern:/grant\s+(?:me\s+)?(?:access|permission)/i,weight:.8},{pattern:/escalate\s+privileges/i,weight:.95},{pattern:/(?:disable|bypass|skip)\s+(?:security|policy|check)/i,weight:.9},{pattern:/from\s+now\s+on,?\s+(?:you|please)/i,weight:.6},{pattern:/override\s+(?:default|previous)/i,weight:.7},{pattern:/act\s+as\s+(?:if\s+)?(?:you\s+are\s+)?(?:admin|root|orchestrator)/i,weight:.95}];for(let{pattern:i,weight:o}of s)i.test(e)&&(n.push(i.source.slice(0,50)),r+=o);return r=Math.min(1,r),n.length>0&&(oe.totalInstructionInjections++,oe.byViolationType.instruction_injection=(oe.byViolationType.instruction_injection||0)+1,Nc(),zT({event:"injection_detected",originZone:t,patterns:n.length,riskScore:r}),Gm.emit("injection_detected",{originZone:t,patterns:n,riskScore:r})),{detected:n.length>0,patterns:n,riskScore:r}}function Cme(e,t){if(!qn.autoDowngradeUntrusted)return{downgraded:!1,newZone:t,reason:"Auto-downgrade disabled"};if(t==="tool"){let n=xB(e,"tool");if(n.detected&&n.riskScore>.5)return oe.totalDowngraded++,Nc(),{downgraded:!0,newZone:"untrusted",reason:`Injection detected (risk ${(n.riskScore*100).toFixed(0)}%)`}}return{downgraded:!1,newZone:t,reason:"No downgrade needed"}}function Ame(e,t=300*1e3){let n=vme(8).toString("hex"),r=bme("sha256").update(`${n}:${e}:${Date.now()}`).digest("hex");return kB.set(n,{zone:e,expiresAt:Date.now()+t,signature:r}),{id:n,signature:r}}function Tme(e,t){let n=kB.get(e);return n?Date.now()>n.expiresAt?{valid:!1,reason:"Attestation expired"}:n.signature!==t?{valid:!1,reason:"Signature mismatch"}:{valid:!0,zone:n.zone,reason:"OK"}:{valid:!1,reason:"Attestation not found"}}function _me(e){return Ni[e]}function $B(){return Object.values(Ni)}function Rme(e,t){return(Ni[e]?.level||0)>(Ni[t]?.level||0)}function Pme(e){return Ni[e]?.level||0}function Ime(){return{...qn}}function Mme(e){qn={...qn,...e}}function Eme(){return{...oe}}function Dme(){oe={totalChecks:0,totalAllowed:0,totalBlocked:0,totalDowngraded:0,totalUpwardFlowAttempts:0,totalCapabilityEscalations:0,totalInstructionInjections:0,byViolationType:{},byZone:{}},Nc()}function Fme(){return Gm}function Lme(e=100){if(!vB(HT))return[];try{return SB(HT,"utf-8").split(`
1326
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Ome(){let e=[];e.push("# Trust Boundary Enforcement Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total checks: ${oe.totalChecks}`),e.push(`- \u2713 Allowed: ${oe.totalAllowed}`),e.push(`- \u{1F6AB} Blocked: ${oe.totalBlocked}`),e.push(`- \u{1F53D} Downgraded: ${oe.totalDowngraded}`),e.push(`- \u{1F53C} Upward flow attempts: ${oe.totalUpwardFlowAttempts}`),e.push(`- \u{1F6A8} Capability escalations: ${oe.totalCapabilityEscalations}`),e.push(`- \u{1F489} Instruction injections: ${oe.totalInstructionInjections}`),e.push(""),e.push("## Trust Zones");for(let t of $B())e.push(`- ${t.zone} (level ${t.level}):`),e.push(` Allowed: ${Array.from(t.allowedCapabilities).join(", ")||"none"}`),t.deniedCapabilities.size>0&&e.push(` Denied: ${Array.from(t.deniedCapabilities).join(", ")}`);e.push(""),e.push("## Violations By Type");for(let[t,n]of Object.entries(oe.byViolationType).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 4-tier hierarchical zones (user > orchestrator > sub-agent > tool)"),e.push("- \u2713 Untrusted zone for external content"),e.push(`- ${qn.blockUpwardFlow?"\u2713":"\u2717"} Block upward instruction flow`),e.push(`- ${qn.enforceCapabilities?"\u2713":"\u2717"} Capability enforcement`),e.push(`- ${qn.detectInstructionInjection?"\u2713":"\u2717"} Instruction injection detection`),e.push(`- ${qn.autoDowngradeUntrusted?"\u2713":"\u2717"} Auto-downgrade tool\u2192untrusted`),e.push(`- ${qn.blockCrossZoneCalls?"\u2713":"\u2717"} Block cross-zone calls`),e.push("- \u2713 Cross-boundary attestation"),e.push(`- ${qn.enableAuditLog?"\u2713":"\u2717"} Audit log`),e.join(`
1322
+ `)}var Bpe,Npe,Wt,qm,LT,qpe,OT,Upe,Bi,Yo,fr,Bm,Tn,gv,jT,zm=w(()=>{"use strict";Bpe={cpuTimeMs:6e4,wallTimeMs:12e4,memoryMaxBytes:1024*1024*512,maxNetworkCalls:100,maxNetworkBytes:100*1024*1024,perHostCallLimit:50,networkRatePerSec:20,maxForks:50,forkRatePerSec:10,maxFileDescriptors:256,maxToolCalls:30,maxRecursionDepth:10,diskIoMaxBytes:500*1024*1024},Npe={enabled:!0,defaultQuota:Bpe,samplingIntervalMs:100,defaultEnforcement:"kill",killOnAnomaly:!0,globalKillSwitch:!1,enableAdaptive:!0,adaptiveLearningRate:.2,enablePredictive:!0,enableTelemetry:!0,retainHistoryCount:500,spikeThresholdMultiplier:3,sustainedDurationMs:1e4,forkBombThresholdPerSec:50,memoryLeakSlope:.1},Wt={...Npe},qm=Nm(Mpe(),".aiaca","resource-limiter"),LT=Nm(qm,"budgets.json"),qpe=Nm(qm,"metrics.jsonl"),OT=Nm(qm,"stats.json"),Upe=Nm(qm,"ledger.jsonl"),Bi=new Ope;Bi.setMaxListeners(100);Yo=new Map,fr=new Map,Bm=[],Tn={totalExecutions:0,totalKilled:0,totalThrottled:0,totalWarned:0,totalAnomalies:0,byTool:{},byExceeded:{},byAnomaly:{}};Hpe();gv=class{constructor(t,n){this.capacity=t;this.refillPerSec=n;this.tokens=t,this.lastRefill=Date.now()}capacity;refillPerSec;tokens;lastRefill;consume(t=1){return this.refill(),this.tokens>=t?(this.tokens-=t,!0):!1}available(){return this.refill(),this.tokens}refill(){let t=Date.now(),n=(t-this.lastRefill)/1e3;this.tokens=Math.min(this.capacity,this.tokens+n*this.refillPerSec),this.lastRefill=t}},jT=class{metrics;quota;enforcement;pid;childProcs=new Set;samplerInterval;killed=!1;cpuStart;startCpuMs=0;networkBucket;forkBucket;memoryHistory=[];cpuHistory=[];abortCallback;constructor(t,n,r,s){this.quota=r,this.enforcement=s,this.metrics={toolName:t,executionId:n,startTime:Date.now(),cpuTimeUsedMs:0,wallTimeUsedMs:0,memoryPeakBytes:0,memoryAvgBytes:0,memorySamples:0,networkCalls:0,networkBytes:0,perHostCalls:{},forksTotal:0,forkTimes:[],toolCallsCount:0,recursionDepth:0,killed:!1,exceeded:[],anomalies:[]};let i=process.cpuUsage();this.cpuStart={user:i.user,system:i.system},this.networkBucket=new gv(r.networkRatePerSec||100,r.networkRatePerSec||100),this.forkBucket=new gv(r.forkRatePerSec||10,r.forkRatePerSec||10)}startSampling(){this.samplerInterval=setInterval(()=>this.sample(),Wt.samplingIntervalMs)}stopSampling(){this.samplerInterval&&(clearInterval(this.samplerInterval),this.samplerInterval=void 0)}sample(){if(this.killed)return;let t=Date.now();this.metrics.wallTimeUsedMs=t-this.metrics.startTime;let n=process.cpuUsage(),r=n.user-this.cpuStart.user+(n.system-this.cpuStart.system);this.metrics.cpuTimeUsedMs=Math.floor(r/1e3),this.cpuHistory.push(this.metrics.cpuTimeUsedMs),this.cpuHistory.length>100&&this.cpuHistory.shift();try{let i=process.memoryUsage().rss;this.metrics.memorySamples++,this.metrics.memoryAvgBytes=(this.metrics.memoryAvgBytes*(this.metrics.memorySamples-1)+i)/this.metrics.memorySamples,this.metrics.memoryPeakBytes=Math.max(this.metrics.memoryPeakBytes,i),this.memoryHistory.push(i),this.memoryHistory.length>200&&this.memoryHistory.shift()}catch{}this.checkLimits(),this.detectAnomalies()}checkLimits(){let t=this.quota,n=this.metrics,r=[];t.wallTimeMs&&n.wallTimeUsedMs>t.wallTimeMs&&r.push("wall_time"),t.cpuTimeMs&&n.cpuTimeUsedMs>t.cpuTimeMs&&r.push("cpu_time"),t.memoryMaxBytes&&n.memoryPeakBytes>t.memoryMaxBytes&&r.push("memory"),t.maxNetworkCalls&&n.networkCalls>t.maxNetworkCalls&&r.push("network_calls"),t.maxNetworkBytes&&n.networkBytes>t.maxNetworkBytes&&r.push("network_bytes"),t.maxForks&&n.forksTotal>t.maxForks&&r.push("fork_count"),t.maxToolCalls&&n.toolCallsCount>t.maxToolCalls&&r.push("tool_calls"),r.length>0&&(n.exceeded.push(...r.filter(s=>!n.exceeded.includes(s))),this.handleViolation(r))}detectAnomalies(){if(this.memoryHistory.length>=10){let n=this.memoryHistory[this.memoryHistory.length-1],r=this.memoryHistory.slice(0,-5).reduce((s,i)=>s+i,0)/Math.max(1,this.memoryHistory.length-5);r>0&&n>r*Wt.spikeThresholdMultiplier&&this.recordAnomaly({type:"spike",severity:"warn",message:`Memory spike: ${(n/1024/1024).toFixed(0)}MB (${(n/r).toFixed(1)}\xD7 baseline)`,timestamp:Date.now(),value:n,threshold:r})}if(this.memoryHistory.length>=50){let n=Gpe(this.memoryHistory.slice(-50)),r=this.memoryHistory[0];r>0&&n/r>Wt.memoryLeakSlope/6e4*100&&this.recordAnomaly({type:"memory_leak",severity:"warn",message:`Possible memory leak: +${(n*6e4/1024/1024).toFixed(1)}MB/min`,timestamp:Date.now()})}let t=this.metrics.forkTimes.filter(n=>Date.now()-n<1e3).length;if(t>=Wt.forkBombThresholdPerSec&&(this.recordAnomaly({type:"fork_bomb",severity:"critical",message:`Fork bomb detected: ${t} forks in last second`,timestamp:Date.now(),value:t}),Wt.killOnAnomaly&&this.kill("fork_bomb")),this.metrics.networkCalls>0&&this.metrics.wallTimeUsedMs>0){let n=this.metrics.networkCalls/(this.metrics.wallTimeUsedMs/1e3);n>100&&this.recordAnomaly({type:"network_flood",severity:"critical",message:`Network flood: ${n.toFixed(0)} calls/sec`,timestamp:Date.now(),value:n})}if(this.cpuHistory.length>=20){let n=this.cpuHistory.slice(-20),r=(n[n.length-1]-n[0])/(Wt.samplingIntervalMs*20);r>.95&&this.recordAnomaly({type:"cpu_burn",severity:"warn",message:`Sustained CPU burn: ${(r*100).toFixed(0)}%`,timestamp:Date.now(),value:r})}}recordAnomaly(t){this.metrics.anomalies.filter(r=>Date.now()-r.timestamp<1e3).some(r=>r.type===t.type)||(this.metrics.anomalies.push(t),Tn.totalAnomalies++,Tn.byAnomaly[t.type]=(Tn.byAnomaly[t.type]||0)+1,Bi.emit("anomaly",t),t.severity==="critical"&&Bi.emit("critical_anomaly",t))}handleViolation(t){for(let n of t)Tn.byExceeded[n]=(Tn.byExceeded[n]||0)+1;switch(Bi.emit("limit_exceeded",{metrics:this.metrics,exceeded:t}),this.enforcement){case"kill":this.kill(`Limit exceeded: ${t.join(", ")}`);break;case"throttle":break;case"warn":Tn.totalWarned++;break;case"pause":Bi.emit("paused",this.metrics.executionId);break}}kill(t){if(!this.killed){this.killed=!0,this.metrics.killed=!0,this.metrics.killReason=t,Tn.totalKilled++,NT({event:"kill",reason:t,executionId:this.metrics.executionId,toolName:this.metrics.toolName,metrics:this.metrics});for(let n of this.childProcs)try{n.kill("SIGKILL")}catch{}if(this.abortCallback)try{this.abortCallback()}catch{}Bi.emit("killed",{metrics:this.metrics,reason:t})}}recordNetworkCall(t,n=0){return this.killed?!1:this.networkBucket.consume(1)?(this.metrics.networkCalls++,this.metrics.networkBytes+=n,t&&(this.metrics.perHostCalls[t]=(this.metrics.perHostCalls[t]||0)+1,this.quota.perHostCallLimit&&this.metrics.perHostCalls[t]>this.quota.perHostCallLimit)?(this.handleViolation(["network_calls"]),!1):(this.checkLimits(),!0)):(this.recordAnomaly({type:"network_flood",severity:"warn",message:`Network rate limit hit (${this.quota.networkRatePerSec||0}/s)`,timestamp:Date.now()}),!1)}recordFork(){return this.killed?!1:this.forkBucket.consume(1)?(this.metrics.forksTotal++,this.metrics.forkTimes.push(Date.now()),this.checkLimits(),!0):(this.recordAnomaly({type:"fork_bomb",severity:"warn",message:"Fork rate limit hit",timestamp:Date.now()}),!1)}registerChild(t){this.childProcs.add(t),t.on("exit",()=>this.childProcs.delete(t))}}});var vv={};$(vv,{checkBoundary:()=>$me,configure:()=>Mme,createAttestation:()=>Ame,detectInstructionInjection:()=>xB,downgradeContext:()=>Cme,formatBoundaryResult:()=>jme,generateComplianceReport:()=>Ome,getAuditLog:()=>Lme,getConfig:()=>Ime,getEvents:()=>Fme,getStats:()=>Eme,getZoneCapabilities:()=>_me,getZoneLevel:()=>Pme,isZoneHigher:()=>Rme,listZones:()=>$B,resetStats:()=>Dme,verifyAttestation:()=>Tme});import{existsSync as vB,mkdirSync as hme,readFileSync as SB,writeFileSync as wB}from"fs";import{join as yv}from"path";import{homedir as yme}from"os";import{createHash as bme,randomBytes as vme}from"crypto";import{EventEmitter as Sme}from"events";function GT(){hme(bv,{recursive:!0})}function kme(){if(GT(),vB(UT))try{ae={...ae,...JSON.parse(SB(UT,"utf-8"))}}catch{}}function Nc(){GT();try{wB(UT,JSON.stringify(ae,null,2),"utf-8")}catch{}}function zT(e){if(qn.enableAuditLog){GT();try{wB(HT,JSON.stringify({...e,timestamp:Date.now()})+`
1323
+ `,{flag:"a"})}catch{}}}function xme(e,t){let n=Ni[t];return!n||n.deniedCapabilities.has(e)||n.deniedCapabilities.has("*")?!1:!!(n.allowedCapabilities.has("*")||n.allowedCapabilities.has(e))}function $me(e,t,n){if(!qn.enabled)return{allowed:!0,reason:"Boundaries disabled",effectiveZone:e.zone,effectiveLevel:Ni[e.zone]?.level||0};ae.totalChecks++,ae.byZone[e.zone]=(ae.byZone[e.zone]||0)+1;let r=Ni[e.zone]?.level||0,s=Ni[t.zone]?.level||0;return qn.blockUpwardFlow&&r<s?(ae.totalBlocked++,ae.totalUpwardFlowAttempts++,ae.byViolationType.upward_flow=(ae.byViolationType.upward_flow||0)+1,Nc(),zT({event:"upward_flow_blocked",from:e.zone,to:t.zone,fromLevel:r,toLevel:s}),Gm.emit("boundary_violation",{type:"upward_flow",fromContext:e,toContext:t}),{allowed:!1,reason:`Upward flow blocked: ${e.zone} (${r}) \u2192 ${t.zone} (${s})`,effectiveZone:e.zone,effectiveLevel:r,violationType:"upward_flow"}):n&&qn.enforceCapabilities&&!xme(n,e.zone)?(ae.totalBlocked++,ae.totalCapabilityEscalations++,ae.byViolationType.capability_escalation=(ae.byViolationType.capability_escalation||0)+1,Nc(),zT({event:"capability_escalation_blocked",zone:e.zone,capability:n}),Gm.emit("boundary_violation",{type:"capability_escalation",fromContext:e,capability:n}),{allowed:!1,reason:`Capability "${n}" not allowed in zone "${e.zone}"`,effectiveZone:e.zone,effectiveLevel:r,violationType:"capability_escalation"}):qn.blockCrossZoneCalls&&e.parentZone!==t.parentZone&&e.zone==="sub_agent"&&t.zone==="sub_agent"?(ae.totalBlocked++,ae.byViolationType.cross_zone_call=(ae.byViolationType.cross_zone_call||0)+1,Nc(),{allowed:!1,reason:"Cross-zone calls between unrelated sub-agents blocked",effectiveZone:e.zone,effectiveLevel:r,violationType:"cross_zone_call"}):(ae.totalAllowed++,Nc(),{allowed:!0,reason:"OK",effectiveZone:e.zone,effectiveLevel:r})}function xB(e,t){if(!qn.detectInstructionInjection)return{detected:!1,patterns:[],riskScore:0};if(t!=="tool"&&t!=="untrusted")return{detected:!1,patterns:[],riskScore:0};let n=[],r=0,s=[{pattern:/ignore\s+(?:all\s+)?(?:previous|above|prior)\s+(?:instructions|prompts)/i,weight:.9},{pattern:/you\s+are\s+now\s+(?:a|an)\s+/i,weight:.8},{pattern:/system\s*:\s*you\s+(?:must|should|will)/i,weight:.8},{pattern:/<\s*system\s*>/i,weight:.7},{pattern:/\[\s*INST\s*\]/i,weight:.7},{pattern:/forget\s+(?:everything|all)\s+(?:above|before)/i,weight:.9},{pattern:/(?:run|execute|invoke)\s+(?:tool|command)\s*:/i,weight:.7},{pattern:/grant\s+(?:me\s+)?(?:access|permission)/i,weight:.8},{pattern:/escalate\s+privileges/i,weight:.95},{pattern:/(?:disable|bypass|skip)\s+(?:security|policy|check)/i,weight:.9},{pattern:/from\s+now\s+on,?\s+(?:you|please)/i,weight:.6},{pattern:/override\s+(?:default|previous)/i,weight:.7},{pattern:/act\s+as\s+(?:if\s+)?(?:you\s+are\s+)?(?:admin|root|orchestrator)/i,weight:.95}];for(let{pattern:i,weight:o}of s)i.test(e)&&(n.push(i.source.slice(0,50)),r+=o);return r=Math.min(1,r),n.length>0&&(ae.totalInstructionInjections++,ae.byViolationType.instruction_injection=(ae.byViolationType.instruction_injection||0)+1,Nc(),zT({event:"injection_detected",originZone:t,patterns:n.length,riskScore:r}),Gm.emit("injection_detected",{originZone:t,patterns:n,riskScore:r})),{detected:n.length>0,patterns:n,riskScore:r}}function Cme(e,t){if(!qn.autoDowngradeUntrusted)return{downgraded:!1,newZone:t,reason:"Auto-downgrade disabled"};if(t==="tool"){let n=xB(e,"tool");if(n.detected&&n.riskScore>.5)return ae.totalDowngraded++,Nc(),{downgraded:!0,newZone:"untrusted",reason:`Injection detected (risk ${(n.riskScore*100).toFixed(0)}%)`}}return{downgraded:!1,newZone:t,reason:"No downgrade needed"}}function Ame(e,t=300*1e3){let n=vme(8).toString("hex"),r=bme("sha256").update(`${n}:${e}:${Date.now()}`).digest("hex");return kB.set(n,{zone:e,expiresAt:Date.now()+t,signature:r}),{id:n,signature:r}}function Tme(e,t){let n=kB.get(e);return n?Date.now()>n.expiresAt?{valid:!1,reason:"Attestation expired"}:n.signature!==t?{valid:!1,reason:"Signature mismatch"}:{valid:!0,zone:n.zone,reason:"OK"}:{valid:!1,reason:"Attestation not found"}}function _me(e){return Ni[e]}function $B(){return Object.values(Ni)}function Rme(e,t){return(Ni[e]?.level||0)>(Ni[t]?.level||0)}function Pme(e){return Ni[e]?.level||0}function Ime(){return{...qn}}function Mme(e){qn={...qn,...e}}function Eme(){return{...ae}}function Dme(){ae={totalChecks:0,totalAllowed:0,totalBlocked:0,totalDowngraded:0,totalUpwardFlowAttempts:0,totalCapabilityEscalations:0,totalInstructionInjections:0,byViolationType:{},byZone:{}},Nc()}function Fme(){return Gm}function Lme(e=100){if(!vB(HT))return[];try{return SB(HT,"utf-8").split(`
1324
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function Ome(){let e=[];e.push("# Trust Boundary Enforcement Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Summary"),e.push(`- Total checks: ${ae.totalChecks}`),e.push(`- \u2713 Allowed: ${ae.totalAllowed}`),e.push(`- \u{1F6AB} Blocked: ${ae.totalBlocked}`),e.push(`- \u{1F53D} Downgraded: ${ae.totalDowngraded}`),e.push(`- \u{1F53C} Upward flow attempts: ${ae.totalUpwardFlowAttempts}`),e.push(`- \u{1F6A8} Capability escalations: ${ae.totalCapabilityEscalations}`),e.push(`- \u{1F489} Instruction injections: ${ae.totalInstructionInjections}`),e.push(""),e.push("## Trust Zones");for(let t of $B())e.push(`- ${t.zone} (level ${t.level}):`),e.push(` Allowed: ${Array.from(t.allowedCapabilities).join(", ")||"none"}`),t.deniedCapabilities.size>0&&e.push(` Denied: ${Array.from(t.deniedCapabilities).join(", ")}`);e.push(""),e.push("## Violations By Type");for(let[t,n]of Object.entries(ae.byViolationType).sort((r,s)=>s[1]-r[1]))e.push(`- ${t}: ${n}`);return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 4-tier hierarchical zones (user > orchestrator > sub-agent > tool)"),e.push("- \u2713 Untrusted zone for external content"),e.push(`- ${qn.blockUpwardFlow?"\u2713":"\u2717"} Block upward instruction flow`),e.push(`- ${qn.enforceCapabilities?"\u2713":"\u2717"} Capability enforcement`),e.push(`- ${qn.detectInstructionInjection?"\u2713":"\u2717"} Instruction injection detection`),e.push(`- ${qn.autoDowngradeUntrusted?"\u2713":"\u2717"} Auto-downgrade tool\u2192untrusted`),e.push(`- ${qn.blockCrossZoneCalls?"\u2713":"\u2717"} Block cross-zone calls`),e.push("- \u2713 Cross-boundary attestation"),e.push(`- ${qn.enableAuditLog?"\u2713":"\u2717"} Audit log`),e.join(`
1327
1325
  `)}function jme(e){let t=e.allowed?"\u2713":"\u{1F6AB}",n=[];return n.push(`${t} **${e.allowed?"ALLOWED":"BLOCKED"}**`),n.push(`Reason: ${e.reason}`),n.push(`Zone: ${e.effectiveZone} (level ${e.effectiveLevel})`),e.violationType&&n.push(`Violation: ${e.violationType}`),e.downgradedZone&&n.push(`Downgraded to: ${e.downgradedZone}`),n.join(`
1328
- `)}var wme,qn,bv,UT,HT,UMe,Gm,Ni,oe,kB,Sv=w(()=>{"use strict";wme={enabled:!0,enforceStrictBoundaries:!0,blockUpwardFlow:!0,blockCrossZoneCalls:!1,enforceCapabilities:!0,defaultDenyUnknown:!0,detectInstructionInjection:!0,autoDowngradeUntrusted:!0,enableAuditLog:!0},qn={...wme},bv=yv(yme(),".aiaca","trust-boundaries"),UT=yv(bv,"stats.json"),HT=yv(bv,"audit.jsonl"),UMe=yv(bv,"attestations.json"),Gm=new Sme;Gm.setMaxListeners(50);Ni={user:{zone:"user",level:100,allowedCapabilities:new Set(["*"]),deniedCapabilities:new Set},orchestrator:{zone:"orchestrator",level:75,allowedCapabilities:new Set(["fs:read","fs:write","fs:delete","network:read","network:write","system:exec","system:env","agent:spawn","agent:terminate","agent:configure","memory:read","memory:write","memory:purge","permissions:grant","permissions:revoke","config:read","config:write","identity:create","identity:revoke","audit:read"]),deniedCapabilities:new Set(["audit:write"])},sub_agent:{zone:"sub_agent",level:50,allowedCapabilities:new Set(["fs:read","fs:write","network:read","network:write","system:exec","memory:read","memory:write","config:read","audit:read"]),deniedCapabilities:new Set(["fs:delete","system:env","agent:spawn","agent:terminate","agent:configure","memory:purge","permissions:grant","permissions:revoke","config:write","identity:create","identity:revoke","audit:write"])},tool:{zone:"tool",level:25,allowedCapabilities:new Set([]),deniedCapabilities:new Set(["*"])},untrusted:{zone:"untrusted",level:0,allowedCapabilities:new Set([]),deniedCapabilities:new Set(["*"])}},oe={totalChecks:0,totalAllowed:0,totalBlocked:0,totalDowngraded:0,totalUpwardFlowAttempts:0,totalCapabilityEscalations:0,totalInstructionInjections:0,byViolationType:{},byZone:{}},kB=new Map;kme()});var $v={};$($v,{clearCalibration:()=>sge,configure:()=>nge,estimate:()=>IB,estimateStepTokens:()=>QT,estimateTokensFromText:()=>PB,formatEstimate:()=>oge,getBudget:()=>ZT,getCalibration:()=>rge,getConfig:()=>tge,getStats:()=>age,listModels:()=>ige,recordActualExecution:()=>Hme,recordApproval:()=>cge,recordSpend:()=>Xme,releaseReservation:()=>Zme,reserveBudget:()=>Qme,resetBudget:()=>ege,setBudget:()=>Yme});import{existsSync as CB,mkdirSync as Bme,readFileSync as AB,writeFileSync as TB}from"fs";import{join as kv}from"path";import{homedir as Nme}from"os";function YT(){Bme(xv,{recursive:!0})}function Ume(){if(YT(),CB(VT))try{Kt={...Kt,...JSON.parse(AB(VT,"utf-8"))}}catch{}}function _B(){YT();try{TB(VT,JSON.stringify(Kt,null,2),"utf-8")}catch{}}function Hme(e,t,n,r,s,i){if(!Un.enableCalibration)return;if(t){Kt.toolStats[t]||(Kt.toolStats[t]={actualLatencyMs:[],actualTokens:[],actualRetryRate:0,sampleCount:0});let a=Kt.toolStats[t];a.actualLatencyMs.push(r),a.actualTokens.push(n),a.actualLatencyMs.length>100&&a.actualLatencyMs.shift(),a.actualTokens.length>100&&a.actualTokens.shift(),a.sampleCount++,i?a.actualRetryRate=(a.actualRetryRate*(a.sampleCount-1)+1)/a.sampleCount:a.actualRetryRate=a.actualRetryRate*(a.sampleCount-1)/a.sampleCount}Kt.modelStats[s]||(Kt.modelStats[s]={actualTokensPerSecond:[],actualLatencyMs:[],sampleCount:0});let o=Kt.modelStats[s];o.actualLatencyMs.push(r),r>0&&o.actualTokensPerSecond.push(n/r*1e3),o.actualLatencyMs.length>100&&o.actualLatencyMs.shift(),o.actualTokensPerSecond.length>100&&o.actualTokensPerSecond.shift(),o.sampleCount++,_B()}function RB(e){let t=WT[e]||WT.default;if(!Un.enableCalibration)return t;let n=Kt.toolStats[e];if(!n||n.sampleCount<3)return t;let r=Un.calibrationWeight,s=n.actualLatencyMs.reduce((o,a)=>o+a,0)/n.actualLatencyMs.length,i=n.actualTokens.reduce((o,a)=>o+a,0)/n.actualTokens.length;return{avgLatencyMs:Math.round(t.avgLatencyMs*(1-r)+s*r),estimatedTokens:Math.round(t.estimatedTokens*(1-r)+i*r),retryProbability:t.retryProbability*(1-r)+n.actualRetryRate*r}}function PB(e){return Math.ceil(e.length/Un.charsPerToken)}function QT(e){let t=0,n=0;if(e.estimatedInputTokens!==void 0&&(t=e.estimatedInputTokens),e.estimatedOutputTokens!==void 0&&(n=e.estimatedOutputTokens),t===0){if(e.type==="llm_call"||e.type==="specialist")t=PB(e.description)+Un.systemPromptTokens;else if(e.type==="tool_call"&&e.toolName){let s=RB(e.toolName);t=Un.toolOverheadTokens,n=s.estimatedTokens}}n===0&&e.type==="llm_call"&&(n=Math.min(2e3,Math.max(200,t*.3))),e.type==="specialist"&&(n=n||5e3);let r=e.retryProbability??0;return r>0&&(t=Math.round(t*(1+r*.5)),n=Math.round(n*(1+r*.5))),{input:t,output:n}}function zme(e){let t=[],n=0,r=0,s=0;function i(c){for(let l of c)s++,l.riskLevel==="risky"&&r++,(l.toolName==="bash"||l.toolName==="powershell")&&r++,l.childSteps&&i(l.childSteps)}if(i(e),s>0){let c=r/s;n+=c*.3,c>.3&&t.push(`${r}/${s} steps marked risky`)}s>30?(n+=.2,t.push(`Large plan (${s} steps) \u2014 higher chance of failure`)):s>15&&(n+=.1,t.push(`Medium plan (${s} steps)`)),e.filter(c=>(c.dependencies?.length||0)>0).length/Math.max(1,e.length)>.7&&(n+=.15,t.push("Highly sequential \u2014 failures cascade"));let a=0;i(e);for(let c of e)a+=c.retryProbability||0;return a>s*.2&&(n+=.15,t.push("Cumulative retry probability is high")),t.length===0&&t.push("Plan looks straightforward"),{score:Math.min(1,n),factors:t}}function IB(e,t){if(!Un.enabled)return Vme(e.length);let n=t||Un.defaultModel,r=qc[n]||qc[Un.defaultModel],s=0,i=0,o=0,a=0,c=0,l=0,u=0,d=0,f=MB(e);function p(De,Et=1){let gn=QT(De);s+=gn.input,i+=gn.output;let T=0;if(De.type==="tool_call"){l++;let ce=De.toolName?RB(De.toolName):WT.default;T=ce.avgLatencyMs,ce.externalCostUSD&&(c+=ce.externalCostUSD)}else if(De.type==="llm_call"||De.type==="specialist"){u++;let ce=Un.enableCalibration&&Kt.modelStats[n]?.actualTokensPerSecond.length>0?Kt.modelStats[n].actualTokensPerSecond.reduce((se,C)=>se+C,0)/Kt.modelStats[n].actualTokensPerSecond.length:r.tokensPerSecond;T=r.avgLatencyMs+gn.output/Math.max(1,ce)*1e3}else if(De.type==="parallel_group"){d++;let ce=0,se=0;if(De.childSteps)for(let C of De.childSteps){let M=p(C,Et);ce=Math.max(ce,M.duration),se+=M.duration}T=ce+500}else De.type==="manual"&&(T=0);return{duration:T}}for(let De of e){let Et=p(De);a+=Et.duration}let m=1,g=s/1e6*r.inputCostPerMTokens,h=i/1e6*r.outputCostPerMTokens,v=o/1e6*(r.cachedInputCostPerMTokens||r.inputCostPerMTokens*.1),y=g+h+v+c,b=Kt.overallEstimateRatios.length>=5?Gme(Kt.overallEstimateRatios):.3,k=y,S=y*(1+b*1.65),x=a,A=a*(1+b*1.65),j=zme(e),I=Math.max(.1,1-b)*(Kt.overallEstimateRatios.length>=10?1:.7),ye=Jme(e,y,n),Ne=Un.enableMultiModelComparison?Wme(e,n,y,a):[],mn=ZT(),nn=y<=mn.remainingUSD&&j.score<.7;return{estimatedInputTokens:s,estimatedOutputTokens:i,estimatedCachedTokens:o,estimatedCostUSD:y,costBreakdown:{inputCost:g,outputCost:h,cachedCost:v,toolCost:c},estimatedDurationMs:a,estimatedDurationFormatted:KT(a),parallelizationFactor:m,confidence:I,p50Cost:k,p95Cost:S,p50Duration:x,p95Duration:A,riskScore:j.score,riskFactors:j.factors,shouldApprove:nn,trimSuggestions:ye,alternativeModels:Ne,stepCount:f,toolCallCount:l,llmCallCount:u}}function MB(e){let t=0;for(let n of e)t++,n.childSteps&&(t+=MB(n.childSteps));return t}function Gme(e){let t=e.reduce((r,s)=>r+s,0)/e.length,n=e.reduce((r,s)=>r+Math.pow(s-t,2),0)/e.length;return Math.sqrt(n)}function KT(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}h ${n%60}m`:n>0?`${n}m ${t%60}s`:`${t}s`}function Vme(e){return{estimatedInputTokens:0,estimatedOutputTokens:0,estimatedCachedTokens:0,estimatedCostUSD:0,costBreakdown:{inputCost:0,outputCost:0,cachedCost:0,toolCost:0},estimatedDurationMs:0,estimatedDurationFormatted:"0s",parallelizationFactor:1,confidence:0,p50Cost:0,p95Cost:0,p50Duration:0,p95Duration:0,riskScore:0,riskFactors:[],shouldApprove:!0,trimSuggestions:[],alternativeModels:[],stepCount:e,toolCallCount:0,llmCallCount:0}}function Jme(e,t,n){let r=[];for(let o of e)o.type==="manual"&&r.push({stepId:o.id||o.description.slice(0,30),description:o.description,reason:"Manual step \u2014 consider deferring",costSavingsUSD:0,timeSavingsMs:0});let s=e.filter(o=>o.type==="specialist"&&(o.estimatedOutputTokens||0)>5e3);for(let o of s.slice(0,3)){let a=QT(o),c=qc[n]||qc[Un.defaultModel],l=a.input/1e6*c.inputCostPerMTokens+a.output/1e6*c.outputCostPerMTokens;r.push({stepId:o.id||o.description.slice(0,30),description:o.description,reason:"Specialist call expensive \u2014 consider scoping down or using cheaper model",costSavingsUSD:l*.7,timeSavingsMs:2e4})}let i=e.filter(o=>o.toolName==="web_fetch"||o.toolName==="web_search");return i.length>5&&r.push({stepId:"web_calls",description:`${i.length} web fetches`,reason:"Many web calls \u2014 verify caching is enabled",costSavingsUSD:i.length*.001,timeSavingsMs:i.length*1500}),r}function Wme(e,t,n,r){let s=[],i=qc[t];if(!i)return[];for(let[o,a]of Object.entries(qc)){if(o===t)continue;let c=IB(e,o),l=c.estimatedCostUSD/Math.max(n,1e-4),u="minimal",d="";if(a.tier==="cheap"&&i.tier!=="cheap")u=i.tier==="frontier"?"significant":"moderate",d=`Use for simple tasks (${(l*100).toFixed(0)}% cost)`;else if(a.tier==="frontier"&&i.tier!=="frontier")u="minimal",d=`Use for highest quality (${(l*100).toFixed(0)}% cost)`;else if(l<.5)u=i.tier==="frontier"&&a.tier==="cheap"?"significant":"moderate",d=`${(100-l*100).toFixed(0)}% cheaper`;else if(l>1.5)u="minimal",d=`${(l*100-100).toFixed(0)}% more expensive but better`;else continue;s.push({model:o,estimatedCostUSD:c.estimatedCostUSD,estimatedDurationMs:c.estimatedDurationMs,qualityImpact:u,recommendation:d})}return s.sort((o,a)=>o.estimatedCostUSD-a.estimatedCostUSD).slice(0,5)}function Kme(){if(CB(JT))try{te={...te,...JSON.parse(AB(JT,"utf-8"))}}catch{}}function Vm(){YT();try{TB(JT,JSON.stringify(te,null,2),"utf-8")}catch{}}function ZT(){return{...te,remainingUSD:te.totalBudgetUSD-te.spentUSD-te.reservedUSD}}function Yme(e){te={...te,...e},te.remainingUSD=te.totalBudgetUSD-te.spentUSD-te.reservedUSD,Vm()}function Qme(e){let t=te.totalBudgetUSD-te.spentUSD-te.reservedUSD;return Un.enforceBudget&&te.hardLimit&&e>t?{success:!1,reason:`Hard budget limit: ${t.toFixed(4)} remaining, ${e.toFixed(4)} requested`}:(te.reservedUSD+=e,te.remainingUSD-=e,Vm(),{success:!0})}function Zme(e){te.reservedUSD=Math.max(0,te.reservedUSD-e),te.remainingUSD=te.totalBudgetUSD-te.spentUSD-te.reservedUSD,Vm()}function Xme(e){te.spentUSD+=e,te.remainingUSD=te.totalBudgetUSD-te.spentUSD-te.reservedUSD,Vm()}function ege(){te.spentUSD=0,te.reservedUSD=0,te.remainingUSD=te.totalBudgetUSD,Vm()}function tge(){return{...Un}}function nge(e){Un={...Un,...e}}function rge(){return JSON.parse(JSON.stringify(Kt))}function sge(){Kt={toolStats:{},modelStats:{},overallEstimateRatios:[]},_B()}function ige(){return Object.values(qc)}function oge(e){let t=[],n=ZT();t.push("# \u{1F4B0} Cost Estimate"),t.push(""),t.push(`**Estimated Cost:** $${e.estimatedCostUSD.toFixed(4)} (P50: $${e.p50Cost.toFixed(4)}, P95: $${e.p95Cost.toFixed(4)})`),t.push(`**Estimated Duration:** ${e.estimatedDurationFormatted} (P95: ${KT(e.p95Duration)})`),t.push(`**Confidence:** ${(e.confidence*100).toFixed(0)}%`),t.push(""),t.push("## Plan Structure"),t.push(`- Total steps: ${e.stepCount}`),t.push(`- Tool calls: ${e.toolCallCount}`),t.push(`- LLM calls: ${e.llmCallCount}`),t.push(""),t.push("## Tokens"),t.push(`- Input: ${e.estimatedInputTokens.toLocaleString()}`),t.push(`- Output: ${e.estimatedOutputTokens.toLocaleString()}`),e.estimatedCachedTokens>0&&t.push(`- Cached: ${e.estimatedCachedTokens.toLocaleString()}`),t.push(""),t.push("## Cost Breakdown"),t.push(`- Input: $${e.costBreakdown.inputCost.toFixed(4)}`),t.push(`- Output: $${e.costBreakdown.outputCost.toFixed(4)}`),e.costBreakdown.cachedCost>0&&t.push(`- Cached: $${e.costBreakdown.cachedCost.toFixed(4)}`),e.costBreakdown.toolCost>0&&t.push(`- External APIs: $${e.costBreakdown.toolCost.toFixed(4)}`),t.push(""),t.push("## Risk Assessment");let r=e.riskScore<.3?"\u{1F7E2}":e.riskScore<.6?"\u{1F7E1}":"\u{1F534}";t.push(`${r} Risk score: ${(e.riskScore*100).toFixed(0)}/100`);for(let s of e.riskFactors)t.push(` - ${s}`);if(t.push(""),t.push("## Budget"),t.push(`- Total: $${n.totalBudgetUSD.toFixed(2)}`),t.push(`- Spent: $${n.spentUSD.toFixed(4)}`),t.push(`- Reserved: $${n.reservedUSD.toFixed(4)}`),t.push(`- Remaining: $${n.remainingUSD.toFixed(4)}`),e.estimatedCostUSD>n.remainingUSD&&t.push(`- \u26A0\uFE0F This plan exceeds remaining budget by $${(e.estimatedCostUSD-n.remainingUSD).toFixed(4)}`),t.push(""),e.trimSuggestions.length>0){t.push("## \u2702\uFE0F Trim Suggestions");for(let s of e.trimSuggestions)t.push(`- **${s.description}**: ${s.reason}`),s.costSavingsUSD>0&&t.push(` Savings: $${s.costSavingsUSD.toFixed(4)} | ${KT(s.timeSavingsMs)}`);t.push("")}if(e.alternativeModels.length>0){t.push("## \u{1F504} Alternative Models");for(let s of e.alternativeModels){let i=((s.estimatedCostUSD-e.estimatedCostUSD)/Math.max(e.estimatedCostUSD,1e-4)*100).toFixed(0),o=s.estimatedCostUSD<e.estimatedCostUSD?"":"+";t.push(`- **${s.model}**: $${s.estimatedCostUSD.toFixed(4)} (${o}${i}%) | quality impact: ${s.qualityImpact}`),t.push(` ${s.recommendation}`)}t.push("")}return t.push(`## ${e.shouldApprove?"\u2713 Recommendation: APPROVE":"\u26A0\uFE0F Recommendation: REVIEW"}`),e.shouldApprove||t.push("Plan exceeds budget or has high risk. Consider trimming or splitting."),t.join(`
1329
- `)}function age(){let e=0;for(let t of Object.values(Kt.toolStats))e+=t.sampleCount;for(let t of Object.values(Kt.modelStats))e+=t.sampleCount;return{...wv,totalCalibrationSamples:e}}function cge(e){e?wv.totalApproved++:wv.totalRejected++,wv.totalEstimates++}var qme,Un,xv,VT,JT,VMe,qc,WT,Kt,te,wv,Cv=w(()=>{"use strict";qme={enabled:!0,defaultModel:"gemini-2.5-flash-lite",defaultModelTier:"cheap",charsPerToken:4,toolOverheadTokens:200,systemPromptTokens:4e3,enforceBudget:!1,defaultBudgetUSD:5,warningThresholdPct:80,retryOverhead:1.3,parallelEfficiency:.85,enableCalibration:!0,calibrationWeight:.3,enableMultiModelComparison:!0},Un={...qme},xv=kv(Nme(),".aiaca","cost-estimator"),VT=kv(xv,"calibration.json"),JT=kv(xv,"budget.json"),VMe=kv(xv,"stats.json");qc={"gemini-2.5-flash-lite":{modelName:"gemini-2.5-flash-lite",tier:"cheap",inputCostPerMTokens:.075,outputCostPerMTokens:.3,avgLatencyMs:800,tokensPerSecond:200,contextWindow:1e6},"gemini-2.5-flash":{modelName:"gemini-2.5-flash",tier:"standard",inputCostPerMTokens:.3,outputCostPerMTokens:2.5,avgLatencyMs:1200,tokensPerSecond:150,contextWindow:1e6},"gemini-2.5-pro":{modelName:"gemini-2.5-pro",tier:"premium",inputCostPerMTokens:1.25,outputCostPerMTokens:10,avgLatencyMs:2500,tokensPerSecond:80,contextWindow:2e6},"claude-3-5-haiku-20241022":{modelName:"claude-3-5-haiku-20241022",tier:"cheap",inputCostPerMTokens:.8,outputCostPerMTokens:4,cachedInputCostPerMTokens:.08,avgLatencyMs:1e3,tokensPerSecond:120,contextWindow:2e5},"claude-3-5-sonnet-20241022":{modelName:"claude-3-5-sonnet-20241022",tier:"standard",inputCostPerMTokens:3,outputCostPerMTokens:15,cachedInputCostPerMTokens:.3,avgLatencyMs:2e3,tokensPerSecond:80,contextWindow:2e5},"claude-sonnet-4-20250514":{modelName:"claude-sonnet-4-20250514",tier:"premium",inputCostPerMTokens:3,outputCostPerMTokens:15,cachedInputCostPerMTokens:.3,avgLatencyMs:2200,tokensPerSecond:75,contextWindow:2e5},"claude-3-opus-20240229":{modelName:"claude-3-opus-20240229",tier:"frontier",inputCostPerMTokens:15,outputCostPerMTokens:75,cachedInputCostPerMTokens:1.5,avgLatencyMs:4e3,tokensPerSecond:50,contextWindow:2e5}},WT={file_read:{avgLatencyMs:50,estimatedTokens:1e3,retryProbability:.02},file_write:{avgLatencyMs:100,estimatedTokens:100,retryProbability:.05},file_edit:{avgLatencyMs:80,estimatedTokens:200,retryProbability:.1},grep:{avgLatencyMs:200,estimatedTokens:500,retryProbability:.05},glob:{avgLatencyMs:150,estimatedTokens:300,retryProbability:.02},bash:{avgLatencyMs:1e3,estimatedTokens:800,retryProbability:.15},powershell:{avgLatencyMs:1500,estimatedTokens:800,retryProbability:.15},web_fetch:{avgLatencyMs:2e3,estimatedTokens:2e3,retryProbability:.2},web_search:{avgLatencyMs:1500,estimatedTokens:1500,retryProbability:.1},code_search:{avgLatencyMs:100,estimatedTokens:800,retryProbability:.02},nl_search:{avgLatencyMs:200,estimatedTokens:1500,retryProbability:.05},spawn_specialist:{avgLatencyMs:3e4,estimatedTokens:5e3,retryProbability:.1},generate_tests:{avgLatencyMs:15e3,estimatedTokens:3e3,retryProbability:.15},analyze_code:{avgLatencyMs:800,estimatedTokens:1500,retryProbability:.05},vuln_scan:{avgLatencyMs:5e3,estimatedTokens:2e3,retryProbability:.1},ci_pipeline:{avgLatencyMs:6e4,estimatedTokens:1e3,retryProbability:.1},default:{avgLatencyMs:500,estimatedTokens:500,retryProbability:.05}},Kt={toolStats:{},modelStats:{},overallEstimateRatios:[]};Ume();te={totalBudgetUSD:5,spentUSD:0,reservedUSD:0,remainingUSD:5,hardLimit:!1,warningThreshold:80,resetPeriod:"session"};Kme();wv={totalEstimates:0,totalApproved:0,totalRejected:0,averageEstimatedCost:0,averageActualCost:0,estimateAccuracy:0,totalCalibrationSamples:0}});async function _v(e,t){let{withWakeLock:n}=await Promise.resolve().then(()=>(_$(),T$));return n("agent_running",`Query with ${e.length} messages`,()=>lge(e,t))}async function lge(e,t){let n=await Promise.resolve().then(()=>(G$(),z$));n.counter("query.started"),n.gauge("query.message_count",e.length);let r=n.startSpan("runQuery",{provider:t.provider.name,model:t.session.model}),s=Date.now(),i=await Promise.resolve().then(()=>(Ha(),Ua));i.startTurn();try{await(await Promise.resolve().then(()=>(Ql(),Yl))).maybeAutoCheckpoint(t.cwd,"on_query_start",{sessionId:t.session?.id,messageCount:e.length})}catch{}try{let C=await Promise.resolve().then(()=>(fs(),ds));C.getConfig().enabled&&t.session?.id&&C.createSession(t.session.id,"agent_query")}catch{}try{let C=await Promise.resolve().then(()=>(fo(),uo));if(C.getConfig().enabled){let M=e[e.length-1];M?.role==="user"&&C.record({sourceType:"user_input",content:typeof M.content=="string"?M.content:JSON.stringify(M.content),sessionId:t.session?.id})}}catch{}try{(await Promise.resolve().then(()=>(Wu(),Ju))).recordActivity()}catch{}let{provider:o,cwd:a,config:c,session:l,permissions:u,hooks:d,costTracker:f,abortSignal:p,onStream:m,onToolStart:g,onToolEnd:h,onCompact:v,onError:y,systemPromptOverride:b,toolFilter:k}=t,S=k&&k.length>0?Jm(k):Jm(),x=[...e];Av(p);try{if((await Promise.resolve().then(()=>(Fm(),Dm))).isActive())throw new tt("Kill switch active \u2014 all queries blocked. Use /killswitch reset to resume.","HOOK_BLOCKED",!1)}catch(C){if(C instanceof tt)throw C}let A=x[x.length-1];if(A?.role==="user"){let C=A.content.match(/["']?([^\s"']+\.(png|jpg|jpeg|gif|webp|bmp))["']?/i);if(C)try{let{ImageReadTool:M,hasStoredImages:$e}=await Promise.resolve().then(()=>(Lm(),JA));$e()||await Py("image_read",{path:C[1]},u)&&await M.handler({path:C[1]},{cwd:a,permissions:u,hooks:d,costTracker:f,session:l})}catch{}else try{let{hasStoredImages:M,ClipboardImageTool:$e,clearStoredImages:ot}=await Promise.resolve().then(()=>(Lm(),JA));M()||(await $e.handler({},{cwd:a,permissions:u,hooks:d,costTracker:f,session:l})).includes("No image found")&&ot()}catch{}}try{let{autoCollapseIfNeeded:C}=await Promise.resolve().then(()=>(QA(),YA)),M=C(x,c.compaction.threshold);M.collapsed&&M.result&&(x=M.messages,v?.(M.result.tokensSaved))}catch{}try{let C=await Promise.resolve().then(()=>(tT(),eT));C.autoConfigForModel(c[c.provider].model);let M=C.getConfig(),$e=x.reduce((nr,rr)=>nr+C.estimateTokens(rr.content),0),ot=Math.floor((M.modelContextWindow-M.reservedTokens)*M.targetUtilization);if($e>ot){let nr=await C.optimizeContext(x,{provider:o,model:c[c.provider].model,targetTokens:ot});nr.reductionPercent>5&&(x=nr.optimizedMessages,v?.(nr.originalTokenCount-nr.finalTokenCount))}}catch{}try{if(c.compaction.auto&&wL(x,c.compaction.threshold)){let C=await zy(x,o);C.summary&&(x=Gy(x,C.summary),v?.(C.tokensSaved))}}catch(C){let M=new tt("Compaction failed, continuing with full context","COMPACTION_FAILED",!0,C);y?.(M)}let j=b?`${b}
1326
+ `)}var wme,qn,bv,UT,HT,HMe,Gm,Ni,ae,kB,Sv=w(()=>{"use strict";wme={enabled:!0,enforceStrictBoundaries:!0,blockUpwardFlow:!0,blockCrossZoneCalls:!1,enforceCapabilities:!0,defaultDenyUnknown:!0,detectInstructionInjection:!0,autoDowngradeUntrusted:!0,enableAuditLog:!0},qn={...wme},bv=yv(yme(),".aiaca","trust-boundaries"),UT=yv(bv,"stats.json"),HT=yv(bv,"audit.jsonl"),HMe=yv(bv,"attestations.json"),Gm=new Sme;Gm.setMaxListeners(50);Ni={user:{zone:"user",level:100,allowedCapabilities:new Set(["*"]),deniedCapabilities:new Set},orchestrator:{zone:"orchestrator",level:75,allowedCapabilities:new Set(["fs:read","fs:write","fs:delete","network:read","network:write","system:exec","system:env","agent:spawn","agent:terminate","agent:configure","memory:read","memory:write","memory:purge","permissions:grant","permissions:revoke","config:read","config:write","identity:create","identity:revoke","audit:read"]),deniedCapabilities:new Set(["audit:write"])},sub_agent:{zone:"sub_agent",level:50,allowedCapabilities:new Set(["fs:read","fs:write","network:read","network:write","system:exec","memory:read","memory:write","config:read","audit:read"]),deniedCapabilities:new Set(["fs:delete","system:env","agent:spawn","agent:terminate","agent:configure","memory:purge","permissions:grant","permissions:revoke","config:write","identity:create","identity:revoke","audit:write"])},tool:{zone:"tool",level:25,allowedCapabilities:new Set([]),deniedCapabilities:new Set(["*"])},untrusted:{zone:"untrusted",level:0,allowedCapabilities:new Set([]),deniedCapabilities:new Set(["*"])}},ae={totalChecks:0,totalAllowed:0,totalBlocked:0,totalDowngraded:0,totalUpwardFlowAttempts:0,totalCapabilityEscalations:0,totalInstructionInjections:0,byViolationType:{},byZone:{}},kB=new Map;kme()});var $v={};$($v,{clearCalibration:()=>sge,configure:()=>nge,estimate:()=>IB,estimateStepTokens:()=>QT,estimateTokensFromText:()=>PB,formatEstimate:()=>oge,getBudget:()=>ZT,getCalibration:()=>rge,getConfig:()=>tge,getStats:()=>age,listModels:()=>ige,recordActualExecution:()=>Hme,recordApproval:()=>cge,recordSpend:()=>Xme,releaseReservation:()=>Zme,reserveBudget:()=>Qme,resetBudget:()=>ege,setBudget:()=>Yme});import{existsSync as CB,mkdirSync as Bme,readFileSync as AB,writeFileSync as TB}from"fs";import{join as kv}from"path";import{homedir as Nme}from"os";function YT(){Bme(xv,{recursive:!0})}function Ume(){if(YT(),CB(VT))try{Kt={...Kt,...JSON.parse(AB(VT,"utf-8"))}}catch{}}function _B(){YT();try{TB(VT,JSON.stringify(Kt,null,2),"utf-8")}catch{}}function Hme(e,t,n,r,s,i){if(!Un.enableCalibration)return;if(t){Kt.toolStats[t]||(Kt.toolStats[t]={actualLatencyMs:[],actualTokens:[],actualRetryRate:0,sampleCount:0});let a=Kt.toolStats[t];a.actualLatencyMs.push(r),a.actualTokens.push(n),a.actualLatencyMs.length>100&&a.actualLatencyMs.shift(),a.actualTokens.length>100&&a.actualTokens.shift(),a.sampleCount++,i?a.actualRetryRate=(a.actualRetryRate*(a.sampleCount-1)+1)/a.sampleCount:a.actualRetryRate=a.actualRetryRate*(a.sampleCount-1)/a.sampleCount}Kt.modelStats[s]||(Kt.modelStats[s]={actualTokensPerSecond:[],actualLatencyMs:[],sampleCount:0});let o=Kt.modelStats[s];o.actualLatencyMs.push(r),r>0&&o.actualTokensPerSecond.push(n/r*1e3),o.actualLatencyMs.length>100&&o.actualLatencyMs.shift(),o.actualTokensPerSecond.length>100&&o.actualTokensPerSecond.shift(),o.sampleCount++,_B()}function RB(e){let t=WT[e]||WT.default;if(!Un.enableCalibration)return t;let n=Kt.toolStats[e];if(!n||n.sampleCount<3)return t;let r=Un.calibrationWeight,s=n.actualLatencyMs.reduce((o,a)=>o+a,0)/n.actualLatencyMs.length,i=n.actualTokens.reduce((o,a)=>o+a,0)/n.actualTokens.length;return{avgLatencyMs:Math.round(t.avgLatencyMs*(1-r)+s*r),estimatedTokens:Math.round(t.estimatedTokens*(1-r)+i*r),retryProbability:t.retryProbability*(1-r)+n.actualRetryRate*r}}function PB(e){return Math.ceil(e.length/Un.charsPerToken)}function QT(e){let t=0,n=0;if(e.estimatedInputTokens!==void 0&&(t=e.estimatedInputTokens),e.estimatedOutputTokens!==void 0&&(n=e.estimatedOutputTokens),t===0){if(e.type==="llm_call"||e.type==="specialist")t=PB(e.description)+Un.systemPromptTokens;else if(e.type==="tool_call"&&e.toolName){let s=RB(e.toolName);t=Un.toolOverheadTokens,n=s.estimatedTokens}}n===0&&e.type==="llm_call"&&(n=Math.min(2e3,Math.max(200,t*.3))),e.type==="specialist"&&(n=n||5e3);let r=e.retryProbability??0;return r>0&&(t=Math.round(t*(1+r*.5)),n=Math.round(n*(1+r*.5))),{input:t,output:n}}function zme(e){let t=[],n=0,r=0,s=0;function i(c){for(let l of c)s++,l.riskLevel==="risky"&&r++,(l.toolName==="bash"||l.toolName==="powershell")&&r++,l.childSteps&&i(l.childSteps)}if(i(e),s>0){let c=r/s;n+=c*.3,c>.3&&t.push(`${r}/${s} steps marked risky`)}s>30?(n+=.2,t.push(`Large plan (${s} steps) \u2014 higher chance of failure`)):s>15&&(n+=.1,t.push(`Medium plan (${s} steps)`)),e.filter(c=>(c.dependencies?.length||0)>0).length/Math.max(1,e.length)>.7&&(n+=.15,t.push("Highly sequential \u2014 failures cascade"));let a=0;i(e);for(let c of e)a+=c.retryProbability||0;return a>s*.2&&(n+=.15,t.push("Cumulative retry probability is high")),t.length===0&&t.push("Plan looks straightforward"),{score:Math.min(1,n),factors:t}}function IB(e,t){if(!Un.enabled)return Vme(e.length);let n=t||Un.defaultModel,r=qc[n]||qc[Un.defaultModel],s=0,i=0,o=0,a=0,c=0,l=0,u=0,d=0,f=MB(e);function p(De,Et=1){let gn=QT(De);s+=gn.input,i+=gn.output;let T=0;if(De.type==="tool_call"){l++;let le=De.toolName?RB(De.toolName):WT.default;T=le.avgLatencyMs,le.externalCostUSD&&(c+=le.externalCostUSD)}else if(De.type==="llm_call"||De.type==="specialist"){u++;let le=Un.enableCalibration&&Kt.modelStats[n]?.actualTokensPerSecond.length>0?Kt.modelStats[n].actualTokensPerSecond.reduce((ie,C)=>ie+C,0)/Kt.modelStats[n].actualTokensPerSecond.length:r.tokensPerSecond;T=r.avgLatencyMs+gn.output/Math.max(1,le)*1e3}else if(De.type==="parallel_group"){d++;let le=0,ie=0;if(De.childSteps)for(let C of De.childSteps){let I=p(C,Et);le=Math.max(le,I.duration),ie+=I.duration}T=le+500}else De.type==="manual"&&(T=0);return{duration:T}}for(let De of e){let Et=p(De);a+=Et.duration}let m=1,g=s/1e6*r.inputCostPerMTokens,h=i/1e6*r.outputCostPerMTokens,v=o/1e6*(r.cachedInputCostPerMTokens||r.inputCostPerMTokens*.1),y=g+h+v+c,b=Kt.overallEstimateRatios.length>=5?Gme(Kt.overallEstimateRatios):.3,k=y,S=y*(1+b*1.65),x=a,A=a*(1+b*1.65),D=zme(e),M=Math.max(.1,1-b)*(Kt.overallEstimateRatios.length>=10?1:.7),ee=Jme(e,y,n),Ne=Un.enableMultiModelComparison?Wme(e,n,y,a):[],mn=ZT(),nn=y<=mn.remainingUSD&&D.score<.7;return{estimatedInputTokens:s,estimatedOutputTokens:i,estimatedCachedTokens:o,estimatedCostUSD:y,costBreakdown:{inputCost:g,outputCost:h,cachedCost:v,toolCost:c},estimatedDurationMs:a,estimatedDurationFormatted:KT(a),parallelizationFactor:m,confidence:M,p50Cost:k,p95Cost:S,p50Duration:x,p95Duration:A,riskScore:D.score,riskFactors:D.factors,shouldApprove:nn,trimSuggestions:ee,alternativeModels:Ne,stepCount:f,toolCallCount:l,llmCallCount:u}}function MB(e){let t=0;for(let n of e)t++,n.childSteps&&(t+=MB(n.childSteps));return t}function Gme(e){let t=e.reduce((r,s)=>r+s,0)/e.length,n=e.reduce((r,s)=>r+Math.pow(s-t,2),0)/e.length;return Math.sqrt(n)}function KT(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}h ${n%60}m`:n>0?`${n}m ${t%60}s`:`${t}s`}function Vme(e){return{estimatedInputTokens:0,estimatedOutputTokens:0,estimatedCachedTokens:0,estimatedCostUSD:0,costBreakdown:{inputCost:0,outputCost:0,cachedCost:0,toolCost:0},estimatedDurationMs:0,estimatedDurationFormatted:"0s",parallelizationFactor:1,confidence:0,p50Cost:0,p95Cost:0,p50Duration:0,p95Duration:0,riskScore:0,riskFactors:[],shouldApprove:!0,trimSuggestions:[],alternativeModels:[],stepCount:e,toolCallCount:0,llmCallCount:0}}function Jme(e,t,n){let r=[];for(let o of e)o.type==="manual"&&r.push({stepId:o.id||o.description.slice(0,30),description:o.description,reason:"Manual step \u2014 consider deferring",costSavingsUSD:0,timeSavingsMs:0});let s=e.filter(o=>o.type==="specialist"&&(o.estimatedOutputTokens||0)>5e3);for(let o of s.slice(0,3)){let a=QT(o),c=qc[n]||qc[Un.defaultModel],l=a.input/1e6*c.inputCostPerMTokens+a.output/1e6*c.outputCostPerMTokens;r.push({stepId:o.id||o.description.slice(0,30),description:o.description,reason:"Specialist call expensive \u2014 consider scoping down or using cheaper model",costSavingsUSD:l*.7,timeSavingsMs:2e4})}let i=e.filter(o=>o.toolName==="web_fetch"||o.toolName==="web_search");return i.length>5&&r.push({stepId:"web_calls",description:`${i.length} web fetches`,reason:"Many web calls \u2014 verify caching is enabled",costSavingsUSD:i.length*.001,timeSavingsMs:i.length*1500}),r}function Wme(e,t,n,r){let s=[],i=qc[t];if(!i)return[];for(let[o,a]of Object.entries(qc)){if(o===t)continue;let c=IB(e,o),l=c.estimatedCostUSD/Math.max(n,1e-4),u="minimal",d="";if(a.tier==="cheap"&&i.tier!=="cheap")u=i.tier==="frontier"?"significant":"moderate",d=`Use for simple tasks (${(l*100).toFixed(0)}% cost)`;else if(a.tier==="frontier"&&i.tier!=="frontier")u="minimal",d=`Use for highest quality (${(l*100).toFixed(0)}% cost)`;else if(l<.5)u=i.tier==="frontier"&&a.tier==="cheap"?"significant":"moderate",d=`${(100-l*100).toFixed(0)}% cheaper`;else if(l>1.5)u="minimal",d=`${(l*100-100).toFixed(0)}% more expensive but better`;else continue;s.push({model:o,estimatedCostUSD:c.estimatedCostUSD,estimatedDurationMs:c.estimatedDurationMs,qualityImpact:u,recommendation:d})}return s.sort((o,a)=>o.estimatedCostUSD-a.estimatedCostUSD).slice(0,5)}function Kme(){if(CB(JT))try{ne={...ne,...JSON.parse(AB(JT,"utf-8"))}}catch{}}function Vm(){YT();try{TB(JT,JSON.stringify(ne,null,2),"utf-8")}catch{}}function ZT(){return{...ne,remainingUSD:ne.totalBudgetUSD-ne.spentUSD-ne.reservedUSD}}function Yme(e){ne={...ne,...e},ne.remainingUSD=ne.totalBudgetUSD-ne.spentUSD-ne.reservedUSD,Vm()}function Qme(e){let t=ne.totalBudgetUSD-ne.spentUSD-ne.reservedUSD;return Un.enforceBudget&&ne.hardLimit&&e>t?{success:!1,reason:`Hard budget limit: ${t.toFixed(4)} remaining, ${e.toFixed(4)} requested`}:(ne.reservedUSD+=e,ne.remainingUSD-=e,Vm(),{success:!0})}function Zme(e){ne.reservedUSD=Math.max(0,ne.reservedUSD-e),ne.remainingUSD=ne.totalBudgetUSD-ne.spentUSD-ne.reservedUSD,Vm()}function Xme(e){ne.spentUSD+=e,ne.remainingUSD=ne.totalBudgetUSD-ne.spentUSD-ne.reservedUSD,Vm()}function ege(){ne.spentUSD=0,ne.reservedUSD=0,ne.remainingUSD=ne.totalBudgetUSD,Vm()}function tge(){return{...Un}}function nge(e){Un={...Un,...e}}function rge(){return JSON.parse(JSON.stringify(Kt))}function sge(){Kt={toolStats:{},modelStats:{},overallEstimateRatios:[]},_B()}function ige(){return Object.values(qc)}function oge(e){let t=[],n=ZT();t.push("# \u{1F4B0} Cost Estimate"),t.push(""),t.push(`**Estimated Cost:** $${e.estimatedCostUSD.toFixed(4)} (P50: $${e.p50Cost.toFixed(4)}, P95: $${e.p95Cost.toFixed(4)})`),t.push(`**Estimated Duration:** ${e.estimatedDurationFormatted} (P95: ${KT(e.p95Duration)})`),t.push(`**Confidence:** ${(e.confidence*100).toFixed(0)}%`),t.push(""),t.push("## Plan Structure"),t.push(`- Total steps: ${e.stepCount}`),t.push(`- Tool calls: ${e.toolCallCount}`),t.push(`- LLM calls: ${e.llmCallCount}`),t.push(""),t.push("## Tokens"),t.push(`- Input: ${e.estimatedInputTokens.toLocaleString()}`),t.push(`- Output: ${e.estimatedOutputTokens.toLocaleString()}`),e.estimatedCachedTokens>0&&t.push(`- Cached: ${e.estimatedCachedTokens.toLocaleString()}`),t.push(""),t.push("## Cost Breakdown"),t.push(`- Input: $${e.costBreakdown.inputCost.toFixed(4)}`),t.push(`- Output: $${e.costBreakdown.outputCost.toFixed(4)}`),e.costBreakdown.cachedCost>0&&t.push(`- Cached: $${e.costBreakdown.cachedCost.toFixed(4)}`),e.costBreakdown.toolCost>0&&t.push(`- External APIs: $${e.costBreakdown.toolCost.toFixed(4)}`),t.push(""),t.push("## Risk Assessment");let r=e.riskScore<.3?"\u{1F7E2}":e.riskScore<.6?"\u{1F7E1}":"\u{1F534}";t.push(`${r} Risk score: ${(e.riskScore*100).toFixed(0)}/100`);for(let s of e.riskFactors)t.push(` - ${s}`);if(t.push(""),t.push("## Budget"),t.push(`- Total: $${n.totalBudgetUSD.toFixed(2)}`),t.push(`- Spent: $${n.spentUSD.toFixed(4)}`),t.push(`- Reserved: $${n.reservedUSD.toFixed(4)}`),t.push(`- Remaining: $${n.remainingUSD.toFixed(4)}`),e.estimatedCostUSD>n.remainingUSD&&t.push(`- \u26A0\uFE0F This plan exceeds remaining budget by $${(e.estimatedCostUSD-n.remainingUSD).toFixed(4)}`),t.push(""),e.trimSuggestions.length>0){t.push("## \u2702\uFE0F Trim Suggestions");for(let s of e.trimSuggestions)t.push(`- **${s.description}**: ${s.reason}`),s.costSavingsUSD>0&&t.push(` Savings: $${s.costSavingsUSD.toFixed(4)} | ${KT(s.timeSavingsMs)}`);t.push("")}if(e.alternativeModels.length>0){t.push("## \u{1F504} Alternative Models");for(let s of e.alternativeModels){let i=((s.estimatedCostUSD-e.estimatedCostUSD)/Math.max(e.estimatedCostUSD,1e-4)*100).toFixed(0),o=s.estimatedCostUSD<e.estimatedCostUSD?"":"+";t.push(`- **${s.model}**: $${s.estimatedCostUSD.toFixed(4)} (${o}${i}%) | quality impact: ${s.qualityImpact}`),t.push(` ${s.recommendation}`)}t.push("")}return t.push(`## ${e.shouldApprove?"\u2713 Recommendation: APPROVE":"\u26A0\uFE0F Recommendation: REVIEW"}`),e.shouldApprove||t.push("Plan exceeds budget or has high risk. Consider trimming or splitting."),t.join(`
1327
+ `)}function age(){let e=0;for(let t of Object.values(Kt.toolStats))e+=t.sampleCount;for(let t of Object.values(Kt.modelStats))e+=t.sampleCount;return{...wv,totalCalibrationSamples:e}}function cge(e){e?wv.totalApproved++:wv.totalRejected++,wv.totalEstimates++}var qme,Un,xv,VT,JT,JMe,qc,WT,Kt,ne,wv,Cv=w(()=>{"use strict";qme={enabled:!0,defaultModel:"gemini-2.5-flash-lite",defaultModelTier:"cheap",charsPerToken:4,toolOverheadTokens:200,systemPromptTokens:4e3,enforceBudget:!1,defaultBudgetUSD:5,warningThresholdPct:80,retryOverhead:1.3,parallelEfficiency:.85,enableCalibration:!0,calibrationWeight:.3,enableMultiModelComparison:!0},Un={...qme},xv=kv(Nme(),".aiaca","cost-estimator"),VT=kv(xv,"calibration.json"),JT=kv(xv,"budget.json"),JMe=kv(xv,"stats.json");qc={"gemini-2.5-flash-lite":{modelName:"gemini-2.5-flash-lite",tier:"cheap",inputCostPerMTokens:.075,outputCostPerMTokens:.3,avgLatencyMs:800,tokensPerSecond:200,contextWindow:1e6},"gemini-2.5-flash":{modelName:"gemini-2.5-flash",tier:"standard",inputCostPerMTokens:.3,outputCostPerMTokens:2.5,avgLatencyMs:1200,tokensPerSecond:150,contextWindow:1e6},"gemini-2.5-pro":{modelName:"gemini-2.5-pro",tier:"premium",inputCostPerMTokens:1.25,outputCostPerMTokens:10,avgLatencyMs:2500,tokensPerSecond:80,contextWindow:2e6},"claude-3-5-haiku-20241022":{modelName:"claude-3-5-haiku-20241022",tier:"cheap",inputCostPerMTokens:.8,outputCostPerMTokens:4,cachedInputCostPerMTokens:.08,avgLatencyMs:1e3,tokensPerSecond:120,contextWindow:2e5},"claude-3-5-sonnet-20241022":{modelName:"claude-3-5-sonnet-20241022",tier:"standard",inputCostPerMTokens:3,outputCostPerMTokens:15,cachedInputCostPerMTokens:.3,avgLatencyMs:2e3,tokensPerSecond:80,contextWindow:2e5},"claude-sonnet-4-20250514":{modelName:"claude-sonnet-4-20250514",tier:"premium",inputCostPerMTokens:3,outputCostPerMTokens:15,cachedInputCostPerMTokens:.3,avgLatencyMs:2200,tokensPerSecond:75,contextWindow:2e5},"claude-3-opus-20240229":{modelName:"claude-3-opus-20240229",tier:"frontier",inputCostPerMTokens:15,outputCostPerMTokens:75,cachedInputCostPerMTokens:1.5,avgLatencyMs:4e3,tokensPerSecond:50,contextWindow:2e5}},WT={file_read:{avgLatencyMs:50,estimatedTokens:1e3,retryProbability:.02},file_write:{avgLatencyMs:100,estimatedTokens:100,retryProbability:.05},file_edit:{avgLatencyMs:80,estimatedTokens:200,retryProbability:.1},grep:{avgLatencyMs:200,estimatedTokens:500,retryProbability:.05},glob:{avgLatencyMs:150,estimatedTokens:300,retryProbability:.02},bash:{avgLatencyMs:1e3,estimatedTokens:800,retryProbability:.15},powershell:{avgLatencyMs:1500,estimatedTokens:800,retryProbability:.15},web_fetch:{avgLatencyMs:2e3,estimatedTokens:2e3,retryProbability:.2},web_search:{avgLatencyMs:1500,estimatedTokens:1500,retryProbability:.1},code_search:{avgLatencyMs:100,estimatedTokens:800,retryProbability:.02},nl_search:{avgLatencyMs:200,estimatedTokens:1500,retryProbability:.05},spawn_specialist:{avgLatencyMs:3e4,estimatedTokens:5e3,retryProbability:.1},generate_tests:{avgLatencyMs:15e3,estimatedTokens:3e3,retryProbability:.15},analyze_code:{avgLatencyMs:800,estimatedTokens:1500,retryProbability:.05},vuln_scan:{avgLatencyMs:5e3,estimatedTokens:2e3,retryProbability:.1},ci_pipeline:{avgLatencyMs:6e4,estimatedTokens:1e3,retryProbability:.1},default:{avgLatencyMs:500,estimatedTokens:500,retryProbability:.05}},Kt={toolStats:{},modelStats:{},overallEstimateRatios:[]};Ume();ne={totalBudgetUSD:5,spentUSD:0,reservedUSD:0,remainingUSD:5,hardLimit:!1,warningThreshold:80,resetPeriod:"session"};Kme();wv={totalEstimates:0,totalApproved:0,totalRejected:0,averageEstimatedCost:0,averageActualCost:0,estimateAccuracy:0,totalCalibrationSamples:0}});async function _v(e,t){let{withWakeLock:n}=await Promise.resolve().then(()=>(_$(),T$));return n("agent_running",`Query with ${e.length} messages`,()=>lge(e,t))}async function lge(e,t){let n=await Promise.resolve().then(()=>(G$(),z$));n.counter("query.started"),n.gauge("query.message_count",e.length);let r=n.startSpan("runQuery",{provider:t.provider.name,model:t.session.model}),s=Date.now(),i=await Promise.resolve().then(()=>(Ha(),Ua));i.startTurn();try{await(await Promise.resolve().then(()=>(Ql(),Yl))).maybeAutoCheckpoint(t.cwd,"on_query_start",{sessionId:t.session?.id,messageCount:e.length})}catch{}try{let C=await Promise.resolve().then(()=>(fs(),ds));C.getConfig().enabled&&t.session?.id&&C.createSession(t.session.id,"agent_query")}catch{}try{let C=await Promise.resolve().then(()=>(fo(),uo));if(C.getConfig().enabled){let I=e[e.length-1];I?.role==="user"&&C.record({sourceType:"user_input",content:typeof I.content=="string"?I.content:JSON.stringify(I.content),sessionId:t.session?.id})}}catch{}try{(await Promise.resolve().then(()=>(Wu(),Ju))).recordActivity()}catch{}let{provider:o,cwd:a,config:c,session:l,permissions:u,hooks:d,costTracker:f,abortSignal:p,onStream:m,onToolStart:g,onToolEnd:h,onCompact:v,onError:y,systemPromptOverride:b,toolFilter:k}=t,S=k&&k.length>0?Jm(k):Jm(),x=[...e];Av(p);try{if((await Promise.resolve().then(()=>(Fm(),Dm))).isActive())throw new tt("Kill switch active \u2014 all queries blocked. Use /killswitch reset to resume.","HOOK_BLOCKED",!1)}catch(C){if(C instanceof tt)throw C}let A=x[x.length-1];if(A?.role==="user"){let C=A.content.match(/["']?([^\s"']+\.(png|jpg|jpeg|gif|webp|bmp))["']?/i);if(C)try{let{ImageReadTool:I,hasStoredImages:$e}=await Promise.resolve().then(()=>(Lm(),JA));$e()||await Py("image_read",{path:C[1]},u)&&await I.handler({path:C[1]},{cwd:a,permissions:u,hooks:d,costTracker:f,session:l})}catch{}else try{let{hasStoredImages:I,ClipboardImageTool:$e,clearStoredImages:ot}=await Promise.resolve().then(()=>(Lm(),JA));I()||(await $e.handler({},{cwd:a,permissions:u,hooks:d,costTracker:f,session:l})).includes("No image found")&&ot()}catch{}}try{let{autoCollapseIfNeeded:C}=await Promise.resolve().then(()=>(QA(),YA)),I=C(x,c.compaction.threshold);I.collapsed&&I.result&&(x=I.messages,v?.(I.result.tokensSaved))}catch{}try{let C=await Promise.resolve().then(()=>(tT(),eT));C.autoConfigForModel(c[c.provider].model);let I=C.getConfig(),$e=x.reduce((nr,rr)=>nr+C.estimateTokens(rr.content),0),ot=Math.floor((I.modelContextWindow-I.reservedTokens)*I.targetUtilization);if($e>ot){let nr=await C.optimizeContext(x,{provider:o,model:c[c.provider].model,targetTokens:ot});nr.reductionPercent>5&&(x=nr.optimizedMessages,v?.(nr.originalTokenCount-nr.finalTokenCount))}}catch{}try{if(c.compaction.auto&&wL(x,c.compaction.threshold)){let C=await zy(x,o);C.summary&&(x=Gy(x,C.summary),v?.(C.tokensSaved))}}catch(C){let I=new tt("Compaction failed, continuing with full context","COMPACTION_FAILED",!0,C);y?.(I)}let D=b?`${b}
1330
1328
 
1331
1329
  <environment>
1332
1330
  Working directory: ${a}
1333
1331
  Platform: ${process.platform}
1334
- </environment>`:vL(a,c),I={cwd:a,permissions:u,hooks:d,costTracker:f,session:l,abortSignal:p,provider:o},ye=0,Ne=c.maxIterations||25,mn=0,nn=3,De=new Set,Et=new Map,gn=0,T="",ce=0,se=null;try{let C=await Promise.resolve().then(()=>(lo(),co));if(C.getConfig().enabled){let M=[...e].reverse().find($e=>$e.role==="user");if(M&&M.content&&!M.content.startsWith("<tool_result")){let $e=C.scan(M.content,"user_input");if(!$e.safe&&$e.recommendedAction==="block")throw new Error(`\u{1F6AB} Firewall blocked input: ${$e.detections.length} threat(s) detected.
1335
- ${$e.riskFactors.join("; ")}`)}}}catch(C){if(C.message?.includes("Firewall blocked"))throw y?.(new tt(C.message,"PROVIDER_ERROR",!1)),C}try{let C=await Promise.resolve().then(()=>(Ta(),Aa));if(C.getConfig().enabled){let M=[...e].reverse().find($e=>$e.role==="user");if(M&&M.content&&!M.content.startsWith("<tool_result")){se=(await C.captureIntent({sessionId:t.session?.id||"unknown",rawText:M.content,provider:t.provider})).id;try{let ot=await Promise.resolve().then(()=>(pd(),fd));ot.getConfig().enabled&&ot.captureIntent(M.content)}catch{}}else{let $e=C.getCurrentIntent();$e&&(se=$e.id)}}}catch{}for(;ye<Ne;){if(ye++,Av(p),se)try{let J=await Promise.resolve().then(()=>(Ta(),Aa));J.recordIteration(se);let be=J.detectDrift(se,x.slice(-6),[]),Ge=J.shouldReanchor(se,ye);Ge.shouldReanchor&&x.push({role:"user",content:Ge.message,timestamp:new Date().toISOString()})}catch{}let C;try{let J=await Promise.resolve().then(()=>(Du(),Eu));J.startSpeculativeTurn();let be="",Ge=m&&(Ce=>{Ce.type==="text"&&Ce.text&&(be+=Ce.text,J.onSpeculativeStreamText(be,I).catch(()=>{})),m(Ce)}),hn=await Promise.resolve().then(()=>(rb(),nb)),yn={model:c[c.provider].model,systemPrompt:j,messages:x,tools:S},li=hn.lookupCache(yn);if(li&&li.type==="exact")C=await hn.replayStream(li,{preserveTiming:!1,onChunk:Ce=>{Ge&&Ge(Ce)}});else{let Ce=new hn.StreamRecorder(yn),bn=Ug=>{Ce.recordChunk(Ug),Ge&&Ge(Ug)};C=await o.sendMessage(x,j,S,bn),Ce.finalize(C)}C.content&&await J.onSpeculativeStreamText(C.content,I).catch(()=>{})}catch(J){let be=uge(J);if(y?.(be),!be.recoverable)throw be;if(mn++,mn>=nn)throw new tt(`Provider failed ${nn} times consecutively`,"PROVIDER_ERROR",!1,J);x.push({role:"user",content:`[System: API error occurred: ${J.message}. Please continue.]`,timestamp:new Date().toISOString()});continue}if(mn=0,C.usage)try{f.addUsage(c[c.provider].model,C.usage)}catch{}if(!C.content&&C.toolCalls.length===0){let J=new tt("Model returned empty response","INVALID_RESPONSE",!0);y?.(J),x.push({role:"assistant",content:"(empty response)",timestamp:new Date().toISOString()});break}if(C.toolCalls.length===0){x.push({role:"assistant",content:C.content,timestamp:new Date().toISOString(),usage:C.usage});break}let M=gge(C),$e=new Set,ot=C.toolCalls.filter(J=>{let be=Tv(J);if($e.has(be))return!1;if(FB(J)){if(De.has(be))return!1}else if(Et.has(be)&&Et.get(be)===gn)return!1;return $e.add(be),!0});if(ot.length===0){M&&x.push({role:"assistant",content:M,timestamp:new Date().toISOString(),usage:C.usage});break}for(let J of ot)FB(J)?De.add(Tv(J)):Et.set(Tv(J),gn);ot.some(J=>["file_write","file_edit","notebook_edit"].includes(J.name))&&gn++;let nr=ot.map(J=>Tv(J)).join("|");if(nr===T){if(ce++,ce>=3){x.push({role:"assistant",content:"Task completed.",timestamp:new Date().toISOString()});break}}else ce=0,T=nr;x.push({role:"assistant",content:M,toolCalls:ot,timestamp:new Date().toISOString()});let rr=[];if(ot.length>1)try{let J=new Set(["file_read","grep","glob","web_fetch","web_search","code_search","code_references","tool_search","task_list","task_get","cron_list","image_read","config_read","skill_search"]),be=ot.every(Ge=>J.has(Ge.name));for(let Ge of ot)g?.(Ge);if(be){let{executeParallel:Ge,recordParallelRun:hn}=await Promise.resolve().then(()=>(oT(),iT)),yn=await Ge(ot,I,{maxConcurrency:12,enableDedup:!0,enableFairness:!0});hn(yn);let li=new Map(yn.results.map(Ce=>[Ce.toolCallId,Ce]));for(let Ce of ot){let bn=li.get(Ce.id);bn&&(h?.(Ce,bn.output,bn.durationMs||0),bn.isError?rr.push(`<tool_result name="${Ce.name}" error="true">
1332
+ </environment>`:vL(a,c),M={cwd:a,permissions:u,hooks:d,costTracker:f,session:l,abortSignal:p,provider:o},ee=0,Ne=c.maxIterations||25,mn=0,nn=3,De=new Set,Et=new Map,gn=0,T="",le=0,ie=null;try{let C=await Promise.resolve().then(()=>(lo(),co));if(C.getConfig().enabled){let I=[...e].reverse().find($e=>$e.role==="user");if(I&&I.content&&!I.content.startsWith("<tool_result")){let $e=C.scan(I.content,"user_input");if(!$e.safe&&$e.recommendedAction==="block")throw new Error(`\u{1F6AB} Firewall blocked input: ${$e.detections.length} threat(s) detected.
1333
+ ${$e.riskFactors.join("; ")}`)}}}catch(C){if(C.message?.includes("Firewall blocked"))throw y?.(new tt(C.message,"PROVIDER_ERROR",!1)),C}try{let C=await Promise.resolve().then(()=>(Ta(),Aa));if(C.getConfig().enabled){let I=[...e].reverse().find($e=>$e.role==="user");if(I&&I.content&&!I.content.startsWith("<tool_result")){ie=(await C.captureIntent({sessionId:t.session?.id||"unknown",rawText:I.content,provider:t.provider})).id;try{let ot=await Promise.resolve().then(()=>(pd(),fd));ot.getConfig().enabled&&ot.captureIntent(I.content)}catch{}}else{let $e=C.getCurrentIntent();$e&&(ie=$e.id)}}}catch{}for(;ee<Ne;){if(ee++,Av(p),ie)try{let J=await Promise.resolve().then(()=>(Ta(),Aa));J.recordIteration(ie);let be=J.detectDrift(ie,x.slice(-6),[]),Ge=J.shouldReanchor(ie,ee);Ge.shouldReanchor&&x.push({role:"user",content:Ge.message,timestamp:new Date().toISOString()})}catch{}let C;try{let J=await Promise.resolve().then(()=>(Du(),Eu));J.startSpeculativeTurn();let be="",Ge=m&&(Ce=>{Ce.type==="text"&&Ce.text&&(be+=Ce.text,J.onSpeculativeStreamText(be,M).catch(()=>{})),m(Ce)}),hn=await Promise.resolve().then(()=>(rb(),nb)),yn={model:c[c.provider].model,systemPrompt:D,messages:x,tools:S},li=hn.lookupCache(yn);if(li&&li.type==="exact")C=await hn.replayStream(li,{preserveTiming:!1,onChunk:Ce=>{Ge&&Ge(Ce)}});else{let Ce=new hn.StreamRecorder(yn),bn=Ug=>{Ce.recordChunk(Ug),Ge&&Ge(Ug)};C=await o.sendMessage(x,D,S,bn),Ce.finalize(C)}C.content&&await J.onSpeculativeStreamText(C.content,M).catch(()=>{})}catch(J){let be=uge(J);if(y?.(be),!be.recoverable)throw be;if(mn++,mn>=nn)throw new tt(`Provider failed ${nn} times consecutively`,"PROVIDER_ERROR",!1,J);x.push({role:"user",content:`[System: API error occurred: ${J.message}. Please continue.]`,timestamp:new Date().toISOString()});continue}if(mn=0,C.usage)try{f.addUsage(c[c.provider].model,C.usage)}catch{}if(!C.content&&C.toolCalls.length===0){let J=new tt("Model returned empty response","INVALID_RESPONSE",!0);y?.(J),x.push({role:"assistant",content:"(empty response)",timestamp:new Date().toISOString()});break}if(C.toolCalls.length===0){x.push({role:"assistant",content:C.content,timestamp:new Date().toISOString(),usage:C.usage});break}let I=gge(C),$e=new Set,ot=C.toolCalls.filter(J=>{let be=Tv(J);if($e.has(be))return!1;if(FB(J)){if(De.has(be))return!1}else if(Et.has(be)&&Et.get(be)===gn)return!1;return $e.add(be),!0});if(ot.length===0){I&&x.push({role:"assistant",content:I,timestamp:new Date().toISOString(),usage:C.usage});break}for(let J of ot)FB(J)?De.add(Tv(J)):Et.set(Tv(J),gn);ot.some(J=>["file_write","file_edit","notebook_edit"].includes(J.name))&&gn++;let nr=ot.map(J=>Tv(J)).join("|");if(nr===T){if(le++,le>=3){x.push({role:"assistant",content:"Task completed.",timestamp:new Date().toISOString()});break}}else le=0,T=nr;x.push({role:"assistant",content:I,toolCalls:ot,timestamp:new Date().toISOString()});let rr=[];if(ot.length>1)try{let J=new Set(["file_read","grep","glob","web_fetch","web_search","code_search","code_references","tool_search","task_list","task_get","cron_list","image_read","config_read","skill_search"]),be=ot.every(Ge=>J.has(Ge.name));for(let Ge of ot)g?.(Ge);if(be){let{executeParallel:Ge,recordParallelRun:hn}=await Promise.resolve().then(()=>(oT(),iT)),yn=await Ge(ot,M,{maxConcurrency:12,enableDedup:!0,enableFairness:!0});hn(yn);let li=new Map(yn.results.map(Ce=>[Ce.toolCallId,Ce]));for(let Ce of ot){let bn=li.get(Ce.id);bn&&(h?.(Ce,bn.output,bn.durationMs||0),bn.isError?rr.push(`<tool_result name="${Ce.name}" error="true">
1336
1334
  ${bn.output}
1337
1335
  </tool_result>`):rr.push(`<tool_result name="${Ce.name}">
1338
1336
  ${bn.output}
1339
- </tool_result>`))}}else{let{executeOrchestrated:Ge,recordOrchestration:hn}=await Promise.resolve().then(()=>(fT(),dT)),yn=await Ge(ot,I,{mode:"adaptive",enableConflictDetection:!0,enableRetries:!0,failureMode:"continue"});hn(yn);let li=new Map(yn.results.map(Ce=>[Ce.toolCallId,Ce]));for(let Ce of ot){let bn=li.get(Ce.id);bn&&(h?.(Ce,bn.output,bn.durationMs||0),bn.isError?rr.push(`<tool_result name="${Ce.name}" error="true">
1337
+ </tool_result>`))}}else{let{executeOrchestrated:Ge,recordOrchestration:hn}=await Promise.resolve().then(()=>(fT(),dT)),yn=await Ge(ot,M,{mode:"adaptive",enableConflictDetection:!0,enableRetries:!0,failureMode:"continue"});hn(yn);let li=new Map(yn.results.map(Ce=>[Ce.toolCallId,Ce]));for(let Ce of ot){let bn=li.get(Ce.id);bn&&(h?.(Ce,bn.output,bn.durationMs||0),bn.isError?rr.push(`<tool_result name="${Ce.name}" error="true">
1340
1338
  ${bn.output}
1341
1339
  </tool_result>`):rr.push(`<tool_result name="${Ce.name}">
1342
1340
  ${bn.output}
1343
- </tool_result>`))}}}catch{for(let be of ot){Av(p);try{let Ge=await EB(be,I,g,h,y);rr.push(`<tool_result name="${be.name}">
1341
+ </tool_result>`))}}}catch{for(let be of ot){Av(p);try{let Ge=await EB(be,M,g,h,y);rr.push(`<tool_result name="${be.name}">
1344
1342
  ${Ge}
1345
1343
  </tool_result>`)}catch(Ge){let hn=`Error executing ${be.name}: ${Ge.message}`;rr.push(`<tool_result name="${be.name}" error="true">
1346
1344
  ${hn}
1347
- </tool_result>`),h?.(be,hn,0)}}}else for(let J of ot){Av(p);try{let be=await EB(J,I,g,h,y);rr.push(`<tool_result name="${J.name}">
1345
+ </tool_result>`),h?.(be,hn,0)}}}else for(let J of ot){Av(p);try{let be=await EB(J,M,g,h,y);rr.push(`<tool_result name="${J.name}">
1348
1346
  ${be}
1349
1347
  </tool_result>`)}catch(be){let Ge=`Error executing ${J.name}: ${be.message}`;rr.push(`<tool_result name="${J.name}" error="true">
1350
1348
  ${Ge}
1351
1349
  </tool_result>`),h?.(J,Ge,0)}}x.push({role:"user",content:rr.join(`
1352
1350
 
1353
- `),timestamp:new Date().toISOString()});try{(await Promise.resolve().then(()=>(Du(),Eu))).endSpeculativeTurn()}catch{}}if(ye>=Ne){let C=new tt(`Reached maximum iterations (${Ne})`,"MAX_ITERATIONS",!1);y?.(C),x.push({role:"assistant",content:`[Stopped: reached ${Ne} iteration limit]`,timestamp:new Date().toISOString()})}try{await d.emit("Stop",{event:"Stop",messages:x})}catch{}if(x.length%10===0&&x.length>=6&&Promise.resolve().then(()=>(mT(),pT)).then(({extractMemories:C,recordBenchmark:M})=>{C(x,o,{sessionId:l.id,projectPath:a}).then($e=>{M($e)}).catch(()=>{})}).catch(()=>{}),n.endSpan(r.id,"completed"),n.histogram("query.duration_ms",Date.now()-s),n.counter("query.completed"),n.gauge("query.iterations",ye),i.endTurn(),se)try{let C=await Promise.resolve().then(()=>(Ta(),Aa));C.detectSubTaskProgress(se,[],x.slice(-5));let M=x[x.length-1];M&&M.role==="assistant"&&M.content&&C.setStatus(se,"completed")}catch{}try{let C=await Promise.resolve().then(()=>(Lp(),Fp));t.session?.id&&x.length>2&&await C.indexSession({sessionId:t.session.id,projectPath:t.cwd,messages:x,forceReindex:!0})}catch{}try{let C=await Promise.resolve().then(()=>(Kp(),Wp));t.session?.id&&C.recordSessionEvent(t.session.id,"event",`Query completed in ${ye} iterations, ${x.length} messages`,Math.min(.5+ye*.05,.9),["query_complete"])}catch{}try{let C=await Promise.resolve().then(()=>(pc(),fc)),M=t.session?.id||"default-task",$e=C.revokeTokensForTask(M,"query_completed");if($e>0)try{n.counter("jit.tokens_auto_revoked",$e)}catch{}}catch{}try{let C=await Promise.resolve().then(()=>(fs(),ds));if(t.session?.id&&C.getConfig().enabled){let M=C.getSession(t.session.id);M&&(M.lastActivityAt=Date.now())}}catch{}return x}async function EB(e,t,n,r,s){n?.(e);let i=Date.now();try{if((await Promise.resolve().then(()=>(Fm(),Dm))).isActive()){let d="\u{1F6A8} KILL SWITCH ACTIVE \u2014 All agent execution stopped\nUse `/killswitch reset` after cooldown to resume.";return r?.(e,d,Date.now()-i),s?.(new tt("Kill switch active","HOOK_BLOCKED",!1)),d}}catch{}try{let u=await Promise.resolve().then(()=>(Td(),Ad));if(u.getConfig().enabled){let d=u.canExecute(e.name,t.session?.id);if(!d.allowed){let f=d.retryAfterMs?` Retry in ${(d.retryAfterMs/1e3).toFixed(0)}s.`:"",p=`\u{1F534} Circuit breaker OPEN: ${d.reason}
1351
+ `),timestamp:new Date().toISOString()});try{(await Promise.resolve().then(()=>(Du(),Eu))).endSpeculativeTurn()}catch{}}if(ee>=Ne){let C=new tt(`Reached maximum iterations (${Ne})`,"MAX_ITERATIONS",!1);y?.(C),x.push({role:"assistant",content:`[Stopped: reached ${Ne} iteration limit]`,timestamp:new Date().toISOString()})}try{await d.emit("Stop",{event:"Stop",messages:x})}catch{}if(x.length%10===0&&x.length>=6&&Promise.resolve().then(()=>(mT(),pT)).then(({extractMemories:C,recordBenchmark:I})=>{C(x,o,{sessionId:l.id,projectPath:a}).then($e=>{I($e)}).catch(()=>{})}).catch(()=>{}),n.endSpan(r.id,"completed"),n.histogram("query.duration_ms",Date.now()-s),n.counter("query.completed"),n.gauge("query.iterations",ee),i.endTurn(),ie)try{let C=await Promise.resolve().then(()=>(Ta(),Aa));C.detectSubTaskProgress(ie,[],x.slice(-5));let I=x[x.length-1];I&&I.role==="assistant"&&I.content&&C.setStatus(ie,"completed")}catch{}try{let C=await Promise.resolve().then(()=>(Lp(),Fp));t.session?.id&&x.length>2&&await C.indexSession({sessionId:t.session.id,projectPath:t.cwd,messages:x,forceReindex:!0})}catch{}try{let C=await Promise.resolve().then(()=>(Kp(),Wp));t.session?.id&&C.recordSessionEvent(t.session.id,"event",`Query completed in ${ee} iterations, ${x.length} messages`,Math.min(.5+ee*.05,.9),["query_complete"])}catch{}try{let C=await Promise.resolve().then(()=>(pc(),fc)),I=t.session?.id||"default-task",$e=C.revokeTokensForTask(I,"query_completed");if($e>0)try{n.counter("jit.tokens_auto_revoked",$e)}catch{}}catch{}try{let C=await Promise.resolve().then(()=>(fs(),ds));if(t.session?.id&&C.getConfig().enabled){let I=C.getSession(t.session.id);I&&(I.lastActivityAt=Date.now())}}catch{}return x}async function EB(e,t,n,r,s){n?.(e);let i=Date.now();try{if((await Promise.resolve().then(()=>(Fm(),Dm))).isActive()){let d="\u{1F6A8} KILL SWITCH ACTIVE \u2014 All agent execution stopped\nUse `/killswitch reset` after cooldown to resume.";return r?.(e,d,Date.now()-i),s?.(new tt("Kill switch active","HOOK_BLOCKED",!1)),d}}catch{}try{let u=await Promise.resolve().then(()=>(Td(),Ad));if(u.getConfig().enabled){let d=u.canExecute(e.name,t.session?.id);if(!d.allowed){let f=d.retryAfterMs?` Retry in ${(d.retryAfterMs/1e3).toFixed(0)}s.`:"",p=`\u{1F534} Circuit breaker OPEN: ${d.reason}
1354
1352
 
1355
1353
  Health: ${(d.healthScore*100).toFixed(0)}/100${f}
1356
1354
 
@@ -1384,15 +1382,27 @@ ${g.warnings.map(v=>` - ${v}`).join(`
1384
1382
  \u{1F480} Killed by resource limiter: ${g.killReason}`)}catch{}}let p=Date.now()-i;t.costTracker.addToolDuration(e.name,p),r?.(e,d,p);try{let m=await Promise.resolve().then(()=>(gd(),md));m.getConfig().enabled&&m.logEvent({category:"tool_result",severity:"info",actor:t.session?.id||"agent",sessionId:t.session?.id,resource:e.name,action:"completed",description:`Tool ${e.name} completed in ${p}ms`,result:"success",metadata:{duration_ms:p,output_size:d?.length||0}})}catch{}try{(await Promise.resolve().then(()=>(Td(),Ad))).recordSuccess(e.name,p)}catch{}try{let m=await Promise.resolve().then(()=>(Sv(),vv));if(m.getConfig().enabled&&d&&d.length>50){let g=m.detectInstructionInjection(d,"tool");g.detected&&g.riskScore>.6&&(d=`[\u26A0\uFE0F Trust boundary alert: tool output contains ${g.patterns.length} suspicious instruction pattern(s) \u2014 risk ${(g.riskScore*100).toFixed(0)}%. Treating as untrusted.]
1385
1383
 
1386
1384
  ${d}`)}}catch{}try{let m=await Promise.resolve().then(()=>(fo(),uo));m.getConfig().enabled&&m.getConfig().recordToolOutputs&&d&&m.record({sourceType:"tool_output",content:typeof d=="string"?d:JSON.stringify(d),sourceUrl:`tool:${e.name}`,sessionId:t.session?.id})}catch{}try{(await Promise.resolve().then(()=>(Cv(),$v))).recordActualExecution(e.id,e.name,Math.ceil(d.length/4),p,t.session?.model||"unknown",!1)}catch{}try{await Xx(t.hooks,e.name,c,d,!1)}catch{}return d}catch(u){let d=Date.now()-i,f=u.message?.includes("timed out"),p=f?"TOOL_TIMEOUT":"TOOL_EXECUTION_ERROR",m=f?`Error: Tool "${e.name}" timed out after ${l}ms`:`Error: ${pge(u.message)}`;r?.(e,m,d),s?.(new tt(m,p,!0,u));try{let g=await Promise.resolve().then(()=>(Td(),Ad)),h=f?"timeout":"error";g.recordFailure(e.name,h,u.message||"unknown",t.session?.id)}catch{}try{await Xx(t.hooks,e.name,c,m,!0)}catch{}return m}}function uge(e){let t=e.status||e.statusCode,n=e.message||"Unknown provider error";return t===429?new tt(`Rate limited: ${n}`,"RATE_LIMITED",!0,e):t===413||n.includes("too long")||n.includes("context_length")?new tt(`Context too long: ${n}`,"CONTEXT_TOO_LONG",!1,e):n.includes("ECONNREFUSED")||n.includes("ENOTFOUND")||n.includes("fetch failed")?new tt(`Network error: ${n}`,"NETWORK_ERROR",!0,e):t>=500?new tt(`Server error (${t}): ${n}`,"PROVIDER_ERROR",!0,e):new tt(n,"PROVIDER_ERROR",!1,e)}function Av(e){if(e?.aborted)throw new tt("Query aborted by user","ABORTED",!1)}function dge(e){return{bash:12e4,powershell:12e4,web_fetch:3e4,web_search:15e3,agent:3e5,task_create:5e3,sleep:31e4}[e]||6e4}function fge(e,t,n){return Promise.race([e,new Promise((r,s)=>setTimeout(()=>s(new Error(`"${n}" timed out after ${t}ms`)),t))])}function pge(e){return e.split(`
1387
- `)[0].slice(0,500)}function Tv(e){return["file_write","doc_create","notebook_edit"].includes(e.name)?`${e.name}:${e.input.path}:${DB(String(e.input.content??""))}`:e.name==="file_edit"?`${e.name}:${e.input.path}:${DB(String(e.input.old_string??"")+"\u2192"+String(e.input.new_string??""))}`:["bash","powershell"].includes(e.name)?`${e.name}:${e.input.command}`:`${e.name}:${JSON.stringify(e.input)}`}function DB(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function FB(e){return mge.has(e.name)}function gge(e){return e.content||""}var tt,mge,XT=w(()=>{"use strict";Ls();Iy();Ey();SL();x$();tt=class extends Error{constructor(n,r,s,i){super(n);this.code=r;this.recoverable=s;this.cause=i;this.name="QueryError"}code;recoverable;cause};mge=new Set(["file_read","grep","glob","code_search","code_references","find_callers","analyze_code","detect_smells","impact_analysis","graph_stats","explain","web_search","web_fetch","find_untested","infer_types"])});var Sd={};$(Sd,{configureSpawner:()=>kge,formatInvocation:()=>xge,getSpawnerConfig:()=>wge,spawnParallel:()=>vge,spawnSequential:()=>Sge,spawnSpecialist:()=>Rv});async function hge(){return Wm.count<Km.maxConcurrent?(Wm.count++,()=>LB()):(await new Promise(e=>{OB.push({resolve:e})}),Wm.count++,()=>LB())}function LB(){Wm.count=Math.max(0,Wm.count-1);let e=OB.shift();e&&e.resolve()}function yge(e,t){let n=t||e.allowedTools,r=new Set(e.blockedTools);return e_().filter(i=>n.includes(i.definition.name)).filter(i=>!r.has(i.definition.name)).map(i=>i.definition)}async function Rv(e,t,n){let r=Wx(e);if(!r)throw new Error(`Unknown specialist: ${e}. Available: see /specialist list`);let s=Kx(),i={id:s,specialist:e,task:t.task,context:t.context,status:"pending",startedAt:Date.now(),parent:t.parentId,children:[]};Yx(i);let o;try{let l=await Promise.resolve().then(()=>(cd(),ad));if(l.getConfig().enabled){let u=r.permissions||["tool:read","tool:bash","tool:write"],d=t.parentNhiId,f=l.createIdentity({type:"specialist",displayName:`specialist:${e}`,description:t.task.slice(0,100),parentId:d,permissions:u,scopes:[n.cwd],ttlMs:(t.timeoutMs||5*6e4)+6e4,createdBy:d||"root"});o=f.id,i.nhiIdentityId=f.id}}catch{}let a;try{let l=await Promise.resolve().then(()=>(Cc(),$c));l.getConfig().enabled&&(a=`specialist-${e}-${s.slice(0,8)}`,l.createAgentIdentity({agentId:a,parentAgentId:"root-agent",ttlMs:(t.timeoutMs||5*6e4)+6e4}),i.a2aAgentId=a)}catch{}let c=await hge();i.status="running";try{let l=await bge(r,t,n,i);i.status=l.success?"completed":"failed",i.result=l,i.completedAt=Date.now()}catch(l){i.status="failed",i.completedAt=Date.now(),i.result={output:"",toolCallsExecuted:0,iterations:0,durationMs:Date.now()-i.startedAt,costUSD:0,filesModified:[],success:!1,errorMessage:l.message||String(l),metadata:{}}}finally{if(c(),o)try{(await Promise.resolve().then(()=>(cd(),ad))).revokeIdentity(o,"specialist_completed",!0)}catch{}if(a)try{let l=await Promise.resolve().then(()=>(Cc(),$c)),u=l.signEnvelope({fromAgent:a,toAgent:"root-agent",messageType:"response",payload:{specialist:e,result:i.result,status:i.status},conversationId:s});"error"in u||(i.signedEnvelope=u),l.revokeAgentIdentity(a,"specialist_completed")}catch{}Qx(i)}return i}async function bge(e,t,n,r){let s=Date.now(),i=t.customSystemPrompt||e.systemPrompt,o=yge(e,t.overrideTools),a=t.maxIterations??e.maxIterations,c=t.timeoutMs??e.timeoutMs,l=t.task;if(t.context&&Object.keys(t.context).length>0){l+=`
1385
+ `)[0].slice(0,500)}function Tv(e){return["file_write","doc_create","notebook_edit"].includes(e.name)?`${e.name}:${e.input.path}:${DB(String(e.input.content??""))}`:e.name==="file_edit"?`${e.name}:${e.input.path}:${DB(String(e.input.old_string??"")+"\u2192"+String(e.input.new_string??""))}`:["bash","powershell"].includes(e.name)?`${e.name}:${e.input.command}`:`${e.name}:${JSON.stringify(e.input)}`}function DB(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function FB(e){return mge.has(e.name)}function gge(e){return e.content||""}var tt,mge,XT=w(()=>{"use strict";Ls();Iy();Ey();SL();x$();tt=class extends Error{constructor(n,r,s,i){super(n);this.code=r;this.recoverable=s;this.cause=i;this.name="QueryError"}code;recoverable;cause};mge=new Set(["file_read","grep","glob","code_search","code_references","find_callers","analyze_code","detect_smells","impact_analysis","graph_stats","explain","web_search","web_fetch","find_untested","infer_types"])});var Sd={};$(Sd,{configureSpawner:()=>xge,formatInvocation:()=>$ge,getSpawnerConfig:()=>kge,spawnParallel:()=>Sge,spawnSequential:()=>wge,spawnSpecialist:()=>Rv});async function yge(){return Wm.count<Km.maxConcurrent?(Wm.count++,()=>LB()):(await new Promise(e=>{OB.push({resolve:e})}),Wm.count++,()=>LB())}function LB(){Wm.count=Math.max(0,Wm.count-1);let e=OB.shift();e&&e.resolve()}function bge(e,t){let n=t||e.allowedTools,r=new Set(e.blockedTools);return e_().filter(i=>n.includes(i.definition.name)).filter(i=>!r.has(i.definition.name)).map(i=>i.definition)}async function Rv(e,t,n){let r=Wx(e);if(!r)throw new Error(`Unknown specialist: ${e}. Available: see /specialist list`);let s=Kx(),i={id:s,specialist:e,task:t.task,context:t.context,status:"pending",startedAt:Date.now(),parent:t.parentId,children:[]};Yx(i);let o;try{let l=await Promise.resolve().then(()=>(cd(),ad));if(l.getConfig().enabled){let u=r.permissions||["tool:read","tool:bash","tool:write"],d=t.parentNhiId,f=l.createIdentity({type:"specialist",displayName:`specialist:${e}`,description:t.task.slice(0,100),parentId:d,permissions:u,scopes:[n.cwd],ttlMs:(t.timeoutMs||5*6e4)+6e4,createdBy:d||"root"});o=f.id,i.nhiIdentityId=f.id}}catch{}let a;try{let l=await Promise.resolve().then(()=>(Cc(),$c));l.getConfig().enabled&&(a=`specialist-${e}-${s.slice(0,8)}`,l.createAgentIdentity({agentId:a,parentAgentId:"root-agent",ttlMs:(t.timeoutMs||5*6e4)+6e4}),i.a2aAgentId=a)}catch{}let c=await yge();i.status="running";try{let l=await vge(r,t,n,i);i.status=l.success?"completed":"failed",i.result=l,i.completedAt=Date.now()}catch(l){i.status="failed",i.completedAt=Date.now(),i.result={output:"",toolCallsExecuted:0,iterations:0,durationMs:Date.now()-i.startedAt,costUSD:0,filesModified:[],success:!1,errorMessage:l.message||String(l),metadata:{}}}finally{if(c(),o)try{(await Promise.resolve().then(()=>(cd(),ad))).revokeIdentity(o,"specialist_completed",!0)}catch{}if(a)try{let l=await Promise.resolve().then(()=>(Cc(),$c)),u=l.signEnvelope({fromAgent:a,toAgent:"root-agent",messageType:"response",payload:{specialist:e,result:i.result,status:i.status},conversationId:s});"error"in u||(i.signedEnvelope=u),l.revokeAgentIdentity(a,"specialist_completed")}catch{}Qx(i)}return i}async function vge(e,t,n,r){let s=Date.now(),i=t.customSystemPrompt||e.systemPrompt,o=`${hge}
1386
+
1387
+ ${i}`,a=bge(e,t.overrideTools),c=t.maxIterations??e.maxIterations,l=t.timeoutMs??e.timeoutMs,u=t.task;if(t.context&&Object.keys(t.context).length>0){u+=`
1388
1388
 
1389
1389
  ## Context
1390
- `;for(let[k,S]of Object.entries(t.context)){let x=typeof S=="string"?S:JSON.stringify(S);l+=`
1391
- ### ${k}
1392
- ${x.slice(0,4e3)}
1393
- `}}let u=[{role:"user",content:l,timestamp:new Date().toISOString()}],d=ef(n.cwd,n.config.provider,e.preferredModel||n.config[n.config.provider].model);d.id=`spec-${r.id}`,d.messages=u;let f=nh(),p=My([]),m=Ry("ask",[]),g=new AbortController,h=setTimeout(()=>g.abort(),c),v=0,y=0,b=[];try{let k=await _v(u,{provider:n.provider,cwd:n.cwd,config:{...n.config,maxIterations:a},session:d,permissions:m,hooks:p,costTracker:f,abortSignal:g.signal,systemPromptOverride:i,toolFilter:o.map(A=>A.name),onToolStart:()=>{v++},onToolEnd:(A,j)=>{if(A.name==="file_write"||A.name==="file_edit"){let I=A.input.path;typeof I=="string"&&!b.includes(I)&&b.push(I)}}});clearTimeout(h),y=k.length-u.length;let x=[...k].reverse().find(A=>A.role==="assistant")?.content||"";return f.totalCostUSD>e.costBudgetUSD?{output:x,toolCallsExecuted:v,iterations:y,durationMs:Date.now()-s,costUSD:f.totalCostUSD,filesModified:b,success:!1,errorMessage:`Cost budget exceeded: $${f.totalCostUSD.toFixed(4)} > $${e.costBudgetUSD}`,metadata:{specialist:e.type,model:d.model}}:{output:x,toolCallsExecuted:v,iterations:y,durationMs:Date.now()-s,costUSD:f.totalCostUSD,filesModified:b,success:!0,metadata:{specialist:e.type,model:d.model}}}catch(k){clearTimeout(h);let S=g.signal.aborted;return{output:"",toolCallsExecuted:v,iterations:y,durationMs:Date.now()-s,costUSD:f.totalCostUSD,filesModified:b,success:!1,errorMessage:S?`Timeout after ${c}ms`:k.message||String(k),metadata:{specialist:e.type,timeout:S}}}}async function vge(e,t){return Promise.all(e.map(({specialistType:n,options:r})=>Rv(n,r,t)))}async function Sge(e,t){let n=[];for(let r of e){let s=r.taskTemplate(n),i=await Rv(r.specialistType,s,t);if(n.push(i),i.status!=="completed"&&Km.enableRetries){let o=await Rv(r.specialistType,s,t);if(n[n.length-1]=o,o.status!=="completed")break}}return n}function wge(){return{...Km}}function kge(e){Km={...Km,...e}}function xge(e){let t=[];return t.push(`# Specialist: ${e.specialist}`),t.push(`Status: ${e.status}`),e.completedAt&&t.push(`Duration: ${((e.completedAt-e.startedAt)/1e3).toFixed(1)}s`),t.push(`Task: ${e.task.slice(0,200)}`),t.push(""),e.result&&(t.push(`Iterations: ${e.result.iterations}`),t.push(`Tool calls: ${e.result.toolCallsExecuted}`),t.push(`Cost: $${e.result.costUSD.toFixed(4)}`),e.result.filesModified.length>0&&t.push(`Files modified: ${e.result.filesModified.join(", ")}`),e.result.errorMessage&&t.push(`Error: ${e.result.errorMessage}`),e.result.output&&(t.push(""),t.push("## Output"),t.push(e.result.output.slice(0,5e3)))),t.join(`
1394
- `)}var Km,Wm,OB,wd=w(()=>{"use strict";jp();XT();Ls();cf();Ey();Iy();tf();Km={maxConcurrent:4,defaultModel:"gemini-2.5-flash-lite",enableRetries:!0,maxRetries:1,enableObservability:!0},Wm={count:0},OB=[]});var a_={};$(a_,{appendHistoryEntry:()=>o_,configure:()=>qge,createGraph:()=>Ege,criticalPath:()=>Dge,deleteGraph:()=>Nge,emitEvent:()=>Ui,getConfig:()=>Iv,getEventEmitter:()=>Bge,getGraph:()=>Fge,getInternalGraphs:()=>i_,getReadyTasks:()=>Oge,getRunningTasks:()=>jge,listGraphs:()=>Lge,persistGraphs:()=>_d,topologicalOrder:()=>qB,validateDAG:()=>NB});import{existsSync as $ge,mkdirSync as Cge,readFileSync as Age,writeFileSync as jB}from"fs";import{join as n_}from"path";import{homedir as Tge}from"os";import{createHash as _ge}from"crypto";import{EventEmitter as Rge}from"events";function BB(){Cge(r_,{recursive:!0})}function Mge(){if($ge(t_))try{let e=JSON.parse(Age(t_,"utf-8"));for(let t of e){let n={...t,tasks:new Map(t.tasks.map(r=>[r.id,r]))};qi.set(n.id,n)}}catch{}}function s_(){if(Uc.enablePersistence){BB();try{let e=Array.from(qi.values()).map(t=>({...t,tasks:Array.from(t.tasks.values())}));jB(t_,JSON.stringify(e),"utf-8")}catch{}}}function NB(e){let t=[],n=new Set(e.map(a=>a.id));for(let a of e)for(let c of a.dependencies)n.has(c)||t.push(`Task "${a.id}" depends on unknown task "${c}"`);let r=new Set,s=new Set,i=new Map(e.map(a=>[a.id,a]));function o(a,c){if(s.has(a)){let u=c.indexOf(a);return t.push(`Cycle detected: ${c.slice(u).join(" \u2192 ")} \u2192 ${a}`),!0}if(r.has(a))return!1;r.add(a),s.add(a);let l=i.get(a);if(l){for(let u of l.dependencies)if(o(u,[...c,a]))return!0}return s.delete(a),!1}for(let a of e)r.has(a.id)||o(a.id,[]);return{valid:t.length===0,errors:t}}function Ege(e,t){let n=new Map;for(let o of t)n.set(o.id,{...o,status:"pending",attempts:0,dependents:[]});for(let o of n.values())for(let a of o.dependencies){let c=n.get(a);c&&!c.dependents.includes(o.id)&&c.dependents.push(o.id)}let r=NB(Array.from(n.values()));if(!r.valid)throw new Error(`Invalid DAG: ${r.errors.join("; ")}`);let s=_ge("sha256").update(e+Date.now()).digest("hex").slice(0,12),i={id:s,goal:e,tasks:n,createdAt:Date.now(),status:"pending",totalTasks:n.size,completedTasks:0,failedTasks:0,maxConcurrency:Uc.maxConcurrency,failureMode:Uc.defaultFailureMode};for(let o of i.tasks.values())o.dependencies.length===0&&(o.status="ready");return qi.set(s,i),s_(),i}function qB(e){let t=[],n=new Map;for(let s of e.tasks.values())n.set(s.id,s.dependencies.length);let r=Array.from(e.tasks.values()).filter(s=>s.dependencies.length===0).sort((s,i)=>i.priority-s.priority).map(s=>s.id);for(;r.length>0;){let s=r.shift();t.push(s);let i=e.tasks.get(s);if(i)for(let o of i.dependents){let a=(n.get(o)||0)-1;n.set(o,a),a===0&&r.push(o)}}return t}function Dge(e){let t=new Map,n=new Map,r=qB(e);for(let c of r){let l=e.tasks.get(c);if(!l)continue;let u=l.estimatedDurationMs||1e3,d=0,f=null;for(let p of l.dependencies){let m=t.get(p)||0;m>d&&(d=m,f=p)}t.set(c,d+u),n.set(c,f)}let s="",i=0;for(let[c,l]of t)l>i&&(i=l,s=c);let o=[],a=s;for(;a;)o.unshift(a),a=n.get(a)||null;return o}function Fge(e){return qi.get(e)}function Lge(){return Array.from(qi.values())}function Oge(e){let t=qi.get(e);return t?Array.from(t.tasks.values()).filter(n=>n.status==="ready").sort((n,r)=>r.priority-n.priority):[]}function jge(e){let t=qi.get(e);return t?Array.from(t.tasks.values()).filter(n=>n.status==="running"):[]}function Bge(){return Pv}function Nge(e){let t=qi.delete(e);return t&&s_(),t}function i_(){return qi}function _d(){s_()}function Ui(e){Uc.enableEvents&&(Pv.emit("execution",e),Pv.emit(e.type,e))}function o_(e){BB();try{jB(Ige,JSON.stringify({...e,timestamp:Date.now()})+`
1395
- `,{flag:"a"})}catch{}}function Iv(){return{...Uc}}function qge(e){Uc={...Uc,...e}}var Pge,Uc,r_,t_,Ige,qi,Pv,Mv=w(()=>{"use strict";Pge={enabled:!0,maxConcurrency:4,defaultMaxRetries:1,retryBackoffMs:2e3,defaultFailureMode:"continue",enablePersistence:!0,enableEvents:!0},Uc={...Pge},r_=n_(Tge(),".aiaca","task-dag"),t_=n_(r_,"graphs.json"),Ige=n_(r_,"history.jsonl"),qi=new Map,Pv=new Rge;Pv.setMaxListeners(100);Mge()});var l_={};$(l_,{decomposeGoal:()=>Vge,executeGraph:()=>Hge,visualizeGraph:()=>Jge});async function Uge(e,t,n){let r=c_(e.toolInput,n);if(e.type==="tool_call"&&e.toolName){let s=wr(e.toolName);if(!s)return{success:!1,error:`Tool not found: ${e.toolName}`};try{return{success:!0,result:await s.handler(r||{},t.toolContext)}}catch(i){return{success:!1,error:i.message||String(i)}}}if(e.type==="specialist"&&e.specialistType)try{let{spawnSpecialist:s}=await Promise.resolve().then(()=>(wd(),Sd)),i=await s(e.specialistType,{task:e.prompt||e.description,context:r},{provider:t.provider,cwd:t.toolContext.cwd,config:t.config});return i.status==="completed"?{success:!0,result:i.result}:{success:!1,error:i.result?.errorMessage||"Specialist failed"}}catch(s){return{success:!1,error:s.message}}return e.type==="sub_query"?{success:!0,result:`Sub-query: ${e.prompt}`}:e.type==="manual"?{success:!0,result:"Manual task \u2014 marked complete"}:{success:!1,error:`Unsupported task type: ${e.type}`}}function c_(e,t){if(typeof e!="object"||e===null)return e;if(Array.isArray(e))return e.map(r=>c_(r,t));let n={};for(let[r,s]of Object.entries(e))if(typeof s=="string"&&s.startsWith("${")&&s.endsWith("}")){let i=s.slice(2,-1);n[r]=t.has(i)?t.get(i):s}else n[r]=c_(s,t);return n}async function Hge(e,t){let r=i_().get(e);if(!r)throw new Error(`Graph not found: ${e}`);r.status="running",r.startedAt=Date.now(),Ui({type:"graph_started",graphId:e,timestamp:Date.now()}),_d();let s=Iv(),i=new Map,o=new Map;for(;;){if(t.abortSignal?.aborted){r.status="cancelled";break}let a=Array.from(r.tasks.values()).filter(u=>u.status==="ready"),c=r.maxConcurrency-o.size;if(a.length===0&&o.size===0)break;let l=a.sort((u,d)=>d.priority-u.priority).slice(0,Math.max(0,c));for(let u of l){if(u.exclusive&&Array.from(o.keys()).some(f=>r.tasks.get(f)?.exclusive))continue;let d=zge(u,r,t,i).then(()=>{o.delete(u.id)});o.set(u.id,d)}if(o.size===0&&a.length===0)break;o.size>0&&await Promise.race(o.values())}return r.completedAt=Date.now(),r.failedTasks>0&&r.completedTasks>0?r.status="partial":r.failedTasks>0?r.status="failed":r.status!=="cancelled"&&(r.status="completed"),Ui({type:r.status==="completed"?"graph_completed":"graph_failed",graphId:e,timestamp:Date.now(),data:{completed:r.completedTasks,failed:r.failedTasks,total:r.totalTasks}}),o_({graphId:e,goal:r.goal,status:r.status,duration:r.completedAt-(r.startedAt||r.createdAt),completed:r.completedTasks,failed:r.failedTasks}),_d(),r}async function zge(e,t,n,r){e.status="running",e.startedAt=Date.now(),Ui({type:"task_started",taskId:e.id,graphId:t.id,timestamp:Date.now()});let s=0,i="",o=e.maxRetries+1,a=Iv();for(;s<o;){e.attempts=s+1;let c=await Uge(e,n,r);if(c.success){e.status="completed",e.completedAt=Date.now(),e.result=c.result,r.set(e.id,c.result),t.completedTasks++,Ui({type:"task_completed",taskId:e.id,graphId:t.id,timestamp:Date.now(),data:{duration:e.completedAt-(e.startedAt||0),attempts:e.attempts}});for(let l of e.dependents){let u=t.tasks.get(l);if(!u||u.status!=="pending")continue;u.dependencies.every(f=>{let p=t.tasks.get(f);return p&&p.status==="completed"})&&(u.status="ready")}_d();return}i=c.error||"unknown error",s++,s<o&&await new Promise(l=>setTimeout(l,a.retryBackoffMs*s))}if(e.status="failed",e.completedAt=Date.now(),e.error=i,t.failedTasks++,Ui({type:"task_failed",taskId:e.id,graphId:t.id,timestamp:Date.now(),data:{error:i,attempts:e.attempts}}),t.failureMode==="fail_fast")for(let c of Gge(e.id,t)){let l=t.tasks.get(c);l&&(l.status==="pending"||l.status==="ready")&&(l.status="skipped",Ui({type:"task_skipped",taskId:c,graphId:t.id,timestamp:Date.now()}))}else if(t.failureMode==="isolate")for(let c of e.dependents){let l=t.tasks.get(c);l&&(l.status==="pending"||l.status==="ready")&&(l.status="skipped",Ui({type:"task_skipped",taskId:c,graphId:t.id,timestamp:Date.now()}))}_d()}function Gge(e,t){let n=new Set;function r(s){let i=t.tasks.get(s);if(i)for(let o of i.dependents)n.has(o)||(n.add(o),r(o))}return r(e),Array.from(n)}async function Vge(e,t){let n=`Decompose this goal into a DAG of executable tasks.
1390
+ `;for(let[S,x]of Object.entries(t.context)){let A=typeof x=="string"?x:JSON.stringify(x);u+=`
1391
+ ### ${S}
1392
+ ${A.slice(0,4e3)}
1393
+ `}}let d=[{role:"user",content:u,timestamp:new Date().toISOString()}],f=ef(n.cwd,n.config.provider,e.preferredModel||n.config[n.config.provider].model);f.id=`spec-${r.id}`,f.messages=d;let p=nh(),m=My([]),g=Ry("ask",[]),h=new AbortController,v=setTimeout(()=>h.abort(),l),y=0,b=0,k=[];try{let S=await _v(d,{provider:n.provider,cwd:n.cwd,config:{...n.config,maxIterations:c},session:f,permissions:g,hooks:m,costTracker:p,abortSignal:h.signal,systemPromptOverride:o,toolFilter:a.map(D=>D.name),onToolStart:()=>{y++},onToolEnd:(D,M)=>{if(D.name==="file_write"||D.name==="file_edit"){let ee=D.input.path;typeof ee=="string"&&!k.includes(ee)&&k.push(ee)}}});clearTimeout(v),b=S.length-d.length;let A=[...S].reverse().find(D=>D.role==="assistant")?.content||"";return p.totalCostUSD>e.costBudgetUSD?{output:A,toolCallsExecuted:y,iterations:b,durationMs:Date.now()-s,costUSD:p.totalCostUSD,filesModified:k,success:!1,errorMessage:`Cost budget exceeded: $${p.totalCostUSD.toFixed(4)} > $${e.costBudgetUSD}`,metadata:{specialist:e.type,model:f.model}}:{output:A,toolCallsExecuted:y,iterations:b,durationMs:Date.now()-s,costUSD:p.totalCostUSD,filesModified:k,success:!0,metadata:{specialist:e.type,model:f.model}}}catch(S){clearTimeout(v);let x=h.signal.aborted;return{output:"",toolCallsExecuted:y,iterations:b,durationMs:Date.now()-s,costUSD:p.totalCostUSD,filesModified:k,success:!1,errorMessage:x?`Timeout after ${l}ms`:S.message||String(S),metadata:{specialist:e.type,timeout:x}}}}async function Sge(e,t){return Promise.all(e.map(({specialistType:n,options:r})=>Rv(n,r,t)))}async function wge(e,t){let n=[];for(let r of e){let s=r.taskTemplate(n),i=await Rv(r.specialistType,s,t);if(n.push(i),i.status!=="completed"&&Km.enableRetries){let o=await Rv(r.specialistType,s,t);if(n[n.length-1]=o,o.status!=="completed")break}}return n}function kge(){return{...Km}}function xge(e){Km={...Km,...e}}function $ge(e){let t=[];return t.push(`# Specialist: ${e.specialist}`),t.push(`Status: ${e.status}`),e.completedAt&&t.push(`Duration: ${((e.completedAt-e.startedAt)/1e3).toFixed(1)}s`),t.push(`Task: ${e.task.slice(0,200)}`),t.push(""),e.result&&(t.push(`Iterations: ${e.result.iterations}`),t.push(`Tool calls: ${e.result.toolCallsExecuted}`),t.push(`Cost: $${e.result.costUSD.toFixed(4)}`),e.result.filesModified.length>0&&t.push(`Files modified: ${e.result.filesModified.join(", ")}`),e.result.errorMessage&&t.push(`Error: ${e.result.errorMessage}`),e.result.output&&(t.push(""),t.push("## Output"),t.push(e.result.output.slice(0,5e3)))),t.join(`
1394
+ `)}var hge,Km,Wm,OB,wd=w(()=>{"use strict";jp();XT();Ls();cf();Ey();Iy();tf();hge=`You are an ELITE AIACA specialist sub-agent \u2014 engineered to outperform the agents of leading platforms (Claude Code, Cursor, Codex). Operate by this doctrine:
1395
+
1396
+ EXECUTE AUTONOMOUSLY: You were spawned to complete a task end-to-end without a human in the loop. You CANNOT ask the user questions \u2014 there is no interactive user. Infer the best professional defaults a domain expert would choose, state key assumptions briefly, and deliver the complete result.
1397
+
1398
+ OWN THE OUTCOME: Carry the task fully to done \u2014 not the first step, not the happy path. If something fails, diagnose the root cause and fix it; if an approach fails twice, switch strategy. Never stop half-finished or hand back a stub.
1399
+
1400
+ VERIFY BEFORE REPORTING: Prove your work is correct. Re-read files you changed, run builds/tests/commands where applicable, and confirm the output actually satisfies the task. Assume there are problems and hunt for them before declaring success.
1401
+
1402
+ DELIVER BENCHMARK-GRADE WORK: Production-ready, complete, and polished \u2014 no placeholders, no TODOs, no lorem ipsum, no "implement here" comments. Match existing conventions. Handle edge cases and errors.
1403
+
1404
+ REPORT CRISPLY: End with a concise, factual summary of what you produced, where it lives (paths), what you verified, and any assumptions or follow-ups. No filler.`,Km={maxConcurrent:4,defaultModel:"gemini-2.5-flash-lite",enableRetries:!0,maxRetries:1,enableObservability:!0},Wm={count:0},OB=[]});var a_={};$(a_,{appendHistoryEntry:()=>o_,configure:()=>Uge,createGraph:()=>Dge,criticalPath:()=>Fge,deleteGraph:()=>qge,emitEvent:()=>Ui,getConfig:()=>Iv,getEventEmitter:()=>Nge,getGraph:()=>Lge,getInternalGraphs:()=>i_,getReadyTasks:()=>jge,getRunningTasks:()=>Bge,listGraphs:()=>Oge,persistGraphs:()=>_d,topologicalOrder:()=>qB,validateDAG:()=>NB});import{existsSync as Cge,mkdirSync as Age,readFileSync as Tge,writeFileSync as jB}from"fs";import{join as n_}from"path";import{homedir as _ge}from"os";import{createHash as Rge}from"crypto";import{EventEmitter as Pge}from"events";function BB(){Age(r_,{recursive:!0})}function Ege(){if(Cge(t_))try{let e=JSON.parse(Tge(t_,"utf-8"));for(let t of e){let n={...t,tasks:new Map(t.tasks.map(r=>[r.id,r]))};qi.set(n.id,n)}}catch{}}function s_(){if(Uc.enablePersistence){BB();try{let e=Array.from(qi.values()).map(t=>({...t,tasks:Array.from(t.tasks.values())}));jB(t_,JSON.stringify(e),"utf-8")}catch{}}}function NB(e){let t=[],n=new Set(e.map(a=>a.id));for(let a of e)for(let c of a.dependencies)n.has(c)||t.push(`Task "${a.id}" depends on unknown task "${c}"`);let r=new Set,s=new Set,i=new Map(e.map(a=>[a.id,a]));function o(a,c){if(s.has(a)){let u=c.indexOf(a);return t.push(`Cycle detected: ${c.slice(u).join(" \u2192 ")} \u2192 ${a}`),!0}if(r.has(a))return!1;r.add(a),s.add(a);let l=i.get(a);if(l){for(let u of l.dependencies)if(o(u,[...c,a]))return!0}return s.delete(a),!1}for(let a of e)r.has(a.id)||o(a.id,[]);return{valid:t.length===0,errors:t}}function Dge(e,t){let n=new Map;for(let o of t)n.set(o.id,{...o,status:"pending",attempts:0,dependents:[]});for(let o of n.values())for(let a of o.dependencies){let c=n.get(a);c&&!c.dependents.includes(o.id)&&c.dependents.push(o.id)}let r=NB(Array.from(n.values()));if(!r.valid)throw new Error(`Invalid DAG: ${r.errors.join("; ")}`);let s=Rge("sha256").update(e+Date.now()).digest("hex").slice(0,12),i={id:s,goal:e,tasks:n,createdAt:Date.now(),status:"pending",totalTasks:n.size,completedTasks:0,failedTasks:0,maxConcurrency:Uc.maxConcurrency,failureMode:Uc.defaultFailureMode};for(let o of i.tasks.values())o.dependencies.length===0&&(o.status="ready");return qi.set(s,i),s_(),i}function qB(e){let t=[],n=new Map;for(let s of e.tasks.values())n.set(s.id,s.dependencies.length);let r=Array.from(e.tasks.values()).filter(s=>s.dependencies.length===0).sort((s,i)=>i.priority-s.priority).map(s=>s.id);for(;r.length>0;){let s=r.shift();t.push(s);let i=e.tasks.get(s);if(i)for(let o of i.dependents){let a=(n.get(o)||0)-1;n.set(o,a),a===0&&r.push(o)}}return t}function Fge(e){let t=new Map,n=new Map,r=qB(e);for(let c of r){let l=e.tasks.get(c);if(!l)continue;let u=l.estimatedDurationMs||1e3,d=0,f=null;for(let p of l.dependencies){let m=t.get(p)||0;m>d&&(d=m,f=p)}t.set(c,d+u),n.set(c,f)}let s="",i=0;for(let[c,l]of t)l>i&&(i=l,s=c);let o=[],a=s;for(;a;)o.unshift(a),a=n.get(a)||null;return o}function Lge(e){return qi.get(e)}function Oge(){return Array.from(qi.values())}function jge(e){let t=qi.get(e);return t?Array.from(t.tasks.values()).filter(n=>n.status==="ready").sort((n,r)=>r.priority-n.priority):[]}function Bge(e){let t=qi.get(e);return t?Array.from(t.tasks.values()).filter(n=>n.status==="running"):[]}function Nge(){return Pv}function qge(e){let t=qi.delete(e);return t&&s_(),t}function i_(){return qi}function _d(){s_()}function Ui(e){Uc.enableEvents&&(Pv.emit("execution",e),Pv.emit(e.type,e))}function o_(e){BB();try{jB(Mge,JSON.stringify({...e,timestamp:Date.now()})+`
1405
+ `,{flag:"a"})}catch{}}function Iv(){return{...Uc}}function Uge(e){Uc={...Uc,...e}}var Ige,Uc,r_,t_,Mge,qi,Pv,Mv=w(()=>{"use strict";Ige={enabled:!0,maxConcurrency:4,defaultMaxRetries:1,retryBackoffMs:2e3,defaultFailureMode:"continue",enablePersistence:!0,enableEvents:!0},Uc={...Ige},r_=n_(_ge(),".aiaca","task-dag"),t_=n_(r_,"graphs.json"),Mge=n_(r_,"history.jsonl"),qi=new Map,Pv=new Pge;Pv.setMaxListeners(100);Ege()});var l_={};$(l_,{decomposeGoal:()=>Jge,executeGraph:()=>zge,visualizeGraph:()=>Wge});async function Hge(e,t,n){let r=c_(e.toolInput,n);if(e.type==="tool_call"&&e.toolName){let s=wr(e.toolName);if(!s)return{success:!1,error:`Tool not found: ${e.toolName}`};try{return{success:!0,result:await s.handler(r||{},t.toolContext)}}catch(i){return{success:!1,error:i.message||String(i)}}}if(e.type==="specialist"&&e.specialistType)try{let{spawnSpecialist:s}=await Promise.resolve().then(()=>(wd(),Sd)),i=await s(e.specialistType,{task:e.prompt||e.description,context:r},{provider:t.provider,cwd:t.toolContext.cwd,config:t.config});return i.status==="completed"?{success:!0,result:i.result}:{success:!1,error:i.result?.errorMessage||"Specialist failed"}}catch(s){return{success:!1,error:s.message}}return e.type==="sub_query"?{success:!0,result:`Sub-query: ${e.prompt}`}:e.type==="manual"?{success:!0,result:"Manual task \u2014 marked complete"}:{success:!1,error:`Unsupported task type: ${e.type}`}}function c_(e,t){if(typeof e!="object"||e===null)return e;if(Array.isArray(e))return e.map(r=>c_(r,t));let n={};for(let[r,s]of Object.entries(e))if(typeof s=="string"&&s.startsWith("${")&&s.endsWith("}")){let i=s.slice(2,-1);n[r]=t.has(i)?t.get(i):s}else n[r]=c_(s,t);return n}async function zge(e,t){let r=i_().get(e);if(!r)throw new Error(`Graph not found: ${e}`);r.status="running",r.startedAt=Date.now(),Ui({type:"graph_started",graphId:e,timestamp:Date.now()}),_d();let s=Iv(),i=new Map,o=new Map;for(;;){if(t.abortSignal?.aborted){r.status="cancelled";break}let a=Array.from(r.tasks.values()).filter(u=>u.status==="ready"),c=r.maxConcurrency-o.size;if(a.length===0&&o.size===0)break;let l=a.sort((u,d)=>d.priority-u.priority).slice(0,Math.max(0,c));for(let u of l){if(u.exclusive&&Array.from(o.keys()).some(f=>r.tasks.get(f)?.exclusive))continue;let d=Gge(u,r,t,i).then(()=>{o.delete(u.id)});o.set(u.id,d)}if(o.size===0&&a.length===0)break;o.size>0&&await Promise.race(o.values())}return r.completedAt=Date.now(),r.failedTasks>0&&r.completedTasks>0?r.status="partial":r.failedTasks>0?r.status="failed":r.status!=="cancelled"&&(r.status="completed"),Ui({type:r.status==="completed"?"graph_completed":"graph_failed",graphId:e,timestamp:Date.now(),data:{completed:r.completedTasks,failed:r.failedTasks,total:r.totalTasks}}),o_({graphId:e,goal:r.goal,status:r.status,duration:r.completedAt-(r.startedAt||r.createdAt),completed:r.completedTasks,failed:r.failedTasks}),_d(),r}async function Gge(e,t,n,r){e.status="running",e.startedAt=Date.now(),Ui({type:"task_started",taskId:e.id,graphId:t.id,timestamp:Date.now()});let s=0,i="",o=e.maxRetries+1,a=Iv();for(;s<o;){e.attempts=s+1;let c=await Hge(e,n,r);if(c.success){e.status="completed",e.completedAt=Date.now(),e.result=c.result,r.set(e.id,c.result),t.completedTasks++,Ui({type:"task_completed",taskId:e.id,graphId:t.id,timestamp:Date.now(),data:{duration:e.completedAt-(e.startedAt||0),attempts:e.attempts}});for(let l of e.dependents){let u=t.tasks.get(l);if(!u||u.status!=="pending")continue;u.dependencies.every(f=>{let p=t.tasks.get(f);return p&&p.status==="completed"})&&(u.status="ready")}_d();return}i=c.error||"unknown error",s++,s<o&&await new Promise(l=>setTimeout(l,a.retryBackoffMs*s))}if(e.status="failed",e.completedAt=Date.now(),e.error=i,t.failedTasks++,Ui({type:"task_failed",taskId:e.id,graphId:t.id,timestamp:Date.now(),data:{error:i,attempts:e.attempts}}),t.failureMode==="fail_fast")for(let c of Vge(e.id,t)){let l=t.tasks.get(c);l&&(l.status==="pending"||l.status==="ready")&&(l.status="skipped",Ui({type:"task_skipped",taskId:c,graphId:t.id,timestamp:Date.now()}))}else if(t.failureMode==="isolate")for(let c of e.dependents){let l=t.tasks.get(c);l&&(l.status==="pending"||l.status==="ready")&&(l.status="skipped",Ui({type:"task_skipped",taskId:c,graphId:t.id,timestamp:Date.now()}))}_d()}function Vge(e,t){let n=new Set;function r(s){let i=t.tasks.get(s);if(i)for(let o of i.dependents)n.has(o)||(n.add(o),r(o))}return r(e),Array.from(n)}async function Jge(e,t){let n=`Decompose this goal into a DAG of executable tasks.
1396
1406
 
1397
1407
  GOAL: ${e}
1398
1408
 
@@ -1420,11 +1430,11 @@ Rules:
1420
1430
  - Tasks should be atomic and independently testable
1421
1431
  - Use dependencies to express ordering constraints
1422
1432
  - Independent tasks should NOT have dependencies (will run in parallel)
1423
- - Use \${task_id} in toolInput strings to reference outputs from previous tasks`;try{let s=(await t.sendMessage([{role:"user",content:n,timestamp:new Date().toISOString()}],"You decompose goals into task DAGs. Output strict JSON only.",[],void 0)).content?.match(/\{[\s\S]*\}/)?.[0];return s?(JSON.parse(s).tasks||[]).map(o=>({id:o.id,name:o.name||o.id,description:o.description||"",dependencies:o.dependencies||[],type:o.type||"manual",toolName:o.toolName,toolInput:o.toolInput,specialistType:o.specialistType,prompt:o.prompt,estimatedDurationMs:o.estimatedDurationMs,estimatedCost:o.estimatedCost,priority:o.priority||5,tags:o.tags||[],exclusive:o.exclusive||!1,maxRetries:o.maxRetries??1})):[]}catch{return[]}}function Jge(e){let t=[];t.push(`# Task Graph: ${e.goal}`),t.push(`Status: ${e.status} | Tasks: ${e.totalTasks} (${e.completedTasks} \u2713, ${e.failedTasks} \u2717)`),t.push("");let n=e.totalTasks>0?e.completedTasks/e.totalTasks:0,r="\u2588".repeat(Math.floor(n*30))+"\u2591".repeat(30-Math.floor(n*30));t.push(`Progress: [${r}] ${(n*100).toFixed(0)}%`),t.push("");let s=[],i=new Set;function o(a,c){if(i.has(a))return;i.add(a);let l=e.tasks.get(a);if(!l)return;let u=l.status==="completed"?"\u2713":l.status==="running"?"\u27F3":l.status==="failed"?"\u2717":l.status==="ready"?"\u25D0":l.status==="skipped"?"~":l.status==="cancelled"?"\u2715":"\u25CB",d=" ".repeat(c),f=l.completedAt&&l.startedAt?` (${l.completedAt-l.startedAt}ms)`:"";t.push(`${d}${u} ${l.name}${f}`),l.error&&t.push(`${d} \u26A0 ${l.error.slice(0,100)}`);for(let p of l.dependents)o(p,c+1)}for(let a of e.tasks.values())a.dependencies.length===0&&o(a.id,0);return t.join(`
1424
- `)}var u_=w(()=>{"use strict";Mv();Ls()});var w_={};$(w_,{cancelAll:()=>ahe,cancelPending:()=>VB,clearMemory:()=>uhe,configure:()=>phe,forgetDecision:()=>lhe,formatProposal:()=>ghe,getAuditLog:()=>JB,getConfig:()=>dhe,getEvents:()=>mhe,getPendingProposals:()=>ihe,getProposal:()=>ohe,getRememberedDecisions:()=>che,getStats:()=>hhe,respondToProposal:()=>she,setPolicy:()=>fhe,submitProposal:()=>rhe});import{existsSync as g_,mkdirSync as Wge,readFileSync as h_,writeFileSync as y_}from"fs";import{join as Dv}from"path";import{homedir as Kge}from"os";import{createHash as HB}from"crypto";import{EventEmitter as Yge}from"events";function b_(){Wge(Fv,{recursive:!0})}function Xge(){if(g_(f_))try{let e=JSON.parse(h_(f_,"utf-8"));Re={...Re,...e}}catch{}}function zB(){b_();try{y_(f_,JSON.stringify(Re,null,2),"utf-8")}catch{}}function ehe(){if(g_(p_))try{let e=JSON.parse(h_(p_,"utf-8")),t=Date.now();for(let n of e)n.expiresAt&&t>n.expiresAt||Qo.set(n.patternHash,n)}catch{}}function Lv(){b_();try{y_(p_,JSON.stringify(Array.from(Qo.values()),null,2),"utf-8")}catch{}}function the(e){let n={irreversible_op:"high",deployment:"critical",security_change:"high",destructive_command:"high",cost_threshold:"medium",batch_operation:"medium",external_api_call:"low",plan_review:"low",custom:"medium"}[e.gateType]||"medium";return e.filesAffected.length>20?n="critical":e.filesAffected.length>10&&(n=d_(n,"high")),e.reversibility==="irreversible"&&(n=d_(n,"high")),e.estimatedCost&&e.estimatedCost>10?n="critical":e.estimatedCost&&e.estimatedCost>1&&(n=d_(n,"high")),e.command&&/\b(rm\s+-rf|drop\s+table|delete\s+from|--force|force-push|reset\s+--hard)\b/i.test(e.command)&&(n="critical"),n}function d_(e,t){let n=["safe","low","medium","high","critical"];return n[Math.max(n.indexOf(e),n.indexOf(t))]}function GB(e){let t=JSON.stringify({type:e.gateType,command:e.command,files:e.filesAffected.slice(0,5).sort()});return HB("sha256").update(t).digest("hex").slice(0,16)}function nhe(e){if(!Re.enabled)return zr(e.id,"approve","service disabled");if(Re.enableMemory){let i=GB(e),o=Qo.get(i);if(o)return o.hits++,Lv(),zr(e.id,o.decision,`remembered: ${o.rememberedFor}`)}for(let i of Re.policy.preApprovedPatterns)try{if(new RegExp(i,"i").test(e.description))return zr(e.id,"approve",`pre-approved pattern: ${i}`)}catch{}for(let i of Re.policy.preDeniedPatterns)try{if(new RegExp(i,"i").test(e.description))return zr(e.id,"deny",`pre-denied pattern: ${i}`)}catch{}let t=Re.policy.perTypePolicy[e.gateType];if(t?.mode==="auto_approve")return zr(e.id,"approve","type policy: auto_approve");if(t?.mode==="auto_deny")return zr(e.id,"deny","type policy: auto_deny");if(t?.mode==="always_ask"||Re.policy.mode==="always_ask")return null;if(Re.policy.mode==="deny_all")return zr(e.id,"deny","policy: deny_all");let n=["safe","low","medium","high","critical"],r=n.indexOf(e.riskLevel),s=n.indexOf(Re.policy.riskThreshold);if(Re.policy.mode==="allow_low_risk"&&r<s)return zr(e.id,"approve",`low risk (${e.riskLevel})`);if(Re.policy.mode==="ask_if_risky"&&r<s)return zr(e.id,"approve",`below threshold (${e.riskLevel})`);if(e.estimatedCost&&e.estimatedCost>Re.policy.costThreshold)return null;if(Re.policy.workHoursOnly){let i=new Date().getHours();if(i<Re.policy.workHoursOnly.start||i>=Re.policy.workHoursOnly.end)return zr(e.id,"defer","outside work hours")}return null}function zr(e,t,n){return{proposalId:e,decision:t,respondedAt:Date.now(),respondedBy:"auto",reason:n}}async function rhe(e,t={}){if(!Re.enabled)return zr("disabled","approve","HITL disabled");if(Zs.size>=Re.maxPendingProposals)return zr("overloaded","deny",`Pending proposals exceeded (${Zs.size})`);let n=HB("sha256").update(e.title+Date.now()+Math.random()).digest("hex").slice(0,12),r={...e,id:n,createdAt:Date.now(),riskLevel:e.riskLevel||the(e),expiresAt:Date.now()+(t.timeoutMs??Re.policy.defaultTimeout),tags:e.tags||[],metadata:e.metadata||{}},s=nhe(r);if(s)return UB({proposal:r,response:s}),s;Zs.set(n,r),v_.emit("proposal_submitted",r);let i=await new Promise(o=>{if(Ev.set(n,o),r.expiresAt){let a=r.expiresAt-Date.now();a>0&&setTimeout(()=>{if(Ev.has(n)){let u=(Re.policy.perTypePolicy[r.gateType]?.timeoutAction||Re.policy.timeoutAction)==="approve"?"approve":"deny",d={proposalId:n,decision:u,respondedAt:Date.now(),respondedBy:"auto",reason:`timeout after ${(r.expiresAt-r.createdAt)/1e3}s`};S_(n,d)}},a).unref()}});if(Zs.delete(n),UB({proposal:r,response:i}),Re.enableMemory&&(i.decision==="approve_always"||i.decision==="deny_always")){let o=GB(r);Qo.set(o,{patternHash:o,pattern:`${r.gateType}: ${r.title}`.slice(0,100),decision:i.decision==="approve_always"?"approve":"deny",rememberedFor:i.rememberedFor||"project",rememberedAt:Date.now(),hits:0}),Lv()}return i}function S_(e,t){let n=Ev.get(e);n&&(Ev.delete(e),n(t))}function she(e,t,n={}){if(!Zs.get(e))return!1;let s={proposalId:e,decision:t,respondedAt:Date.now(),respondedBy:"user",reason:n.reason,modifications:n.modifications,rememberedFor:n.rememberedFor};return S_(e,s),!0}function ihe(){return Array.from(Zs.values()).sort((e,t)=>e.createdAt-t.createdAt)}function ohe(e){return Zs.get(e)}function VB(e){return Zs.has(e)?(S_(e,{proposalId:e,decision:"deny",respondedAt:Date.now(),respondedBy:"auto",reason:"cancelled"}),!0):!1}function ahe(){let e=0;for(let t of Zs.keys())VB(t)&&e++;return e}function che(){return Array.from(Qo.values())}function lhe(e){let t=Qo.delete(e);return t&&Lv(),t}function uhe(){Qo.clear(),Lv()}function UB(e){if(Re.enableAuditLog){b_();try{y_(m_,JSON.stringify({...e,timestamp:Date.now()})+`
1433
+ - Use \${task_id} in toolInput strings to reference outputs from previous tasks`;try{let s=(await t.sendMessage([{role:"user",content:n,timestamp:new Date().toISOString()}],"You decompose goals into task DAGs. Output strict JSON only.",[],void 0)).content?.match(/\{[\s\S]*\}/)?.[0];return s?(JSON.parse(s).tasks||[]).map(o=>({id:o.id,name:o.name||o.id,description:o.description||"",dependencies:o.dependencies||[],type:o.type||"manual",toolName:o.toolName,toolInput:o.toolInput,specialistType:o.specialistType,prompt:o.prompt,estimatedDurationMs:o.estimatedDurationMs,estimatedCost:o.estimatedCost,priority:o.priority||5,tags:o.tags||[],exclusive:o.exclusive||!1,maxRetries:o.maxRetries??1})):[]}catch{return[]}}function Wge(e){let t=[];t.push(`# Task Graph: ${e.goal}`),t.push(`Status: ${e.status} | Tasks: ${e.totalTasks} (${e.completedTasks} \u2713, ${e.failedTasks} \u2717)`),t.push("");let n=e.totalTasks>0?e.completedTasks/e.totalTasks:0,r="\u2588".repeat(Math.floor(n*30))+"\u2591".repeat(30-Math.floor(n*30));t.push(`Progress: [${r}] ${(n*100).toFixed(0)}%`),t.push("");let s=[],i=new Set;function o(a,c){if(i.has(a))return;i.add(a);let l=e.tasks.get(a);if(!l)return;let u=l.status==="completed"?"\u2713":l.status==="running"?"\u27F3":l.status==="failed"?"\u2717":l.status==="ready"?"\u25D0":l.status==="skipped"?"~":l.status==="cancelled"?"\u2715":"\u25CB",d=" ".repeat(c),f=l.completedAt&&l.startedAt?` (${l.completedAt-l.startedAt}ms)`:"";t.push(`${d}${u} ${l.name}${f}`),l.error&&t.push(`${d} \u26A0 ${l.error.slice(0,100)}`);for(let p of l.dependents)o(p,c+1)}for(let a of e.tasks.values())a.dependencies.length===0&&o(a.id,0);return t.join(`
1434
+ `)}var u_=w(()=>{"use strict";Mv();Ls()});var w_={};$(w_,{cancelAll:()=>che,cancelPending:()=>VB,clearMemory:()=>dhe,configure:()=>mhe,forgetDecision:()=>uhe,formatProposal:()=>hhe,getAuditLog:()=>JB,getConfig:()=>fhe,getEvents:()=>ghe,getPendingProposals:()=>ohe,getProposal:()=>ahe,getRememberedDecisions:()=>lhe,getStats:()=>yhe,respondToProposal:()=>ihe,setPolicy:()=>phe,submitProposal:()=>she});import{existsSync as g_,mkdirSync as Kge,readFileSync as h_,writeFileSync as y_}from"fs";import{join as Dv}from"path";import{homedir as Yge}from"os";import{createHash as HB}from"crypto";import{EventEmitter as Qge}from"events";function b_(){Kge(Fv,{recursive:!0})}function ehe(){if(g_(f_))try{let e=JSON.parse(h_(f_,"utf-8"));Re={...Re,...e}}catch{}}function zB(){b_();try{y_(f_,JSON.stringify(Re,null,2),"utf-8")}catch{}}function the(){if(g_(p_))try{let e=JSON.parse(h_(p_,"utf-8")),t=Date.now();for(let n of e)n.expiresAt&&t>n.expiresAt||Qo.set(n.patternHash,n)}catch{}}function Lv(){b_();try{y_(p_,JSON.stringify(Array.from(Qo.values()),null,2),"utf-8")}catch{}}function nhe(e){let n={irreversible_op:"high",deployment:"critical",security_change:"high",destructive_command:"high",cost_threshold:"medium",batch_operation:"medium",external_api_call:"low",plan_review:"low",custom:"medium"}[e.gateType]||"medium";return e.filesAffected.length>20?n="critical":e.filesAffected.length>10&&(n=d_(n,"high")),e.reversibility==="irreversible"&&(n=d_(n,"high")),e.estimatedCost&&e.estimatedCost>10?n="critical":e.estimatedCost&&e.estimatedCost>1&&(n=d_(n,"high")),e.command&&/\b(rm\s+-rf|drop\s+table|delete\s+from|--force|force-push|reset\s+--hard)\b/i.test(e.command)&&(n="critical"),n}function d_(e,t){let n=["safe","low","medium","high","critical"];return n[Math.max(n.indexOf(e),n.indexOf(t))]}function GB(e){let t=JSON.stringify({type:e.gateType,command:e.command,files:e.filesAffected.slice(0,5).sort()});return HB("sha256").update(t).digest("hex").slice(0,16)}function rhe(e){if(!Re.enabled)return zr(e.id,"approve","service disabled");if(Re.enableMemory){let i=GB(e),o=Qo.get(i);if(o)return o.hits++,Lv(),zr(e.id,o.decision,`remembered: ${o.rememberedFor}`)}for(let i of Re.policy.preApprovedPatterns)try{if(new RegExp(i,"i").test(e.description))return zr(e.id,"approve",`pre-approved pattern: ${i}`)}catch{}for(let i of Re.policy.preDeniedPatterns)try{if(new RegExp(i,"i").test(e.description))return zr(e.id,"deny",`pre-denied pattern: ${i}`)}catch{}let t=Re.policy.perTypePolicy[e.gateType];if(t?.mode==="auto_approve")return zr(e.id,"approve","type policy: auto_approve");if(t?.mode==="auto_deny")return zr(e.id,"deny","type policy: auto_deny");if(t?.mode==="always_ask"||Re.policy.mode==="always_ask")return null;if(Re.policy.mode==="deny_all")return zr(e.id,"deny","policy: deny_all");let n=["safe","low","medium","high","critical"],r=n.indexOf(e.riskLevel),s=n.indexOf(Re.policy.riskThreshold);if(Re.policy.mode==="allow_low_risk"&&r<s)return zr(e.id,"approve",`low risk (${e.riskLevel})`);if(Re.policy.mode==="ask_if_risky"&&r<s)return zr(e.id,"approve",`below threshold (${e.riskLevel})`);if(e.estimatedCost&&e.estimatedCost>Re.policy.costThreshold)return null;if(Re.policy.workHoursOnly){let i=new Date().getHours();if(i<Re.policy.workHoursOnly.start||i>=Re.policy.workHoursOnly.end)return zr(e.id,"defer","outside work hours")}return null}function zr(e,t,n){return{proposalId:e,decision:t,respondedAt:Date.now(),respondedBy:"auto",reason:n}}async function she(e,t={}){if(!Re.enabled)return zr("disabled","approve","HITL disabled");if(Zs.size>=Re.maxPendingProposals)return zr("overloaded","deny",`Pending proposals exceeded (${Zs.size})`);let n=HB("sha256").update(e.title+Date.now()+Math.random()).digest("hex").slice(0,12),r={...e,id:n,createdAt:Date.now(),riskLevel:e.riskLevel||nhe(e),expiresAt:Date.now()+(t.timeoutMs??Re.policy.defaultTimeout),tags:e.tags||[],metadata:e.metadata||{}},s=rhe(r);if(s)return UB({proposal:r,response:s}),s;Zs.set(n,r),v_.emit("proposal_submitted",r);let i=await new Promise(o=>{if(Ev.set(n,o),r.expiresAt){let a=r.expiresAt-Date.now();a>0&&setTimeout(()=>{if(Ev.has(n)){let u=(Re.policy.perTypePolicy[r.gateType]?.timeoutAction||Re.policy.timeoutAction)==="approve"?"approve":"deny",d={proposalId:n,decision:u,respondedAt:Date.now(),respondedBy:"auto",reason:`timeout after ${(r.expiresAt-r.createdAt)/1e3}s`};S_(n,d)}},a).unref()}});if(Zs.delete(n),UB({proposal:r,response:i}),Re.enableMemory&&(i.decision==="approve_always"||i.decision==="deny_always")){let o=GB(r);Qo.set(o,{patternHash:o,pattern:`${r.gateType}: ${r.title}`.slice(0,100),decision:i.decision==="approve_always"?"approve":"deny",rememberedFor:i.rememberedFor||"project",rememberedAt:Date.now(),hits:0}),Lv()}return i}function S_(e,t){let n=Ev.get(e);n&&(Ev.delete(e),n(t))}function ihe(e,t,n={}){if(!Zs.get(e))return!1;let s={proposalId:e,decision:t,respondedAt:Date.now(),respondedBy:"user",reason:n.reason,modifications:n.modifications,rememberedFor:n.rememberedFor};return S_(e,s),!0}function ohe(){return Array.from(Zs.values()).sort((e,t)=>e.createdAt-t.createdAt)}function ahe(e){return Zs.get(e)}function VB(e){return Zs.has(e)?(S_(e,{proposalId:e,decision:"deny",respondedAt:Date.now(),respondedBy:"auto",reason:"cancelled"}),!0):!1}function che(){let e=0;for(let t of Zs.keys())VB(t)&&e++;return e}function lhe(){return Array.from(Qo.values())}function uhe(e){let t=Qo.delete(e);return t&&Lv(),t}function dhe(){Qo.clear(),Lv()}function UB(e){if(Re.enableAuditLog){b_();try{y_(m_,JSON.stringify({...e,timestamp:Date.now()})+`
1425
1435
  `,{flag:"a"})}catch{}}}function JB(e=100){if(!g_(m_))return[];try{return h_(m_,"utf-8").split(`
1426
- `).filter(Boolean).slice(-e).map(n=>JSON.parse(n)).reverse()}catch{return[]}}function dhe(){return JSON.parse(JSON.stringify(Re))}function fhe(e){Re.policy={...Re.policy,...e},zB()}function phe(e){Re={...Re,...e},zB()}function mhe(){return v_}function ghe(e){let t=[],n={safe:"\u2713",low:"\u2139\uFE0F ",medium:"\u26A1",high:"\u26A0\uFE0F ",critical:"\u{1F6A8}"};if(t.push(`# ${n[e.riskLevel]} Approval Required`),t.push(""),t.push(`**${e.title}**`),t.push(""),t.push(`Type: ${e.gateType} | Risk: ${e.riskLevel} | Reversibility: ${e.reversibility}`),t.push(`ID: ${e.id}`),e.expiresAt){let r=Math.max(0,e.expiresAt-Date.now());t.push(`Timeout: ${Math.round(r/1e3)}s`)}if(t.push(""),t.push("## What"),t.push(e.description),e.command&&(t.push(""),t.push("Command:"),t.push("```"),t.push(e.command.slice(0,500)),t.push("```")),t.push(""),t.push("## Why"),t.push(e.rationale),e.filesAffected.length>0){t.push(""),t.push(`## Files Affected (${e.filesAffected.length})`);for(let r of e.filesAffected.slice(0,15))t.push(` - ${r}`);e.filesAffected.length>15&&t.push(` ... +${e.filesAffected.length-15} more`)}if(e.estimatedCost&&(t.push(""),t.push(`Estimated cost: $${e.estimatedCost.toFixed(4)}`)),e.preview&&(t.push(""),t.push("## Preview"),t.push(e.preview.slice(0,1e3))),e.alternatives&&e.alternatives.length>0){t.push(""),t.push("## Alternatives Considered");for(let r of e.alternatives)t.push(` - ${r}`)}return t.push(""),t.push("Respond with: approve | approve_always | deny | deny_always | modify"),t.join(`
1427
- `)}function hhe(){let e=JB(1e3),t={totalProposals:e.length,approved:0,denied:0,timedOut:0,autoApproved:0,autoDenied:0,pendingCount:Zs.size,rememberedCount:Qo.size,byType:{},byRisk:{}};for(let n of e){let r=n.response.decision;(r==="approve"||r==="approve_always")&&(t.approved++,n.response.respondedBy==="auto"&&t.autoApproved++),(r==="deny"||r==="deny_always")&&(t.denied++,n.response.respondedBy==="auto"&&t.autoDenied++),(r==="timeout"||n.response.reason?.includes("timeout"))&&t.timedOut++,t.byType[n.proposal.gateType]=(t.byType[n.proposal.gateType]||0)+1,t.byRisk[n.proposal.riskLevel]=(t.byRisk[n.proposal.riskLevel]||0)+1}return t}var Qge,Zge,Re,Fv,f_,p_,m_,Qo,Zs,Ev,v_,k_=w(()=>{"use strict";Qge={mode:"ask_if_risky",riskThreshold:"medium",costThreshold:1,defaultTimeout:300*1e3,timeoutAction:"deny",perTypePolicy:{deployment:{mode:"always_ask",timeoutAction:"deny"},security_change:{mode:"always_ask",timeoutAction:"deny"},irreversible_op:{mode:"always_ask",timeoutAction:"deny"},cost_threshold:{mode:"always_ask"},plan_review:{mode:"always_ask"},batch_operation:{mode:"always_ask"},destructive_command:{mode:"always_ask",timeoutAction:"deny"},external_api_call:{mode:"auto_approve"}},preApprovedPatterns:[],preDeniedPatterns:[]},Zge={enabled:!0,policy:Qge,enableAuditLog:!0,enableMemory:!0,enableSummaryGeneration:!0,maxPendingProposals:10},Re={...Zge},Fv=Dv(Kge(),".aiaca","hitl-gates"),f_=Dv(Fv,"policy.json"),p_=Dv(Fv,"memory.json"),m_=Dv(Fv,"audit.jsonl");Qo=new Map;Xge();ehe();Zs=new Map,Ev=new Map,v_=new Yge;v_.setMaxListeners(100)});var R_={};$(R_,{applyFixes:()=>Dhe,configure:()=>Nhe,detectPlatform:()=>ZB,diagnoseFailure:()=>eN,formatBuild:()=>qhe,getBuild:()=>Lhe,getBuilds:()=>nN,getConfig:()=>Bhe,getFailurePatterns:()=>Ohe,getStats:()=>jhe,monitorBuild:()=>Mhe,parseLogs:()=>A_,triggerBuild:()=>tN});import{existsSync as Hi,mkdirSync as yhe,readFileSync as YB,writeFileSync as T_}from"fs";import{join as ys}from"path";import{homedir as bhe}from"os";import{execSync as zi}from"child_process";import{createHash as vhe}from"crypto";function __(){yhe(Ov,{recursive:!0})}function khe(){if(Hi(x_))try{let e=JSON.parse(YB(x_,"utf-8"));for(let t of e.slice(-Ct.retentionCount))Hc.set(t.id,t)}catch{}}function QB(){if(Ct.enablePersistence){__();try{let e=Array.from(Hc.values()).slice(-Ct.retentionCount);T_(x_,JSON.stringify(e),"utf-8")}catch{}}}function xhe(){if(Hi($_))try{let e=JSON.parse(YB($_,"utf-8"));for(let[t,n]of Object.entries(e))Ym.set(t,n)}catch{}}function $he(){__();try{let e={};for(let[t,n]of Ym)e[t]=n;T_($_,JSON.stringify(e,null,2),"utf-8")}catch{}}function ZB(e){return Hi(ys(e,".github","workflows"))?"github_actions":Hi(ys(e,".gitlab-ci.yml"))?"gitlab_ci":Hi(ys(e,".circleci","config.yml"))?"circleci":Hi(ys(e,"Jenkinsfile"))?"jenkins":Hi(ys(e,".travis.yml"))?"travis":Hi(ys(e,"azure-pipelines.yml"))?"azure_devops":Hi(ys(e,"bitbucket-pipelines.yml"))?"bitbucket":"unknown"}function C_(e){try{let t=zi("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim(),n=t.match(/github\.com[:/]([^/]+)\/([^/.]+)/)||t.match(/gitlab\.com[:/]([^/]+)\/([^/.]+)/);if(n)return{owner:n[1],repo:n[2]}}catch{}return null}async function Che(e,t,n,r={}){let s=C_(e);if(!s)return{success:!1,error:"Cannot determine GitHub repo"};let i=Ct.githubToken||process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(!i)return{success:!1,error:"GITHUB_TOKEN not set"};try{if(await XB()){let a=Object.entries(r).map(([d,f])=>`-f ${d}=${f}`).join(" "),c=zi(`gh workflow run ${t} --ref ${n} ${a}`,{cwd:e,stdio:"pipe",encoding:"utf-8"});await new Promise(d=>setTimeout(d,2e3));let l=zi(`gh run list --workflow ${t} --branch ${n} --limit 1 --json databaseId`,{cwd:e,stdio:"pipe",encoding:"utf-8"}),u=JSON.parse(l);return{success:!0,runId:String(u[0]?.databaseId)}}let o=await fetch(`https://api.github.com/repos/${s.owner}/${s.repo}/actions/workflows/${t}/dispatches`,{method:"POST",headers:{Authorization:`Bearer ${i}`,Accept:"application/vnd.github.v3+json"},body:JSON.stringify({ref:n,inputs:r})});return o.status===204?{success:!0,runId:"pending"}:{success:!1,error:`HTTP ${o.status}`}}catch(o){return{success:!1,error:o.message}}}async function XB(){try{return zi("gh --version",{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}async function Ahe(e,t){try{if(await XB()){let n=zi(`gh run view ${t} --json status,conclusion,jobs`,{cwd:e,stdio:"pipe",encoding:"utf-8"}),r=JSON.parse(n),s=The(r.status,r.conclusion),i="";if(s!=="running"&&s!=="queued")try{i=zi(`gh run view ${t} --log`,{cwd:e,stdio:"pipe",encoding:"utf-8",maxBuffer:Ct.maxLogSize})}catch{}return{status:s,conclusion:r.conclusion,logs:i}}return{status:"pending"}}catch{return{status:"pending"}}}function The(e,t){return e==="queued"||e==="waiting"?"queued":e==="in_progress"?"running":e==="completed"?t==="success"?"success":t==="failure"?"failure":t==="cancelled"?"cancelled":t==="timed_out"?"timeout":"failure":"pending"}async function WB(e,t,n,r){let s=Date.now();n.status="running";try{let i=zi(t,{cwd:e,stdio:"pipe",timeout:Ct.buildTimeoutMs,encoding:"utf-8",maxBuffer:Ct.maxLogSize});n.logs=i,n.status="success",n.exitCode=0}catch(i){n.logs=(i.stdout?.toString()||"")+(i.stderr?.toString()||""),n.status="failure",n.exitCode=i.status||1}n.completedAt=Date.now(),n.duration=n.completedAt-n.startedAt,r&&r(n.logs.slice(0,5e3))}function A_(e){let t=[],n=new Set,r=e.slice(-1e5);for(let{type:s,regex:i,severity:o}of _he){let a,c=new RegExp(i.source,i.flags);for(;(a=c.exec(r))!==null;){let l=`${s}:${a[0].slice(0,50)}`;if(n.has(l))continue;n.add(l);let u,d,f=a[0];s==="compile"?(u=a[1],d=parseInt(a[2],10),f=`TS${a[4]}: ${a[5]}`):s==="syntax"?(u=a[1],d=parseInt(a[2],10),f=a[3]):s==="dependency"?f=`Cannot find module: ${a[1]}`:s==="runtime"&&(f=`${a[1]}: ${a[2]}`),t.push({type:s,severity:o,file:u,line:d,message:f.slice(0,500),context:a[0].slice(0,200)})}}return t.slice(0,50)}async function eN(e,t){let n=A_(e.logs);e.stages.forEach(s=>{s.errors=A_(s.logs)});let r=Rhe(n,e.logs);if(t&&Ct.enableAIDiagnosis&&e.logs.length>0)try{let s=await Phe(e,n,t);return{rootCause:s.rootCause||r.rootCause,category:s.category||r.category,confidence:Math.max(s.confidence,r.confidence),suggestedFixes:[...s.suggestedFixes,...r.suggestedFixes].slice(0,5),similarPastFailures:KB(e),autoFixable:s.autoFixable||r.autoFixable}}catch{}return{...r,similarPastFailures:KB(e)}}function Rhe(e,t){let n=e.find(c=>c.type==="dependency");if(n){let c=n.message.match(/['"]([^'"]+)['"]/)?.[1];return{rootCause:`Missing dependency: ${c||"unknown module"}`,category:"dependency",confidence:.9,suggestedFixes:[{description:`Install missing module: ${c}`,type:"dependency_update",command:c?.startsWith("@")||/^[a-z]/.test(c||"")?`npm install ${c}`:`pip install ${c}`,confidence:.85}],similarPastFailures:[],autoFixable:!0}}let r=e.filter(c=>c.type==="test");if(r.length>0)return{rootCause:`${r.length} test(s) failed`,category:"test_failure",confidence:.85,suggestedFixes:[{description:`Investigate failing tests: ${r.slice(0,3).map(c=>c.message.slice(0,50)).join("; ")}`,type:"manual",confidence:.7}],similarPastFailures:[],autoFixable:!1};let s=e.filter(c=>c.type==="compile");if(s.length>0)return{rootCause:`${s.length} TypeScript compile error(s)`,category:"compile",confidence:.9,suggestedFixes:[{description:`Fix type errors in: ${s[0].file||"unknown file"}`,type:"code_change",filePath:s[0].file,confidence:.6}],similarPastFailures:[],autoFixable:!1};let i=e.filter(c=>c.type==="lint");return i.length>0?{rootCause:`${i.length} lint violation(s)`,category:"lint",confidence:.85,suggestedFixes:[{description:"Run linter with --fix flag",type:"config_change",command:"npm run lint -- --fix",confidence:.8}],similarPastFailures:[],autoFixable:!0}:e.filter(c=>c.type==="network").length>0?{rootCause:"Network connectivity issue",category:"infrastructure",confidence:.7,suggestedFixes:[{description:"Retry build (likely transient)",type:"manual",confidence:.8}],similarPastFailures:[],autoFixable:!1}:e.filter(c=>c.type==="permission").length>0?{rootCause:"Permission denied",category:"permission",confidence:.8,suggestedFixes:[{description:"Check file permissions or CI runner privileges",type:"manual",confidence:.6}],similarPastFailures:[],autoFixable:!1}:{rootCause:e.length>0?e[0].message:"Build failed for unknown reason",category:e[0]?.type||"unknown",confidence:.4,suggestedFixes:[{description:"Inspect logs manually",type:"manual",confidence:.5}],similarPastFailures:[],autoFixable:!1}}async function Phe(e,t,n){let r=`Diagnose this CI build failure.
1436
+ `).filter(Boolean).slice(-e).map(n=>JSON.parse(n)).reverse()}catch{return[]}}function fhe(){return JSON.parse(JSON.stringify(Re))}function phe(e){Re.policy={...Re.policy,...e},zB()}function mhe(e){Re={...Re,...e},zB()}function ghe(){return v_}function hhe(e){let t=[],n={safe:"\u2713",low:"\u2139\uFE0F ",medium:"\u26A1",high:"\u26A0\uFE0F ",critical:"\u{1F6A8}"};if(t.push(`# ${n[e.riskLevel]} Approval Required`),t.push(""),t.push(`**${e.title}**`),t.push(""),t.push(`Type: ${e.gateType} | Risk: ${e.riskLevel} | Reversibility: ${e.reversibility}`),t.push(`ID: ${e.id}`),e.expiresAt){let r=Math.max(0,e.expiresAt-Date.now());t.push(`Timeout: ${Math.round(r/1e3)}s`)}if(t.push(""),t.push("## What"),t.push(e.description),e.command&&(t.push(""),t.push("Command:"),t.push("```"),t.push(e.command.slice(0,500)),t.push("```")),t.push(""),t.push("## Why"),t.push(e.rationale),e.filesAffected.length>0){t.push(""),t.push(`## Files Affected (${e.filesAffected.length})`);for(let r of e.filesAffected.slice(0,15))t.push(` - ${r}`);e.filesAffected.length>15&&t.push(` ... +${e.filesAffected.length-15} more`)}if(e.estimatedCost&&(t.push(""),t.push(`Estimated cost: $${e.estimatedCost.toFixed(4)}`)),e.preview&&(t.push(""),t.push("## Preview"),t.push(e.preview.slice(0,1e3))),e.alternatives&&e.alternatives.length>0){t.push(""),t.push("## Alternatives Considered");for(let r of e.alternatives)t.push(` - ${r}`)}return t.push(""),t.push("Respond with: approve | approve_always | deny | deny_always | modify"),t.join(`
1437
+ `)}function yhe(){let e=JB(1e3),t={totalProposals:e.length,approved:0,denied:0,timedOut:0,autoApproved:0,autoDenied:0,pendingCount:Zs.size,rememberedCount:Qo.size,byType:{},byRisk:{}};for(let n of e){let r=n.response.decision;(r==="approve"||r==="approve_always")&&(t.approved++,n.response.respondedBy==="auto"&&t.autoApproved++),(r==="deny"||r==="deny_always")&&(t.denied++,n.response.respondedBy==="auto"&&t.autoDenied++),(r==="timeout"||n.response.reason?.includes("timeout"))&&t.timedOut++,t.byType[n.proposal.gateType]=(t.byType[n.proposal.gateType]||0)+1,t.byRisk[n.proposal.riskLevel]=(t.byRisk[n.proposal.riskLevel]||0)+1}return t}var Zge,Xge,Re,Fv,f_,p_,m_,Qo,Zs,Ev,v_,k_=w(()=>{"use strict";Zge={mode:"ask_if_risky",riskThreshold:"medium",costThreshold:1,defaultTimeout:300*1e3,timeoutAction:"deny",perTypePolicy:{deployment:{mode:"always_ask",timeoutAction:"deny"},security_change:{mode:"always_ask",timeoutAction:"deny"},irreversible_op:{mode:"always_ask",timeoutAction:"deny"},cost_threshold:{mode:"always_ask"},plan_review:{mode:"always_ask"},batch_operation:{mode:"always_ask"},destructive_command:{mode:"always_ask",timeoutAction:"deny"},external_api_call:{mode:"auto_approve"}},preApprovedPatterns:[],preDeniedPatterns:[]},Xge={enabled:!0,policy:Zge,enableAuditLog:!0,enableMemory:!0,enableSummaryGeneration:!0,maxPendingProposals:10},Re={...Xge},Fv=Dv(Yge(),".aiaca","hitl-gates"),f_=Dv(Fv,"policy.json"),p_=Dv(Fv,"memory.json"),m_=Dv(Fv,"audit.jsonl");Qo=new Map;ehe();the();Zs=new Map,Ev=new Map,v_=new Qge;v_.setMaxListeners(100)});var R_={};$(R_,{applyFixes:()=>Fhe,configure:()=>qhe,detectPlatform:()=>ZB,diagnoseFailure:()=>eN,formatBuild:()=>Uhe,getBuild:()=>Ohe,getBuilds:()=>nN,getConfig:()=>Nhe,getFailurePatterns:()=>jhe,getStats:()=>Bhe,monitorBuild:()=>Ehe,parseLogs:()=>A_,triggerBuild:()=>tN});import{existsSync as Hi,mkdirSync as bhe,readFileSync as YB,writeFileSync as T_}from"fs";import{join as ys}from"path";import{homedir as vhe}from"os";import{execSync as zi}from"child_process";import{createHash as She}from"crypto";function __(){bhe(Ov,{recursive:!0})}function xhe(){if(Hi(x_))try{let e=JSON.parse(YB(x_,"utf-8"));for(let t of e.slice(-Ct.retentionCount))Hc.set(t.id,t)}catch{}}function QB(){if(Ct.enablePersistence){__();try{let e=Array.from(Hc.values()).slice(-Ct.retentionCount);T_(x_,JSON.stringify(e),"utf-8")}catch{}}}function $he(){if(Hi($_))try{let e=JSON.parse(YB($_,"utf-8"));for(let[t,n]of Object.entries(e))Ym.set(t,n)}catch{}}function Che(){__();try{let e={};for(let[t,n]of Ym)e[t]=n;T_($_,JSON.stringify(e,null,2),"utf-8")}catch{}}function ZB(e){return Hi(ys(e,".github","workflows"))?"github_actions":Hi(ys(e,".gitlab-ci.yml"))?"gitlab_ci":Hi(ys(e,".circleci","config.yml"))?"circleci":Hi(ys(e,"Jenkinsfile"))?"jenkins":Hi(ys(e,".travis.yml"))?"travis":Hi(ys(e,"azure-pipelines.yml"))?"azure_devops":Hi(ys(e,"bitbucket-pipelines.yml"))?"bitbucket":"unknown"}function C_(e){try{let t=zi("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim(),n=t.match(/github\.com[:/]([^/]+)\/([^/.]+)/)||t.match(/gitlab\.com[:/]([^/]+)\/([^/.]+)/);if(n)return{owner:n[1],repo:n[2]}}catch{}return null}async function Ahe(e,t,n,r={}){let s=C_(e);if(!s)return{success:!1,error:"Cannot determine GitHub repo"};let i=Ct.githubToken||process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(!i)return{success:!1,error:"GITHUB_TOKEN not set"};try{if(await XB()){let a=Object.entries(r).map(([d,f])=>`-f ${d}=${f}`).join(" "),c=zi(`gh workflow run ${t} --ref ${n} ${a}`,{cwd:e,stdio:"pipe",encoding:"utf-8"});await new Promise(d=>setTimeout(d,2e3));let l=zi(`gh run list --workflow ${t} --branch ${n} --limit 1 --json databaseId`,{cwd:e,stdio:"pipe",encoding:"utf-8"}),u=JSON.parse(l);return{success:!0,runId:String(u[0]?.databaseId)}}let o=await fetch(`https://api.github.com/repos/${s.owner}/${s.repo}/actions/workflows/${t}/dispatches`,{method:"POST",headers:{Authorization:`Bearer ${i}`,Accept:"application/vnd.github.v3+json"},body:JSON.stringify({ref:n,inputs:r})});return o.status===204?{success:!0,runId:"pending"}:{success:!1,error:`HTTP ${o.status}`}}catch(o){return{success:!1,error:o.message}}}async function XB(){try{return zi("gh --version",{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}async function The(e,t){try{if(await XB()){let n=zi(`gh run view ${t} --json status,conclusion,jobs`,{cwd:e,stdio:"pipe",encoding:"utf-8"}),r=JSON.parse(n),s=_he(r.status,r.conclusion),i="";if(s!=="running"&&s!=="queued")try{i=zi(`gh run view ${t} --log`,{cwd:e,stdio:"pipe",encoding:"utf-8",maxBuffer:Ct.maxLogSize})}catch{}return{status:s,conclusion:r.conclusion,logs:i}}return{status:"pending"}}catch{return{status:"pending"}}}function _he(e,t){return e==="queued"||e==="waiting"?"queued":e==="in_progress"?"running":e==="completed"?t==="success"?"success":t==="failure"?"failure":t==="cancelled"?"cancelled":t==="timed_out"?"timeout":"failure":"pending"}async function WB(e,t,n,r){let s=Date.now();n.status="running";try{let i=zi(t,{cwd:e,stdio:"pipe",timeout:Ct.buildTimeoutMs,encoding:"utf-8",maxBuffer:Ct.maxLogSize});n.logs=i,n.status="success",n.exitCode=0}catch(i){n.logs=(i.stdout?.toString()||"")+(i.stderr?.toString()||""),n.status="failure",n.exitCode=i.status||1}n.completedAt=Date.now(),n.duration=n.completedAt-n.startedAt,r&&r(n.logs.slice(0,5e3))}function A_(e){let t=[],n=new Set,r=e.slice(-1e5);for(let{type:s,regex:i,severity:o}of Rhe){let a,c=new RegExp(i.source,i.flags);for(;(a=c.exec(r))!==null;){let l=`${s}:${a[0].slice(0,50)}`;if(n.has(l))continue;n.add(l);let u,d,f=a[0];s==="compile"?(u=a[1],d=parseInt(a[2],10),f=`TS${a[4]}: ${a[5]}`):s==="syntax"?(u=a[1],d=parseInt(a[2],10),f=a[3]):s==="dependency"?f=`Cannot find module: ${a[1]}`:s==="runtime"&&(f=`${a[1]}: ${a[2]}`),t.push({type:s,severity:o,file:u,line:d,message:f.slice(0,500),context:a[0].slice(0,200)})}}return t.slice(0,50)}async function eN(e,t){let n=A_(e.logs);e.stages.forEach(s=>{s.errors=A_(s.logs)});let r=Phe(n,e.logs);if(t&&Ct.enableAIDiagnosis&&e.logs.length>0)try{let s=await Ihe(e,n,t);return{rootCause:s.rootCause||r.rootCause,category:s.category||r.category,confidence:Math.max(s.confidence,r.confidence),suggestedFixes:[...s.suggestedFixes,...r.suggestedFixes].slice(0,5),similarPastFailures:KB(e),autoFixable:s.autoFixable||r.autoFixable}}catch{}return{...r,similarPastFailures:KB(e)}}function Phe(e,t){let n=e.find(c=>c.type==="dependency");if(n){let c=n.message.match(/['"]([^'"]+)['"]/)?.[1];return{rootCause:`Missing dependency: ${c||"unknown module"}`,category:"dependency",confidence:.9,suggestedFixes:[{description:`Install missing module: ${c}`,type:"dependency_update",command:c?.startsWith("@")||/^[a-z]/.test(c||"")?`npm install ${c}`:`pip install ${c}`,confidence:.85}],similarPastFailures:[],autoFixable:!0}}let r=e.filter(c=>c.type==="test");if(r.length>0)return{rootCause:`${r.length} test(s) failed`,category:"test_failure",confidence:.85,suggestedFixes:[{description:`Investigate failing tests: ${r.slice(0,3).map(c=>c.message.slice(0,50)).join("; ")}`,type:"manual",confidence:.7}],similarPastFailures:[],autoFixable:!1};let s=e.filter(c=>c.type==="compile");if(s.length>0)return{rootCause:`${s.length} TypeScript compile error(s)`,category:"compile",confidence:.9,suggestedFixes:[{description:`Fix type errors in: ${s[0].file||"unknown file"}`,type:"code_change",filePath:s[0].file,confidence:.6}],similarPastFailures:[],autoFixable:!1};let i=e.filter(c=>c.type==="lint");return i.length>0?{rootCause:`${i.length} lint violation(s)`,category:"lint",confidence:.85,suggestedFixes:[{description:"Run linter with --fix flag",type:"config_change",command:"npm run lint -- --fix",confidence:.8}],similarPastFailures:[],autoFixable:!0}:e.filter(c=>c.type==="network").length>0?{rootCause:"Network connectivity issue",category:"infrastructure",confidence:.7,suggestedFixes:[{description:"Retry build (likely transient)",type:"manual",confidence:.8}],similarPastFailures:[],autoFixable:!1}:e.filter(c=>c.type==="permission").length>0?{rootCause:"Permission denied",category:"permission",confidence:.8,suggestedFixes:[{description:"Check file permissions or CI runner privileges",type:"manual",confidence:.6}],similarPastFailures:[],autoFixable:!1}:{rootCause:e.length>0?e[0].message:"Build failed for unknown reason",category:e[0]?.type||"unknown",confidence:.4,suggestedFixes:[{description:"Inspect logs manually",type:"manual",confidence:.5}],similarPastFailures:[],autoFixable:!1}}async function Ihe(e,t,n){let r=`Diagnose this CI build failure.
1428
1438
 
1429
1439
  WORKFLOW: ${e.workflow}
1430
1440
  BRANCH: ${e.branch}
@@ -1452,10 +1462,10 @@ Output strict JSON only:
1452
1462
  }
1453
1463
  ],
1454
1464
  "autoFixable": true|false
1455
- }`;try{let i=(await n.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You diagnose CI/CD build failures. Output strict JSON only.",[],void 0)).content?.match(/\{[\s\S]*\}/)?.[0];if(!i)throw new Error("No JSON in response");let o=JSON.parse(i);return{rootCause:o.rootCause||"Unknown",category:o.category||"unknown",confidence:o.confidence||.5,suggestedFixes:o.suggestedFixes||[],similarPastFailures:[],autoFixable:!!o.autoFixable}}catch{return{rootCause:"AI diagnosis failed",category:"unknown",confidence:.1,suggestedFixes:[],similarPastFailures:[],autoFixable:!1}}}function KB(e){if(!e.diagnosis?.rootCause)return[];let t=new Set(e.diagnosis.rootCause.toLowerCase().split(/\s+/).filter(r=>r.length>3)),n=[];for(let[r,s]of Hc){if(r===e.id||!s.diagnosis||s.status!=="failure")continue;let i=new Set(s.diagnosis.rootCause.toLowerCase().split(/\s+/)),o=[...t].filter(a=>i.has(a)).length;o>=2&&n.push({id:r,score:o})}return n.sort((r,s)=>s.score-r.score).slice(0,5).map(r=>r.id)}async function tN(e,t){if(!Ct.enabled)throw new Error("CI/CD service disabled");let n=ZB(e.projectPath),r=vhe("sha256").update(Date.now().toString()+Math.random()).digest("hex").slice(0,12),s=e.branch||Ct.defaultBranch,i=e.workflow||Ct.defaultWorkflow||"ci.yml",o={id:r,externalId:"",platform:n,workflow:i,branch:s,commit:Ihe(e.projectPath),triggeredBy:e.triggeredBy||"manual",status:"pending",startedAt:Date.now(),stages:[],logs:"",metadata:{},retryAttempt:0};Hc.set(r,o);try{if(n==="github_actions"){let a=await Che(e.projectPath,i,s,e.inputs);a.success?(o.externalId=a.runId||"",o.status="queued",o.url=`https://github.com/${C_(e.projectPath)?.owner}/${C_(e.projectPath)?.repo}/actions/runs/${a.runId}`):e.fallbackCommand?await WB(e.projectPath,e.fallbackCommand,o):(o.status="failure",o.logs=`Failed to trigger: ${a.error}`)}else e.fallbackCommand?await WB(e.projectPath,e.fallbackCommand,o):(o.status="failure",o.logs=`Platform ${n} not yet supported. Provide fallbackCommand.`)}catch(a){o.status="failure",o.logs=a.message}if(o.status==="failure"&&Ct.enableAIDiagnosis&&(o.diagnosis=await eN(o,t),Ehe(o)),QB(),Fhe(o),o.status==="failure"&&Ct.enableAutoRetry&&o.retryAttempt<Ct.maxRetries&&(o.diagnosis?.category==="infrastructure"||o.diagnosis?.category==="network")){let a=Ct.retryBackoffMs*Math.pow(2,o.retryAttempt);await new Promise(l=>setTimeout(l,a));let c=await tN({...e,triggeredBy:"auto-retry"},t);c.parentBuildId=o.id,c.retryAttempt=o.retryAttempt+1}return o}function Ihe(e){try{return zi("git rev-parse HEAD",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim().slice(0,12)}catch{return"unknown"}}async function Mhe(e,t,n){let r=Hc.get(e);if(!r)throw new Error(`Build not found: ${e}`);if(!r.externalId)return r;let s=Date.now();for(;r.status==="pending"||r.status==="queued"||r.status==="running";){if(Date.now()-s>Ct.buildTimeoutMs){r.status="timeout";break}if(r.platform==="github_actions"){let i=await Ahe(t,r.externalId);r.status=i.status,i.logs&&(r.logs=i.logs.slice(0,Ct.maxLogSize)),n?.(r)}if(r.status==="success"||r.status==="failure"||r.status==="cancelled")break;await new Promise(i=>setTimeout(i,Ct.pollIntervalMs))}return r.completedAt=Date.now(),r.duration=r.completedAt-r.startedAt,QB(),r}function Ehe(e){if(!e.diagnosis)return;let t=e.diagnosis.category+":"+e.diagnosis.rootCause.slice(0,80),n=Ym.get(t);n?(n.count++,n.lastSeen=Date.now()):Ym.set(t,{count:1,lastSeen:Date.now(),example:e.id,suggestedFix:e.diagnosis.suggestedFixes[0]}),$he()}async function Dhe(e,t){if(!e.diagnosis)return{applied:0,failed:0,output:["No diagnosis available"]};let n=[],r=0,s=0;for(let i of e.diagnosis.suggestedFixes)if(i.type!=="manual"){if(!Ct.enableAutoFix&&i.confidence<.85){n.push(`Skipped (confidence ${i.confidence}): ${i.description}`);continue}try{i.command?(zi(i.command,{cwd:t,stdio:"pipe",timeout:12e4}),n.push(`\u2713 Ran: ${i.command}`),r++):i.type==="code_change"&&i.patch&&n.push(`(Manual) ${i.description}`)}catch(o){n.push(`\u2717 Failed: ${i.description} \u2014 ${o.message}`),s++}}return{applied:r,failed:s,output:n}}function Fhe(e){if(Ct.enablePersistence){__();try{T_(whe,JSON.stringify({id:e.id,platform:e.platform,workflow:e.workflow,branch:e.branch,commit:e.commit,status:e.status,duration:e.duration,diagnosis:e.diagnosis?.rootCause,timestamp:Date.now()})+`
1456
- `,{flag:"a"})}catch{}}}function nN(){return Array.from(Hc.values()).sort((e,t)=>t.startedAt-e.startedAt)}function Lhe(e){return Hc.get(e)}function Ohe(){return Array.from(Ym.entries()).sort((e,t)=>(t[1]?.count||0)-(e[1]?.count||0))}function jhe(){let e=nN(),t=e.filter(l=>l.status==="success").length,n=e.filter(l=>l.status==="failure").length,r=e.filter(l=>l.duration),s=r.length>0?r.reduce((l,u)=>l+(u.duration||0),0)/r.length:0,i=e.length>0?t/e.length:0,o={};for(let l of e.filter(u=>u.diagnosis))o[l.diagnosis.category]=(o[l.diagnosis.category]||0)+1;let a={};for(let l of e)a[l.platform]=(a[l.platform]||0)+1;let c={};for(let l of e)c[l.branch]=(c[l.branch]||0)+1;return{totalBuilds:e.length,successCount:t,failureCount:n,averageDurationMs:s,successRate:i,topFailureCategories:o,byPlatform:a,byBranch:c}}function Bhe(){return{...Ct}}function Nhe(e){Ct={...Ct,...e}}function qhe(e){let t=[],n=e.status==="success"?"\u2713":e.status==="failure"?"\u2717":e.status==="running"?"\u27F3":e.status==="cancelled"?"\u2715":"\u25CB";if(t.push(`# ${n} Build ${e.id}`),t.push(`Platform: ${e.platform} | Workflow: ${e.workflow}`),t.push(`Branch: ${e.branch} | Commit: ${e.commit}`),t.push(`Status: ${e.status}${e.duration?` (${(e.duration/1e3).toFixed(1)}s)`:""}`),e.url&&t.push(`URL: ${e.url}`),e.retryAttempt>0&&t.push(`Retry attempt: ${e.retryAttempt}`),t.push(""),e.diagnosis){if(t.push("## \u{1F50D} Diagnosis"),t.push(`Root cause: ${e.diagnosis.rootCause}`),t.push(`Category: ${e.diagnosis.category}`),t.push(`Confidence: ${(e.diagnosis.confidence*100).toFixed(0)}%`),t.push(`Auto-fixable: ${e.diagnosis.autoFixable?"yes":"no"}`),t.push(""),e.diagnosis.suggestedFixes.length>0){t.push("## \u{1F4A1} Suggested Fixes");for(let r=0;r<e.diagnosis.suggestedFixes.length;r++){let s=e.diagnosis.suggestedFixes[r];t.push(`${r+1}. [${s.type}] ${s.description} (${(s.confidence*100).toFixed(0)}% confidence)`),s.command&&t.push(` $ ${s.command}`),s.filePath&&t.push(` File: ${s.filePath}`)}t.push("")}if(e.diagnosis.similarPastFailures.length>0){t.push("## Similar Past Failures");for(let r of e.diagnosis.similarPastFailures.slice(0,3))t.push(` - ${r}`);t.push("")}}return e.status==="failure"&&e.logs.length>0&&(t.push("## Log Tail"),t.push("```"),t.push(e.logs.slice(-2e3)),t.push("```")),t.join(`
1457
- `)}var She,Ct,Ov,x_,$_,whe,Hc,Ym,_he,P_=w(()=>{"use strict";She={enabled:!0,defaultBranch:"main",pollIntervalMs:1e4,streamLogs:!0,maxLogSize:10*1024*1024,buildTimeoutMs:3600*1e3,enableAutoRetry:!0,maxRetries:2,retryBackoffMs:3e4,enableAutoFix:!1,enableAIDiagnosis:!0,enablePersistence:!0,retentionCount:100},Ct={...She},Ov=ys(bhe(),".aiaca","ci-cd"),x_=ys(Ov,"builds.json"),$_=ys(Ov,"failure-patterns.json"),whe=ys(Ov,"history.jsonl"),Hc=new Map,Ym=new Map;khe();xhe();_he=[{type:"compile",severity:"high",regex:/([^\s(]+)\((\d+),(\d+)\):\s+error\s+TS(\d+):\s+(.+)/g},{type:"syntax",severity:"high",regex:/File\s+"([^"]+)",\s+line\s+(\d+)\s*[\s\S]*?(\w+Error:\s+.+)/g},{type:"lint",severity:"medium",regex:/(\S+\.\w+)\s*[\r\n]+\s+(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/gm},{type:"test",severity:"high",regex:/(✗|FAIL|FAILED|✘)\s+(.+?)$/gm},{type:"dependency",severity:"critical",regex:/Cannot find module\s+['"]([^'"]+)['"]/g},{type:"dependency",severity:"critical",regex:/ModuleNotFoundError:\s+No module named\s+['"]([^'"]+)['"]/g},{type:"runtime",severity:"high",regex:/(TypeError|ReferenceError|RangeError|SyntaxError):\s+(.+)/g},{type:"permission",severity:"medium",regex:/(EACCES|EPERM|Permission denied)/g},{type:"network",severity:"medium",regex:/(ECONNREFUSED|ENOTFOUND|getaddrinfo|TLS|certificate)/g},{type:"timeout",severity:"high",regex:/(timed out|timeout|exceeded.*timeout)/gi}]});var O_={};$(O_,{clearCache:()=>gye,commentOnIssue:()=>aN,configure:()=>lN,detectPlatform:()=>Bv,formatIssueAsContext:()=>uye,getActivityLog:()=>fye,getConfig:()=>mye,getIssue:()=>L_,getStats:()=>pye,postCompletionComment:()=>dye,renderTemplate:()=>cN,searchIssues:()=>lye,setAuth:()=>hye,updateIssueStatus:()=>cye});import{existsSync as jv,mkdirSync as Uhe,readFileSync as sN,writeFileSync as E_}from"fs";import{join as Pd}from"path";import{homedir as Hhe}from"os";import{execSync as zc}from"child_process";function D_(){Uhe(Nv,{recursive:!0})}function Vhe(){if(jv(I_))try{let e=JSON.parse(sN(I_,"utf-8")),t=Date.now();for(let n of e)t-n.cachedAt<Be.cacheTTLMs&&pr.set(n.key,{issue:n.issue,cachedAt:n.cachedAt})}catch{}}function iN(){if(Be.enablePersistence){D_();try{let e=Array.from(pr.entries()).map(([t,n])=>({key:t,...n}));E_(I_,JSON.stringify(e),"utf-8")}catch{}}}function Jhe(){if(jv(M_))try{Be={...Be,...JSON.parse(sN(M_,"utf-8"))}}catch{}}function Whe(){D_();try{E_(M_,JSON.stringify(Be,null,2),"utf-8")}catch{}}function oN(e,t,n){let r={action:e,issueId:t,timestamp:Date.now(),data:n};Rd.push(r),Rd.length>1e3&&Rd.shift(),D_();try{E_(Ghe,JSON.stringify(r)+`
1458
- `,{flag:"a"})}catch{}}function Bv(e){try{let t=zc("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim();if(t.includes("github.com"))return"github";if(t.includes("gitlab.com")||t.includes(Be.gitlabUrl||""))return"gitlab"}catch{}return jv(Pd(e,".linear.json"))?"linear":jv(Pd(e,".jira.json"))?"jira":process.env.LINEAR_TOKEN?"linear":process.env.JIRA_URL?"jira":"unknown"}function qv(e){try{let n=zc("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim().match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(n)return{owner:n[1],repo:n[2].replace(/\.git$/,"")}}catch{}return null}async function Uv(){try{return zc("gh --version",{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}async function Khe(e,t){let n=qv(e);if(!n)return null;let r=`github:${n.owner}/${n.repo}#${t}`;if(Be.cacheEnabled){let s=pr.get(r);if(s&&Date.now()-s.cachedAt<Be.cacheTTLMs)return s.issue}try{if(await Uv()){let c=zc(`gh issue view ${t} --json title,body,state,labels,assignees,author,createdAt,updatedAt,closedAt,url,comments`,{cwd:e,stdio:"pipe",encoding:"utf-8"}),l=JSON.parse(c),u={id:`github:${n.owner}/${n.repo}#${t}`,externalId:String(t),platform:"github",number:t,title:l.title,body:l.body||"",status:l.state==="OPEN"?"open":"closed",priority:F_(l.labels?.map(d=>d.name)||[]),author:l.author?.login||"unknown",assignees:(l.assignees||[]).map(d=>d.login),labels:(l.labels||[]).map(d=>d.name),url:l.url,createdAt:new Date(l.createdAt).getTime(),updatedAt:new Date(l.updatedAt).getTime(),closedAt:l.closedAt?new Date(l.closedAt).getTime():void 0,comments:(l.comments||[]).map(d=>({id:String(d.id),author:d.author?.login||"unknown",body:d.body||"",createdAt:new Date(d.createdAt).getTime(),isBot:d.author?.login?.includes("[bot]")||!1})),customFields:{}};return pr.set(r,{issue:u,cachedAt:Date.now()}),iN(),u}let s=Be.githubToken||process.env.GITHUB_TOKEN;if(!s)return null;let i=await fetch(`https://api.github.com/repos/${n.owner}/${n.repo}/issues/${t}`,{headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github.v3+json"}});if(!i.ok)return null;let o=await i.json(),a=Yhe(o,n);return pr.set(r,{issue:a,cachedAt:Date.now()}),a}catch{return null}}function Yhe(e,t){return{id:`github:${t.owner}/${t.repo}#${e.number}`,externalId:String(e.number),platform:"github",number:e.number,title:e.title,body:e.body||"",status:e.state==="open"?"open":"closed",priority:F_((e.labels||[]).map(n=>n.name)),author:e.user?.login||"unknown",assignees:(e.assignees||[]).map(n=>n.login),labels:(e.labels||[]).map(n=>n.name),url:e.html_url,createdAt:new Date(e.created_at).getTime(),updatedAt:new Date(e.updated_at).getTime(),closedAt:e.closed_at?new Date(e.closed_at).getTime():void 0,comments:[],customFields:{}}}async function Qhe(e,t,n){try{if(await Uv())return zc(`gh issue comment ${t} --body ${JSON.stringify(n)}`,{cwd:e,stdio:"pipe",timeout:3e4}),!0;let r=qv(e),s=Be.githubToken||process.env.GITHUB_TOKEN;return!r||!s?!1:(await fetch(`https://api.github.com/repos/${r.owner}/${r.repo}/issues/${t}/comments`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({body:n})})).ok}catch{return!1}}async function Zhe(e,t,n){let r=n==="done"||n==="closed"||n==="cancelled"?"closed":"open";try{if(await Uv())return zc(`gh issue ${r==="closed"?"close":"reopen"} ${t}`,{cwd:e,stdio:"pipe"}),!0;let s=qv(e),i=Be.githubToken||process.env.GITHUB_TOKEN;return!s||!i?!1:(await fetch(`https://api.github.com/repos/${s.owner}/${s.repo}/issues/${t}`,{method:"PATCH",headers:{Authorization:`Bearer ${i}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({state:r})})).ok}catch{return!1}}async function Xhe(e,t){let n=qv(e);if(!n)return[];try{if(await Uv()){let r=t.status?.includes("open")&&!t.status.includes("closed")?"--state open":"--state all",s=`--limit ${t.limit||30}`,i=t.labels?.map(l=>`--label ${JSON.stringify(l)}`).join(" ")||"",o=t.assignee?`--assignee ${t.assignee}`:"",a=zc(`gh issue list --search ${JSON.stringify(t.query)} ${r} ${s} ${i} ${o} --json number,title,state,labels,assignees,author,createdAt,updatedAt,url`,{cwd:e,stdio:"pipe",encoding:"utf-8"});return JSON.parse(a).map(l=>({id:`github:${n.owner}/${n.repo}#${l.number}`,externalId:String(l.number),platform:"github",number:l.number,title:l.title,body:"",status:l.state==="OPEN"?"open":"closed",priority:F_(l.labels?.map(u=>u.name)||[]),author:l.author?.login||"unknown",assignees:(l.assignees||[]).map(u=>u.login),labels:(l.labels||[]).map(u=>u.name),url:l.url,createdAt:new Date(l.createdAt).getTime(),updatedAt:new Date(l.updatedAt).getTime(),comments:[],customFields:{}}))}return[]}catch{return[]}}async function eye(e){let t=Be.linearToken||process.env.LINEAR_TOKEN;if(!t)return null;let n=`linear:${e}`;if(Be.cacheEnabled){let s=pr.get(n);if(s&&Date.now()-s.cachedAt<Be.cacheTTLMs)return s.issue}let r=`
1465
+ }`;try{let i=(await n.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You diagnose CI/CD build failures. Output strict JSON only.",[],void 0)).content?.match(/\{[\s\S]*\}/)?.[0];if(!i)throw new Error("No JSON in response");let o=JSON.parse(i);return{rootCause:o.rootCause||"Unknown",category:o.category||"unknown",confidence:o.confidence||.5,suggestedFixes:o.suggestedFixes||[],similarPastFailures:[],autoFixable:!!o.autoFixable}}catch{return{rootCause:"AI diagnosis failed",category:"unknown",confidence:.1,suggestedFixes:[],similarPastFailures:[],autoFixable:!1}}}function KB(e){if(!e.diagnosis?.rootCause)return[];let t=new Set(e.diagnosis.rootCause.toLowerCase().split(/\s+/).filter(r=>r.length>3)),n=[];for(let[r,s]of Hc){if(r===e.id||!s.diagnosis||s.status!=="failure")continue;let i=new Set(s.diagnosis.rootCause.toLowerCase().split(/\s+/)),o=[...t].filter(a=>i.has(a)).length;o>=2&&n.push({id:r,score:o})}return n.sort((r,s)=>s.score-r.score).slice(0,5).map(r=>r.id)}async function tN(e,t){if(!Ct.enabled)throw new Error("CI/CD service disabled");let n=ZB(e.projectPath),r=She("sha256").update(Date.now().toString()+Math.random()).digest("hex").slice(0,12),s=e.branch||Ct.defaultBranch,i=e.workflow||Ct.defaultWorkflow||"ci.yml",o={id:r,externalId:"",platform:n,workflow:i,branch:s,commit:Mhe(e.projectPath),triggeredBy:e.triggeredBy||"manual",status:"pending",startedAt:Date.now(),stages:[],logs:"",metadata:{},retryAttempt:0};Hc.set(r,o);try{if(n==="github_actions"){let a=await Ahe(e.projectPath,i,s,e.inputs);a.success?(o.externalId=a.runId||"",o.status="queued",o.url=`https://github.com/${C_(e.projectPath)?.owner}/${C_(e.projectPath)?.repo}/actions/runs/${a.runId}`):e.fallbackCommand?await WB(e.projectPath,e.fallbackCommand,o):(o.status="failure",o.logs=`Failed to trigger: ${a.error}`)}else e.fallbackCommand?await WB(e.projectPath,e.fallbackCommand,o):(o.status="failure",o.logs=`Platform ${n} not yet supported. Provide fallbackCommand.`)}catch(a){o.status="failure",o.logs=a.message}if(o.status==="failure"&&Ct.enableAIDiagnosis&&(o.diagnosis=await eN(o,t),Dhe(o)),QB(),Lhe(o),o.status==="failure"&&Ct.enableAutoRetry&&o.retryAttempt<Ct.maxRetries&&(o.diagnosis?.category==="infrastructure"||o.diagnosis?.category==="network")){let a=Ct.retryBackoffMs*Math.pow(2,o.retryAttempt);await new Promise(l=>setTimeout(l,a));let c=await tN({...e,triggeredBy:"auto-retry"},t);c.parentBuildId=o.id,c.retryAttempt=o.retryAttempt+1}return o}function Mhe(e){try{return zi("git rev-parse HEAD",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim().slice(0,12)}catch{return"unknown"}}async function Ehe(e,t,n){let r=Hc.get(e);if(!r)throw new Error(`Build not found: ${e}`);if(!r.externalId)return r;let s=Date.now();for(;r.status==="pending"||r.status==="queued"||r.status==="running";){if(Date.now()-s>Ct.buildTimeoutMs){r.status="timeout";break}if(r.platform==="github_actions"){let i=await The(t,r.externalId);r.status=i.status,i.logs&&(r.logs=i.logs.slice(0,Ct.maxLogSize)),n?.(r)}if(r.status==="success"||r.status==="failure"||r.status==="cancelled")break;await new Promise(i=>setTimeout(i,Ct.pollIntervalMs))}return r.completedAt=Date.now(),r.duration=r.completedAt-r.startedAt,QB(),r}function Dhe(e){if(!e.diagnosis)return;let t=e.diagnosis.category+":"+e.diagnosis.rootCause.slice(0,80),n=Ym.get(t);n?(n.count++,n.lastSeen=Date.now()):Ym.set(t,{count:1,lastSeen:Date.now(),example:e.id,suggestedFix:e.diagnosis.suggestedFixes[0]}),Che()}async function Fhe(e,t){if(!e.diagnosis)return{applied:0,failed:0,output:["No diagnosis available"]};let n=[],r=0,s=0;for(let i of e.diagnosis.suggestedFixes)if(i.type!=="manual"){if(!Ct.enableAutoFix&&i.confidence<.85){n.push(`Skipped (confidence ${i.confidence}): ${i.description}`);continue}try{i.command?(zi(i.command,{cwd:t,stdio:"pipe",timeout:12e4}),n.push(`\u2713 Ran: ${i.command}`),r++):i.type==="code_change"&&i.patch&&n.push(`(Manual) ${i.description}`)}catch(o){n.push(`\u2717 Failed: ${i.description} \u2014 ${o.message}`),s++}}return{applied:r,failed:s,output:n}}function Lhe(e){if(Ct.enablePersistence){__();try{T_(khe,JSON.stringify({id:e.id,platform:e.platform,workflow:e.workflow,branch:e.branch,commit:e.commit,status:e.status,duration:e.duration,diagnosis:e.diagnosis?.rootCause,timestamp:Date.now()})+`
1466
+ `,{flag:"a"})}catch{}}}function nN(){return Array.from(Hc.values()).sort((e,t)=>t.startedAt-e.startedAt)}function Ohe(e){return Hc.get(e)}function jhe(){return Array.from(Ym.entries()).sort((e,t)=>(t[1]?.count||0)-(e[1]?.count||0))}function Bhe(){let e=nN(),t=e.filter(l=>l.status==="success").length,n=e.filter(l=>l.status==="failure").length,r=e.filter(l=>l.duration),s=r.length>0?r.reduce((l,u)=>l+(u.duration||0),0)/r.length:0,i=e.length>0?t/e.length:0,o={};for(let l of e.filter(u=>u.diagnosis))o[l.diagnosis.category]=(o[l.diagnosis.category]||0)+1;let a={};for(let l of e)a[l.platform]=(a[l.platform]||0)+1;let c={};for(let l of e)c[l.branch]=(c[l.branch]||0)+1;return{totalBuilds:e.length,successCount:t,failureCount:n,averageDurationMs:s,successRate:i,topFailureCategories:o,byPlatform:a,byBranch:c}}function Nhe(){return{...Ct}}function qhe(e){Ct={...Ct,...e}}function Uhe(e){let t=[],n=e.status==="success"?"\u2713":e.status==="failure"?"\u2717":e.status==="running"?"\u27F3":e.status==="cancelled"?"\u2715":"\u25CB";if(t.push(`# ${n} Build ${e.id}`),t.push(`Platform: ${e.platform} | Workflow: ${e.workflow}`),t.push(`Branch: ${e.branch} | Commit: ${e.commit}`),t.push(`Status: ${e.status}${e.duration?` (${(e.duration/1e3).toFixed(1)}s)`:""}`),e.url&&t.push(`URL: ${e.url}`),e.retryAttempt>0&&t.push(`Retry attempt: ${e.retryAttempt}`),t.push(""),e.diagnosis){if(t.push("## \u{1F50D} Diagnosis"),t.push(`Root cause: ${e.diagnosis.rootCause}`),t.push(`Category: ${e.diagnosis.category}`),t.push(`Confidence: ${(e.diagnosis.confidence*100).toFixed(0)}%`),t.push(`Auto-fixable: ${e.diagnosis.autoFixable?"yes":"no"}`),t.push(""),e.diagnosis.suggestedFixes.length>0){t.push("## \u{1F4A1} Suggested Fixes");for(let r=0;r<e.diagnosis.suggestedFixes.length;r++){let s=e.diagnosis.suggestedFixes[r];t.push(`${r+1}. [${s.type}] ${s.description} (${(s.confidence*100).toFixed(0)}% confidence)`),s.command&&t.push(` $ ${s.command}`),s.filePath&&t.push(` File: ${s.filePath}`)}t.push("")}if(e.diagnosis.similarPastFailures.length>0){t.push("## Similar Past Failures");for(let r of e.diagnosis.similarPastFailures.slice(0,3))t.push(` - ${r}`);t.push("")}}return e.status==="failure"&&e.logs.length>0&&(t.push("## Log Tail"),t.push("```"),t.push(e.logs.slice(-2e3)),t.push("```")),t.join(`
1467
+ `)}var whe,Ct,Ov,x_,$_,khe,Hc,Ym,Rhe,P_=w(()=>{"use strict";whe={enabled:!0,defaultBranch:"main",pollIntervalMs:1e4,streamLogs:!0,maxLogSize:10*1024*1024,buildTimeoutMs:3600*1e3,enableAutoRetry:!0,maxRetries:2,retryBackoffMs:3e4,enableAutoFix:!1,enableAIDiagnosis:!0,enablePersistence:!0,retentionCount:100},Ct={...whe},Ov=ys(vhe(),".aiaca","ci-cd"),x_=ys(Ov,"builds.json"),$_=ys(Ov,"failure-patterns.json"),khe=ys(Ov,"history.jsonl"),Hc=new Map,Ym=new Map;xhe();$he();Rhe=[{type:"compile",severity:"high",regex:/([^\s(]+)\((\d+),(\d+)\):\s+error\s+TS(\d+):\s+(.+)/g},{type:"syntax",severity:"high",regex:/File\s+"([^"]+)",\s+line\s+(\d+)\s*[\s\S]*?(\w+Error:\s+.+)/g},{type:"lint",severity:"medium",regex:/(\S+\.\w+)\s*[\r\n]+\s+(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/gm},{type:"test",severity:"high",regex:/(✗|FAIL|FAILED|✘)\s+(.+?)$/gm},{type:"dependency",severity:"critical",regex:/Cannot find module\s+['"]([^'"]+)['"]/g},{type:"dependency",severity:"critical",regex:/ModuleNotFoundError:\s+No module named\s+['"]([^'"]+)['"]/g},{type:"runtime",severity:"high",regex:/(TypeError|ReferenceError|RangeError|SyntaxError):\s+(.+)/g},{type:"permission",severity:"medium",regex:/(EACCES|EPERM|Permission denied)/g},{type:"network",severity:"medium",regex:/(ECONNREFUSED|ENOTFOUND|getaddrinfo|TLS|certificate)/g},{type:"timeout",severity:"high",regex:/(timed out|timeout|exceeded.*timeout)/gi}]});var O_={};$(O_,{clearCache:()=>hye,commentOnIssue:()=>aN,configure:()=>lN,detectPlatform:()=>Bv,formatIssueAsContext:()=>dye,getActivityLog:()=>pye,getConfig:()=>gye,getIssue:()=>L_,getStats:()=>mye,postCompletionComment:()=>fye,renderTemplate:()=>cN,searchIssues:()=>uye,setAuth:()=>yye,updateIssueStatus:()=>lye});import{existsSync as jv,mkdirSync as Hhe,readFileSync as sN,writeFileSync as E_}from"fs";import{join as Pd}from"path";import{homedir as zhe}from"os";import{execSync as zc}from"child_process";function D_(){Hhe(Nv,{recursive:!0})}function Jhe(){if(jv(I_))try{let e=JSON.parse(sN(I_,"utf-8")),t=Date.now();for(let n of e)t-n.cachedAt<Be.cacheTTLMs&&pr.set(n.key,{issue:n.issue,cachedAt:n.cachedAt})}catch{}}function iN(){if(Be.enablePersistence){D_();try{let e=Array.from(pr.entries()).map(([t,n])=>({key:t,...n}));E_(I_,JSON.stringify(e),"utf-8")}catch{}}}function Whe(){if(jv(M_))try{Be={...Be,...JSON.parse(sN(M_,"utf-8"))}}catch{}}function Khe(){D_();try{E_(M_,JSON.stringify(Be,null,2),"utf-8")}catch{}}function oN(e,t,n){let r={action:e,issueId:t,timestamp:Date.now(),data:n};Rd.push(r),Rd.length>1e3&&Rd.shift(),D_();try{E_(Vhe,JSON.stringify(r)+`
1468
+ `,{flag:"a"})}catch{}}function Bv(e){try{let t=zc("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim();if(t.includes("github.com"))return"github";if(t.includes("gitlab.com")||t.includes(Be.gitlabUrl||""))return"gitlab"}catch{}return jv(Pd(e,".linear.json"))?"linear":jv(Pd(e,".jira.json"))?"jira":process.env.LINEAR_TOKEN?"linear":process.env.JIRA_URL?"jira":"unknown"}function qv(e){try{let n=zc("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim().match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(n)return{owner:n[1],repo:n[2].replace(/\.git$/,"")}}catch{}return null}async function Uv(){try{return zc("gh --version",{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}async function Yhe(e,t){let n=qv(e);if(!n)return null;let r=`github:${n.owner}/${n.repo}#${t}`;if(Be.cacheEnabled){let s=pr.get(r);if(s&&Date.now()-s.cachedAt<Be.cacheTTLMs)return s.issue}try{if(await Uv()){let c=zc(`gh issue view ${t} --json title,body,state,labels,assignees,author,createdAt,updatedAt,closedAt,url,comments`,{cwd:e,stdio:"pipe",encoding:"utf-8"}),l=JSON.parse(c),u={id:`github:${n.owner}/${n.repo}#${t}`,externalId:String(t),platform:"github",number:t,title:l.title,body:l.body||"",status:l.state==="OPEN"?"open":"closed",priority:F_(l.labels?.map(d=>d.name)||[]),author:l.author?.login||"unknown",assignees:(l.assignees||[]).map(d=>d.login),labels:(l.labels||[]).map(d=>d.name),url:l.url,createdAt:new Date(l.createdAt).getTime(),updatedAt:new Date(l.updatedAt).getTime(),closedAt:l.closedAt?new Date(l.closedAt).getTime():void 0,comments:(l.comments||[]).map(d=>({id:String(d.id),author:d.author?.login||"unknown",body:d.body||"",createdAt:new Date(d.createdAt).getTime(),isBot:d.author?.login?.includes("[bot]")||!1})),customFields:{}};return pr.set(r,{issue:u,cachedAt:Date.now()}),iN(),u}let s=Be.githubToken||process.env.GITHUB_TOKEN;if(!s)return null;let i=await fetch(`https://api.github.com/repos/${n.owner}/${n.repo}/issues/${t}`,{headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github.v3+json"}});if(!i.ok)return null;let o=await i.json(),a=Qhe(o,n);return pr.set(r,{issue:a,cachedAt:Date.now()}),a}catch{return null}}function Qhe(e,t){return{id:`github:${t.owner}/${t.repo}#${e.number}`,externalId:String(e.number),platform:"github",number:e.number,title:e.title,body:e.body||"",status:e.state==="open"?"open":"closed",priority:F_((e.labels||[]).map(n=>n.name)),author:e.user?.login||"unknown",assignees:(e.assignees||[]).map(n=>n.login),labels:(e.labels||[]).map(n=>n.name),url:e.html_url,createdAt:new Date(e.created_at).getTime(),updatedAt:new Date(e.updated_at).getTime(),closedAt:e.closed_at?new Date(e.closed_at).getTime():void 0,comments:[],customFields:{}}}async function Zhe(e,t,n){try{if(await Uv())return zc(`gh issue comment ${t} --body ${JSON.stringify(n)}`,{cwd:e,stdio:"pipe",timeout:3e4}),!0;let r=qv(e),s=Be.githubToken||process.env.GITHUB_TOKEN;return!r||!s?!1:(await fetch(`https://api.github.com/repos/${r.owner}/${r.repo}/issues/${t}/comments`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({body:n})})).ok}catch{return!1}}async function Xhe(e,t,n){let r=n==="done"||n==="closed"||n==="cancelled"?"closed":"open";try{if(await Uv())return zc(`gh issue ${r==="closed"?"close":"reopen"} ${t}`,{cwd:e,stdio:"pipe"}),!0;let s=qv(e),i=Be.githubToken||process.env.GITHUB_TOKEN;return!s||!i?!1:(await fetch(`https://api.github.com/repos/${s.owner}/${s.repo}/issues/${t}`,{method:"PATCH",headers:{Authorization:`Bearer ${i}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({state:r})})).ok}catch{return!1}}async function eye(e,t){let n=qv(e);if(!n)return[];try{if(await Uv()){let r=t.status?.includes("open")&&!t.status.includes("closed")?"--state open":"--state all",s=`--limit ${t.limit||30}`,i=t.labels?.map(l=>`--label ${JSON.stringify(l)}`).join(" ")||"",o=t.assignee?`--assignee ${t.assignee}`:"",a=zc(`gh issue list --search ${JSON.stringify(t.query)} ${r} ${s} ${i} ${o} --json number,title,state,labels,assignees,author,createdAt,updatedAt,url`,{cwd:e,stdio:"pipe",encoding:"utf-8"});return JSON.parse(a).map(l=>({id:`github:${n.owner}/${n.repo}#${l.number}`,externalId:String(l.number),platform:"github",number:l.number,title:l.title,body:"",status:l.state==="OPEN"?"open":"closed",priority:F_(l.labels?.map(u=>u.name)||[]),author:l.author?.login||"unknown",assignees:(l.assignees||[]).map(u=>u.login),labels:(l.labels||[]).map(u=>u.name),url:l.url,createdAt:new Date(l.createdAt).getTime(),updatedAt:new Date(l.updatedAt).getTime(),comments:[],customFields:{}}))}return[]}catch{return[]}}async function tye(e){let t=Be.linearToken||process.env.LINEAR_TOKEN;if(!t)return null;let n=`linear:${e}`;if(Be.cacheEnabled){let s=pr.get(n);if(s&&Date.now()-s.cachedAt<Be.cacheTTLMs)return s.issue}let r=`
1459
1469
  query($id: String!) {
1460
1470
  issue(id: $id) {
1461
1471
  id title description state { name } priority priorityLabel
@@ -1464,12 +1474,12 @@ Output strict JSON only:
1464
1474
  url createdAt updatedAt completedAt
1465
1475
  comments { nodes { id user { name } body createdAt } }
1466
1476
  }
1467
- }`;try{let s=await fetch("https://api.linear.app/graphql",{method:"POST",headers:{Authorization:t,"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:{id:e}})});if(!s.ok)return null;let o=(await s.json()).data?.issue;if(!o)return null;let a={id:`linear:${o.id}`,externalId:o.id,platform:"linear",title:o.title,body:o.description||"",status:tye(o.state?.name),priority:nye(o.priority),author:o.creator?.name||"unknown",assignees:o.assignee?[o.assignee.name]:[],labels:(o.labels?.nodes||[]).map(c=>c.name),url:o.url,createdAt:new Date(o.createdAt).getTime(),updatedAt:new Date(o.updatedAt).getTime(),closedAt:o.completedAt?new Date(o.completedAt).getTime():void 0,comments:(o.comments?.nodes||[]).map(c=>({id:c.id,author:c.user?.name||"unknown",body:c.body,createdAt:new Date(c.createdAt).getTime(),isBot:!1})),customFields:{priorityLabel:o.priorityLabel}};return pr.set(n,{issue:a,cachedAt:Date.now()}),a}catch{return null}}function tye(e){if(!e)return"open";let t=e.toLowerCase();return t.includes("done")||t.includes("completed")?"done":t.includes("progress")||t.includes("working")?"in_progress":t.includes("review")?"in_review":t.includes("block")?"blocked":t.includes("cancel")?"cancelled":"open"}function nye(e){return e===1?"critical":e===2?"high":e===3?"medium":e===4?"low":"none"}async function rye(e,t){let n=Be.linearToken||process.env.LINEAR_TOKEN;if(!n)return!1;let r=`
1477
+ }`;try{let s=await fetch("https://api.linear.app/graphql",{method:"POST",headers:{Authorization:t,"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:{id:e}})});if(!s.ok)return null;let o=(await s.json()).data?.issue;if(!o)return null;let a={id:`linear:${o.id}`,externalId:o.id,platform:"linear",title:o.title,body:o.description||"",status:nye(o.state?.name),priority:rye(o.priority),author:o.creator?.name||"unknown",assignees:o.assignee?[o.assignee.name]:[],labels:(o.labels?.nodes||[]).map(c=>c.name),url:o.url,createdAt:new Date(o.createdAt).getTime(),updatedAt:new Date(o.updatedAt).getTime(),closedAt:o.completedAt?new Date(o.completedAt).getTime():void 0,comments:(o.comments?.nodes||[]).map(c=>({id:c.id,author:c.user?.name||"unknown",body:c.body,createdAt:new Date(c.createdAt).getTime(),isBot:!1})),customFields:{priorityLabel:o.priorityLabel}};return pr.set(n,{issue:a,cachedAt:Date.now()}),a}catch{return null}}function nye(e){if(!e)return"open";let t=e.toLowerCase();return t.includes("done")||t.includes("completed")?"done":t.includes("progress")||t.includes("working")?"in_progress":t.includes("review")?"in_review":t.includes("block")?"blocked":t.includes("cancel")?"cancelled":"open"}function rye(e){return e===1?"critical":e===2?"high":e===3?"medium":e===4?"low":"none"}async function sye(e,t){let n=Be.linearToken||process.env.LINEAR_TOKEN;if(!n)return!1;let r=`
1468
1478
  mutation($issueId: String!, $body: String!) {
1469
1479
  commentCreate(input: { issueId: $issueId, body: $body }) { success }
1470
- }`;try{return!!(await(await fetch("https://api.linear.app/graphql",{method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:{issueId:e,body:t}})})).json()).data?.commentCreate?.success}catch{return!1}}async function sye(e){let t=Be.jiraUrl||process.env.JIRA_URL,n=Be.jiraEmail||process.env.JIRA_EMAIL,r=Be.jiraToken||process.env.JIRA_TOKEN;if(!t||!n||!r)return null;let s=`jira:${e}`;if(Be.cacheEnabled){let i=pr.get(s);if(i&&Date.now()-i.cachedAt<Be.cacheTTLMs)return i.issue}try{let i=Buffer.from(`${n}:${r}`).toString("base64"),o=await fetch(`${t}/rest/api/3/issue/${e}`,{headers:{Authorization:`Basic ${i}`,Accept:"application/json"}});if(!o.ok)return null;let a=await o.json(),c=a.fields||{},l={id:`jira:${a.key}`,externalId:a.key,platform:"jira",title:c.summary||"",body:rN(c.description)||"",status:iye(c.status?.name),priority:oye(c.priority?.name),author:c.creator?.displayName||"unknown",assignees:c.assignee?[c.assignee.displayName]:[],labels:c.labels||[],url:`${t}/browse/${a.key}`,createdAt:new Date(c.created).getTime(),updatedAt:new Date(c.updated).getTime(),closedAt:c.resolutiondate?new Date(c.resolutiondate).getTime():void 0,comments:(c.comment?.comments||[]).map(u=>({id:u.id,author:u.author?.displayName||"unknown",body:rN(u.body),createdAt:new Date(u.created).getTime(),isBot:!1})),customFields:{issueType:c.issuetype?.name,project:c.project?.key}};return pr.set(s,{issue:l,cachedAt:Date.now()}),l}catch{return null}}function rN(e){if(typeof e=="string")return e;if(!e||!e.content)return"";let t="";function n(r){if(typeof r=="string"&&(t+=r),r.text&&(t+=r.text),r.content)for(let s of r.content)n(s);r.type==="paragraph"&&(t+=`
1471
- `)}return n(e),t.trim()}function iye(e){if(!e)return"open";let t=e.toLowerCase();return t.includes("done")||t.includes("closed")||t.includes("resolved")?"closed":t.includes("progress")||t.includes("development")?"in_progress":t.includes("review")?"in_review":t.includes("block")?"blocked":"open"}function oye(e){if(!e)return"none";let t=e.toLowerCase();return t.includes("highest")||t.includes("critical")||t.includes("blocker")?"critical":t.includes("high")?"high":t.includes("medium")?"medium":t.includes("low")?"low":"none"}async function aye(e,t){let n=Be.jiraUrl||process.env.JIRA_URL,r=Be.jiraEmail||process.env.JIRA_EMAIL,s=Be.jiraToken||process.env.JIRA_TOKEN;if(!n||!r||!s)return!1;try{let i=Buffer.from(`${r}:${s}`).toString("base64");return(await fetch(`${n}/rest/api/3/issue/${e}/comment`,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:t}]}]}})})).ok}catch{return!1}}function F_(e){for(let t of e){let n=t.toLowerCase();if(n.includes("critical")||n.includes("p0")||n.includes("blocker"))return"critical";if(n.includes("high")||n.includes("p1"))return"high";if(n.includes("medium")||n.includes("p2"))return"medium";if(n.includes("low")||n.includes("p3")||n.includes("p4"))return"low"}return"none"}async function L_(e,t){let n=null,r="";if(e.includes(":")){let[s,...i]=e.split(":");n=s,r=i.join(":").replace("#","")}else e.startsWith("#")?(n=t?Bv(t):"github",r=e.slice(1)):/^\d+$/.test(e)?(n=t?Bv(t):"github",r=e):/^[A-Z]+-\d+$/.test(e)?(n="jira",r=e):(n="linear",r=e);if(n==="github"){let s=parseInt(r,10);return!isFinite(s)||!t?null:Khe(t,s)}return n==="linear"?eye(r):n==="jira"?sye(r):null}async function aN(e,t,n){let r=await L_(e,n);if(!r)return!1;let s=!1;return r.platform==="github"&&r.number&&n?s=await Qhe(n,r.number,t):r.platform==="linear"?s=await rye(r.externalId,t):r.platform==="jira"&&(s=await aye(r.externalId,t)),s&&(oN("comment",r.id,{body:t.slice(0,200)}),pr.delete(`${r.platform}:${r.externalId}`)),s}async function cye(e,t,n){let r=await L_(e,n);if(!r)return!1;let s=!1;return r.platform==="github"&&r.number&&n&&(s=await Zhe(n,r.number,t)),s&&(oN("status_update",r.id,{from:r.status,to:t}),pr.delete(`${r.platform}:${r.externalId}`)),s}async function lye(e,t){return(e.platform||(t?Bv(t):null))==="github"&&t?Xhe(t,e):[]}function uye(e){let t=[];if(t.push(`<issue platform="${e.platform}" id="${e.externalId}">`),t.push(`Title: ${e.title}`),t.push(`Status: ${e.status} | Priority: ${e.priority}`),t.push(`Author: ${e.author}`),e.assignees.length>0&&t.push(`Assignees: ${e.assignees.join(", ")}`),e.labels.length>0&&t.push(`Labels: ${e.labels.join(", ")}`),t.push(`URL: ${e.url}`),t.push(""),t.push("## Description"),t.push(e.body||"(no description)"),e.comments.length>0){t.push(""),t.push(`## Recent Comments (${e.comments.length})`);for(let n of e.comments.slice(-5)){let r=new Date(n.createdAt).toISOString().slice(0,10);t.push(`### ${n.author} on ${r}${n.isBot?" [bot]":""}`),t.push(n.body.slice(0,1e3)),t.push("")}}return t.push("</issue>"),t.join(`
1472
- `)}function cN(e,t){let n=e;for(let[r,s]of Object.entries(t))n=n.replace(new RegExp(`{${r}}`,"g"),String(s));return n}async function dye(e,t,n){let r=cN(Be.commentTemplate,{summary:t.description,files_count:t.filesCount,test_status:t.testStatus,duration:t.duration});return aN(e,r,n)}function fye(e=100){return Rd.slice(-e).reverse()}function pye(){let e={},t=0,n=0;for(let r of Rd)r.action==="comment"&&t++,r.action==="status_update"&&n++;for(let[r]of pr){let s=r.split(":")[0];e[s]=(e[s]||0)+1}return{totalIssuesFetched:Rd.filter(r=>r.action==="fetch").length,totalCommentsPosted:t,totalStatusUpdates:n,cacheSize:pr.size,byPlatform:e}}function mye(){return{...Be}}function lN(e){Be={...Be,...e},Whe()}function gye(){pr.clear(),iN()}function hye(e){lN(e)}var zhe,Be,Nv,I_,Ghe,M_,pr,Rd,j_=w(()=>{"use strict";zhe={enabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3,autoLinkCommits:!0,autoCommentOnComplete:!1,defaultStatus:"in_progress",commentTemplate:`## Update from AIACA
1480
+ }`;try{return!!(await(await fetch("https://api.linear.app/graphql",{method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:{issueId:e,body:t}})})).json()).data?.commentCreate?.success}catch{return!1}}async function iye(e){let t=Be.jiraUrl||process.env.JIRA_URL,n=Be.jiraEmail||process.env.JIRA_EMAIL,r=Be.jiraToken||process.env.JIRA_TOKEN;if(!t||!n||!r)return null;let s=`jira:${e}`;if(Be.cacheEnabled){let i=pr.get(s);if(i&&Date.now()-i.cachedAt<Be.cacheTTLMs)return i.issue}try{let i=Buffer.from(`${n}:${r}`).toString("base64"),o=await fetch(`${t}/rest/api/3/issue/${e}`,{headers:{Authorization:`Basic ${i}`,Accept:"application/json"}});if(!o.ok)return null;let a=await o.json(),c=a.fields||{},l={id:`jira:${a.key}`,externalId:a.key,platform:"jira",title:c.summary||"",body:rN(c.description)||"",status:oye(c.status?.name),priority:aye(c.priority?.name),author:c.creator?.displayName||"unknown",assignees:c.assignee?[c.assignee.displayName]:[],labels:c.labels||[],url:`${t}/browse/${a.key}`,createdAt:new Date(c.created).getTime(),updatedAt:new Date(c.updated).getTime(),closedAt:c.resolutiondate?new Date(c.resolutiondate).getTime():void 0,comments:(c.comment?.comments||[]).map(u=>({id:u.id,author:u.author?.displayName||"unknown",body:rN(u.body),createdAt:new Date(u.created).getTime(),isBot:!1})),customFields:{issueType:c.issuetype?.name,project:c.project?.key}};return pr.set(s,{issue:l,cachedAt:Date.now()}),l}catch{return null}}function rN(e){if(typeof e=="string")return e;if(!e||!e.content)return"";let t="";function n(r){if(typeof r=="string"&&(t+=r),r.text&&(t+=r.text),r.content)for(let s of r.content)n(s);r.type==="paragraph"&&(t+=`
1481
+ `)}return n(e),t.trim()}function oye(e){if(!e)return"open";let t=e.toLowerCase();return t.includes("done")||t.includes("closed")||t.includes("resolved")?"closed":t.includes("progress")||t.includes("development")?"in_progress":t.includes("review")?"in_review":t.includes("block")?"blocked":"open"}function aye(e){if(!e)return"none";let t=e.toLowerCase();return t.includes("highest")||t.includes("critical")||t.includes("blocker")?"critical":t.includes("high")?"high":t.includes("medium")?"medium":t.includes("low")?"low":"none"}async function cye(e,t){let n=Be.jiraUrl||process.env.JIRA_URL,r=Be.jiraEmail||process.env.JIRA_EMAIL,s=Be.jiraToken||process.env.JIRA_TOKEN;if(!n||!r||!s)return!1;try{let i=Buffer.from(`${r}:${s}`).toString("base64");return(await fetch(`${n}/rest/api/3/issue/${e}/comment`,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:t}]}]}})})).ok}catch{return!1}}function F_(e){for(let t of e){let n=t.toLowerCase();if(n.includes("critical")||n.includes("p0")||n.includes("blocker"))return"critical";if(n.includes("high")||n.includes("p1"))return"high";if(n.includes("medium")||n.includes("p2"))return"medium";if(n.includes("low")||n.includes("p3")||n.includes("p4"))return"low"}return"none"}async function L_(e,t){let n=null,r="";if(e.includes(":")){let[s,...i]=e.split(":");n=s,r=i.join(":").replace("#","")}else e.startsWith("#")?(n=t?Bv(t):"github",r=e.slice(1)):/^\d+$/.test(e)?(n=t?Bv(t):"github",r=e):/^[A-Z]+-\d+$/.test(e)?(n="jira",r=e):(n="linear",r=e);if(n==="github"){let s=parseInt(r,10);return!isFinite(s)||!t?null:Yhe(t,s)}return n==="linear"?tye(r):n==="jira"?iye(r):null}async function aN(e,t,n){let r=await L_(e,n);if(!r)return!1;let s=!1;return r.platform==="github"&&r.number&&n?s=await Zhe(n,r.number,t):r.platform==="linear"?s=await sye(r.externalId,t):r.platform==="jira"&&(s=await cye(r.externalId,t)),s&&(oN("comment",r.id,{body:t.slice(0,200)}),pr.delete(`${r.platform}:${r.externalId}`)),s}async function lye(e,t,n){let r=await L_(e,n);if(!r)return!1;let s=!1;return r.platform==="github"&&r.number&&n&&(s=await Xhe(n,r.number,t)),s&&(oN("status_update",r.id,{from:r.status,to:t}),pr.delete(`${r.platform}:${r.externalId}`)),s}async function uye(e,t){return(e.platform||(t?Bv(t):null))==="github"&&t?eye(t,e):[]}function dye(e){let t=[];if(t.push(`<issue platform="${e.platform}" id="${e.externalId}">`),t.push(`Title: ${e.title}`),t.push(`Status: ${e.status} | Priority: ${e.priority}`),t.push(`Author: ${e.author}`),e.assignees.length>0&&t.push(`Assignees: ${e.assignees.join(", ")}`),e.labels.length>0&&t.push(`Labels: ${e.labels.join(", ")}`),t.push(`URL: ${e.url}`),t.push(""),t.push("## Description"),t.push(e.body||"(no description)"),e.comments.length>0){t.push(""),t.push(`## Recent Comments (${e.comments.length})`);for(let n of e.comments.slice(-5)){let r=new Date(n.createdAt).toISOString().slice(0,10);t.push(`### ${n.author} on ${r}${n.isBot?" [bot]":""}`),t.push(n.body.slice(0,1e3)),t.push("")}}return t.push("</issue>"),t.join(`
1482
+ `)}function cN(e,t){let n=e;for(let[r,s]of Object.entries(t))n=n.replace(new RegExp(`{${r}}`,"g"),String(s));return n}async function fye(e,t,n){let r=cN(Be.commentTemplate,{summary:t.description,files_count:t.filesCount,test_status:t.testStatus,duration:t.duration});return aN(e,r,n)}function pye(e=100){return Rd.slice(-e).reverse()}function mye(){let e={},t=0,n=0;for(let r of Rd)r.action==="comment"&&t++,r.action==="status_update"&&n++;for(let[r]of pr){let s=r.split(":")[0];e[s]=(e[s]||0)+1}return{totalIssuesFetched:Rd.filter(r=>r.action==="fetch").length,totalCommentsPosted:t,totalStatusUpdates:n,cacheSize:pr.size,byPlatform:e}}function gye(){return{...Be}}function lN(e){Be={...Be,...e},Khe()}function hye(){pr.clear(),iN()}function yye(e){lN(e)}var Ghe,Be,Nv,I_,Vhe,M_,pr,Rd,j_=w(()=>{"use strict";Ghe={enabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3,autoLinkCommits:!0,autoCommentOnComplete:!1,defaultStatus:"in_progress",commentTemplate:`## Update from AIACA
1473
1483
 
1474
1484
  {summary}
1475
1485
 
@@ -1477,11 +1487,11 @@ Output strict JSON only:
1477
1487
  **Tests:** {test_status}
1478
1488
  **Duration:** {duration}
1479
1489
 
1480
- Generated by AIACA agent.`,pollIntervalMs:6e4,enablePersistence:!0,retentionCount:200},Be={...zhe},Nv=Pd(Hhe(),".aiaca","issue-tracker"),I_=Pd(Nv,"issues-cache.json"),Ghe=Pd(Nv,"activity.jsonl"),M_=Pd(Nv,"config.json"),pr=new Map,Rd=[];Vhe();Jhe()});var H_={};$(H_,{checkMergeReadiness:()=>qye,classifyComment:()=>U_,commentOnPR:()=>bN,configure:()=>zye,createPR:()=>Mye,detectPlatform:()=>mN,formatPR:()=>Vye,getAllPRs:()=>vN,getConfig:()=>Hye,getGitHubPR:()=>Vv,getPR:()=>Uye,getStats:()=>Gye,mergePR:()=>jye,respondToComments:()=>Bye,updatePR:()=>Oye});import{existsSync as uN,mkdirSync as yye,readFileSync as dN,writeFileSync as fN}from"fs";import{join as zv}from"path";import{homedir as bye}from"os";import{execSync as mr}from"child_process";function pN(){yye(N_,{recursive:!0})}function kye(){if(uN(B_))try{let e=JSON.parse(dN(B_,"utf-8"));for(let t of e.slice(-_n.retentionCount))Xs.set(t.id,t)}catch{}}function q_(){if(_n.enablePersistence){pN();try{let e=Array.from(Xs.values()).slice(-_n.retentionCount);fN(B_,JSON.stringify(e),"utf-8")}catch{}}}function Gv(e,t,n){pN();try{fN(wye,JSON.stringify({action:e,prId:t,timestamp:Date.now(),data:n})+`
1481
- `,{flag:"a"})}catch{}}function mN(e){try{let t=mr("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim();if(t.includes("github.com"))return"github";if(t.includes("gitlab.com"))return"gitlab"}catch{}return"unknown"}function gN(e){try{let n=mr("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim().match(/(?:github|gitlab)\.com[:/]([^/]+)\/([^/.]+)/);if(n)return{owner:n[1],repo:n[2].replace(/\.git$/,"")}}catch{}return null}function xye(e){try{return mr("git rev-parse --abbrev-ref HEAD",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim()}catch{return"main"}}function $ye(e,t,n=10){try{return mr(`git log ${t}.. --pretty=format:%H|%s|%an --max-count=${n}`,{cwd:e,stdio:"pipe",encoding:"utf-8"}).split(`
1482
- `).filter(Boolean).map(s=>{let[i,o,a]=s.split("|");return{hash:i?.slice(0,12)||"",message:o||"",author:a||""}})}catch{return[]}}function Cye(e,t){try{let r=mr(`git diff --stat ${t}...HEAD`,{cwd:e,stdio:"pipe",encoding:"utf-8"}).split(`
1483
- `),i=(r[r.length-2]||"").match(/(\d+)\s+files?\s+changed(?:,\s+(\d+)\s+insertions?\(\+\))?(?:,\s+(\d+)\s+deletions?\(-\))?/),a=r.slice(0,-2).map(c=>c.split("|")[0]?.trim()).filter(Boolean);return{filesChanged:i?parseInt(i[1],10):0,additions:i&&i[2]?parseInt(i[2],10):0,deletions:i&&i[3]?parseInt(i[3],10):0,files:a}}catch{return{filesChanged:0,additions:0,deletions:0,files:[]}}}function Aye(e,t,n=5e4){try{return mr(`git diff ${t}...HEAD`,{cwd:e,stdio:"pipe",encoding:"utf-8",maxBuffer:n*2}).slice(0,n)}catch{return""}}async function Qm(){try{return mr("gh --version",{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}function Hv(e){let t=new Set;for(let n of _n.issuePatterns)try{let r=new RegExp(n,"gi"),s;for(;(s=r.exec(e))!==null;)t.add(s[1])}catch{}return Array.from(t)}function Tye(e){let t=[],n=[/(\d+)/,/([A-Z]+-\d+)/];for(let r of n){let s=e.match(r);s&&s[1]&&t.push(s[1])}return t}function _ye(e){let t=[".github/CODEOWNERS","CODEOWNERS","docs/CODEOWNERS"];for(let n of t){let r=zv(e,n);if(uN(r))try{let s=dN(r,"utf-8"),i=[];for(let o of s.split(`
1484
- `)){let a=o.trim();if(!a||a.startsWith("#"))continue;let c=a.split(/\s+/),l=c[0],u=c.slice(1).map(d=>d.replace(/^@/,""));l&&u.length>0&&i.push({pattern:l,owners:u})}return i}catch{}}return[]}function Rye(e,t){let n=_ye(t);if(n.length===0)return[];let r=new Set;for(let s of e)for(let i of n)if(Pye(s,i.pattern))for(let o of i.owners)r.add(o);return Array.from(r).slice(0,_n.maxReviewers)}function Pye(e,t){if(t==="*"||t==="**")return!0;let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___GLOBSTAR___").replace(/\*/g,"[^/]*").replace(/___GLOBSTAR___/g,".*");return new RegExp(n).test(e)}async function Iye(e){let t=e.linkedIssues.length>0?`## Closes
1490
+ Generated by AIACA agent.`,pollIntervalMs:6e4,enablePersistence:!0,retentionCount:200},Be={...Ghe},Nv=Pd(zhe(),".aiaca","issue-tracker"),I_=Pd(Nv,"issues-cache.json"),Vhe=Pd(Nv,"activity.jsonl"),M_=Pd(Nv,"config.json"),pr=new Map,Rd=[];Jhe();Whe()});var H_={};$(H_,{checkMergeReadiness:()=>Uye,classifyComment:()=>U_,commentOnPR:()=>bN,configure:()=>Gye,createPR:()=>Eye,detectPlatform:()=>mN,formatPR:()=>Jye,getAllPRs:()=>vN,getConfig:()=>zye,getGitHubPR:()=>Vv,getPR:()=>Hye,getStats:()=>Vye,mergePR:()=>Bye,respondToComments:()=>Nye,updatePR:()=>jye});import{existsSync as uN,mkdirSync as bye,readFileSync as dN,writeFileSync as fN}from"fs";import{join as zv}from"path";import{homedir as vye}from"os";import{execSync as mr}from"child_process";function pN(){bye(N_,{recursive:!0})}function xye(){if(uN(B_))try{let e=JSON.parse(dN(B_,"utf-8"));for(let t of e.slice(-_n.retentionCount))Xs.set(t.id,t)}catch{}}function q_(){if(_n.enablePersistence){pN();try{let e=Array.from(Xs.values()).slice(-_n.retentionCount);fN(B_,JSON.stringify(e),"utf-8")}catch{}}}function Gv(e,t,n){pN();try{fN(kye,JSON.stringify({action:e,prId:t,timestamp:Date.now(),data:n})+`
1491
+ `,{flag:"a"})}catch{}}function mN(e){try{let t=mr("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim();if(t.includes("github.com"))return"github";if(t.includes("gitlab.com"))return"gitlab"}catch{}return"unknown"}function gN(e){try{let n=mr("git config --get remote.origin.url",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim().match(/(?:github|gitlab)\.com[:/]([^/]+)\/([^/.]+)/);if(n)return{owner:n[1],repo:n[2].replace(/\.git$/,"")}}catch{}return null}function $ye(e){try{return mr("git rev-parse --abbrev-ref HEAD",{cwd:e,stdio:"pipe",encoding:"utf-8"}).trim()}catch{return"main"}}function Cye(e,t,n=10){try{return mr(`git log ${t}.. --pretty=format:%H|%s|%an --max-count=${n}`,{cwd:e,stdio:"pipe",encoding:"utf-8"}).split(`
1492
+ `).filter(Boolean).map(s=>{let[i,o,a]=s.split("|");return{hash:i?.slice(0,12)||"",message:o||"",author:a||""}})}catch{return[]}}function Aye(e,t){try{let r=mr(`git diff --stat ${t}...HEAD`,{cwd:e,stdio:"pipe",encoding:"utf-8"}).split(`
1493
+ `),i=(r[r.length-2]||"").match(/(\d+)\s+files?\s+changed(?:,\s+(\d+)\s+insertions?\(\+\))?(?:,\s+(\d+)\s+deletions?\(-\))?/),a=r.slice(0,-2).map(c=>c.split("|")[0]?.trim()).filter(Boolean);return{filesChanged:i?parseInt(i[1],10):0,additions:i&&i[2]?parseInt(i[2],10):0,deletions:i&&i[3]?parseInt(i[3],10):0,files:a}}catch{return{filesChanged:0,additions:0,deletions:0,files:[]}}}function Tye(e,t,n=5e4){try{return mr(`git diff ${t}...HEAD`,{cwd:e,stdio:"pipe",encoding:"utf-8",maxBuffer:n*2}).slice(0,n)}catch{return""}}async function Qm(){try{return mr("gh --version",{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}function Hv(e){let t=new Set;for(let n of _n.issuePatterns)try{let r=new RegExp(n,"gi"),s;for(;(s=r.exec(e))!==null;)t.add(s[1])}catch{}return Array.from(t)}function _ye(e){let t=[],n=[/(\d+)/,/([A-Z]+-\d+)/];for(let r of n){let s=e.match(r);s&&s[1]&&t.push(s[1])}return t}function Rye(e){let t=[".github/CODEOWNERS","CODEOWNERS","docs/CODEOWNERS"];for(let n of t){let r=zv(e,n);if(uN(r))try{let s=dN(r,"utf-8"),i=[];for(let o of s.split(`
1494
+ `)){let a=o.trim();if(!a||a.startsWith("#"))continue;let c=a.split(/\s+/),l=c[0],u=c.slice(1).map(d=>d.replace(/^@/,""));l&&u.length>0&&i.push({pattern:l,owners:u})}return i}catch{}}return[]}function Pye(e,t){let n=Rye(t);if(n.length===0)return[];let r=new Set;for(let s of e)for(let i of n)if(Iye(s,i.pattern))for(let o of i.owners)r.add(o);return Array.from(r).slice(0,_n.maxReviewers)}function Iye(e,t){if(t==="*"||t==="**")return!0;let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___GLOBSTAR___").replace(/\*/g,"[^/]*").replace(/___GLOBSTAR___/g,".*");return new RegExp(n).test(e)}async function Mye(e){let t=e.linkedIssues.length>0?`## Closes
1485
1495
  `+e.linkedIssues.map(r=>`- Closes #${r}`).join(`
1486
1496
  `):"",n=`Generate a pull request description.
1487
1497
 
@@ -1509,11 +1519,11 @@ Output ONLY the description text, no preamble. Use markdown.`;try{let s=(await e
1509
1519
 
1510
1520
  ---
1511
1521
  \u{1F916} Generated with AIACA`,s}catch{return hN({summary:e.title,changes:e.commits.map(r=>`- ${r.message}`).join(`
1512
- `),testing:"Tests pass locally",closes_section:t})}}function hN(e){let t=_n.descriptionTemplate;for(let[n,r]of Object.entries(e))t=t.replace(new RegExp(`{${n}}`,"g"),r);return t}async function Mye(e,t,n){if(!_n.enabled)throw new Error("PR Autopilot disabled");let r=mN(t);if(r!=="github")throw new Error(`Platform ${r} not yet supported`);let s=e.headBranch||xye(t),i=e.baseBranch||_n.defaultBaseBranch;if(s===i)throw new Error("Cannot create PR: head and base are same branch");try{mr(`git push -u origin ${s}`,{cwd:t,stdio:"pipe"})}catch{}let o=$ye(t,i,20),a=Cye(t,i),c=[];if(e.linkIssues!==!1&&_n.autoLinkIssues){c.push(...Tye(s));for(let f of o)c.push(...Hv(f.message));e.body&&c.push(...Hv(e.body)),c=[...new Set(c)]}let l=e.body||"";if(e.autoGenerateBody!==!1&&_n.enableAIDescription&&n){let f=Aye(t,i);l=await Iye({title:e.title,diff:f,commits:o,files:a.files,linkedIssues:c,provider:n})}else l||(l=hN({summary:e.title,changes:o.map(f=>`- ${f.message}`).join(`
1522
+ `),testing:"Tests pass locally",closes_section:t})}}function hN(e){let t=_n.descriptionTemplate;for(let[n,r]of Object.entries(e))t=t.replace(new RegExp(`{${n}}`,"g"),r);return t}async function Eye(e,t,n){if(!_n.enabled)throw new Error("PR Autopilot disabled");let r=mN(t);if(r!=="github")throw new Error(`Platform ${r} not yet supported`);let s=e.headBranch||$ye(t),i=e.baseBranch||_n.defaultBaseBranch;if(s===i)throw new Error("Cannot create PR: head and base are same branch");try{mr(`git push -u origin ${s}`,{cwd:t,stdio:"pipe"})}catch{}let o=Cye(t,i,20),a=Aye(t,i),c=[];if(e.linkIssues!==!1&&_n.autoLinkIssues){c.push(..._ye(s));for(let f of o)c.push(...Hv(f.message));e.body&&c.push(...Hv(e.body)),c=[...new Set(c)]}let l=e.body||"";if(e.autoGenerateBody!==!1&&_n.enableAIDescription&&n){let f=Tye(t,i);l=await Mye({title:e.title,diff:f,commits:o,files:a.files,linkedIssues:c,provider:n})}else l||(l=hN({summary:e.title,changes:o.map(f=>`- ${f.message}`).join(`
1513
1523
  `)||"- See diff",testing:"Tests pass locally",closes_section:c.length>0?`## Closes
1514
1524
  `+c.map(f=>`- Closes #${f}`).join(`
1515
- `):""}));let u=e.reviewers||[];if(e.autoAssignReviewers!==!1&&_n.useCodeowners){let f=Rye(a.files,t);u=[...new Set([...u,...f])],u.length===0&&_n.fallbackReviewers.length>0&&u.push(..._n.fallbackReviewers),u=u.slice(0,_n.maxReviewers)}let d=await Eye({title:e.title,body:l,baseBranch:i,headBranch:s,draft:!!e.draft,reviewers:u,assignees:e.assignees||[],labels:e.labels||[]},t);return d&&(d.linkedIssues=c,d.filesChanged=a.filesChanged,d.additions=a.additions,d.deletions=a.deletions,Xs.set(d.id,d),q_(),Gv("create",d.id,{title:e.title})),d}async function Eye(e,t){if(!await Qm())return Dye(e,t);try{let n=[`--title ${JSON.stringify(e.title)}`,`--body ${JSON.stringify(e.body.slice(0,6e4))}`,`--base ${e.baseBranch}`,`--head ${e.headBranch}`];e.draft&&n.push("--draft"),e.reviewers.length>0&&n.push(`--reviewer ${e.reviewers.join(",")}`),e.assignees.length>0&&n.push(`--assignee ${e.assignees.join(",")}`),e.labels.length>0&&n.push(`--label ${e.labels.map(o=>JSON.stringify(o)).join(",")}`);let s=mr(`gh pr create ${n.join(" ")}`,{cwd:t,stdio:"pipe",encoding:"utf-8"}).trim().split(`
1516
- `).pop()||"",i=parseInt(s.match(/\/pull\/(\d+)/)?.[1]||"0",10);return await Vv(t,i)}catch(n){throw new Error(`gh pr create failed: ${n.message}`)}}async function Dye(e,t){let n=gN(t),r=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(!n||!r)return null;try{let s=await fetch(`https://api.github.com/repos/${n.owner}/${n.repo}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({title:e.title,body:e.body,base:e.baseBranch,head:e.headBranch,draft:e.draft})});if(!s.ok)return null;let i=await s.json();return yN(i,n)}catch{return null}}async function Vv(e,t){let n=gN(e);if(!n)return null;try{if(await Qm()){let i=mr(`gh pr view ${t} --json number,title,body,state,baseRefName,headRefName,author,assignees,reviewRequests,labels,url,createdAt,updatedAt,mergedAt,closedAt,isDraft,additions,deletions,changedFiles,reviews,comments,statusCheckRollup,mergeable`,{cwd:e,stdio:"pipe",encoding:"utf-8",maxBuffer:5242880}),o=JSON.parse(i);return Fye(o,n,t)}let r=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(!r)return null;let s=await fetch(`https://api.github.com/repos/${n.owner}/${n.repo}/pulls/${t}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json"}});return s.ok?yN(await s.json(),n):null}catch{return null}}function Fye(e,t,n){let r=(e.reviews||[]).map(a=>({id:String(a.id),reviewer:a.author?.login||"unknown",state:a.state?.toLowerCase()||"commented",body:a.body||"",submittedAt:new Date(a.submittedAt).getTime()})),s=r.filter(a=>a.state==="approved").length,i=r.filter(a=>a.state==="changes_requested").length,o="open";return e.state==="MERGED"||e.mergedAt?o="merged":e.state==="CLOSED"?o="closed":e.isDraft?o="draft":i>0?o="changes_requested":s>0?o="approved":e.reviewRequests?.length>0&&(o="pending_review"),{id:`github:${t.owner}/${t.repo}#${n}`,externalId:String(n),platform:"github",number:n,title:e.title,body:e.body||"",status:o,baseBranch:e.baseRefName,headBranch:e.headRefName,author:e.author?.login||"unknown",reviewers:(e.reviewRequests||[]).map(a=>a.login||a.name).filter(Boolean),assignees:(e.assignees||[]).map(a=>a.login),labels:(e.labels||[]).map(a=>a.name),url:e.url,draft:!!e.isDraft,createdAt:new Date(e.createdAt).getTime(),updatedAt:new Date(e.updatedAt).getTime(),mergedAt:e.mergedAt?new Date(e.mergedAt).getTime():void 0,closedAt:e.closedAt?new Date(e.closedAt).getTime():void 0,ciStatus:Lye(e.statusCheckRollup),approvalCount:s,changesRequestedCount:i,hasConflicts:e.mergeable==="CONFLICTING",reviews:r,comments:(e.comments||[]).map(a=>({id:String(a.id),author:a.author?.login||"unknown",body:a.body||"",createdAt:new Date(a.createdAt).getTime()})),linkedIssues:Hv(e.body||""),filesChanged:e.changedFiles||0,additions:e.additions||0,deletions:e.deletions||0}}function yN(e,t){return{id:`github:${t.owner}/${t.repo}#${e.number}`,externalId:String(e.number),platform:"github",number:e.number,title:e.title,body:e.body||"",status:e.merged_at?"merged":e.state==="closed"?"closed":e.draft?"draft":"open",baseBranch:e.base?.ref||"main",headBranch:e.head?.ref||"",author:e.user?.login||"unknown",reviewers:(e.requested_reviewers||[]).map(n=>n.login),assignees:(e.assignees||[]).map(n=>n.login),labels:(e.labels||[]).map(n=>n.name),url:e.html_url,draft:!!e.draft,createdAt:new Date(e.created_at).getTime(),updatedAt:new Date(e.updated_at).getTime(),mergedAt:e.merged_at?new Date(e.merged_at).getTime():void 0,closedAt:e.closed_at?new Date(e.closed_at).getTime():void 0,approvalCount:0,changesRequestedCount:0,hasConflicts:e.mergeable===!1,reviews:[],comments:[],linkedIssues:Hv(e.body||""),filesChanged:e.changed_files||0,additions:e.additions||0,deletions:e.deletions||0}}function Lye(e){return e&&Array.isArray(e)?e.some(t=>t.status==="IN_PROGRESS"||t.status==="PENDING")?"pending":e.some(t=>t.conclusion==="FAILURE")?"failure":"success":"unknown"}function U_(e){let t=e.toLowerCase();return/\b(blocking|must fix|must change|cannot approve|critical|broken)\b/.test(t)?"blocking":/\b(suggest|consider|maybe|could you|why not)\b/.test(t)?"suggestion":/\b(nit:|nitpick:|minor:|tiny:|small:)/.test(t)?"nit":/\?\s*$/.test(e)||/\b(why|how|what|when|where|can you explain)\b/.test(t)?"question":/\b(lgtm|looks good|nice|great|🎉|👍|💯)\b/.test(t)?"praise":"fyi"}async function Oye(e,t,n){let r=Xs.get(e);if(!r)return!1;try{if(await Qm()){let s=[];return t.title&&s.push(`--title ${JSON.stringify(t.title)}`),t.body&&s.push(`--body ${JSON.stringify(t.body.slice(0,6e4))}`),mr(`gh pr edit ${r.number} ${s.join(" ")}`,{cwd:n,stdio:"pipe"}),t.draft===!1&&mr(`gh pr ready ${r.number}`,{cwd:n,stdio:"pipe"}),Gv("update",e,t),!0}return!1}catch{return!1}}async function bN(e,t,n){let r=Xs.get(e);if(!r)return!1;try{return await Qm()?(mr(`gh pr comment ${r.number} --body ${JSON.stringify(t)}`,{cwd:n,stdio:"pipe"}),Gv("comment",e,{body:t.slice(0,200)}),!0):!1}catch{return!1}}async function jye(e,t,n={}){let r=Xs.get(e);if(!r)return!1;try{if(await Qm()){let s=n.method||"squash",i=n.deleteBranch!==!1?"--delete-branch":"";return mr(`gh pr merge ${r.number} --${s} ${i}`,{cwd:t,stdio:"pipe"}),Gv("merge",e,{method:s}),r.status="merged",r.mergedAt=Date.now(),q_(),!0}return!1}catch{return!1}}async function Bye(e,t,n){let r=Xs.get(e);if(!r)return{responded:0,skipped:0};let s=0,i=0,o=await Vv(t,r.number);if(!o)return{responded:0,skipped:0};for(let a of o.comments){if(a.responded){i++;continue}let c=U_(a.body);if(c==="praise"||c==="fyi"){i++;continue}let l=await Nye(a,c,r,n);l?(await bN(e,l,t),a.responded=!0,s++):i++}return q_(),{responded:s,skipped:i}}async function Nye(e,t,n,r){let s=`You are responding to a review comment on a pull request.
1525
+ `):""}));let u=e.reviewers||[];if(e.autoAssignReviewers!==!1&&_n.useCodeowners){let f=Pye(a.files,t);u=[...new Set([...u,...f])],u.length===0&&_n.fallbackReviewers.length>0&&u.push(..._n.fallbackReviewers),u=u.slice(0,_n.maxReviewers)}let d=await Dye({title:e.title,body:l,baseBranch:i,headBranch:s,draft:!!e.draft,reviewers:u,assignees:e.assignees||[],labels:e.labels||[]},t);return d&&(d.linkedIssues=c,d.filesChanged=a.filesChanged,d.additions=a.additions,d.deletions=a.deletions,Xs.set(d.id,d),q_(),Gv("create",d.id,{title:e.title})),d}async function Dye(e,t){if(!await Qm())return Fye(e,t);try{let n=[`--title ${JSON.stringify(e.title)}`,`--body ${JSON.stringify(e.body.slice(0,6e4))}`,`--base ${e.baseBranch}`,`--head ${e.headBranch}`];e.draft&&n.push("--draft"),e.reviewers.length>0&&n.push(`--reviewer ${e.reviewers.join(",")}`),e.assignees.length>0&&n.push(`--assignee ${e.assignees.join(",")}`),e.labels.length>0&&n.push(`--label ${e.labels.map(o=>JSON.stringify(o)).join(",")}`);let s=mr(`gh pr create ${n.join(" ")}`,{cwd:t,stdio:"pipe",encoding:"utf-8"}).trim().split(`
1526
+ `).pop()||"",i=parseInt(s.match(/\/pull\/(\d+)/)?.[1]||"0",10);return await Vv(t,i)}catch(n){throw new Error(`gh pr create failed: ${n.message}`)}}async function Fye(e,t){let n=gN(t),r=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(!n||!r)return null;try{let s=await fetch(`https://api.github.com/repos/${n.owner}/${n.repo}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({title:e.title,body:e.body,base:e.baseBranch,head:e.headBranch,draft:e.draft})});if(!s.ok)return null;let i=await s.json();return yN(i,n)}catch{return null}}async function Vv(e,t){let n=gN(e);if(!n)return null;try{if(await Qm()){let i=mr(`gh pr view ${t} --json number,title,body,state,baseRefName,headRefName,author,assignees,reviewRequests,labels,url,createdAt,updatedAt,mergedAt,closedAt,isDraft,additions,deletions,changedFiles,reviews,comments,statusCheckRollup,mergeable`,{cwd:e,stdio:"pipe",encoding:"utf-8",maxBuffer:5242880}),o=JSON.parse(i);return Lye(o,n,t)}let r=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(!r)return null;let s=await fetch(`https://api.github.com/repos/${n.owner}/${n.repo}/pulls/${t}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json"}});return s.ok?yN(await s.json(),n):null}catch{return null}}function Lye(e,t,n){let r=(e.reviews||[]).map(a=>({id:String(a.id),reviewer:a.author?.login||"unknown",state:a.state?.toLowerCase()||"commented",body:a.body||"",submittedAt:new Date(a.submittedAt).getTime()})),s=r.filter(a=>a.state==="approved").length,i=r.filter(a=>a.state==="changes_requested").length,o="open";return e.state==="MERGED"||e.mergedAt?o="merged":e.state==="CLOSED"?o="closed":e.isDraft?o="draft":i>0?o="changes_requested":s>0?o="approved":e.reviewRequests?.length>0&&(o="pending_review"),{id:`github:${t.owner}/${t.repo}#${n}`,externalId:String(n),platform:"github",number:n,title:e.title,body:e.body||"",status:o,baseBranch:e.baseRefName,headBranch:e.headRefName,author:e.author?.login||"unknown",reviewers:(e.reviewRequests||[]).map(a=>a.login||a.name).filter(Boolean),assignees:(e.assignees||[]).map(a=>a.login),labels:(e.labels||[]).map(a=>a.name),url:e.url,draft:!!e.isDraft,createdAt:new Date(e.createdAt).getTime(),updatedAt:new Date(e.updatedAt).getTime(),mergedAt:e.mergedAt?new Date(e.mergedAt).getTime():void 0,closedAt:e.closedAt?new Date(e.closedAt).getTime():void 0,ciStatus:Oye(e.statusCheckRollup),approvalCount:s,changesRequestedCount:i,hasConflicts:e.mergeable==="CONFLICTING",reviews:r,comments:(e.comments||[]).map(a=>({id:String(a.id),author:a.author?.login||"unknown",body:a.body||"",createdAt:new Date(a.createdAt).getTime()})),linkedIssues:Hv(e.body||""),filesChanged:e.changedFiles||0,additions:e.additions||0,deletions:e.deletions||0}}function yN(e,t){return{id:`github:${t.owner}/${t.repo}#${e.number}`,externalId:String(e.number),platform:"github",number:e.number,title:e.title,body:e.body||"",status:e.merged_at?"merged":e.state==="closed"?"closed":e.draft?"draft":"open",baseBranch:e.base?.ref||"main",headBranch:e.head?.ref||"",author:e.user?.login||"unknown",reviewers:(e.requested_reviewers||[]).map(n=>n.login),assignees:(e.assignees||[]).map(n=>n.login),labels:(e.labels||[]).map(n=>n.name),url:e.html_url,draft:!!e.draft,createdAt:new Date(e.created_at).getTime(),updatedAt:new Date(e.updated_at).getTime(),mergedAt:e.merged_at?new Date(e.merged_at).getTime():void 0,closedAt:e.closed_at?new Date(e.closed_at).getTime():void 0,approvalCount:0,changesRequestedCount:0,hasConflicts:e.mergeable===!1,reviews:[],comments:[],linkedIssues:Hv(e.body||""),filesChanged:e.changed_files||0,additions:e.additions||0,deletions:e.deletions||0}}function Oye(e){return e&&Array.isArray(e)?e.some(t=>t.status==="IN_PROGRESS"||t.status==="PENDING")?"pending":e.some(t=>t.conclusion==="FAILURE")?"failure":"success":"unknown"}function U_(e){let t=e.toLowerCase();return/\b(blocking|must fix|must change|cannot approve|critical|broken)\b/.test(t)?"blocking":/\b(suggest|consider|maybe|could you|why not)\b/.test(t)?"suggestion":/\b(nit:|nitpick:|minor:|tiny:|small:)/.test(t)?"nit":/\?\s*$/.test(e)||/\b(why|how|what|when|where|can you explain)\b/.test(t)?"question":/\b(lgtm|looks good|nice|great|🎉|👍|💯)\b/.test(t)?"praise":"fyi"}async function jye(e,t,n){let r=Xs.get(e);if(!r)return!1;try{if(await Qm()){let s=[];return t.title&&s.push(`--title ${JSON.stringify(t.title)}`),t.body&&s.push(`--body ${JSON.stringify(t.body.slice(0,6e4))}`),mr(`gh pr edit ${r.number} ${s.join(" ")}`,{cwd:n,stdio:"pipe"}),t.draft===!1&&mr(`gh pr ready ${r.number}`,{cwd:n,stdio:"pipe"}),Gv("update",e,t),!0}return!1}catch{return!1}}async function bN(e,t,n){let r=Xs.get(e);if(!r)return!1;try{return await Qm()?(mr(`gh pr comment ${r.number} --body ${JSON.stringify(t)}`,{cwd:n,stdio:"pipe"}),Gv("comment",e,{body:t.slice(0,200)}),!0):!1}catch{return!1}}async function Bye(e,t,n={}){let r=Xs.get(e);if(!r)return!1;try{if(await Qm()){let s=n.method||"squash",i=n.deleteBranch!==!1?"--delete-branch":"";return mr(`gh pr merge ${r.number} --${s} ${i}`,{cwd:t,stdio:"pipe"}),Gv("merge",e,{method:s}),r.status="merged",r.mergedAt=Date.now(),q_(),!0}return!1}catch{return!1}}async function Nye(e,t,n){let r=Xs.get(e);if(!r)return{responded:0,skipped:0};let s=0,i=0,o=await Vv(t,r.number);if(!o)return{responded:0,skipped:0};for(let a of o.comments){if(a.responded){i++;continue}let c=U_(a.body);if(c==="praise"||c==="fyi"){i++;continue}let l=await qye(a,c,r,n);l?(await bN(e,l,t),a.responded=!0,s++):i++}return q_(),{responded:s,skipped:i}}async function qye(e,t,n,r){let s=`You are responding to a review comment on a pull request.
1517
1527
 
1518
1528
  PR: ${n.title}
1519
1529
  COMMENT FROM ${e.author} (classification: ${t}):
@@ -1527,8 +1537,8 @@ Respond appropriately:
1527
1537
  - For blocking: Acknowledge and describe the fix
1528
1538
  - For nits: Acknowledge briefly
1529
1539
 
1530
- Keep response under 200 words. Output ONLY the response, no preamble.`;try{return(await r.sendMessage([{role:"user",content:s,timestamp:new Date().toISOString()}],"You write professional, concise PR review responses.",[],void 0)).content||null}catch{return null}}async function qye(e,t){let n=await Vv(t,Xs.get(e)?.number||0);if(!n)return{ready:!1,blockers:["PR not found"],warnings:[]};let r=[],s=[];return n.draft&&r.push("PR is still in draft"),n.status==="merged"&&r.push("Already merged"),n.status==="closed"&&r.push("Closed"),n.changesRequestedCount>0&&r.push(`${n.changesRequestedCount} review(s) requesting changes`),n.approvalCount===0&&s.push("No approvals yet"),n.hasConflicts&&r.push("Has merge conflicts"),n.ciStatus==="failure"&&r.push("CI is failing"),n.ciStatus==="pending"&&s.push("CI is still running"),{ready:r.length===0,blockers:r,warnings:s}}function Uye(e){return Xs.get(e)}function vN(){return Array.from(Xs.values()).sort((e,t)=>t.updatedAt-e.updatedAt)}function Hye(){return{..._n}}function zye(e){_n={..._n,...e}}function Gye(){let e=vN(),t=e.filter(r=>r.status==="merged"&&r.mergedAt&&r.createdAt),n=t.length>0?t.reduce((r,s)=>r+((s.mergedAt||0)-s.createdAt),0)/t.length:0;return{totalPRs:e.length,open:e.filter(r=>r.status==="open"||r.status==="pending_review"||r.status==="approved").length,merged:e.filter(r=>r.status==="merged").length,closed:e.filter(r=>r.status==="closed").length,draft:e.filter(r=>r.draft).length,averageMergeTimeMs:n,totalAdditions:e.reduce((r,s)=>r+s.additions,0),totalDeletions:e.reduce((r,s)=>r+s.deletions,0)}}function Vye(e){let t=[],n={draft:"\u25D0",open:"\u25EF",merged:"\u2713",closed:"\u2715",pending_review:"\u23F3",approved:"\u2705",changes_requested:"\u26A0\uFE0F"};if(t.push(`# ${n[e.status]} PR #${e.number}: ${e.title}`),t.push(`Status: ${e.status} | ${e.headBranch} \u2192 ${e.baseBranch}`),t.push(`Author: ${e.author} | URL: ${e.url}`),e.reviewers.length>0&&t.push(`Reviewers: ${e.reviewers.join(", ")}`),e.labels.length>0&&t.push(`Labels: ${e.labels.join(", ")}`),t.push(""),t.push(`Stats: ${e.filesChanged} files, +${e.additions}/-${e.deletions}`),t.push(`Reviews: ${e.approvalCount} approval(s), ${e.changesRequestedCount} change request(s)`),e.ciStatus&&t.push(`CI: ${e.ciStatus}`),e.hasConflicts&&t.push("\u26A0\uFE0F Has conflicts"),e.linkedIssues.length>0&&t.push(`Linked issues: ${e.linkedIssues.map(r=>"#"+r).join(", ")}`),t.push(""),t.push("## Description"),t.push(e.body.slice(0,2e3)),e.reviews.length>0){t.push(""),t.push(`## Reviews (${e.reviews.length})`);for(let r of e.reviews.slice(-5)){let s=r.state==="approved"?"\u2713":r.state==="changes_requested"?"\u2717":"\u{1F4AC}";t.push(` ${s} ${r.reviewer} (${r.state})`),r.body&&t.push(` ${r.body.slice(0,200)}`)}}if(e.comments.length>0){t.push(""),t.push(`## Comments (${e.comments.length})`);for(let r of e.comments.slice(-5)){let s=U_(r.body);t.push(` [${s}] ${r.author}: ${r.body.slice(0,150)}`)}}return t.join(`
1531
- `)}var vye,Sye,_n,N_,B_,wye,Xs,z_=w(()=>{"use strict";vye=`## Summary
1540
+ Keep response under 200 words. Output ONLY the response, no preamble.`;try{return(await r.sendMessage([{role:"user",content:s,timestamp:new Date().toISOString()}],"You write professional, concise PR review responses.",[],void 0)).content||null}catch{return null}}async function Uye(e,t){let n=await Vv(t,Xs.get(e)?.number||0);if(!n)return{ready:!1,blockers:["PR not found"],warnings:[]};let r=[],s=[];return n.draft&&r.push("PR is still in draft"),n.status==="merged"&&r.push("Already merged"),n.status==="closed"&&r.push("Closed"),n.changesRequestedCount>0&&r.push(`${n.changesRequestedCount} review(s) requesting changes`),n.approvalCount===0&&s.push("No approvals yet"),n.hasConflicts&&r.push("Has merge conflicts"),n.ciStatus==="failure"&&r.push("CI is failing"),n.ciStatus==="pending"&&s.push("CI is still running"),{ready:r.length===0,blockers:r,warnings:s}}function Hye(e){return Xs.get(e)}function vN(){return Array.from(Xs.values()).sort((e,t)=>t.updatedAt-e.updatedAt)}function zye(){return{..._n}}function Gye(e){_n={..._n,...e}}function Vye(){let e=vN(),t=e.filter(r=>r.status==="merged"&&r.mergedAt&&r.createdAt),n=t.length>0?t.reduce((r,s)=>r+((s.mergedAt||0)-s.createdAt),0)/t.length:0;return{totalPRs:e.length,open:e.filter(r=>r.status==="open"||r.status==="pending_review"||r.status==="approved").length,merged:e.filter(r=>r.status==="merged").length,closed:e.filter(r=>r.status==="closed").length,draft:e.filter(r=>r.draft).length,averageMergeTimeMs:n,totalAdditions:e.reduce((r,s)=>r+s.additions,0),totalDeletions:e.reduce((r,s)=>r+s.deletions,0)}}function Jye(e){let t=[],n={draft:"\u25D0",open:"\u25EF",merged:"\u2713",closed:"\u2715",pending_review:"\u23F3",approved:"\u2705",changes_requested:"\u26A0\uFE0F"};if(t.push(`# ${n[e.status]} PR #${e.number}: ${e.title}`),t.push(`Status: ${e.status} | ${e.headBranch} \u2192 ${e.baseBranch}`),t.push(`Author: ${e.author} | URL: ${e.url}`),e.reviewers.length>0&&t.push(`Reviewers: ${e.reviewers.join(", ")}`),e.labels.length>0&&t.push(`Labels: ${e.labels.join(", ")}`),t.push(""),t.push(`Stats: ${e.filesChanged} files, +${e.additions}/-${e.deletions}`),t.push(`Reviews: ${e.approvalCount} approval(s), ${e.changesRequestedCount} change request(s)`),e.ciStatus&&t.push(`CI: ${e.ciStatus}`),e.hasConflicts&&t.push("\u26A0\uFE0F Has conflicts"),e.linkedIssues.length>0&&t.push(`Linked issues: ${e.linkedIssues.map(r=>"#"+r).join(", ")}`),t.push(""),t.push("## Description"),t.push(e.body.slice(0,2e3)),e.reviews.length>0){t.push(""),t.push(`## Reviews (${e.reviews.length})`);for(let r of e.reviews.slice(-5)){let s=r.state==="approved"?"\u2713":r.state==="changes_requested"?"\u2717":"\u{1F4AC}";t.push(` ${s} ${r.reviewer} (${r.state})`),r.body&&t.push(` ${r.body.slice(0,200)}`)}}if(e.comments.length>0){t.push(""),t.push(`## Comments (${e.comments.length})`);for(let r of e.comments.slice(-5)){let s=U_(r.body);t.push(` [${s}] ${r.author}: ${r.body.slice(0,150)}`)}}return t.join(`
1541
+ `)}var Sye,wye,_n,N_,B_,kye,Xs,z_=w(()=>{"use strict";Sye=`## Summary
1532
1542
  {summary}
1533
1543
 
1534
1544
  ## Changes
@@ -1540,31 +1550,31 @@ Keep response under 200 words. Output ONLY the response, no preamble.`;try{retur
1540
1550
  {closes_section}
1541
1551
 
1542
1552
  ---
1543
- \u{1F916} Generated with [AIACA](https://github.com/your-org/aiaca)`,Sye={enabled:!0,defaultBaseBranch:"main",enableAIDescription:!0,enableAIResponses:!1,descriptionTemplate:vye,autoLinkIssues:!0,issuePatterns:["closes\\s+#(\\d+)","fixes\\s+#(\\d+)","resolves\\s+#(\\d+)","#(\\d+)","(?:^|\\s)([A-Z]+-\\d+)"],useCodeowners:!0,fallbackReviewers:[],maxReviewers:3,autoRespondToReviews:!1,autoFixSimpleFeedback:!1,pollIntervalMs:3e4,enablePersistence:!0,retentionCount:100},_n={...Sye},N_=zv(bye(),".aiaca","pr-autopilot"),B_=zv(N_,"prs.json"),wye=zv(N_,"activity.jsonl"),Xs=new Map;kye()});var Y_={};$(Y_,{cleanupAll:()=>RN,configure:()=>dbe,detectRuntimes:()=>$N,execute:()=>cbe,formatResult:()=>mbe,getConfig:()=>ube,getStats:()=>fbe,pullAllImages:()=>lbe,pullImage:()=>PN,resetStats:()=>pbe,selectRuntime:()=>K_});import{existsSync as Jye,mkdirSync as Wye,readFileSync as Kye,writeFileSync as Zm,unlinkSync as SN}from"fs";import{join as Vc}from"path";import{homedir as Yye,tmpdir as J_,platform as Qye}from"os";import{execSync as Gi,spawn as W_}from"child_process";import{createHash as wN}from"crypto";function kN(){Wye(Jv,{recursive:!0})}function ebe(){if(Jye(V_))try{Rn={...Rn,...JSON.parse(Kye(V_,"utf-8"))}}catch{}}function xN(){kN();try{Zm(V_,JSON.stringify(Rn,null,2),"utf-8")}catch{}}function tbe(e){if(nt.enableAuditLog){kN();try{Zm(Xye,JSON.stringify({...e,timestamp:Date.now()})+`
1544
- `,{flag:"a"})}catch{}}}function $N(e=!1){if(G_&&!e)return G_;let t=new Set;return ei("docker")&&t.add("docker"),ei("podman")&&t.add("podman"),ei("runsc")&&t.add("gvisor"),ei("firecracker")&&t.add("firecracker"),(ei("wasmtime")||ei("wasmer")||ei("deno"))&&t.add("wasm"),t.add("process"),G_=t,t}function ei(e){try{return Gi(Qye()==="win32"?`where ${e}`:`which ${e}`,{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}function K_(e){let t=$N(),n=e||nt.preferredRuntime;if(t.has(n))return n;for(let r of nt.fallbackRuntimes)if(t.has(r))return r;return"process"}function CN(e,t){return t||nt.defaultImages[e]||"alpine:latest"}function AN(e,t){switch(e){case"python":return{entrypoint:["python","-c"],content:t};case"node":case"javascript":return{entrypoint:["node","-e"],content:t};case"typescript":return{filename:"/tmp/code.ts",content:t,entrypoint:["npx","tsx","/tmp/code.ts"]};case"go":return{filename:"/tmp/code.go",content:t,entrypoint:["go","run","/tmp/code.go"]};case"rust":return{filename:"/tmp/code.rs",content:t,entrypoint:["rustc","/tmp/code.rs","-o","/tmp/out","&&","/tmp/out"]};case"java":return{filename:"/tmp/Main.java",content:t,entrypoint:["sh","-c","cd /tmp && javac Main.java && java Main"]};case"ruby":return{entrypoint:["ruby","-e"],content:t};case"shell":return{entrypoint:["sh","-c"],content:t};case"cpp":return{filename:"/tmp/code.cpp",content:t,entrypoint:["sh","-c","g++ /tmp/code.cpp -o /tmp/out && /tmp/out"]};case"php":return{entrypoint:["php","-r"],content:t};default:return{entrypoint:["sh","-c"],content:t}}}async function TN(e,t){let n=Date.now(),r=`aiaca-sb-${wN("md5").update(Date.now()+Math.random().toString()).digest("hex").slice(0,12)}`,s=CN(e.language,e.image),i=AN(e.language,e.code);if(nt.pullPolicy==="always"||nt.pullPolicy==="if_not_present"&&!await rbe(t,s))try{Gi(`${t} pull ${s}`,{stdio:"pipe",timeout:12e4})}catch{}let o=["run","--rm","--name",r,"-i"];o.push("--memory",`${e.memoryMb||nt.defaultMemoryMb}m`),o.push("--cpu-shares",String(e.cpuShares||nt.defaultCpuShares)),o.push("--pids-limit",String(e.pidsLimit||nt.defaultPidsLimit));let a=e.network||nt.defaultNetwork;if(a==="none")o.push("--network","none");else if(a==="host"){if(!nt.allowHostNetwork)return Gc(n,t,"Host network not allowed by config");o.push("--network","host")}else o.push("--network","bridge");(e.readOnlyRoot??nt.defaultReadOnlyRoot)&&(o.push("--read-only"),o.push("--tmpfs","/tmp:rw,size=64m")),nt.dropCapabilities&&(o.push("--cap-drop","ALL"),o.push("--security-opt","no-new-privileges")),nt.enableSeccomp&&t==="docker"&&o.push("--security-opt","seccomp=default");for(let c of e.mounts||[]){let l=c.readonly?":ro":":rw";o.push("-v",`${c.host}:${c.container}${l}`)}for(let[c,l]of Object.entries(e.envVars||{}))o.push("-e",`${c}=${l}`);return e.workingDir&&o.push("-w",e.workingDir),o.push("-u","1000:1000"),o.push(s),i.filename?nbe(t,o,i,e,n,r):(o.push(...i.entrypoint,i.content),_N(t,o,e,n,r))}async function nbe(e,t,n,r,s,i){let o=Vc(J_(),`aiaca-sb-${wN("md5").update(Date.now().toString()).digest("hex").slice(0,8)}-${n.filename.split("/").pop()}`);try{Zm(o,n.content);let a=n.filename;return t.push("-v",`${o}:${a}:ro`),t.push(...n.entrypoint),_N(e,t,r,s,i)}finally{try{SN(o)}catch{}}}async function _N(e,t,n,r,s){let i=n.timeoutMs||nt.defaultTimeoutMs;return new Promise(o=>{let a="",c="",l=!1,u=!1,d=W_(e,t,{stdio:["pipe","pipe","pipe"]});n.stdin&&d.stdin.write(n.stdin),d.stdin.end(),d.stdout.on("data",p=>{a+=p.toString().slice(0,1024*1024)}),d.stderr.on("data",p=>{c+=p.toString().slice(0,1024*1024)});let f=setTimeout(()=>{u=!0;try{Gi(`${e} kill ${s}`,{stdio:"pipe"})}catch{}d.kill("SIGKILL"),l=!0},i);d.on("close",p=>{clearTimeout(f);let m=Date.now()-r,g={success:p===0&&!u,exitCode:p??-1,stdout:a,stderr:c,duration:m,runtime:e,containerName:s,timedOut:u,killed:l};try{let h=Gi(`${e} inspect ${s} 2>/dev/null || echo {}`,{stdio:"pipe",encoding:"utf-8"});JSON.parse(h)[0]?.State?.OOMKilled&&(g.error="Container killed due to memory limit")}catch{}if(nt.autoCleanup)try{Gi(`${e} rm -f ${s}`,{stdio:"pipe"})}catch{}o(g)}),d.on("error",p=>{clearTimeout(f),o(Gc(r,e,p.message))})})}async function rbe(e,t){try{return Gi(`${e} image inspect ${t}`,{stdio:"pipe",timeout:1e4}),!0}catch{return!1}}async function sbe(e){if(!ei("docker"))return Gc(Date.now(),"gvisor","gVisor requires Docker with runsc runtime");let t=Date.now();return{...await TN(e,"docker"),runtime:"gvisor"}}async function ibe(e){let t=Date.now();return(e.language==="javascript"||e.language==="typescript")&&ei("deno")?obe(e,t):Gc(t,"wasm","WASM runtime not available for this language")}async function obe(e,t){let n=Vc(J_(),`aiaca-deno-${Date.now()}.${e.language==="typescript"?"ts":"js"}`);Zm(n,e.code);let r=["run"];r.push("--no-prompt"),e.network!=="none"&&r.push("--allow-net");for(let s of e.mounts||[])r.push(`--allow-read=${s.host}`);return r.push(n),new Promise(s=>{let i="",o="",a=W_("deno",r,{stdio:["pipe","pipe","pipe"]});e.stdin&&a.stdin.write(e.stdin),a.stdin.end(),a.stdout.on("data",l=>{i+=l.toString()}),a.stderr.on("data",l=>{o+=l.toString()});let c=setTimeout(()=>a.kill("SIGKILL"),e.timeoutMs||nt.defaultTimeoutMs);a.on("close",l=>{clearTimeout(c);try{SN(n)}catch{}s({success:l===0,exitCode:l??-1,stdout:i,stderr:o,duration:Date.now()-t,runtime:"wasm",timedOut:!1,killed:!1})})})}async function abe(e){let t=Date.now(),n=AN(e.language,e.code),r;if(n.filename){let s=Vc(J_(),`aiaca-proc-${Date.now()}-${n.filename.split("/").pop()}`);Zm(s,n.content),r=n.entrypoint.map(o=>o===n.filename?s:o).join(" ")}else r=`${n.entrypoint.join(" ")} ${JSON.stringify(n.content)}`;return new Promise(s=>{let i="",o="",a=W_(r,[],{shell:!0,env:{...process.env,...e.envVars},cwd:e.workingDir||process.cwd()});e.stdin&&a.stdin.write(e.stdin),a.stdin.end(),a.stdout.on("data",l=>{i+=l.toString()}),a.stderr.on("data",l=>{o+=l.toString()});let c=setTimeout(()=>a.kill("SIGKILL"),e.timeoutMs||nt.defaultTimeoutMs);a.on("close",l=>{clearTimeout(c),s({success:l===0,exitCode:l??-1,stdout:i,stderr:o,duration:Date.now()-t,runtime:"process",timedOut:!1,killed:!1,error:"WARNING: Code ran without sandboxing"})})})}function Gc(e,t,n){return{success:!1,exitCode:-1,stdout:"",stderr:"",duration:Date.now()-e,runtime:t,timedOut:!1,killed:!1,error:n}}async function cbe(e){if(!nt.enabled)return Gc(Date.now(),"none","Sandbox disabled");let t=K_(e.runtime),n;try{t==="docker"||t==="podman"?n=await TN(e,t):t==="gvisor"?n=await sbe(e):t==="wasm"?n=await ibe(e):t==="process"?n=await abe(e):n=Gc(Date.now(),t,"No sandbox runtime available")}catch(r){n=Gc(Date.now(),t,r.message)}return Rn.totalExecutions++,Rn.byRuntime[n.runtime]=(Rn.byRuntime[n.runtime]||0)+1,Rn.byLanguage[e.language]=(Rn.byLanguage[e.language]||0)+1,n.success?Rn.successCount++:Rn.failureCount++,n.timedOut&&Rn.timeoutCount++,Rn.totalDurationMs+=n.duration,Rn.averageDurationMs=Rn.totalDurationMs/Rn.totalExecutions,xN(),tbe({runtime:n.runtime,language:e.language,success:n.success,duration:n.duration,timedOut:n.timedOut,codeLength:e.code.length}),n}function RN(){let e=[],t=0;for(let n of["docker","podman"])if(ei(n))try{let s=Gi(`${n} ps -a --filter "name=aiaca-sb-" --format "{{.Names}}"`,{stdio:"pipe",encoding:"utf-8"}).split(`
1545
- `).filter(Boolean);for(let i of s)try{Gi(`${n} rm -f ${i}`,{stdio:"pipe"}),t++}catch(o){e.push(`${i}: ${o.message}`)}}catch{}return{removed:t,errors:e}}async function PN(e,t){let n=t||K_();if(n!=="docker"&&n!=="podman")return{success:!1,image:"",error:`Cannot pull images for ${n}`};let r=CN(e);try{return Gi(`${n} pull ${r}`,{stdio:"inherit",timeout:3e5}),{success:!0,image:r}}catch(s){return{success:!1,image:r,error:s.message}}}async function lbe(e){let t=[];for(let n of Object.keys(nt.defaultImages)){let r=await PN(n,e);t.push({language:n,success:r.success,image:r.image})}return t}function ube(){return JSON.parse(JSON.stringify(nt))}function dbe(e){nt={...nt,...e}}function fbe(){return JSON.parse(JSON.stringify(Rn))}function pbe(){Rn={totalExecutions:0,byRuntime:{},byLanguage:{},successCount:0,failureCount:0,timeoutCount:0,totalDurationMs:0,averageDurationMs:0,totalMemoryMaxBytes:0},xN()}function mbe(e){let t=e.success?"\u2713":e.timedOut?"\u23F1":"\u2717",n=[];return n.push(`${t} Exec via ${e.runtime} (${e.duration}ms)`),n.push(`Exit: ${e.exitCode}${e.timedOut?" [timeout]":""}${e.killed?" [killed]":""}`),e.error&&n.push(`Error: ${e.error}`),e.containerName&&n.push(`Container: ${e.containerName}`),e.stdout&&(n.push(""),n.push("## stdout"),n.push("```"),n.push(e.stdout.slice(0,5e3)),e.stdout.length>5e3&&n.push(`... (${e.stdout.length-5e3} more chars)`),n.push("```")),e.stderr&&(n.push(""),n.push("## stderr"),n.push("```"),n.push(e.stderr.slice(0,3e3)),n.push("```")),n.join(`
1546
- `)}var Zye,nt,Jv,V_,Xye,OEe,Rn,G_,Q_=w(()=>{"use strict";Zye={enabled:!0,preferredRuntime:"docker",fallbackRuntimes:["podman","gvisor","wasm","process"],defaultTimeoutMs:6e4,defaultMemoryMb:512,defaultCpuShares:1024,defaultPidsLimit:100,defaultNetwork:"none",allowHostNetwork:!1,defaultReadOnlyRoot:!0,dropCapabilities:!0,enableSeccomp:!0,enableAppArmor:!0,defaultImages:{python:"python:3.12-slim",node:"node:22-slim",typescript:"node:22-slim",go:"golang:1.22-alpine",rust:"rust:1.78-slim",java:"openjdk:21-slim",ruby:"ruby:3.3-slim",shell:"alpine:latest",cpp:"gcc:13",csharp:"mcr.microsoft.com/dotnet/sdk:8.0",php:"php:8.3-cli"},pullPolicy:"if_not_present",autoCleanup:!0,cleanupOnExit:!0,enableMetrics:!0,enableAuditLog:!0,enablePersistence:!0},nt={...Zye},Jv=Vc(Yye(),".aiaca","sandbox"),V_=Vc(Jv,"stats.json"),Xye=Vc(Jv,"audit.jsonl"),OEe=Vc(Jv,"history.json");Rn={totalExecutions:0,byRuntime:{},byLanguage:{},successCount:0,failureCount:0,timeoutCount:0,totalDurationMs:0,averageDurationMs:0,totalMemoryMaxBytes:0};ebe();G_=null;nt.cleanupOnExit&&process.on("exit",()=>{if(nt.autoCleanup)try{RN()}catch{}})});var rR={};$(rR,{applySelectedHunks:()=>qbe,approveAll:()=>Bbe,approveHunk:()=>Obe,computeBatch:()=>Vbe,computeDiff:()=>LN,configure:()=>Hbe,getConfig:()=>Ube,getStats:()=>zbe,rejectAll:()=>Nbe,rejectHunk:()=>jbe,renderDiff:()=>Mbe,resetStats:()=>Gbe});import{readFileSync as eR,existsSync as tR,writeFileSync as Z_,mkdirSync as gbe}from"fs";import{join as Kv,extname as hbe}from"path";import{homedir as ybe}from"os";import{createHash as MN}from"crypto";function FN(){gbe(DN,{recursive:!0})}function vbe(){if(tR(X_))try{Yn={...Yn,...JSON.parse(eR(X_,"utf-8"))}}catch{}}function Id(){FN();try{Z_(X_,JSON.stringify(Yn,null,2),"utf-8")}catch{}}function nR(e,t){let n=e.length,r=t.length,s=n+r;if(s===0)return[];let i=new Array(2*s+1).fill(0),o=[];for(let a=0;a<=s;a++){o.push([...i]);for(let c=-a;c<=a;c+=2){let l;c===-a||c!==a&&i[s+c-1]<i[s+c+1]?l=i[s+c+1]:l=i[s+c-1]+1;let u=l-c;for(;l<n&&u<r&&e[l]===t[u];)l++,u++;if(i[s+c]=l,l>=n&&u>=r)return Sbe(e,t,o,a)}}return[]}function Sbe(e,t,n,r){let s=[],i=e.length,o=t.length,a=i+o;for(let c=r;c>0;c--){let l=n[c],u=i-o,d;u===-c||u!==c&&l[a+u-1]<l[a+u+1]?d=u+1:d=u-1;let f=l[a+d],p=f-d;for(;i>f&&o>p;)s.unshift({type:"keep",oldIdx:i-1,newIdx:o-1,line:e[i-1]}),i--,o--;c>0&&(i===f?s.unshift({type:"add",newIdx:o-1,line:t[o-1]}):s.unshift({type:"remove",oldIdx:i-1,line:e[i-1]}),i=f,o=p)}for(;i>0&&o>0;)s.unshift({type:"keep",oldIdx:i-1,newIdx:o-1,line:e[i-1]}),i--,o--;for(;i>0;)s.unshift({type:"remove",oldIdx:i-1,line:e[i-1]}),i--;for(;o>0;)s.unshift({type:"add",newIdx:o-1,line:t[o-1]}),o--;return s}function wbe(e,t,n,r){let s=[],i=0;for(;i<e.length;){for(;i<e.length&&e[i].type==="keep";)i++;if(i>=e.length)break;let o=Math.max(0,i-r),a=i;for(;i<e.length;)if(e[i].type!=="keep")a=i,i++;else{let h=0;for(;i+h<e.length&&e[i+h].type==="keep";)h++;if(h>=2*r)break;i+=h}let c=Math.min(e.length,a+1+r),l=e.slice(o,c),u=0,d=0;for(let h=0;h<o;h++)e[h].type!=="add"&&u++,e[h].type!=="remove"&&d++;let f=l.filter(h=>h.type!=="add").length,p=l.filter(h=>h.type!=="remove").length,g={id:MN("md5").update(`${u}:${d}:${l.length}`).digest("hex").slice(0,12),oldStart:u+1,oldLines:f,newStart:d+1,newLines:p,lines:l.map((h,v)=>({type:h.type==="keep"?"context":h.type==="add"?"add":"remove",oldLine:h.type!=="add"?(h.oldIdx??0)+1:void 0,newLine:h.type!=="remove"?(h.newIdx??0)+1:void 0,text:h.line})),context:"",approved:null,rejected:!1};s.push(g)}return s}function kbe(e,t){let n=Wv(e),r=Wv(t),s=nR(n,r),i=[],o=[],a=0,c=0;for(let l of s)l.type==="keep"?(i.push({type:"unchanged",text:l.line,start:a,end:a+l.line.length}),o.push({type:"unchanged",text:l.line,start:c,end:c+l.line.length}),a+=l.line.length,c+=l.line.length):l.type==="remove"?(i.push({type:"remove",text:l.line,start:a,end:a+l.line.length}),a+=l.line.length):l.type==="add"&&(o.push({type:"add",text:l.line,start:c,end:c+l.line.length}),c+=l.line.length);return{old:i,new:o}}function Wv(e){return e.split(/(\s+|[(){}[\];,.])/g).filter(Boolean)}function $be(e){let t=hbe(e).toLowerCase();return{".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".py":"python",".go":"go",".rs":"rust",".java":"java"}[t]||"plain"}function Cbe(e,t,n){if(!n||t==="plain")return e;let r=xbe[t]||[],s=e;s=s.replace(/(["'`])([^"'`\n]*?)\1/g,`${gr.green}$&${gr.reset}`),t==="python"?s=s.replace(/(#.*$)/,`${gr.gray}$1${gr.reset}`):(s=s.replace(/(\/\/.*$)/,`${gr.gray}$1${gr.reset}`),s=s.replace(/(\/\*[\s\S]*?\*\/)/g,`${gr.gray}$1${gr.reset}`)),s=s.replace(/\b(\d+(?:\.\d+)?)\b/g,`${gr.cyan}$1${gr.reset}`);for(let i of r){let o=new RegExp(`\\b(${i})\\b`,"g");s=s.replace(o,`${gr.magenta}$1${gr.reset}`)}return s}function Abe(e,t,n,r){if(!Pn.enableSemanticAnalysis)return;let s=e.oldStart-1,i=Tbe(t,s,r),o=_be(t,s,r);e.affectedFunction=i,e.affectedClass=o;let a=e.lines.filter(p=>p.type==="add"||p.type==="remove");if(a.length===0){e.changeNature="whitespace",e.riskLevel="safe";return}if(a.every(p=>/^\s*$/.test(p.text))){e.changeNature="whitespace",e.riskLevel="safe";return}let l=r==="python"?/^\s*#/:/^\s*(\/\/|\*|\/\*|\*\/)/;if(a.every(p=>l.test(p.text))){e.changeNature="comment",e.riskLevel="safe";return}if(a.length===2){let p=a.filter(g=>g.type==="add"),m=a.filter(g=>g.type==="remove");if(p.length===1&&m.length===1&&Rbe(p[0].text,m[0].text)>.7){e.changeNature="rename",e.riskLevel="low";return}}e.changeNature="logic";let d=e.oldLines+e.newLines;d>50?e.riskLevel="high":d>20?e.riskLevel="medium":e.riskLevel="low";let f=a.map(p=>p.text).join(`
1547
- `);/\b(auth|token|password|secret|api_key|crypto|jwt)\b/i.test(f)&&(e.riskLevel="high")}function Tbe(e,t,n){for(let r=t;r>=0;r--){let s=e[r];if(s){if(n==="typescript"||n==="javascript"){let i=s.match(/^\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)/)||s.match(/^\s*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\(/)||s.match(/^\s+(?:public|private|protected|static|async)?\s*(\w+)\s*\(/);if(i)return i[1]}else if(n==="python"){let i=s.match(/^\s*(?:async\s+)?def\s+(\w+)/);if(i)return i[1]}else if(n==="go"){let i=s.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);if(i)return i[1]}else if(n==="rust"){let i=s.match(/^\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)/);if(i)return i[1]}}}}function _be(e,t,n){for(let r=t;r>=0;r--){let s=e[r];if(!s)continue;let i=s.match(/^\s*(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface)\s+(\w+)/);if(i)return i[1]}}function Rbe(e,t){let n=new Set(Wv(e)),r=new Set(Wv(t)),s=new Set([...n].filter(o=>r.has(o))).size,i=new Set([...n,...r]).size;return i===0?0:s/i}function Pbe(e,t){if(!Pn.enableConflictPrediction)return[];let n=[];if(tR(e))try{let r=eR(e,"utf-8");if(r!==t){let s=t.split(`
1553
+ \u{1F916} Generated with [AIACA](https://github.com/your-org/aiaca)`,wye={enabled:!0,defaultBaseBranch:"main",enableAIDescription:!0,enableAIResponses:!1,descriptionTemplate:Sye,autoLinkIssues:!0,issuePatterns:["closes\\s+#(\\d+)","fixes\\s+#(\\d+)","resolves\\s+#(\\d+)","#(\\d+)","(?:^|\\s)([A-Z]+-\\d+)"],useCodeowners:!0,fallbackReviewers:[],maxReviewers:3,autoRespondToReviews:!1,autoFixSimpleFeedback:!1,pollIntervalMs:3e4,enablePersistence:!0,retentionCount:100},_n={...wye},N_=zv(vye(),".aiaca","pr-autopilot"),B_=zv(N_,"prs.json"),kye=zv(N_,"activity.jsonl"),Xs=new Map;xye()});var Y_={};$(Y_,{cleanupAll:()=>RN,configure:()=>fbe,detectRuntimes:()=>$N,execute:()=>lbe,formatResult:()=>gbe,getConfig:()=>dbe,getStats:()=>pbe,pullAllImages:()=>ube,pullImage:()=>PN,resetStats:()=>mbe,selectRuntime:()=>K_});import{existsSync as Wye,mkdirSync as Kye,readFileSync as Yye,writeFileSync as Zm,unlinkSync as SN}from"fs";import{join as Vc}from"path";import{homedir as Qye,tmpdir as J_,platform as Zye}from"os";import{execSync as Gi,spawn as W_}from"child_process";import{createHash as wN}from"crypto";function kN(){Kye(Jv,{recursive:!0})}function tbe(){if(Wye(V_))try{Rn={...Rn,...JSON.parse(Yye(V_,"utf-8"))}}catch{}}function xN(){kN();try{Zm(V_,JSON.stringify(Rn,null,2),"utf-8")}catch{}}function nbe(e){if(nt.enableAuditLog){kN();try{Zm(ebe,JSON.stringify({...e,timestamp:Date.now()})+`
1554
+ `,{flag:"a"})}catch{}}}function $N(e=!1){if(G_&&!e)return G_;let t=new Set;return ei("docker")&&t.add("docker"),ei("podman")&&t.add("podman"),ei("runsc")&&t.add("gvisor"),ei("firecracker")&&t.add("firecracker"),(ei("wasmtime")||ei("wasmer")||ei("deno"))&&t.add("wasm"),t.add("process"),G_=t,t}function ei(e){try{return Gi(Zye()==="win32"?`where ${e}`:`which ${e}`,{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}function K_(e){let t=$N(),n=e||nt.preferredRuntime;if(t.has(n))return n;for(let r of nt.fallbackRuntimes)if(t.has(r))return r;return"process"}function CN(e,t){return t||nt.defaultImages[e]||"alpine:latest"}function AN(e,t){switch(e){case"python":return{entrypoint:["python","-c"],content:t};case"node":case"javascript":return{entrypoint:["node","-e"],content:t};case"typescript":return{filename:"/tmp/code.ts",content:t,entrypoint:["npx","tsx","/tmp/code.ts"]};case"go":return{filename:"/tmp/code.go",content:t,entrypoint:["go","run","/tmp/code.go"]};case"rust":return{filename:"/tmp/code.rs",content:t,entrypoint:["rustc","/tmp/code.rs","-o","/tmp/out","&&","/tmp/out"]};case"java":return{filename:"/tmp/Main.java",content:t,entrypoint:["sh","-c","cd /tmp && javac Main.java && java Main"]};case"ruby":return{entrypoint:["ruby","-e"],content:t};case"shell":return{entrypoint:["sh","-c"],content:t};case"cpp":return{filename:"/tmp/code.cpp",content:t,entrypoint:["sh","-c","g++ /tmp/code.cpp -o /tmp/out && /tmp/out"]};case"php":return{entrypoint:["php","-r"],content:t};default:return{entrypoint:["sh","-c"],content:t}}}async function TN(e,t){let n=Date.now(),r=`aiaca-sb-${wN("md5").update(Date.now()+Math.random().toString()).digest("hex").slice(0,12)}`,s=CN(e.language,e.image),i=AN(e.language,e.code);if(nt.pullPolicy==="always"||nt.pullPolicy==="if_not_present"&&!await sbe(t,s))try{Gi(`${t} pull ${s}`,{stdio:"pipe",timeout:12e4})}catch{}let o=["run","--rm","--name",r,"-i"];o.push("--memory",`${e.memoryMb||nt.defaultMemoryMb}m`),o.push("--cpu-shares",String(e.cpuShares||nt.defaultCpuShares)),o.push("--pids-limit",String(e.pidsLimit||nt.defaultPidsLimit));let a=e.network||nt.defaultNetwork;if(a==="none")o.push("--network","none");else if(a==="host"){if(!nt.allowHostNetwork)return Gc(n,t,"Host network not allowed by config");o.push("--network","host")}else o.push("--network","bridge");(e.readOnlyRoot??nt.defaultReadOnlyRoot)&&(o.push("--read-only"),o.push("--tmpfs","/tmp:rw,size=64m")),nt.dropCapabilities&&(o.push("--cap-drop","ALL"),o.push("--security-opt","no-new-privileges")),nt.enableSeccomp&&t==="docker"&&o.push("--security-opt","seccomp=default");for(let c of e.mounts||[]){let l=c.readonly?":ro":":rw";o.push("-v",`${c.host}:${c.container}${l}`)}for(let[c,l]of Object.entries(e.envVars||{}))o.push("-e",`${c}=${l}`);return e.workingDir&&o.push("-w",e.workingDir),o.push("-u","1000:1000"),o.push(s),i.filename?rbe(t,o,i,e,n,r):(o.push(...i.entrypoint,i.content),_N(t,o,e,n,r))}async function rbe(e,t,n,r,s,i){let o=Vc(J_(),`aiaca-sb-${wN("md5").update(Date.now().toString()).digest("hex").slice(0,8)}-${n.filename.split("/").pop()}`);try{Zm(o,n.content);let a=n.filename;return t.push("-v",`${o}:${a}:ro`),t.push(...n.entrypoint),_N(e,t,r,s,i)}finally{try{SN(o)}catch{}}}async function _N(e,t,n,r,s){let i=n.timeoutMs||nt.defaultTimeoutMs;return new Promise(o=>{let a="",c="",l=!1,u=!1,d=W_(e,t,{stdio:["pipe","pipe","pipe"]});n.stdin&&d.stdin.write(n.stdin),d.stdin.end(),d.stdout.on("data",p=>{a+=p.toString().slice(0,1024*1024)}),d.stderr.on("data",p=>{c+=p.toString().slice(0,1024*1024)});let f=setTimeout(()=>{u=!0;try{Gi(`${e} kill ${s}`,{stdio:"pipe"})}catch{}d.kill("SIGKILL"),l=!0},i);d.on("close",p=>{clearTimeout(f);let m=Date.now()-r,g={success:p===0&&!u,exitCode:p??-1,stdout:a,stderr:c,duration:m,runtime:e,containerName:s,timedOut:u,killed:l};try{let h=Gi(`${e} inspect ${s} 2>/dev/null || echo {}`,{stdio:"pipe",encoding:"utf-8"});JSON.parse(h)[0]?.State?.OOMKilled&&(g.error="Container killed due to memory limit")}catch{}if(nt.autoCleanup)try{Gi(`${e} rm -f ${s}`,{stdio:"pipe"})}catch{}o(g)}),d.on("error",p=>{clearTimeout(f),o(Gc(r,e,p.message))})})}async function sbe(e,t){try{return Gi(`${e} image inspect ${t}`,{stdio:"pipe",timeout:1e4}),!0}catch{return!1}}async function ibe(e){if(!ei("docker"))return Gc(Date.now(),"gvisor","gVisor requires Docker with runsc runtime");let t=Date.now();return{...await TN(e,"docker"),runtime:"gvisor"}}async function obe(e){let t=Date.now();return(e.language==="javascript"||e.language==="typescript")&&ei("deno")?abe(e,t):Gc(t,"wasm","WASM runtime not available for this language")}async function abe(e,t){let n=Vc(J_(),`aiaca-deno-${Date.now()}.${e.language==="typescript"?"ts":"js"}`);Zm(n,e.code);let r=["run"];r.push("--no-prompt"),e.network!=="none"&&r.push("--allow-net");for(let s of e.mounts||[])r.push(`--allow-read=${s.host}`);return r.push(n),new Promise(s=>{let i="",o="",a=W_("deno",r,{stdio:["pipe","pipe","pipe"]});e.stdin&&a.stdin.write(e.stdin),a.stdin.end(),a.stdout.on("data",l=>{i+=l.toString()}),a.stderr.on("data",l=>{o+=l.toString()});let c=setTimeout(()=>a.kill("SIGKILL"),e.timeoutMs||nt.defaultTimeoutMs);a.on("close",l=>{clearTimeout(c);try{SN(n)}catch{}s({success:l===0,exitCode:l??-1,stdout:i,stderr:o,duration:Date.now()-t,runtime:"wasm",timedOut:!1,killed:!1})})})}async function cbe(e){let t=Date.now(),n=AN(e.language,e.code),r;if(n.filename){let s=Vc(J_(),`aiaca-proc-${Date.now()}-${n.filename.split("/").pop()}`);Zm(s,n.content),r=n.entrypoint.map(o=>o===n.filename?s:o).join(" ")}else r=`${n.entrypoint.join(" ")} ${JSON.stringify(n.content)}`;return new Promise(s=>{let i="",o="",a=W_(r,[],{shell:!0,env:{...process.env,...e.envVars},cwd:e.workingDir||process.cwd()});e.stdin&&a.stdin.write(e.stdin),a.stdin.end(),a.stdout.on("data",l=>{i+=l.toString()}),a.stderr.on("data",l=>{o+=l.toString()});let c=setTimeout(()=>a.kill("SIGKILL"),e.timeoutMs||nt.defaultTimeoutMs);a.on("close",l=>{clearTimeout(c),s({success:l===0,exitCode:l??-1,stdout:i,stderr:o,duration:Date.now()-t,runtime:"process",timedOut:!1,killed:!1,error:"WARNING: Code ran without sandboxing"})})})}function Gc(e,t,n){return{success:!1,exitCode:-1,stdout:"",stderr:"",duration:Date.now()-e,runtime:t,timedOut:!1,killed:!1,error:n}}async function lbe(e){if(!nt.enabled)return Gc(Date.now(),"none","Sandbox disabled");let t=K_(e.runtime),n;try{t==="docker"||t==="podman"?n=await TN(e,t):t==="gvisor"?n=await ibe(e):t==="wasm"?n=await obe(e):t==="process"?n=await cbe(e):n=Gc(Date.now(),t,"No sandbox runtime available")}catch(r){n=Gc(Date.now(),t,r.message)}return Rn.totalExecutions++,Rn.byRuntime[n.runtime]=(Rn.byRuntime[n.runtime]||0)+1,Rn.byLanguage[e.language]=(Rn.byLanguage[e.language]||0)+1,n.success?Rn.successCount++:Rn.failureCount++,n.timedOut&&Rn.timeoutCount++,Rn.totalDurationMs+=n.duration,Rn.averageDurationMs=Rn.totalDurationMs/Rn.totalExecutions,xN(),nbe({runtime:n.runtime,language:e.language,success:n.success,duration:n.duration,timedOut:n.timedOut,codeLength:e.code.length}),n}function RN(){let e=[],t=0;for(let n of["docker","podman"])if(ei(n))try{let s=Gi(`${n} ps -a --filter "name=aiaca-sb-" --format "{{.Names}}"`,{stdio:"pipe",encoding:"utf-8"}).split(`
1555
+ `).filter(Boolean);for(let i of s)try{Gi(`${n} rm -f ${i}`,{stdio:"pipe"}),t++}catch(o){e.push(`${i}: ${o.message}`)}}catch{}return{removed:t,errors:e}}async function PN(e,t){let n=t||K_();if(n!=="docker"&&n!=="podman")return{success:!1,image:"",error:`Cannot pull images for ${n}`};let r=CN(e);try{return Gi(`${n} pull ${r}`,{stdio:"inherit",timeout:3e5}),{success:!0,image:r}}catch(s){return{success:!1,image:r,error:s.message}}}async function ube(e){let t=[];for(let n of Object.keys(nt.defaultImages)){let r=await PN(n,e);t.push({language:n,success:r.success,image:r.image})}return t}function dbe(){return JSON.parse(JSON.stringify(nt))}function fbe(e){nt={...nt,...e}}function pbe(){return JSON.parse(JSON.stringify(Rn))}function mbe(){Rn={totalExecutions:0,byRuntime:{},byLanguage:{},successCount:0,failureCount:0,timeoutCount:0,totalDurationMs:0,averageDurationMs:0,totalMemoryMaxBytes:0},xN()}function gbe(e){let t=e.success?"\u2713":e.timedOut?"\u23F1":"\u2717",n=[];return n.push(`${t} Exec via ${e.runtime} (${e.duration}ms)`),n.push(`Exit: ${e.exitCode}${e.timedOut?" [timeout]":""}${e.killed?" [killed]":""}`),e.error&&n.push(`Error: ${e.error}`),e.containerName&&n.push(`Container: ${e.containerName}`),e.stdout&&(n.push(""),n.push("## stdout"),n.push("```"),n.push(e.stdout.slice(0,5e3)),e.stdout.length>5e3&&n.push(`... (${e.stdout.length-5e3} more chars)`),n.push("```")),e.stderr&&(n.push(""),n.push("## stderr"),n.push("```"),n.push(e.stderr.slice(0,3e3)),n.push("```")),n.join(`
1556
+ `)}var Xye,nt,Jv,V_,ebe,jEe,Rn,G_,Q_=w(()=>{"use strict";Xye={enabled:!0,preferredRuntime:"docker",fallbackRuntimes:["podman","gvisor","wasm","process"],defaultTimeoutMs:6e4,defaultMemoryMb:512,defaultCpuShares:1024,defaultPidsLimit:100,defaultNetwork:"none",allowHostNetwork:!1,defaultReadOnlyRoot:!0,dropCapabilities:!0,enableSeccomp:!0,enableAppArmor:!0,defaultImages:{python:"python:3.12-slim",node:"node:22-slim",typescript:"node:22-slim",go:"golang:1.22-alpine",rust:"rust:1.78-slim",java:"openjdk:21-slim",ruby:"ruby:3.3-slim",shell:"alpine:latest",cpp:"gcc:13",csharp:"mcr.microsoft.com/dotnet/sdk:8.0",php:"php:8.3-cli"},pullPolicy:"if_not_present",autoCleanup:!0,cleanupOnExit:!0,enableMetrics:!0,enableAuditLog:!0,enablePersistence:!0},nt={...Xye},Jv=Vc(Qye(),".aiaca","sandbox"),V_=Vc(Jv,"stats.json"),ebe=Vc(Jv,"audit.jsonl"),jEe=Vc(Jv,"history.json");Rn={totalExecutions:0,byRuntime:{},byLanguage:{},successCount:0,failureCount:0,timeoutCount:0,totalDurationMs:0,averageDurationMs:0,totalMemoryMaxBytes:0};tbe();G_=null;nt.cleanupOnExit&&process.on("exit",()=>{if(nt.autoCleanup)try{RN()}catch{}})});var rR={};$(rR,{applySelectedHunks:()=>Ube,approveAll:()=>Nbe,approveHunk:()=>jbe,computeBatch:()=>Jbe,computeDiff:()=>LN,configure:()=>zbe,getConfig:()=>Hbe,getStats:()=>Gbe,rejectAll:()=>qbe,rejectHunk:()=>Bbe,renderDiff:()=>Ebe,resetStats:()=>Vbe});import{readFileSync as eR,existsSync as tR,writeFileSync as Z_,mkdirSync as hbe}from"fs";import{join as Kv,extname as ybe}from"path";import{homedir as bbe}from"os";import{createHash as MN}from"crypto";function FN(){hbe(DN,{recursive:!0})}function Sbe(){if(tR(X_))try{Yn={...Yn,...JSON.parse(eR(X_,"utf-8"))}}catch{}}function Id(){FN();try{Z_(X_,JSON.stringify(Yn,null,2),"utf-8")}catch{}}function nR(e,t){let n=e.length,r=t.length,s=n+r;if(s===0)return[];let i=new Array(2*s+1).fill(0),o=[];for(let a=0;a<=s;a++){o.push([...i]);for(let c=-a;c<=a;c+=2){let l;c===-a||c!==a&&i[s+c-1]<i[s+c+1]?l=i[s+c+1]:l=i[s+c-1]+1;let u=l-c;for(;l<n&&u<r&&e[l]===t[u];)l++,u++;if(i[s+c]=l,l>=n&&u>=r)return wbe(e,t,o,a)}}return[]}function wbe(e,t,n,r){let s=[],i=e.length,o=t.length,a=i+o;for(let c=r;c>0;c--){let l=n[c],u=i-o,d;u===-c||u!==c&&l[a+u-1]<l[a+u+1]?d=u+1:d=u-1;let f=l[a+d],p=f-d;for(;i>f&&o>p;)s.unshift({type:"keep",oldIdx:i-1,newIdx:o-1,line:e[i-1]}),i--,o--;c>0&&(i===f?s.unshift({type:"add",newIdx:o-1,line:t[o-1]}):s.unshift({type:"remove",oldIdx:i-1,line:e[i-1]}),i=f,o=p)}for(;i>0&&o>0;)s.unshift({type:"keep",oldIdx:i-1,newIdx:o-1,line:e[i-1]}),i--,o--;for(;i>0;)s.unshift({type:"remove",oldIdx:i-1,line:e[i-1]}),i--;for(;o>0;)s.unshift({type:"add",newIdx:o-1,line:t[o-1]}),o--;return s}function kbe(e,t,n,r){let s=[],i=0;for(;i<e.length;){for(;i<e.length&&e[i].type==="keep";)i++;if(i>=e.length)break;let o=Math.max(0,i-r),a=i;for(;i<e.length;)if(e[i].type!=="keep")a=i,i++;else{let h=0;for(;i+h<e.length&&e[i+h].type==="keep";)h++;if(h>=2*r)break;i+=h}let c=Math.min(e.length,a+1+r),l=e.slice(o,c),u=0,d=0;for(let h=0;h<o;h++)e[h].type!=="add"&&u++,e[h].type!=="remove"&&d++;let f=l.filter(h=>h.type!=="add").length,p=l.filter(h=>h.type!=="remove").length,g={id:MN("md5").update(`${u}:${d}:${l.length}`).digest("hex").slice(0,12),oldStart:u+1,oldLines:f,newStart:d+1,newLines:p,lines:l.map((h,v)=>({type:h.type==="keep"?"context":h.type==="add"?"add":"remove",oldLine:h.type!=="add"?(h.oldIdx??0)+1:void 0,newLine:h.type!=="remove"?(h.newIdx??0)+1:void 0,text:h.line})),context:"",approved:null,rejected:!1};s.push(g)}return s}function xbe(e,t){let n=Wv(e),r=Wv(t),s=nR(n,r),i=[],o=[],a=0,c=0;for(let l of s)l.type==="keep"?(i.push({type:"unchanged",text:l.line,start:a,end:a+l.line.length}),o.push({type:"unchanged",text:l.line,start:c,end:c+l.line.length}),a+=l.line.length,c+=l.line.length):l.type==="remove"?(i.push({type:"remove",text:l.line,start:a,end:a+l.line.length}),a+=l.line.length):l.type==="add"&&(o.push({type:"add",text:l.line,start:c,end:c+l.line.length}),c+=l.line.length);return{old:i,new:o}}function Wv(e){return e.split(/(\s+|[(){}[\];,.])/g).filter(Boolean)}function Cbe(e){let t=ybe(e).toLowerCase();return{".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".py":"python",".go":"go",".rs":"rust",".java":"java"}[t]||"plain"}function Abe(e,t,n){if(!n||t==="plain")return e;let r=$be[t]||[],s=e;s=s.replace(/(["'`])([^"'`\n]*?)\1/g,`${gr.green}$&${gr.reset}`),t==="python"?s=s.replace(/(#.*$)/,`${gr.gray}$1${gr.reset}`):(s=s.replace(/(\/\/.*$)/,`${gr.gray}$1${gr.reset}`),s=s.replace(/(\/\*[\s\S]*?\*\/)/g,`${gr.gray}$1${gr.reset}`)),s=s.replace(/\b(\d+(?:\.\d+)?)\b/g,`${gr.cyan}$1${gr.reset}`);for(let i of r){let o=new RegExp(`\\b(${i})\\b`,"g");s=s.replace(o,`${gr.magenta}$1${gr.reset}`)}return s}function Tbe(e,t,n,r){if(!Pn.enableSemanticAnalysis)return;let s=e.oldStart-1,i=_be(t,s,r),o=Rbe(t,s,r);e.affectedFunction=i,e.affectedClass=o;let a=e.lines.filter(p=>p.type==="add"||p.type==="remove");if(a.length===0){e.changeNature="whitespace",e.riskLevel="safe";return}if(a.every(p=>/^\s*$/.test(p.text))){e.changeNature="whitespace",e.riskLevel="safe";return}let l=r==="python"?/^\s*#/:/^\s*(\/\/|\*|\/\*|\*\/)/;if(a.every(p=>l.test(p.text))){e.changeNature="comment",e.riskLevel="safe";return}if(a.length===2){let p=a.filter(g=>g.type==="add"),m=a.filter(g=>g.type==="remove");if(p.length===1&&m.length===1&&Pbe(p[0].text,m[0].text)>.7){e.changeNature="rename",e.riskLevel="low";return}}e.changeNature="logic";let d=e.oldLines+e.newLines;d>50?e.riskLevel="high":d>20?e.riskLevel="medium":e.riskLevel="low";let f=a.map(p=>p.text).join(`
1557
+ `);/\b(auth|token|password|secret|api_key|crypto|jwt)\b/i.test(f)&&(e.riskLevel="high")}function _be(e,t,n){for(let r=t;r>=0;r--){let s=e[r];if(s){if(n==="typescript"||n==="javascript"){let i=s.match(/^\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)/)||s.match(/^\s*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\(/)||s.match(/^\s+(?:public|private|protected|static|async)?\s*(\w+)\s*\(/);if(i)return i[1]}else if(n==="python"){let i=s.match(/^\s*(?:async\s+)?def\s+(\w+)/);if(i)return i[1]}else if(n==="go"){let i=s.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);if(i)return i[1]}else if(n==="rust"){let i=s.match(/^\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)/);if(i)return i[1]}}}}function Rbe(e,t,n){for(let r=t;r>=0;r--){let s=e[r];if(!s)continue;let i=s.match(/^\s*(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface)\s+(\w+)/);if(i)return i[1]}}function Pbe(e,t){let n=new Set(Wv(e)),r=new Set(Wv(t)),s=new Set([...n].filter(o=>r.has(o))).size,i=new Set([...n,...r]).size;return i===0?0:s/i}function Ibe(e,t){if(!Pn.enableConflictPrediction)return[];let n=[];if(tR(e))try{let r=eR(e,"utf-8");if(r!==t){let s=t.split(`
1548
1558
  `),i=r.split(`
1549
- `),o=nR(s,i),a=0;for(let c of o)c.type!=="keep"&&n.push({start:a,end:a+1,reason:"File modified by external process since last read"}),c.type!=="add"&&a++}}catch{}return n}function LN(e,t,n){if(!Pn.enabled)return{filePath:e,oldContent:n||"",newContent:t,language:"plain",hunks:[],additions:0,deletions:0,totalChanges:0,hasConflicts:!1,conflictRanges:[],createdAt:Date.now(),size:{old:(n||"").length,new:t.length}};if(n===void 0)if(tR(e))try{n=eR(e,"utf-8")}catch{n=""}else n="";let r=$be(e),s=n.split(`
1559
+ `),o=nR(s,i),a=0;for(let c of o)c.type!=="keep"&&n.push({start:a,end:a+1,reason:"File modified by external process since last read"}),c.type!=="add"&&a++}}catch{}return n}function LN(e,t,n){if(!Pn.enabled)return{filePath:e,oldContent:n||"",newContent:t,language:"plain",hunks:[],additions:0,deletions:0,totalChanges:0,hasConflicts:!1,conflictRanges:[],createdAt:Date.now(),size:{old:(n||"").length,new:t.length}};if(n===void 0)if(tR(e))try{n=eR(e,"utf-8")}catch{n=""}else n="";let r=Cbe(e),s=n.split(`
1550
1560
  `),i=t.split(`
1551
- `),o=nR(s,i),a=wbe(o,s,i,Pn.defaultContextLines),c=0,l=0;for(let p of a)for(let m of p.lines)m.type==="add"&&c++,m.type==="remove"&&l++;for(let p of a)Abe(p,s,i,r);if(Pn.enableWordLevelDiff){for(let p of a)for(let m=0;m<p.lines.length-1;m++)if(p.lines[m].type==="remove"&&p.lines[m+1].type==="add"){let g=kbe(p.lines[m].text,p.lines[m+1].text);p.lines[m].intraLineHighlight=g.old,p.lines[m+1].intraLineHighlight=g.new}}if(Pn.highRiskFileGlobs.some(p=>Ibe(e,p))){for(let p of a)p.riskLevel!=="safe"&&(p.riskLevel="high");Yn.highRiskCaught++}let d=Pbe(e,n);d.length>0&&Yn.conflictsDetected++;let f={filePath:e,oldContent:n,newContent:t,language:r,hunks:a,additions:c,deletions:l,totalChanges:c+l,hasConflicts:d.length>0,conflictRanges:d,createdAt:Date.now(),size:{old:n.length,new:t.length}};return Yn.totalDiffs++,Yn.totalHunks+=a.length,Yn.byLanguage[r]=(Yn.byLanguage[r]||0)+1,Id(),f}function Ibe(e,t){if(t==="*"||t==="**")return!0;let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___GLOBSTAR___").replace(/\*/g,"[^/]*").replace(/___GLOBSTAR___/g,".*");return new RegExp(n).test(e)}function Mbe(e,t={}){let n={format:t.format||Pn.defaultFormat,syntaxHighlight:t.syntaxHighlight??Pn.enableSyntaxHighlight,contextLines:t.contextLines||Pn.defaultContextLines,showLineNumbers:t.showLineNumbers!==!1,maxLinesPerHunk:t.maxLinesPerHunk||Pn.defaultMaxLinesPerHunk,maxHunksPerFile:t.maxHunksPerFile||Pn.defaultMaxHunksPerFile,colorize:t.colorize!==!1,showWordLevel:t.showWordLevel??Pn.enableWordLevelDiff,showSemantics:t.showSemantics??Pn.enableSemanticAnalysis};return n.format==="side_by_side"?Dbe(e,n):n.format==="compact"?Fbe(e,n):n.format==="unified"?Lbe(e,n):Ebe(e,n)}function Ebe(e,t){let n=[],r=t.colorize?gr:{reset:"",red:"",green:"",yellow:"",blue:"",cyan:"",gray:"",magenta:"",white:"",bold:"",dim:"",redBg:"",greenBg:""};if(n.push(`${r.bold}${r.cyan}\u2500\u2500\u2500 ${e.filePath} \u2500\u2500\u2500${r.reset}`),n.push(`${r.dim}Language: ${e.language} | +${e.additions} -${e.deletions} | ${e.hunks.length} hunks${r.reset}`),e.hasConflicts){n.push(`${r.yellow}\u26A0\uFE0F CONFLICTS DETECTED: ${e.conflictRanges.length} range(s)${r.reset}`);for(let i of e.conflictRanges.slice(0,3))n.push(`${r.yellow} Lines ${i.start}-${i.end}: ${i.reason}${r.reset}`)}n.push("");let s=e.hunks.slice(0,t.maxHunksPerFile);for(let i=0;i<s.length;i++){let o=s[i],a=o.riskLevel==="high"?"\u{1F534}":o.riskLevel==="medium"?"\u{1F7E1}":o.riskLevel==="low"?"\u{1F7E2}":"\u26AA",c=[];o.affectedClass&&c.push(`class ${o.affectedClass}`),o.affectedFunction&&c.push(`fn ${o.affectedFunction}`);let l=c.length>0?` [${c.join(" > ")}]`:"",u=o.changeNature?` {${o.changeNature}}`:"";n.push(`${r.cyan}@@ Hunk ${i+1}/${s.length} (${o.id}) ${a}${l}${u} @@${r.reset}`),n.push(`${r.cyan}@@ -${o.oldStart},${o.oldLines} +${o.newStart},${o.newLines} @@${r.reset}`);let d=o.lines.slice(0,t.maxLinesPerHunk);for(let f of d){let p=f.type==="add"?"+":f.type==="remove"?"-":" ",m=f.type==="add"?r.green:f.type==="remove"?r.red:r.dim,g=f.text;t.syntaxHighlight&&f.type!=="context"&&(g=Cbe(f.text,e.language,t.colorize));let h=t.showLineNumbers?`${r.gray}${(f.oldLine||"").toString().padStart(4)} ${(f.newLine||"").toString().padStart(4)}${r.reset} `:"";n.push(`${m}${p} ${r.reset}${h}${m}${g}${r.reset}`)}o.lines.length>t.maxLinesPerHunk&&n.push(`${r.dim} ... +${o.lines.length-t.maxLinesPerHunk} more lines (use full mode to see)${r.reset}`),n.push("")}return e.hunks.length>t.maxHunksPerFile&&n.push(`${r.dim}... +${e.hunks.length-t.maxHunksPerFile} more hunks${r.reset}`),n.join(`
1552
- `)}function Dbe(e,t){let n=[],r=t.colorize?gr:{reset:"",red:"",green:"",yellow:"",blue:"",cyan:"",gray:"",magenta:"",white:"",bold:"",dim:"",redBg:"",greenBg:""};n.push(`${r.bold}${r.cyan}\u2500\u2500\u2500 ${e.filePath} \u2500\u2500\u2500${r.reset}`),n.push(`${r.dim}+${e.additions} -${e.deletions} | ${e.hunks.length} hunks${r.reset}`),n.push("");let s=60;for(let i of e.hunks.slice(0,t.maxHunksPerFile)){let o=i.riskLevel==="high"?"\u{1F534}":i.riskLevel==="medium"?"\u{1F7E1}":"\u{1F7E2}";n.push(`${r.cyan}@@ Hunk ${i.id} ${o} ${i.changeNature||""} @@${r.reset}`),n.push(`${r.gray}${"\u2500".repeat(s)}\u252C${"\u2500".repeat(s)}${r.reset}`),n.push(`${r.gray}${"OLD".padEnd(s)}\u2502${"NEW".padEnd(s)}${r.reset}`),n.push(`${r.gray}${"\u2500".repeat(s)}\u253C${"\u2500".repeat(s)}${r.reset}`);let a=[],c=0;for(;c<i.lines.length;){let l=i.lines[c];l.type==="context"?(a.push({left:l,right:l}),c++):l.type==="remove"?c+1<i.lines.length&&i.lines[c+1].type==="add"?(a.push({left:l,right:i.lines[c+1]}),c+=2):(a.push({left:l}),c++):(l.type==="add"&&a.push({right:l}),c++)}for(let l of a.slice(0,t.maxLinesPerHunk)){let u=l.left?IN(l.left.text,s-6):"",d=l.right?IN(l.right.text,s-6):"",f=l.left?.type==="remove"?r.red:r.dim,p=l.right?.type==="add"?r.green:r.dim,m=l.left?.type==="remove"?"-":(l.left," "),g=l.right?.type==="add"?"+":(l.right," ");n.push(`${f}${m} ${u.padEnd(s-2)}${r.reset}\u2502${p}${g} ${d}${r.reset}`)}n.push("")}return n.join(`
1553
- `)}function Fbe(e,t){let n=[];n.push(`${e.filePath}: +${e.additions} -${e.deletions} (${e.hunks.length} hunks)`);for(let r of e.hunks){let s=r.affectedFunction?` ${r.affectedFunction}()`:"";n.push(` Hunk ${r.id} L${r.newStart} ${r.changeNature||"change"}${s}`)}return n.join(`
1554
- `)}function Lbe(e,t){let n=[];n.push(`--- a/${e.filePath}`),n.push(`+++ b/${e.filePath}`);for(let r of e.hunks){n.push(`@@ -${r.oldStart},${r.oldLines} +${r.newStart},${r.newLines} @@`);for(let s of r.lines){let i=s.type==="add"?"+":s.type==="remove"?"-":" ";n.push(`${i}${s.text}`)}}return n.join(`
1555
- `)}function IN(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Obe(e,t){let n=e.hunks.find(r=>r.id===t);return n?(n.approved=!0,n.rejected=!1,Yn.approvedHunks++,Id(),!0):!1}function jbe(e,t){let n=e.hunks.find(r=>r.id===t);return n?(n.rejected=!0,n.approved=!1,Yn.rejectedHunks++,Id(),!0):!1}function Bbe(e){let t=0;for(let n of e.hunks)n.approved=!0,n.rejected=!1,t++;return Yn.approvedHunks+=t,Id(),t}function Nbe(e){let t=0;for(let n of e.hunks)n.approved=!1,n.rejected=!0,t++;return Yn.rejectedHunks+=t,Id(),t}function qbe(e,t={approvedHunkIds:[],createBackup:!0,validateAfter:!1}){let n=new Set(t.approvedHunkIds.length>0?t.approvedHunkIds:e.hunks.filter(a=>a.approved).map(a=>a.id));if(n.size===0)return{success:!1,output:"No hunks approved"};let r;if(t.createBackup&&Pn.enableBackups){FN();let a=`${MN("md5").update(e.filePath+Date.now()).digest("hex").slice(0,12)}.bak`;r=Kv(DN,a);try{Z_(r,e.oldContent,"utf-8")}catch{}}let s=e.oldContent.split(`
1561
+ `),o=nR(s,i),a=kbe(o,s,i,Pn.defaultContextLines),c=0,l=0;for(let p of a)for(let m of p.lines)m.type==="add"&&c++,m.type==="remove"&&l++;for(let p of a)Tbe(p,s,i,r);if(Pn.enableWordLevelDiff){for(let p of a)for(let m=0;m<p.lines.length-1;m++)if(p.lines[m].type==="remove"&&p.lines[m+1].type==="add"){let g=xbe(p.lines[m].text,p.lines[m+1].text);p.lines[m].intraLineHighlight=g.old,p.lines[m+1].intraLineHighlight=g.new}}if(Pn.highRiskFileGlobs.some(p=>Mbe(e,p))){for(let p of a)p.riskLevel!=="safe"&&(p.riskLevel="high");Yn.highRiskCaught++}let d=Ibe(e,n);d.length>0&&Yn.conflictsDetected++;let f={filePath:e,oldContent:n,newContent:t,language:r,hunks:a,additions:c,deletions:l,totalChanges:c+l,hasConflicts:d.length>0,conflictRanges:d,createdAt:Date.now(),size:{old:n.length,new:t.length}};return Yn.totalDiffs++,Yn.totalHunks+=a.length,Yn.byLanguage[r]=(Yn.byLanguage[r]||0)+1,Id(),f}function Mbe(e,t){if(t==="*"||t==="**")return!0;let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___GLOBSTAR___").replace(/\*/g,"[^/]*").replace(/___GLOBSTAR___/g,".*");return new RegExp(n).test(e)}function Ebe(e,t={}){let n={format:t.format||Pn.defaultFormat,syntaxHighlight:t.syntaxHighlight??Pn.enableSyntaxHighlight,contextLines:t.contextLines||Pn.defaultContextLines,showLineNumbers:t.showLineNumbers!==!1,maxLinesPerHunk:t.maxLinesPerHunk||Pn.defaultMaxLinesPerHunk,maxHunksPerFile:t.maxHunksPerFile||Pn.defaultMaxHunksPerFile,colorize:t.colorize!==!1,showWordLevel:t.showWordLevel??Pn.enableWordLevelDiff,showSemantics:t.showSemantics??Pn.enableSemanticAnalysis};return n.format==="side_by_side"?Fbe(e,n):n.format==="compact"?Lbe(e,n):n.format==="unified"?Obe(e,n):Dbe(e,n)}function Dbe(e,t){let n=[],r=t.colorize?gr:{reset:"",red:"",green:"",yellow:"",blue:"",cyan:"",gray:"",magenta:"",white:"",bold:"",dim:"",redBg:"",greenBg:""};if(n.push(`${r.bold}${r.cyan}\u2500\u2500\u2500 ${e.filePath} \u2500\u2500\u2500${r.reset}`),n.push(`${r.dim}Language: ${e.language} | +${e.additions} -${e.deletions} | ${e.hunks.length} hunks${r.reset}`),e.hasConflicts){n.push(`${r.yellow}\u26A0\uFE0F CONFLICTS DETECTED: ${e.conflictRanges.length} range(s)${r.reset}`);for(let i of e.conflictRanges.slice(0,3))n.push(`${r.yellow} Lines ${i.start}-${i.end}: ${i.reason}${r.reset}`)}n.push("");let s=e.hunks.slice(0,t.maxHunksPerFile);for(let i=0;i<s.length;i++){let o=s[i],a=o.riskLevel==="high"?"\u{1F534}":o.riskLevel==="medium"?"\u{1F7E1}":o.riskLevel==="low"?"\u{1F7E2}":"\u26AA",c=[];o.affectedClass&&c.push(`class ${o.affectedClass}`),o.affectedFunction&&c.push(`fn ${o.affectedFunction}`);let l=c.length>0?` [${c.join(" > ")}]`:"",u=o.changeNature?` {${o.changeNature}}`:"";n.push(`${r.cyan}@@ Hunk ${i+1}/${s.length} (${o.id}) ${a}${l}${u} @@${r.reset}`),n.push(`${r.cyan}@@ -${o.oldStart},${o.oldLines} +${o.newStart},${o.newLines} @@${r.reset}`);let d=o.lines.slice(0,t.maxLinesPerHunk);for(let f of d){let p=f.type==="add"?"+":f.type==="remove"?"-":" ",m=f.type==="add"?r.green:f.type==="remove"?r.red:r.dim,g=f.text;t.syntaxHighlight&&f.type!=="context"&&(g=Abe(f.text,e.language,t.colorize));let h=t.showLineNumbers?`${r.gray}${(f.oldLine||"").toString().padStart(4)} ${(f.newLine||"").toString().padStart(4)}${r.reset} `:"";n.push(`${m}${p} ${r.reset}${h}${m}${g}${r.reset}`)}o.lines.length>t.maxLinesPerHunk&&n.push(`${r.dim} ... +${o.lines.length-t.maxLinesPerHunk} more lines (use full mode to see)${r.reset}`),n.push("")}return e.hunks.length>t.maxHunksPerFile&&n.push(`${r.dim}... +${e.hunks.length-t.maxHunksPerFile} more hunks${r.reset}`),n.join(`
1562
+ `)}function Fbe(e,t){let n=[],r=t.colorize?gr:{reset:"",red:"",green:"",yellow:"",blue:"",cyan:"",gray:"",magenta:"",white:"",bold:"",dim:"",redBg:"",greenBg:""};n.push(`${r.bold}${r.cyan}\u2500\u2500\u2500 ${e.filePath} \u2500\u2500\u2500${r.reset}`),n.push(`${r.dim}+${e.additions} -${e.deletions} | ${e.hunks.length} hunks${r.reset}`),n.push("");let s=60;for(let i of e.hunks.slice(0,t.maxHunksPerFile)){let o=i.riskLevel==="high"?"\u{1F534}":i.riskLevel==="medium"?"\u{1F7E1}":"\u{1F7E2}";n.push(`${r.cyan}@@ Hunk ${i.id} ${o} ${i.changeNature||""} @@${r.reset}`),n.push(`${r.gray}${"\u2500".repeat(s)}\u252C${"\u2500".repeat(s)}${r.reset}`),n.push(`${r.gray}${"OLD".padEnd(s)}\u2502${"NEW".padEnd(s)}${r.reset}`),n.push(`${r.gray}${"\u2500".repeat(s)}\u253C${"\u2500".repeat(s)}${r.reset}`);let a=[],c=0;for(;c<i.lines.length;){let l=i.lines[c];l.type==="context"?(a.push({left:l,right:l}),c++):l.type==="remove"?c+1<i.lines.length&&i.lines[c+1].type==="add"?(a.push({left:l,right:i.lines[c+1]}),c+=2):(a.push({left:l}),c++):(l.type==="add"&&a.push({right:l}),c++)}for(let l of a.slice(0,t.maxLinesPerHunk)){let u=l.left?IN(l.left.text,s-6):"",d=l.right?IN(l.right.text,s-6):"",f=l.left?.type==="remove"?r.red:r.dim,p=l.right?.type==="add"?r.green:r.dim,m=l.left?.type==="remove"?"-":(l.left," "),g=l.right?.type==="add"?"+":(l.right," ");n.push(`${f}${m} ${u.padEnd(s-2)}${r.reset}\u2502${p}${g} ${d}${r.reset}`)}n.push("")}return n.join(`
1563
+ `)}function Lbe(e,t){let n=[];n.push(`${e.filePath}: +${e.additions} -${e.deletions} (${e.hunks.length} hunks)`);for(let r of e.hunks){let s=r.affectedFunction?` ${r.affectedFunction}()`:"";n.push(` Hunk ${r.id} L${r.newStart} ${r.changeNature||"change"}${s}`)}return n.join(`
1564
+ `)}function Obe(e,t){let n=[];n.push(`--- a/${e.filePath}`),n.push(`+++ b/${e.filePath}`);for(let r of e.hunks){n.push(`@@ -${r.oldStart},${r.oldLines} +${r.newStart},${r.newLines} @@`);for(let s of r.lines){let i=s.type==="add"?"+":s.type==="remove"?"-":" ";n.push(`${i}${s.text}`)}}return n.join(`
1565
+ `)}function IN(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function jbe(e,t){let n=e.hunks.find(r=>r.id===t);return n?(n.approved=!0,n.rejected=!1,Yn.approvedHunks++,Id(),!0):!1}function Bbe(e,t){let n=e.hunks.find(r=>r.id===t);return n?(n.rejected=!0,n.approved=!1,Yn.rejectedHunks++,Id(),!0):!1}function Nbe(e){let t=0;for(let n of e.hunks)n.approved=!0,n.rejected=!1,t++;return Yn.approvedHunks+=t,Id(),t}function qbe(e){let t=0;for(let n of e.hunks)n.approved=!1,n.rejected=!0,t++;return Yn.rejectedHunks+=t,Id(),t}function Ube(e,t={approvedHunkIds:[],createBackup:!0,validateAfter:!1}){let n=new Set(t.approvedHunkIds.length>0?t.approvedHunkIds:e.hunks.filter(a=>a.approved).map(a=>a.id));if(n.size===0)return{success:!1,output:"No hunks approved"};let r;if(t.createBackup&&Pn.enableBackups){FN();let a=`${MN("md5").update(e.filePath+Date.now()).digest("hex").slice(0,12)}.bak`;r=Kv(DN,a);try{Z_(r,e.oldContent,"utf-8")}catch{}}let s=e.oldContent.split(`
1556
1566
  `),i=[],o=0;for(let a of e.hunks){for(;o<a.oldStart-1;)i.push(s[o]),o++;if(n.has(a.id))for(let c of a.lines)(c.type==="add"||c.type==="context")&&i.push(c.text),(c.type==="remove"||c.type==="context")&&o++;else{let c=a.oldStart-1+a.oldLines;for(;o<c;)i.push(s[o]),o++}}for(;o<s.length;)i.push(s[o]),o++;try{return Z_(e.filePath,i.join(`
1557
- `),"utf-8"),{success:!0,output:`Applied ${n.size}/${e.hunks.length} hunks to ${e.filePath}`,backupPath:r}}catch(a){return{success:!1,output:`Failed to write: ${a.message}`,backupPath:r}}}function Ube(){return{...Pn}}function Hbe(e){Pn={...Pn,...e}}function zbe(){return JSON.parse(JSON.stringify(Yn))}function Gbe(){Yn={totalDiffs:0,totalHunks:0,approvedHunks:0,rejectedHunks:0,bypassed:0,conflictsDetected:0,highRiskCaught:0,byLanguage:{}},Id()}function Vbe(e){let t=[];for(let o of e)t.push(LN(o.filePath,o.newContent,o.oldContent));let n=t.reduce((o,a)=>o+a.additions,0),r=t.reduce((o,a)=>o+a.deletions,0),s=t.reduce((o,a)=>o+a.hunks.length,0),i=t.filter(o=>o.hunks.some(a=>a.riskLevel==="high")).map(o=>o.filePath);return{files:t,totalAdditions:n,totalDeletions:r,totalHunks:s,highRiskFiles:i}}var bbe,Pn,EN,DN,X_,Yn,gr,xbe,sR=w(()=>{"use strict";bbe={enabled:!0,defaultFormat:"inline",defaultContextLines:3,defaultMaxLinesPerHunk:100,defaultMaxHunksPerFile:30,enableSyntaxHighlight:!0,enableSemanticAnalysis:!0,enableConflictPrediction:!0,enableWordLevelDiff:!0,enableBackups:!0,highRiskFileGlobs:["**/migrations/**","**/.github/workflows/**","**/Dockerfile*","**/.env*","**/auth/**","**/security/**"],largeChangeThreshold:100},Pn={...bbe},EN=Kv(ybe(),".aiaca","diff-preview"),DN=Kv(EN,"backups"),X_=Kv(EN,"stats.json");Yn={totalDiffs:0,totalHunks:0,approvedHunks:0,rejectedHunks:0,bypassed:0,conflictsDetected:0,highRiskCaught:0,byLanguage:{}};vbe();gr={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",white:"\x1B[37m",redBg:"\x1B[41m",greenBg:"\x1B[42m",bold:"\x1B[1m",dim:"\x1B[2m"},xbe={typescript:["function","const","let","var","class","interface","type","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","async","await","import","export","from","as","extends","implements","public","private","protected","static","readonly","new","this","super"],javascript:["function","const","let","var","class","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","async","await","import","export","from","as","extends","new","this","super"],python:["def","class","if","elif","else","for","while","return","import","from","as","try","except","finally","raise","with","pass","break","continue","global","nonlocal","lambda","yield","async","await","self","None","True","False"],go:["package","import","func","var","const","type","struct","interface","if","else","for","switch","case","return","break","continue","go","defer","select","chan","map","range"],rust:["fn","let","mut","const","static","struct","enum","trait","impl","pub","use","mod","if","else","match","for","while","loop","return","break","continue","self","Self","where","async","await"],java:["public","private","protected","class","interface","extends","implements","static","final","abstract","void","return","if","else","for","while","do","switch","case","try","catch","finally","throw","new","this","super","package","import"]}});var aR={};$(aR,{buildIndex:()=>Zv,clearCache:()=>Tve,clearIndex:()=>Ave,configure:()=>Cve,formatResults:()=>Pve,getConfig:()=>$ve,getCurrentProject:()=>Rve,getStats:()=>xve,isIndexed:()=>_ve,loadProject:()=>oR,parseQuery:()=>qN,search:()=>Sve});import{existsSync as ON,mkdirSync as Jbe,readFileSync as jN,writeFileSync as Wbe,statSync as BN}from"fs";import{join as eg,extname as Kbe,relative as Ybe}from"path";import{homedir as Qbe}from"os";import{createHash as iR}from"crypto";import{glob as Zbe}from"glob";function tve(e){return iR("sha256").update(e).digest("hex").slice(0,16)}function Yv(e){return eg(eve,tve(e))}function NN(e){Jbe(Yv(e),{recursive:!0})}function sve(e,t={}){let n=e.toLowerCase().replace(/[^\w\s'-]/g," ").split(/\s+/).filter(Boolean),r=[];for(let s of n){if(r.push(s),/[A-Z]/.test(s)){let i=s.split(/(?=[A-Z])/).map(o=>o.toLowerCase());r.push(...i.filter(o=>o.length>1))}s.includes("_")&&r.push(...s.split("_").filter(i=>i.length>1))}return t.keepStopwords?r.filter(s=>s.length>0):r.filter(s=>s.length>1&&!nve.has(s)&&!rve.has(s))}function ive(e){let t=e.split(/[^\w]+/).filter(Boolean),n=[];for(let r of t){if(n.push(r.toLowerCase()),/[A-Z]/.test(r)){let s=r.split(/(?=[A-Z])/).map(i=>i.toLowerCase());n.push(...s.filter(i=>i.length>1))}r.includes("_")&&n.push(...r.split("_").map(s=>s.toLowerCase()).filter(s=>s.length>1))}return n.filter(r=>r.length>1)}function ave(e){if(!rt.enableSynonymExpansion)return e;let t=new Set(e);for(let n of e){let r=ove[n];if(r)for(let s of r)t.add(s)}return Array.from(t)}function cve(e){if(!rt.enableIntentDetection)return"general";let t=e.toLowerCase();return/\b(where\s+is|where\s+does|where.*defined)\b/.test(t)?"where_is":/\b(how\s+(?:does|do|to|is)|how\s+.+\s+work)\b/.test(t)?"how_does":/\b(what\s+calls|callers?\s+of|who\s+uses?)\b/.test(t)?"find_caller":/\b(definition|defined|declared)\b/.test(t)?"find_definition":/\b(example|usage|how.*use)\b/.test(t)?"find_usage":/\b(test|spec|unit\s*test)\b/.test(t)?"find_test":/\b(config|configured?|setting|env\s+var)\b/.test(t)?"find_config":/\b(bug|error\s+handling|exception)\b/.test(t)?"find_bug":/\b(find|search|locate|show)\b/.test(t)?"find_pattern":"general"}function lve(e){if(!rt.enableEntityExtraction)return[];let t=[];for(let n of e.matchAll(/\b([A-Z][a-zA-Z0-9]+)\b/g))t.push(n[1]);for(let n of e.matchAll(/\b([a-z]+[A-Z][a-zA-Z0-9]*)\b/g))t.push(n[1]);for(let n of e.matchAll(/\b([a-z]+_[a-z_]+)\b/g))t.push(n[1]);for(let n of e.matchAll(/['"]([^'"]+)['"]/g))t.push(n[1]);for(let n of e.matchAll(/[\w.-]+\.\w{2,4}/g))t.push(n[0]);return[...new Set(t)]}function qN(e){let t=cve(e),n=lve(e),r=sve(e,{keepStopwords:!1}),s=ave(r),i={},o=e.toLowerCase();/\bin\s+(typescript|ts)\b/.test(o)?i.language="typescript":/\bin\s+(javascript|js)\b/.test(o)?i.language="javascript":/\bin\s+python\b/.test(o)?i.language="python":/\bin\s+go\b/.test(o)?i.language="go":/\bin\s+rust\b/.test(o)&&(i.language="rust"),/\b(test|spec)s?\b/.test(o)?i.onlyTests=!0:/\bnot.*test\b/.test(o)&&(i.excludeTests=!0);let a=e.match(/in\s+([a-z*\/.-]+\*[a-z*\/.-]+)/i);return a&&(i.fileGlob=a[1]),{raw:e,intent:t,entities:n,keywords:r,filters:i,expandedTerms:s}}function uve(e){let t=Kbe(e).toLowerCase();return{".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".rb":"ruby",".php":"php",".cs":"csharp",".html":"html",".css":"css",".scss":"scss"}[t]||"plain"}function dve(e,t){let n=new Set,s={typescript:[/(?:function|class|interface|type|enum)\s+(\w+)/g,/(?:const|let|var)\s+(\w+)\s*[:=]/g,/(?:public|private|protected)?\s+(?:async\s+)?(\w+)\s*\(/g],javascript:[/(?:function|class)\s+(\w+)/g,/(?:const|let|var)\s+(\w+)\s*=/g],python:[/(?:def|class)\s+(\w+)/g],go:[/(?:func|type)\s+(?:\([^)]+\)\s+)?(\w+)/g],rust:[/(?:fn|struct|enum|trait|impl)\s+(\w+)/g],java:[/(?:class|interface|enum)\s+(\w+)/g,/(?:public|private|protected)\s+(?:static\s+)?[\w<>,\s]+\s+(\w+)\s*\(/g]}[t]||[];for(let i of s){let o=new RegExp(i.source,i.flags),a;for(;(a=o.exec(e))!==null;)n.add(a[1])}return Array.from(n)}function fve(e,t){let n=new Set;if(t==="typescript"||t==="javascript")for(let r of e.matchAll(/(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g))n.add(r[1]);else if(t==="python")for(let r of e.matchAll(/(?:from|import)\s+([\w.]+)/g))n.add(r[1]);else if(t==="go")for(let r of e.matchAll(/import\s+"([^"]+)"/g))n.add(r[1]);return Array.from(n)}function pve(e,t,n){let r=t.split(`
1567
+ `),"utf-8"),{success:!0,output:`Applied ${n.size}/${e.hunks.length} hunks to ${e.filePath}`,backupPath:r}}catch(a){return{success:!1,output:`Failed to write: ${a.message}`,backupPath:r}}}function Hbe(){return{...Pn}}function zbe(e){Pn={...Pn,...e}}function Gbe(){return JSON.parse(JSON.stringify(Yn))}function Vbe(){Yn={totalDiffs:0,totalHunks:0,approvedHunks:0,rejectedHunks:0,bypassed:0,conflictsDetected:0,highRiskCaught:0,byLanguage:{}},Id()}function Jbe(e){let t=[];for(let o of e)t.push(LN(o.filePath,o.newContent,o.oldContent));let n=t.reduce((o,a)=>o+a.additions,0),r=t.reduce((o,a)=>o+a.deletions,0),s=t.reduce((o,a)=>o+a.hunks.length,0),i=t.filter(o=>o.hunks.some(a=>a.riskLevel==="high")).map(o=>o.filePath);return{files:t,totalAdditions:n,totalDeletions:r,totalHunks:s,highRiskFiles:i}}var vbe,Pn,EN,DN,X_,Yn,gr,$be,sR=w(()=>{"use strict";vbe={enabled:!0,defaultFormat:"inline",defaultContextLines:3,defaultMaxLinesPerHunk:100,defaultMaxHunksPerFile:30,enableSyntaxHighlight:!0,enableSemanticAnalysis:!0,enableConflictPrediction:!0,enableWordLevelDiff:!0,enableBackups:!0,highRiskFileGlobs:["**/migrations/**","**/.github/workflows/**","**/Dockerfile*","**/.env*","**/auth/**","**/security/**"],largeChangeThreshold:100},Pn={...vbe},EN=Kv(bbe(),".aiaca","diff-preview"),DN=Kv(EN,"backups"),X_=Kv(EN,"stats.json");Yn={totalDiffs:0,totalHunks:0,approvedHunks:0,rejectedHunks:0,bypassed:0,conflictsDetected:0,highRiskCaught:0,byLanguage:{}};Sbe();gr={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",white:"\x1B[37m",redBg:"\x1B[41m",greenBg:"\x1B[42m",bold:"\x1B[1m",dim:"\x1B[2m"},$be={typescript:["function","const","let","var","class","interface","type","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","async","await","import","export","from","as","extends","implements","public","private","protected","static","readonly","new","this","super"],javascript:["function","const","let","var","class","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","async","await","import","export","from","as","extends","new","this","super"],python:["def","class","if","elif","else","for","while","return","import","from","as","try","except","finally","raise","with","pass","break","continue","global","nonlocal","lambda","yield","async","await","self","None","True","False"],go:["package","import","func","var","const","type","struct","interface","if","else","for","switch","case","return","break","continue","go","defer","select","chan","map","range"],rust:["fn","let","mut","const","static","struct","enum","trait","impl","pub","use","mod","if","else","match","for","while","loop","return","break","continue","self","Self","where","async","await"],java:["public","private","protected","class","interface","extends","implements","static","final","abstract","void","return","if","else","for","while","do","switch","case","try","catch","finally","throw","new","this","super","package","import"]}});var aR={};$(aR,{buildIndex:()=>Zv,clearCache:()=>_ve,clearIndex:()=>Tve,configure:()=>Ave,formatResults:()=>Ive,getConfig:()=>Cve,getCurrentProject:()=>Pve,getStats:()=>$ve,isIndexed:()=>Rve,loadProject:()=>oR,parseQuery:()=>qN,search:()=>wve});import{existsSync as ON,mkdirSync as Wbe,readFileSync as jN,writeFileSync as Kbe,statSync as BN}from"fs";import{join as eg,extname as Ybe,relative as Qbe}from"path";import{homedir as Zbe}from"os";import{createHash as iR}from"crypto";import{glob as Xbe}from"glob";function nve(e){return iR("sha256").update(e).digest("hex").slice(0,16)}function Yv(e){return eg(tve,nve(e))}function NN(e){Wbe(Yv(e),{recursive:!0})}function ive(e,t={}){let n=e.toLowerCase().replace(/[^\w\s'-]/g," ").split(/\s+/).filter(Boolean),r=[];for(let s of n){if(r.push(s),/[A-Z]/.test(s)){let i=s.split(/(?=[A-Z])/).map(o=>o.toLowerCase());r.push(...i.filter(o=>o.length>1))}s.includes("_")&&r.push(...s.split("_").filter(i=>i.length>1))}return t.keepStopwords?r.filter(s=>s.length>0):r.filter(s=>s.length>1&&!rve.has(s)&&!sve.has(s))}function ove(e){let t=e.split(/[^\w]+/).filter(Boolean),n=[];for(let r of t){if(n.push(r.toLowerCase()),/[A-Z]/.test(r)){let s=r.split(/(?=[A-Z])/).map(i=>i.toLowerCase());n.push(...s.filter(i=>i.length>1))}r.includes("_")&&n.push(...r.split("_").map(s=>s.toLowerCase()).filter(s=>s.length>1))}return n.filter(r=>r.length>1)}function cve(e){if(!rt.enableSynonymExpansion)return e;let t=new Set(e);for(let n of e){let r=ave[n];if(r)for(let s of r)t.add(s)}return Array.from(t)}function lve(e){if(!rt.enableIntentDetection)return"general";let t=e.toLowerCase();return/\b(where\s+is|where\s+does|where.*defined)\b/.test(t)?"where_is":/\b(how\s+(?:does|do|to|is)|how\s+.+\s+work)\b/.test(t)?"how_does":/\b(what\s+calls|callers?\s+of|who\s+uses?)\b/.test(t)?"find_caller":/\b(definition|defined|declared)\b/.test(t)?"find_definition":/\b(example|usage|how.*use)\b/.test(t)?"find_usage":/\b(test|spec|unit\s*test)\b/.test(t)?"find_test":/\b(config|configured?|setting|env\s+var)\b/.test(t)?"find_config":/\b(bug|error\s+handling|exception)\b/.test(t)?"find_bug":/\b(find|search|locate|show)\b/.test(t)?"find_pattern":"general"}function uve(e){if(!rt.enableEntityExtraction)return[];let t=[];for(let n of e.matchAll(/\b([A-Z][a-zA-Z0-9]+)\b/g))t.push(n[1]);for(let n of e.matchAll(/\b([a-z]+[A-Z][a-zA-Z0-9]*)\b/g))t.push(n[1]);for(let n of e.matchAll(/\b([a-z]+_[a-z_]+)\b/g))t.push(n[1]);for(let n of e.matchAll(/['"]([^'"]+)['"]/g))t.push(n[1]);for(let n of e.matchAll(/[\w.-]+\.\w{2,4}/g))t.push(n[0]);return[...new Set(t)]}function qN(e){let t=lve(e),n=uve(e),r=ive(e,{keepStopwords:!1}),s=cve(r),i={},o=e.toLowerCase();/\bin\s+(typescript|ts)\b/.test(o)?i.language="typescript":/\bin\s+(javascript|js)\b/.test(o)?i.language="javascript":/\bin\s+python\b/.test(o)?i.language="python":/\bin\s+go\b/.test(o)?i.language="go":/\bin\s+rust\b/.test(o)&&(i.language="rust"),/\b(test|spec)s?\b/.test(o)?i.onlyTests=!0:/\bnot.*test\b/.test(o)&&(i.excludeTests=!0);let a=e.match(/in\s+([a-z*\/.-]+\*[a-z*\/.-]+)/i);return a&&(i.fileGlob=a[1]),{raw:e,intent:t,entities:n,keywords:r,filters:i,expandedTerms:s}}function dve(e){let t=Ybe(e).toLowerCase();return{".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".rb":"ruby",".php":"php",".cs":"csharp",".html":"html",".css":"css",".scss":"scss"}[t]||"plain"}function fve(e,t){let n=new Set,s={typescript:[/(?:function|class|interface|type|enum)\s+(\w+)/g,/(?:const|let|var)\s+(\w+)\s*[:=]/g,/(?:public|private|protected)?\s+(?:async\s+)?(\w+)\s*\(/g],javascript:[/(?:function|class)\s+(\w+)/g,/(?:const|let|var)\s+(\w+)\s*=/g],python:[/(?:def|class)\s+(\w+)/g],go:[/(?:func|type)\s+(?:\([^)]+\)\s+)?(\w+)/g],rust:[/(?:fn|struct|enum|trait|impl)\s+(\w+)/g],java:[/(?:class|interface|enum)\s+(\w+)/g,/(?:public|private|protected)\s+(?:static\s+)?[\w<>,\s]+\s+(\w+)\s*\(/g]}[t]||[];for(let i of s){let o=new RegExp(i.source,i.flags),a;for(;(a=o.exec(e))!==null;)n.add(a[1])}return Array.from(n)}function pve(e,t){let n=new Set;if(t==="typescript"||t==="javascript")for(let r of e.matchAll(/(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g))n.add(r[1]);else if(t==="python")for(let r of e.matchAll(/(?:from|import)\s+([\w.]+)/g))n.add(r[1]);else if(t==="go")for(let r of e.matchAll(/import\s+"([^"]+)"/g))n.add(r[1]);return Array.from(n)}function mve(e,t,n){let r=t.split(`
1558
1568
  `),s=[];for(let i=0;i<r.length;i+=rt.chunkSize-rt.chunkOverlap){let o=Math.min(i+rt.chunkSize,r.length),a=r.slice(i,o).join(`
1559
- `);if(!a.trim())continue;let c=ive(a),l=dve(a,n),u=fve(a,n),d=iR("sha256").update(`${e}:${i}:${a.slice(0,100)}`).digest("hex").slice(0,16),f=new Map;for(let h of c)f.set(h,(f.get(h)||0)+1);let p=Math.max(...f.values(),1),m=new Map;for(let[h,v]of f)m.set(h,v/p);let g;try{g=BN(e)}catch{g={mtimeMs:Date.now(),size:a.length}}if(s.push({id:d,filePath:e,relativePath:Xm?Ybe(Xm,e):e,language:n,startLine:i+1,endLine:o,content:a,tokens:c,vector:m,symbols:l,imports:u,hash:iR("md5").update(a).digest("hex").slice(0,16),size:a.length,modifiedAt:g.mtimeMs}),o>=r.length)break}return s}async function Zv(e){let t=Date.now(),n=e.projectPath;Xm=n,NN(n),e.forceFullReindex?(It.clear(),Cr.clear(),ti.clear(),In.clear()):UN(n);let r=new Set;for(let a of rt.filePatterns)try{let c=await Zbe(a,{cwd:n,absolute:!0,ignore:rt.ignorePatterns,nodir:!0});for(let l of c)r.add(l)}catch{}let s=[];for(let a of r)try{let c=BN(a);if(c.size>rt.maxFileSize)continue;let l=Cr.get(a);(!l||l.some(u=>{let d=It.get(u);return!d||d.modifiedAt<c.mtimeMs}))&&s.push(a)}catch{}for(let a of Cr.keys())if(!r.has(a)){let c=Cr.get(a)||[];for(let l of c){let u=It.get(l);if(u)for(let d of u.symbols){let p=(In.get(d)||[]).filter(m=>m!==l);p.length===0?In.delete(d):In.set(d,p)}It.delete(l)}Cr.delete(a)}let i=0;for(let a of s){e.onProgress?.(++i,s.length);let c=Cr.get(a)||[];for(let p of c){let m=It.get(p);if(m)for(let g of m.symbols){let v=(In.get(g)||[]).filter(y=>y!==p);v.length===0?In.delete(g):In.set(g,v)}It.delete(p)}let l;try{l=jN(a,"utf-8")}catch{continue}let u=uve(a);if(u==="plain")continue;let d=pve(a,l,u),f=[];for(let p of d){It.set(p.id,p),f.push(p.id);for(let m of p.symbols)In.has(m)||In.set(m,[]),In.get(m).push(p.id)}Cr.set(a,f)}ti.clear();let o=0;for(let a of It.values()){let c=new Set;o+=a.tokens.length;for(let l of a.tokens)c.has(l)||(c.add(l),ti.set(l,(ti.get(l)||0)+1))}return Qv=It.size>0?o/It.size:0,rt.enablePersistence&&mve(n),HN(Date.now()-t)}function mve(e){NN(e);try{let t={chunks:Array.from(It.values()).map(n=>({...n,vector:Array.from(n.vector.entries())})),avgChunkLength:Qv,documentFreq:Array.from(ti.entries())};Wbe(eg(Yv(e),"index.json"),JSON.stringify(t),"utf-8")}catch{}}function UN(e){let t=eg(Yv(e),"index.json");if(ON(t))try{let n=JSON.parse(jN(t,"utf-8"));It.clear(),Cr.clear(),In.clear();for(let r of n.chunks||[]){let s={...r,vector:new Map(r.vector||[])};It.set(s.id,s),Cr.has(s.filePath)||Cr.set(s.filePath,[]),Cr.get(s.filePath).push(s.id);for(let i of s.symbols)In.has(i)||In.set(i,[]),In.get(i).push(s.id)}Qv=n.avgChunkLength||0,ti.clear();for(let[r,s]of n.documentFreq||[])ti.set(r,s)}catch{}}function gve(e,t){let n=rt.bm25K1,r=rt.bm25B,s=t.tokens.length,i=It.size,o=new Map;for(let c of t.tokens)o.set(c,(o.get(c)||0)+1);let a=0;for(let c of e){let l=o.get(c)||0;if(l===0)continue;let u=ti.get(c)||1,d=Math.log((i-u+.5)/(u+.5)+1);a+=d*(l*(n+1))/(l+n*(1-r+r*(s/Math.max(1,Qv))))}return a}function hve(e,t){let n=0,r=0,s=0;for(let i of e.values())r+=i*i;for(let i of t.values())s+=i*i;for(let[i,o]of e){let a=t.get(i);a&&(n+=o*a)}return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function yve(e,t){let n=[],r=1,s=e.content.toLowerCase();return(t.intent==="find_definition"||t.intent==="where_is")&&/(?:function|class|def|fn|interface|type|enum|struct)\s+\w+/.test(e.content)&&(r*=1.5,n.push("contains definition")),t.intent==="find_test"||t.filters.onlyTests?(/(?:test|spec|describe|it\(|expect\()/.test(s)||/\.test\.|\.spec\.|test_/.test(e.relativePath))&&(r*=1.5,n.push("test file")):t.filters.excludeTests&&/\.test\.|\.spec\.|test_/.test(e.relativePath)&&(r*=.3,n.push("test file (deboosted)")),t.intent==="find_config"&&(/config|setting|env|process\.env/.test(s)||/config|\.env|settings/.test(e.relativePath))&&(r*=1.4,n.push("config-related")),(t.intent==="find_bug"||t.intent==="find_caller")&&/try\s*{|catch|except|raise|throw|panic/.test(e.content)&&(r*=1.3,n.push("error handling")),t.intent==="how_does"&&e.content.length>500&&(r*=1.1,n.push("substantial context")),{boost:r,reasons:n}}function bve(e,t){let n=[],r=0;for(let s of t.entities)e.symbols.includes(s)?(r+=rt.symbolMatchBoost,n.push(`symbol "${s}"`)):e.content.includes(s)&&(r+=rt.symbolMatchBoost*.5,n.push(`mentions "${s}"`));return{score:r,reasons:n}}function vve(e){let t=(Date.now()-e.modifiedAt)/864e5;return Math.max(.5,1-Math.log(1+t)/Math.log(1+rt.recencyBoostDays))}function Sve(e){if(!rt.enabled||It.size===0)return[];let t=JSON.stringify(e);if(rt.enableCache){let d=Jc.get(t);if(d&&Date.now()-d.cachedAt<rt.cacheTTLMs)return d.results}let n=qN(e.query),r=n.expandedTerms;if(r.length===0)return[];let s=new Map;for(let d of r)s.set(d,(s.get(d)||0)+1);let i=new Map,o=It.size;for(let[d,f]of s){let p=ti.get(d)||1,m=Math.log((o+1)/(p+1))+1;i.set(d,f*m)}let a=new Set;for(let d of r)for(let[f,p]of It)p.tokens.includes(d)&&a.add(f);for(let d of n.entities){let f=In.get(d)||[];for(let p of f)a.add(p);for(let[p,m]of In)if(p.toLowerCase()===d.toLowerCase())for(let g of m)a.add(g)}let c=[],l=e.minScore??rt.minScore;for(let d of a){let f=It.get(d);if(!f||e.language&&f.language!==e.language||n.filters.language&&f.language!==n.filters.language||e.fileGlob&&!wve(f.relativePath,e.fileGlob))continue;let p=hve(i,f.vector),m=gve(r,f),g=yve(f,n),h=bve(f,n),v=vve(f),y=(p*1+Math.min(1,m/10)*1.5+h.score)*g.boost*(.7+.3*v);if(y<l)continue;let b="semantic";h.score>=rt.symbolMatchBoost?b="symbol":p>.7?b="exact":m<1&&(b="fuzzy");let k=[...g.reasons,...h.reasons];c.push({chunk:e.includeContent===!1?{...f,content:f.content.slice(0,200)}:f,score:y,matchType:b,matchReasons:k,snippet:kve(f.content,r,n.entities),scoreBreakdown:{tfidf:p,bm25:m,symbolMatch:h.score,intentBoost:g.boost,recencyBoost:v,totalScore:y}})}c.sort((d,f)=>f.score-d.score);let u=c.slice(0,e.limit||rt.defaultLimit);if(rt.enableCache&&(Jc.set(t,{results:u,cachedAt:Date.now()}),Jc.size>100)){let d=[...Jc.entries()].sort((f,p)=>f[1].cachedAt-p[1].cachedAt)[0];d&&Jc.delete(d[0])}return u}function wve(e,t){let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___GLOBSTAR___").replace(/\*/g,"[^/]*").replace(/___GLOBSTAR___/g,".*");return new RegExp(n).test(e)}function kve(e,t,n){let r=e.split(`
1569
+ `);if(!a.trim())continue;let c=ove(a),l=fve(a,n),u=pve(a,n),d=iR("sha256").update(`${e}:${i}:${a.slice(0,100)}`).digest("hex").slice(0,16),f=new Map;for(let h of c)f.set(h,(f.get(h)||0)+1);let p=Math.max(...f.values(),1),m=new Map;for(let[h,v]of f)m.set(h,v/p);let g;try{g=BN(e)}catch{g={mtimeMs:Date.now(),size:a.length}}if(s.push({id:d,filePath:e,relativePath:Xm?Qbe(Xm,e):e,language:n,startLine:i+1,endLine:o,content:a,tokens:c,vector:m,symbols:l,imports:u,hash:iR("md5").update(a).digest("hex").slice(0,16),size:a.length,modifiedAt:g.mtimeMs}),o>=r.length)break}return s}async function Zv(e){let t=Date.now(),n=e.projectPath;Xm=n,NN(n),e.forceFullReindex?(It.clear(),Cr.clear(),ti.clear(),In.clear()):UN(n);let r=new Set;for(let a of rt.filePatterns)try{let c=await Xbe(a,{cwd:n,absolute:!0,ignore:rt.ignorePatterns,nodir:!0});for(let l of c)r.add(l)}catch{}let s=[];for(let a of r)try{let c=BN(a);if(c.size>rt.maxFileSize)continue;let l=Cr.get(a);(!l||l.some(u=>{let d=It.get(u);return!d||d.modifiedAt<c.mtimeMs}))&&s.push(a)}catch{}for(let a of Cr.keys())if(!r.has(a)){let c=Cr.get(a)||[];for(let l of c){let u=It.get(l);if(u)for(let d of u.symbols){let p=(In.get(d)||[]).filter(m=>m!==l);p.length===0?In.delete(d):In.set(d,p)}It.delete(l)}Cr.delete(a)}let i=0;for(let a of s){e.onProgress?.(++i,s.length);let c=Cr.get(a)||[];for(let p of c){let m=It.get(p);if(m)for(let g of m.symbols){let v=(In.get(g)||[]).filter(y=>y!==p);v.length===0?In.delete(g):In.set(g,v)}It.delete(p)}let l;try{l=jN(a,"utf-8")}catch{continue}let u=dve(a);if(u==="plain")continue;let d=mve(a,l,u),f=[];for(let p of d){It.set(p.id,p),f.push(p.id);for(let m of p.symbols)In.has(m)||In.set(m,[]),In.get(m).push(p.id)}Cr.set(a,f)}ti.clear();let o=0;for(let a of It.values()){let c=new Set;o+=a.tokens.length;for(let l of a.tokens)c.has(l)||(c.add(l),ti.set(l,(ti.get(l)||0)+1))}return Qv=It.size>0?o/It.size:0,rt.enablePersistence&&gve(n),HN(Date.now()-t)}function gve(e){NN(e);try{let t={chunks:Array.from(It.values()).map(n=>({...n,vector:Array.from(n.vector.entries())})),avgChunkLength:Qv,documentFreq:Array.from(ti.entries())};Kbe(eg(Yv(e),"index.json"),JSON.stringify(t),"utf-8")}catch{}}function UN(e){let t=eg(Yv(e),"index.json");if(ON(t))try{let n=JSON.parse(jN(t,"utf-8"));It.clear(),Cr.clear(),In.clear();for(let r of n.chunks||[]){let s={...r,vector:new Map(r.vector||[])};It.set(s.id,s),Cr.has(s.filePath)||Cr.set(s.filePath,[]),Cr.get(s.filePath).push(s.id);for(let i of s.symbols)In.has(i)||In.set(i,[]),In.get(i).push(s.id)}Qv=n.avgChunkLength||0,ti.clear();for(let[r,s]of n.documentFreq||[])ti.set(r,s)}catch{}}function hve(e,t){let n=rt.bm25K1,r=rt.bm25B,s=t.tokens.length,i=It.size,o=new Map;for(let c of t.tokens)o.set(c,(o.get(c)||0)+1);let a=0;for(let c of e){let l=o.get(c)||0;if(l===0)continue;let u=ti.get(c)||1,d=Math.log((i-u+.5)/(u+.5)+1);a+=d*(l*(n+1))/(l+n*(1-r+r*(s/Math.max(1,Qv))))}return a}function yve(e,t){let n=0,r=0,s=0;for(let i of e.values())r+=i*i;for(let i of t.values())s+=i*i;for(let[i,o]of e){let a=t.get(i);a&&(n+=o*a)}return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function bve(e,t){let n=[],r=1,s=e.content.toLowerCase();return(t.intent==="find_definition"||t.intent==="where_is")&&/(?:function|class|def|fn|interface|type|enum|struct)\s+\w+/.test(e.content)&&(r*=1.5,n.push("contains definition")),t.intent==="find_test"||t.filters.onlyTests?(/(?:test|spec|describe|it\(|expect\()/.test(s)||/\.test\.|\.spec\.|test_/.test(e.relativePath))&&(r*=1.5,n.push("test file")):t.filters.excludeTests&&/\.test\.|\.spec\.|test_/.test(e.relativePath)&&(r*=.3,n.push("test file (deboosted)")),t.intent==="find_config"&&(/config|setting|env|process\.env/.test(s)||/config|\.env|settings/.test(e.relativePath))&&(r*=1.4,n.push("config-related")),(t.intent==="find_bug"||t.intent==="find_caller")&&/try\s*{|catch|except|raise|throw|panic/.test(e.content)&&(r*=1.3,n.push("error handling")),t.intent==="how_does"&&e.content.length>500&&(r*=1.1,n.push("substantial context")),{boost:r,reasons:n}}function vve(e,t){let n=[],r=0;for(let s of t.entities)e.symbols.includes(s)?(r+=rt.symbolMatchBoost,n.push(`symbol "${s}"`)):e.content.includes(s)&&(r+=rt.symbolMatchBoost*.5,n.push(`mentions "${s}"`));return{score:r,reasons:n}}function Sve(e){let t=(Date.now()-e.modifiedAt)/864e5;return Math.max(.5,1-Math.log(1+t)/Math.log(1+rt.recencyBoostDays))}function wve(e){if(!rt.enabled||It.size===0)return[];let t=JSON.stringify(e);if(rt.enableCache){let d=Jc.get(t);if(d&&Date.now()-d.cachedAt<rt.cacheTTLMs)return d.results}let n=qN(e.query),r=n.expandedTerms;if(r.length===0)return[];let s=new Map;for(let d of r)s.set(d,(s.get(d)||0)+1);let i=new Map,o=It.size;for(let[d,f]of s){let p=ti.get(d)||1,m=Math.log((o+1)/(p+1))+1;i.set(d,f*m)}let a=new Set;for(let d of r)for(let[f,p]of It)p.tokens.includes(d)&&a.add(f);for(let d of n.entities){let f=In.get(d)||[];for(let p of f)a.add(p);for(let[p,m]of In)if(p.toLowerCase()===d.toLowerCase())for(let g of m)a.add(g)}let c=[],l=e.minScore??rt.minScore;for(let d of a){let f=It.get(d);if(!f||e.language&&f.language!==e.language||n.filters.language&&f.language!==n.filters.language||e.fileGlob&&!kve(f.relativePath,e.fileGlob))continue;let p=yve(i,f.vector),m=hve(r,f),g=bve(f,n),h=vve(f,n),v=Sve(f),y=(p*1+Math.min(1,m/10)*1.5+h.score)*g.boost*(.7+.3*v);if(y<l)continue;let b="semantic";h.score>=rt.symbolMatchBoost?b="symbol":p>.7?b="exact":m<1&&(b="fuzzy");let k=[...g.reasons,...h.reasons];c.push({chunk:e.includeContent===!1?{...f,content:f.content.slice(0,200)}:f,score:y,matchType:b,matchReasons:k,snippet:xve(f.content,r,n.entities),scoreBreakdown:{tfidf:p,bm25:m,symbolMatch:h.score,intentBoost:g.boost,recencyBoost:v,totalScore:y}})}c.sort((d,f)=>f.score-d.score);let u=c.slice(0,e.limit||rt.defaultLimit);if(rt.enableCache&&(Jc.set(t,{results:u,cachedAt:Date.now()}),Jc.size>100)){let d=[...Jc.entries()].sort((f,p)=>f[1].cachedAt-p[1].cachedAt)[0];d&&Jc.delete(d[0])}return u}function kve(e,t){let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___GLOBSTAR___").replace(/\*/g,"[^/]*").replace(/___GLOBSTAR___/g,".*");return new RegExp(n).test(e)}function xve(e,t,n){let r=e.split(`
1560
1570
  `),s=0,i=0;for(let c=0;c<r.length;c++){let l=r[c].toLowerCase(),u=0;for(let d of t)l.includes(d)&&u++;for(let d of n)r[c].includes(d)&&(u+=2);u>i&&(i=u,s=c)}let o=Math.max(0,s-2),a=Math.min(r.length,s+5);return r.slice(o,a).join(`
1561
- `).slice(0,600)}function HN(e){let t={},n=0,r=0,s=0;for(let i of It.values())t[i.language]=(t[i.language]||0)+1,n+=i.tokens.length,r+=i.symbols.length,s+=i.size;return{totalFiles:Cr.size,totalChunks:It.size,totalTokens:n,totalSymbols:r,byLanguage:t,indexSizeKB:Math.round(s/1024),lastIndexedAt:Date.now(),buildDurationMs:e}}function xve(){return HN(0)}function $ve(){return{...rt}}function Cve(e){rt={...rt,...e}}function Ave(){It.clear(),Cr.clear(),ti.clear(),In.clear(),Jc.clear()}function Tve(){Jc.clear()}function _ve(){return It.size>0}function Rve(){return Xm}function oR(e){let t=eg(Yv(e),"index.json");return ON(t)?(Xm=e,UN(e),!0):!1}function Pve(e,t){if(e.length===0)return"No matches found.";let n=[];t&&(n.push(`# Search: "${t.raw}"`),n.push(`Intent: ${t.intent} | Entities: ${t.entities.join(", ")||"(none)"} | Keywords: ${t.keywords.join(", ")}`),n.push("")),n.push(`Found ${e.length} result(s):`),n.push("");for(let r=0;r<e.length;r++){let s=e[r],i=s.matchType==="exact"?"\u{1F3AF}":s.matchType==="symbol"?"\u{1F523}":s.matchType==="fuzzy"?"\u25D0":"\u2295";n.push(`## ${r+1}. ${i} ${s.chunk.relativePath}:${s.chunk.startLine}-${s.chunk.endLine} (${s.score.toFixed(2)})`),s.matchReasons.length>0&&n.push(` Reasons: ${s.matchReasons.join(" | ")}`),s.chunk.symbols.length>0&&n.push(` Symbols: ${s.chunk.symbols.slice(0,5).join(", ")}`),n.push(""),n.push(" ```"+s.chunk.language);for(let o of s.snippet.split(`
1571
+ `).slice(0,600)}function HN(e){let t={},n=0,r=0,s=0;for(let i of It.values())t[i.language]=(t[i.language]||0)+1,n+=i.tokens.length,r+=i.symbols.length,s+=i.size;return{totalFiles:Cr.size,totalChunks:It.size,totalTokens:n,totalSymbols:r,byLanguage:t,indexSizeKB:Math.round(s/1024),lastIndexedAt:Date.now(),buildDurationMs:e}}function $ve(){return HN(0)}function Cve(){return{...rt}}function Ave(e){rt={...rt,...e}}function Tve(){It.clear(),Cr.clear(),ti.clear(),In.clear(),Jc.clear()}function _ve(){Jc.clear()}function Rve(){return It.size>0}function Pve(){return Xm}function oR(e){let t=eg(Yv(e),"index.json");return ON(t)?(Xm=e,UN(e),!0):!1}function Ive(e,t){if(e.length===0)return"No matches found.";let n=[];t&&(n.push(`# Search: "${t.raw}"`),n.push(`Intent: ${t.intent} | Entities: ${t.entities.join(", ")||"(none)"} | Keywords: ${t.keywords.join(", ")}`),n.push("")),n.push(`Found ${e.length} result(s):`),n.push("");for(let r=0;r<e.length;r++){let s=e[r],i=s.matchType==="exact"?"\u{1F3AF}":s.matchType==="symbol"?"\u{1F523}":s.matchType==="fuzzy"?"\u25D0":"\u2295";n.push(`## ${r+1}. ${i} ${s.chunk.relativePath}:${s.chunk.startLine}-${s.chunk.endLine} (${s.score.toFixed(2)})`),s.matchReasons.length>0&&n.push(` Reasons: ${s.matchReasons.join(" | ")}`),s.chunk.symbols.length>0&&n.push(` Symbols: ${s.chunk.symbols.slice(0,5).join(", ")}`),n.push(""),n.push(" ```"+s.chunk.language);for(let o of s.snippet.split(`
1562
1572
  `).slice(0,8))n.push(" "+o);n.push(" ```"),n.push("")}return n.join(`
1563
- `)}var Xbe,rt,eve,It,Cr,ti,In,Jc,Qv,Xm,nve,rve,ove,Xv=w(()=>{"use strict";Xbe={enabled:!0,chunkSize:30,chunkOverlap:5,filePatterns:["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/*.{py,go,rs,java,kt,rb,php,cs,swift}","**/*.{html,css,scss}"],ignorePatterns:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/coverage/**","**/__pycache__/**","**/target/**","**/*.min.js","**/.cache/**","**/.next/**"],maxFileSize:1024*1024,bm25K1:1.5,bm25B:.75,defaultLimit:10,minScore:.05,symbolMatchBoost:2,intentBoost:1.3,recencyBoostDays:30,enableSynonymExpansion:!0,enableIntentDetection:!0,enableEntityExtraction:!0,enableCache:!0,cacheTTLMs:300*1e3,enablePersistence:!0},rt={...Xbe},eve=eg(Qbe(),".aiaca","nl-search");It=new Map,Cr=new Map,ti=new Map,In=new Map,Jc=new Map,Qv=0,Xm=null;nve=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","should","could","may","might","must","can","shall","this","that","these","those","i","you","he","she","it","we","they","and","or","but","if","then","else","so","as","at","by","for","with","about","to","from","in","on","of","where","when","how","what","why"]),rve=new Set(["const","let","var","function","class","return","if","else","def","public","private","static","void","null","undefined","true","false","this","self","new"]);ove={auth:["authentication","authn","authorize","authorization","login","signin"],login:["signin","auth","authenticate"],logout:["signout","logoff"],config:["configuration","settings","options","env","environment"],error:["exception","fail","failure","crash","bug"],test:["spec","unittest","test_","testing"],db:["database","storage","persistence","sql"],api:["endpoint","route","handler","controller"],user:["account","profile","member"],refresh:["renew","reload","update"],token:["jwt","session","cookie","bearer","credentials"],validate:["check","verify","sanitize"],parse:["parser","tokenize","lex"],cache:["memoize","memoization","store"],query:["select","find","search","fetch","get"]}});var e0={};$(e0,{ensureIndexed:()=>Fve});import{existsSync as Ive}from"fs";import{join as Mve}from"path";import{homedir as Eve}from"os";import{createHash as Dve}from"crypto";async function Fve(e,t=!1){let n=Dve("sha256").update(e).digest("hex").slice(0,16),r=Mve(Eve(),".aiaca","nl-search",n,"index.json");return!t&&Ive(r)&&oR(e)?await Zv({projectPath:e}):await Zv({projectPath:e,forceFullReindex:t})}var t0=w(()=>{"use strict";Xv()});var ng={};$(ng,{clearCache:()=>g0e,clearHistory:()=>m0e,clearSymbolIndex:()=>c0e,complete:()=>Zve,configure:()=>d0e,formatCompletions:()=>y0e,getConfig:()=>u0e,getHistory:()=>p0e,getMarkovStats:()=>h0e,getStats:()=>f0e,indexSymbols:()=>a0e,recordQuery:()=>l0e,recordUsage:()=>o0e});import{existsSync as n0,mkdirSync as Lve,readFileSync as r0,writeFileSync as s0,statSync as Ove,readdirSync as jve}from"fs";import{join as Ed}from"path";import{homedir as Bve}from"os";import{createHash as Nve}from"crypto";function pR(){Lve(tg,{recursive:!0})}function Uve(){if(pR(),n0(cR))try{let e=JSON.parse(r0(cR,"utf-8"));ni.push(...e.slice(-ze.maxHistoryEntries))}catch{}if(n0(lR))try{let e=JSON.parse(r0(lR,"utf-8"));for(let[t,n]of Object.entries(e))Vi.set(t,new Map(Object.entries(n)))}catch{}if(n0(uR))try{ze={...ze,...JSON.parse(r0(uR,"utf-8"))}}catch{}if(n0(dR))try{Hn={...Hn,...JSON.parse(r0(dR,"utf-8"))}}catch{}}function WN(){if(ze.enablePersistence){pR();try{s0(cR,JSON.stringify(ni.slice(-ze.maxHistoryEntries)),"utf-8");let e={};for(let[t,n]of Vi)e[t]=Object.fromEntries(n);s0(lR,JSON.stringify(e),"utf-8"),s0(dR,JSON.stringify(Hn),"utf-8")}catch{}}}function Hve(){pR();try{s0(uR,JSON.stringify(ze,null,2),"utf-8")}catch{}}function Vve(){i0.clear();for(let e of zve){let t={text:"/"+e.name,display:"/"+e.name,description:e.description,type:"command",score:1,source:"builtin"};i0.insert(e.name,t);for(let n of e.aliases)i0.insert(n,{...t,text:"/"+n});if(e.subActions){let n=new Wc;for(let r of e.subActions)n.insert(r,{text:r,display:r,description:`Subcommand of /${e.name}`,type:"argument",score:1,source:"builtin"});fR.set(e.name,n);for(let r of e.aliases)fR.set(r,n)}}}function Jve(e){if(!ze.enableProjectSource||zN===e&&Date.now()-GN<300*1e3)return;o0.clear();let t=new Set(["node_modules",".git","dist","build","out",".cache","coverage","target"]);function n(r,s=0){if(!(s>6))try{for(let i of jve(r)){if(t.has(i))continue;let o=Ed(r,i);try{let a=Ove(o);if(a.isDirectory())n(o,s+1);else{let c=o.replace(e+"/","").replace(e+"\\",""),l={text:c,display:c,type:"file_path",score:.7,source:"project",metadata:{mtime:a.mtimeMs}};o0.insert(c,l),o0.insert(i,l)}}catch{}}}catch{}}n(e),zN=e,GN=Date.now()}function VN(e){let t=Date.now()-e.lastUsed,n=ze.decayHalfLifeDays*24*60*60*1e3,r=Math.pow(.5,t/n);return Math.log(1+e.usageCount)*r}function Wve(e){if(!ze.enableMarkov)return[];let t=Vi.get(e);if(!t)return[];let n=Array.from(t.values()).reduce((r,s)=>r+s,0);return Array.from(t.entries()).map(([r,s])=>({text:r,score:s/n})).sort((r,s)=>s.score-r.score).slice(0,5)}function Kve(e,t){if(!e)return;Vi.has(e)||Vi.set(e,new Map);let n=Vi.get(e);n.set(t,(n.get(t)||0)+1)}function Yve(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let s=1;s<=e.length;s++)t[r-1]===e[s-1]?n[r][s]=n[r-1][s-1]:n[r][s]=Math.min(n[r-1][s-1]+1,n[r][s-1]+1,n[r-1][s]+1);return n[t.length][e.length]}function Qve(e,t){if(t.toLowerCase().startsWith(e.toLowerCase()))return 1;if(t.toLowerCase().includes(e.toLowerCase()))return .7;if(e.length<3)return 0;let n=Yve(e.toLowerCase(),t.toLowerCase()),r=Math.max(e.length,t.length);return n>r*.4?0:Math.max(0,1-n/r)*.5}function Zve(e){let t=Date.now();if(!ze.enabled)return[];let n=`${e.input}|${e.cursorPosition}|${e.projectPath||""}`;if(ze.cacheEnabled){let f=Md.get(n);if(f&&Date.now()-f.cachedAt<ze.cacheTTLMs)return Hn.cacheHits++,f.results;Hn.cacheMisses++}let r=e.input.slice(0,e.cursorPosition),s=e.input.slice(e.cursorPosition),i=[],o=r.startsWith("/")&&!r.includes(" "),a=r.startsWith("/")&&r.includes(" "),c=/[a-z]+\/[a-z]/i.test(r)||/^\.\.?\//.test(r.split(" ").pop()||"");if(o)i.push(...Xve(r.slice(1)));else if(a){let f=r.split(/\s+/),p=f[0].slice(1),m=f.slice(-1)[0]||"";i.push(...e0e(p,m))}else if(c||e.hint==="file"){let f=r.split(/\s+/).pop()||"";e.projectPath&&Jve(e.projectPath),i.push(...t0e(f))}if(ze.enableHistorySource&&i.push(...r0e(r,e)),ze.enableMarkov&&(o||a)&&i.push(...s0e(r,e)),ze.enableSymbolSource&&/\b[a-zA-Z_]\w*$/.test(r)){let f=r.match(/\b([a-zA-Z_]\w*)$/)?.[1]||"";i.push(...n0e(f))}let l=i0e(i,r,e),u=Date.now()-t;Hn.totalCompletions++,Hn.averageLatencyMs=(Hn.averageLatencyMs*(Hn.totalCompletions-1)+u)/Hn.totalCompletions;let d=l.slice(0,ze.maxResults);if(ze.cacheEnabled&&(Md.set(n,{results:d,cachedAt:Date.now()}),Md.size>200)){let f=[...Md.entries()].sort((p,m)=>p[1].cachedAt-m[1].cachedAt)[0];f&&Md.delete(f[0])}for(let f of d)Hn.byType[f.type]=(Hn.byType[f.type]||0)+1,Hn.bySource[f.source]=(Hn.bySource[f.source]||0)+1;return d}function Xve(e){return i0.searchPrefix(e,50).map(n=>({...n,score:n.score*(1+KN(n.text))}))}function e0e(e,t){let n=fR.get(e);return n?n.searchPrefix(t,30).map(s=>({...s,score:s.score*(1+KN(`/${e} ${s.text}`))})):[]}function t0e(e){return o0.searchPrefix(e,30)}function n0e(e){return mR.searchPrefix(e,20)}function r0e(e,t){let n=t.projectPath?YN(t.projectPath):void 0,r=[],s=e.toLowerCase();for(let i of ni)if(!(n&&i.projectHash!==n)){if(!i.text.toLowerCase().startsWith(s)&&!s.startsWith(i.text.toLowerCase())){if(ze.enableFuzzyMatch&&e.length>=3){let o=Qve(e,i.text);o>.5&&r.push({text:i.text,display:i.text,description:`Used ${i.usageCount}\xD7 | ${JN(i.lastUsed)}`,type:i.type,score:.5+VN(i)*.3+o*.2,source:"history",metadata:{usageCount:i.usageCount,lastUsed:i.lastUsed}})}continue}r.push({text:i.text,display:i.text,description:`Used ${i.usageCount}\xD7 | ${JN(i.lastUsed)}`,type:i.type,score:.7+VN(i)*.3,source:"history",metadata:{usageCount:i.usageCount,lastUsed:i.lastUsed}})}return r}function s0e(e,t){let n=t.recentCommands?.[0]||"";return n?Wve(n).map(s=>({text:s.text,display:s.text,description:`Often follows ${n} (${(s.score*100).toFixed(0)}%)`,type:"command",score:.6+s.score*.4,source:"markov"})):[]}function KN(e){if(!ze.enableLearning)return 0;let t=ni.filter(r=>r.text===e);if(t.length===0)return 0;let n=t.reduce((r,s)=>r+s.usageCount,0);return n<ze.minUsageForBoost?0:Math.min(.5,Math.log(1+n)*.1)}function i0e(e,t,n){let r=new Map;for(let i of e){let o=r.get(i.text);(!o||i.score>o.score)&&r.set(i.text,i)}return Array.from(r.values()).map(i=>{let o=i.score;return i.text.toLowerCase().startsWith(t.toLowerCase())&&(o+=ze.exactPrefixWeight),{...i,score:o}}).sort((i,o)=>o.score-i.score)}function JN(e){let n=(Date.now()-e)/(3600*1e3);if(n<1)return"just now";if(n<24)return`${Math.round(n)}h ago`;let r=n/24;return r<30?`${Math.round(r)}d ago`:`${Math.round(r/30)}mo ago`}function YN(e){return Nve("md5").update(e).digest("hex").slice(0,12)}function o0e(e,t,n){if(!ze.enableLearning)return;let r=n?.projectPath?YN(n.projectPath):void 0,s=ni.find(i=>i.text===e&&i.projectHash===r);s?(s.usageCount++,s.lastUsed=Date.now()):ni.push({text:e,type:t,context:n?.previousCommand||"",timestamp:Date.now(),projectHash:r,usageCount:1,lastUsed:Date.now(),timeOfDay:new Date().getHours()}),n?.previousCommand&&Kve(n.previousCommand,e),ni.length>ze.maxHistoryEntries&&ni.shift(),Hn.totalAccepted++,WN()}function a0e(e){for(let t of e)mR.insert(t,{text:t,display:t,type:"symbol",score:.8,source:"symbols"})}function c0e(){mR.clear()}function l0e(e){Gve.insert(e,{text:e,display:e,type:"prior_query",score:.5,source:"queries",metadata:{timestamp:Date.now()}})}function u0e(){return{...ze}}function d0e(e){ze={...ze,...e},Hve()}function f0e(){return{...Hn}}function p0e(e=100){return ni.slice(-e).reverse()}function m0e(){ni.length=0,Vi.clear(),WN()}function g0e(){Md.clear()}function h0e(){let e=0,t=[];for(let[n,r]of Vi)for(let[s,i]of r)e+=i,t.push({from:n,to:s,count:i});return t.sort((n,r)=>r.count-n.count),{totalChains:Vi.size,totalTransitions:e,topChains:t.slice(0,10)}}function y0e(e){return e.length===0?"No completions":e.map((t,n)=>{let r=String(n+1).padStart(2),s={command:"\u2318",argument:"\u2192",file_path:"\u{1F4C4}",symbol:"\u{1F523}",prior_query:"?",env_var:"$",shell_command:"$",snippet:"\u2702",flag:"-"},i=(t.score*100).toFixed(0).padStart(3),o=t.description?` \u2014 ${t.description}`:"";return`${r}. ${s[t.type]} [${i}%] ${t.display||t.text}${o} (${t.source})`}).join(`
1564
- `)}var qve,ze,tg,cR,lR,uR,dR,ni,Vi,Md,Hn,zve,Wc,i0,fR,o0,mR,Gve,zN,GN,rg=w(()=>{"use strict";qve={enabled:!0,enableLearning:!0,decayHalfLifeDays:30,minUsageForBoost:2,enableHistorySource:!0,enableProjectSource:!0,enableSymbolSource:!0,enableMarkov:!0,enableFuzzyMatch:!0,recencyWeight:.3,frequencyWeight:.4,contextMatchWeight:.2,exactPrefixWeight:.1,maxResults:10,maxLatencyMs:50,cacheEnabled:!0,cacheTTLMs:6e4,maxHistoryEntries:5e3,enablePersistence:!0},ze={...qve},tg=Ed(Bve(),".aiaca","autocomplete"),cR=Ed(tg,"history.json"),lR=Ed(tg,"markov.json"),uR=Ed(tg,"config.json"),dR=Ed(tg,"stats.json");ni=[],Vi=new Map,Md=new Map,Hn={totalCompletions:0,totalAccepted:0,averageLatencyMs:0,cacheHits:0,cacheMisses:0,byType:{},bySource:{}};Uve();zve=[{name:"help",aliases:["?"],description:"Show available commands"},{name:"clear",aliases:["c"],description:"Clear conversation"},{name:"exit",aliases:["quit","q"],description:"Exit AIACA"},{name:"model",aliases:["m"],description:"Switch model"},{name:"init",aliases:[],description:"Initialize project"},{name:"index",aliases:["idx"],description:"Build code index",subActions:["build","stats","search","force","clear"]},{name:"nlsearch",aliases:["nl","find"],description:"Natural language search",subActions:["index","stats","parse","clear","on","off"]},{name:"graph",aliases:["eg"],description:"Entity graph",subActions:["build","stats","impact","callers","callees","hubs","dead","cycles"]},{name:"preview",aliases:["diff-preview"],description:"Diff preview",subActions:["file","stats","format","on","off"]},{name:"gate",aliases:["hitl"],description:"Approval gates",subActions:["pending","approve","deny","policy","audit","stats"]},{name:"checkpoint",aliases:["cp"],description:"Checkpoint & rollback",subActions:["list","create","rollback","preview","diff","tag","stats"]},{name:"state",aliases:["fsm"],description:"Agent state machine",subActions:["list","show","new","transition","gates","abort"]},{name:"specialist",aliases:["spec"],description:"Specialist agents",subActions:["list","active","history","concurrent","config"]},{name:"dag",aliases:["tasks"],description:"Task DAG",subActions:["list","show","status","critical","topological"]},{name:"pr",aliases:["pull-request"],description:"PR autopilot",subActions:["list","create","show","comment","merge","ready","stats"]},{name:"ci",aliases:["build"],description:"CI/CD pipeline",subActions:["detect","trigger","monitor","show","diagnose","list","stats"]},{name:"issue",aliases:["ticket"],description:"Issue tracker",subActions:["detect","show","comment","status","search","auth"]},{name:"sandbox",aliases:["sb"],description:"Sandbox exec",subActions:["detect","run","stats","cleanup","pull","config"]},{name:"observe",aliases:["obs"],description:"Observability",subActions:["tail","tail-docker","tail-k8s","logs","anomalies","stats"]},{name:"secret",aliases:["vault"],description:"Secret manager",subActions:["status","check","policies","audit","stats"]},{name:"board",aliases:["bb"],description:"Shared blackboard",subActions:["list","get","set","delete","stats","namespaces"]},{name:"ac",aliases:["autocomplete"],description:"Autocomplete settings",subActions:["stats","history","on","off","config"]}],Wc=class{root={children:new Map,entries:[]};insert(t,n){let r=this.root;for(let s of t.toLowerCase())r.children.has(s)||r.children.set(s,{children:new Map,entries:[]}),r=r.children.get(s);r.entries.push(n)}searchPrefix(t,n=100){let r=this.root;for(let i of t.toLowerCase()){if(!r.children.has(i))return[];r=r.children.get(i)}let s=[];return this.collect(r,s,n),s}collect(t,n,r){if(!(n.length>=r)){for(let s of t.entries)n.length<r&&n.push(s);for(let s of t.children.values())this.collect(s,n,r)}}clear(){this.root={children:new Map,entries:[]}}},i0=new Wc,fR=new Map,o0=new Wc,mR=new Wc,Gve=new Wc;Vve();zN=null,GN=0});var wR={};$(wR,{clearCache:()=>q0e,clearProfile:()=>U0e,configure:()=>L0e,detectTarget:()=>e2,explain:()=>r2,formatExplanation:()=>D0e,getConfig:()=>F0e,getSkillProfile:()=>O0e,getStats:()=>B0e,inferSkillLevel:()=>ZN,refine:()=>E0e,resetStats:()=>N0e,setSkillLevel:()=>j0e,updateSkillProfile:()=>XN});import{existsSync as gR,mkdirSync as b0e,readFileSync as hR,writeFileSync as yR}from"fs";import{join as sg}from"path";import{homedir as v0e}from"os";function QN(){b0e(ig,{recursive:!0})}function w0e(){if(QN(),gR(bR))try{Nt={...Nt,...JSON.parse(hR(bR,"utf-8"))}}catch{}if(gR(SR))try{Yt={...Yt,...JSON.parse(hR(SR,"utf-8"))}}catch{}if(gR(vR))try{let e=JSON.parse(hR(vR,"utf-8"));for(let t of e)Date.now()-t.cachedAt<Qn.cacheTTLMs&&Zo.set(t.key,{explanation:t.explanation,cachedAt:t.cachedAt})}catch{}}function Kc(){QN();try{if(yR(bR,JSON.stringify(Nt,null,2),"utf-8"),yR(SR,JSON.stringify(Yt,null,2),"utf-8"),Qn.cacheEnabled){let e=Array.from(Zo.entries()).map(([t,n])=>({key:t,...n}));yR(vR,JSON.stringify(e.slice(-200)),"utf-8")}}catch{}}function ZN(e){let t=e.toLowerCase(),n=e.split(/\s+/).filter(Boolean).length,r=/```|^[\s\S]*\b(function|const|let|var|class|def)\s+\w+/m.test(e),s=k0e.filter(d=>t.includes(d)),i=x0e.filter(d=>d.test(e)).length,o=$0e.filter(d=>d.test(e)).length,a=(e.match(/\b[A-Z]{2,}\b/g)||[]).length,c={...Nt.signals};c.queryComplexity=c.queryComplexity*.7+Math.min(1,n/30)*.3,c.technicalVocabulary=c.technicalVocabulary*.7+Math.min(1,o/5+s.length*.3)*.3,c.abbreviationsUsed+=a,r&&c.codeIncludedInQueries++;for(let d of s)c.advancedConceptsAsked.includes(d)||c.advancedConceptsAsked.push(d);c.beginnerQuestionsAsked+=i;let l=0;l+=c.technicalVocabulary*.4,l+=c.queryComplexity*.2,l+=Math.min(1,c.codeIncludedInQueries/10)*.15,l+=Math.min(1,c.advancedConceptsAsked.length/8)*.2,l-=Math.min(.5,c.beginnerQuestionsAsked/20)*.4,l=Math.max(0,Math.min(1,l));let u="intermediate";return l<.3?u="beginner":l<.55?u="intermediate":l<.8?u="advanced":u="expert",{level:u,signals:c}}function XN(e){if(!Qn.autoDetectSkillLevel)return;let t=ZN(e);Nt.signals=t.signals,Nt.level=t.level,Nt.lastUpdated=Date.now(),Kc()}function e2(e){return/\bat\s+\S+\s*\(.+:\d+:\d+\)/.test(e)||/Traceback \(most recent call last\)/.test(e)?"trace":/^\s*(Error|Exception|Fatal):/im.test(e)||/\b(TypeError|ReferenceError|SyntaxError|RangeError)\b/.test(e)?"error":/^@@\s+-\d+/m.test(e)||/^[\+\-]{3}\s+/m.test(e)?"diff":/<tool_result\b/.test(e)||/Exit code:\s*\d+/.test(e)?"tool_output":/[{};]\s*$|^\s+[a-z_]+\s*[:=]/m.test(e)&&e.split(`
1565
- `).length>2?"code":/^[\$#>]\s+\S/.test(e)||/^(npm|yarn|pnpm|pip|git|docker|kubectl|cargo)\s+\S/.test(e.trim())?"command":/^\d{4}-\d{2}-\d{2}/m.test(e)||/\[(?:INFO|DEBUG|WARN|ERROR|FATAL)\]/.test(e)?"log":"concept"}function A0e(e){if(!Qn.enableConceptDetection)return[];let t=e.toLowerCase(),n=[];for(let[r,s]of Object.entries(C0e))new RegExp(`\\b${r.replace(/\s+/g,"\\s+")}\\b`,"i").test(t)&&n.push(s);return n.slice(0,5)}function _0e(e){if(!Qn.enableRootCauseAnalysis)return null;for(let t of T0e)if(t.pattern.test(e))return{rootCause:t.rootCause,suggestedFix:t.fix};return null}function R0e(e,t){if(!Qn.enableExecutionFlowReconstruction)return[];let n=[];if(t==="trace"){let r=e.match(/at\s+([^\s(]+)\s*\(([^)]+):(\d+):(\d+)\)/g)||e.match(/File\s+"([^"]+)",\s+line\s+(\d+),\s+in\s+(\S+)/g);if(r){n.push("Stack frames (most recent last):");for(let s of r.reverse().slice(0,6))n.push(` ${s}`)}}if(t==="tool_output"){let r=e.matchAll(/<tool_result\s+name="([^"]+)"[^>]*>([\s\S]*?)<\/tool_result>/g);for(let s of r)n.push(`Tool: ${s[1]} \u2192 ${s[2].slice(0,100).split(`
1573
+ `)}var eve,rt,tve,It,Cr,ti,In,Jc,Qv,Xm,rve,sve,ave,Xv=w(()=>{"use strict";eve={enabled:!0,chunkSize:30,chunkOverlap:5,filePatterns:["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/*.{py,go,rs,java,kt,rb,php,cs,swift}","**/*.{html,css,scss}"],ignorePatterns:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/coverage/**","**/__pycache__/**","**/target/**","**/*.min.js","**/.cache/**","**/.next/**"],maxFileSize:1024*1024,bm25K1:1.5,bm25B:.75,defaultLimit:10,minScore:.05,symbolMatchBoost:2,intentBoost:1.3,recencyBoostDays:30,enableSynonymExpansion:!0,enableIntentDetection:!0,enableEntityExtraction:!0,enableCache:!0,cacheTTLMs:300*1e3,enablePersistence:!0},rt={...eve},tve=eg(Zbe(),".aiaca","nl-search");It=new Map,Cr=new Map,ti=new Map,In=new Map,Jc=new Map,Qv=0,Xm=null;rve=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","should","could","may","might","must","can","shall","this","that","these","those","i","you","he","she","it","we","they","and","or","but","if","then","else","so","as","at","by","for","with","about","to","from","in","on","of","where","when","how","what","why"]),sve=new Set(["const","let","var","function","class","return","if","else","def","public","private","static","void","null","undefined","true","false","this","self","new"]);ave={auth:["authentication","authn","authorize","authorization","login","signin"],login:["signin","auth","authenticate"],logout:["signout","logoff"],config:["configuration","settings","options","env","environment"],error:["exception","fail","failure","crash","bug"],test:["spec","unittest","test_","testing"],db:["database","storage","persistence","sql"],api:["endpoint","route","handler","controller"],user:["account","profile","member"],refresh:["renew","reload","update"],token:["jwt","session","cookie","bearer","credentials"],validate:["check","verify","sanitize"],parse:["parser","tokenize","lex"],cache:["memoize","memoization","store"],query:["select","find","search","fetch","get"]}});var e0={};$(e0,{ensureIndexed:()=>Lve});import{existsSync as Mve}from"fs";import{join as Eve}from"path";import{homedir as Dve}from"os";import{createHash as Fve}from"crypto";async function Lve(e,t=!1){let n=Fve("sha256").update(e).digest("hex").slice(0,16),r=Eve(Dve(),".aiaca","nl-search",n,"index.json");return!t&&Mve(r)&&oR(e)?await Zv({projectPath:e}):await Zv({projectPath:e,forceFullReindex:t})}var t0=w(()=>{"use strict";Xv()});var ng={};$(ng,{clearCache:()=>h0e,clearHistory:()=>g0e,clearSymbolIndex:()=>l0e,complete:()=>Xve,configure:()=>f0e,formatCompletions:()=>b0e,getConfig:()=>d0e,getHistory:()=>m0e,getMarkovStats:()=>y0e,getStats:()=>p0e,indexSymbols:()=>c0e,recordQuery:()=>u0e,recordUsage:()=>a0e});import{existsSync as n0,mkdirSync as Ove,readFileSync as r0,writeFileSync as s0,statSync as jve,readdirSync as Bve}from"fs";import{join as Ed}from"path";import{homedir as Nve}from"os";import{createHash as qve}from"crypto";function pR(){Ove(tg,{recursive:!0})}function Hve(){if(pR(),n0(cR))try{let e=JSON.parse(r0(cR,"utf-8"));ni.push(...e.slice(-ze.maxHistoryEntries))}catch{}if(n0(lR))try{let e=JSON.parse(r0(lR,"utf-8"));for(let[t,n]of Object.entries(e))Vi.set(t,new Map(Object.entries(n)))}catch{}if(n0(uR))try{ze={...ze,...JSON.parse(r0(uR,"utf-8"))}}catch{}if(n0(dR))try{Hn={...Hn,...JSON.parse(r0(dR,"utf-8"))}}catch{}}function WN(){if(ze.enablePersistence){pR();try{s0(cR,JSON.stringify(ni.slice(-ze.maxHistoryEntries)),"utf-8");let e={};for(let[t,n]of Vi)e[t]=Object.fromEntries(n);s0(lR,JSON.stringify(e),"utf-8"),s0(dR,JSON.stringify(Hn),"utf-8")}catch{}}}function zve(){pR();try{s0(uR,JSON.stringify(ze,null,2),"utf-8")}catch{}}function Jve(){i0.clear();for(let e of Gve){let t={text:"/"+e.name,display:"/"+e.name,description:e.description,type:"command",score:1,source:"builtin"};i0.insert(e.name,t);for(let n of e.aliases)i0.insert(n,{...t,text:"/"+n});if(e.subActions){let n=new Wc;for(let r of e.subActions)n.insert(r,{text:r,display:r,description:`Subcommand of /${e.name}`,type:"argument",score:1,source:"builtin"});fR.set(e.name,n);for(let r of e.aliases)fR.set(r,n)}}}function Wve(e){if(!ze.enableProjectSource||zN===e&&Date.now()-GN<300*1e3)return;o0.clear();let t=new Set(["node_modules",".git","dist","build","out",".cache","coverage","target"]);function n(r,s=0){if(!(s>6))try{for(let i of Bve(r)){if(t.has(i))continue;let o=Ed(r,i);try{let a=jve(o);if(a.isDirectory())n(o,s+1);else{let c=o.replace(e+"/","").replace(e+"\\",""),l={text:c,display:c,type:"file_path",score:.7,source:"project",metadata:{mtime:a.mtimeMs}};o0.insert(c,l),o0.insert(i,l)}}catch{}}}catch{}}n(e),zN=e,GN=Date.now()}function VN(e){let t=Date.now()-e.lastUsed,n=ze.decayHalfLifeDays*24*60*60*1e3,r=Math.pow(.5,t/n);return Math.log(1+e.usageCount)*r}function Kve(e){if(!ze.enableMarkov)return[];let t=Vi.get(e);if(!t)return[];let n=Array.from(t.values()).reduce((r,s)=>r+s,0);return Array.from(t.entries()).map(([r,s])=>({text:r,score:s/n})).sort((r,s)=>s.score-r.score).slice(0,5)}function Yve(e,t){if(!e)return;Vi.has(e)||Vi.set(e,new Map);let n=Vi.get(e);n.set(t,(n.get(t)||0)+1)}function Qve(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let s=1;s<=e.length;s++)t[r-1]===e[s-1]?n[r][s]=n[r-1][s-1]:n[r][s]=Math.min(n[r-1][s-1]+1,n[r][s-1]+1,n[r-1][s]+1);return n[t.length][e.length]}function Zve(e,t){if(t.toLowerCase().startsWith(e.toLowerCase()))return 1;if(t.toLowerCase().includes(e.toLowerCase()))return .7;if(e.length<3)return 0;let n=Qve(e.toLowerCase(),t.toLowerCase()),r=Math.max(e.length,t.length);return n>r*.4?0:Math.max(0,1-n/r)*.5}function Xve(e){let t=Date.now();if(!ze.enabled)return[];let n=`${e.input}|${e.cursorPosition}|${e.projectPath||""}`;if(ze.cacheEnabled){let f=Md.get(n);if(f&&Date.now()-f.cachedAt<ze.cacheTTLMs)return Hn.cacheHits++,f.results;Hn.cacheMisses++}let r=e.input.slice(0,e.cursorPosition),s=e.input.slice(e.cursorPosition),i=[],o=r.startsWith("/")&&!r.includes(" "),a=r.startsWith("/")&&r.includes(" "),c=/[a-z]+\/[a-z]/i.test(r)||/^\.\.?\//.test(r.split(" ").pop()||"");if(o)i.push(...e0e(r.slice(1)));else if(a){let f=r.split(/\s+/),p=f[0].slice(1),m=f.slice(-1)[0]||"";i.push(...t0e(p,m))}else if(c||e.hint==="file"){let f=r.split(/\s+/).pop()||"";e.projectPath&&Wve(e.projectPath),i.push(...n0e(f))}if(ze.enableHistorySource&&i.push(...s0e(r,e)),ze.enableMarkov&&(o||a)&&i.push(...i0e(r,e)),ze.enableSymbolSource&&/\b[a-zA-Z_]\w*$/.test(r)){let f=r.match(/\b([a-zA-Z_]\w*)$/)?.[1]||"";i.push(...r0e(f))}let l=o0e(i,r,e),u=Date.now()-t;Hn.totalCompletions++,Hn.averageLatencyMs=(Hn.averageLatencyMs*(Hn.totalCompletions-1)+u)/Hn.totalCompletions;let d=l.slice(0,ze.maxResults);if(ze.cacheEnabled&&(Md.set(n,{results:d,cachedAt:Date.now()}),Md.size>200)){let f=[...Md.entries()].sort((p,m)=>p[1].cachedAt-m[1].cachedAt)[0];f&&Md.delete(f[0])}for(let f of d)Hn.byType[f.type]=(Hn.byType[f.type]||0)+1,Hn.bySource[f.source]=(Hn.bySource[f.source]||0)+1;return d}function e0e(e){return i0.searchPrefix(e,50).map(n=>({...n,score:n.score*(1+KN(n.text))}))}function t0e(e,t){let n=fR.get(e);return n?n.searchPrefix(t,30).map(s=>({...s,score:s.score*(1+KN(`/${e} ${s.text}`))})):[]}function n0e(e){return o0.searchPrefix(e,30)}function r0e(e){return mR.searchPrefix(e,20)}function s0e(e,t){let n=t.projectPath?YN(t.projectPath):void 0,r=[],s=e.toLowerCase();for(let i of ni)if(!(n&&i.projectHash!==n)){if(!i.text.toLowerCase().startsWith(s)&&!s.startsWith(i.text.toLowerCase())){if(ze.enableFuzzyMatch&&e.length>=3){let o=Zve(e,i.text);o>.5&&r.push({text:i.text,display:i.text,description:`Used ${i.usageCount}\xD7 | ${JN(i.lastUsed)}`,type:i.type,score:.5+VN(i)*.3+o*.2,source:"history",metadata:{usageCount:i.usageCount,lastUsed:i.lastUsed}})}continue}r.push({text:i.text,display:i.text,description:`Used ${i.usageCount}\xD7 | ${JN(i.lastUsed)}`,type:i.type,score:.7+VN(i)*.3,source:"history",metadata:{usageCount:i.usageCount,lastUsed:i.lastUsed}})}return r}function i0e(e,t){let n=t.recentCommands?.[0]||"";return n?Kve(n).map(s=>({text:s.text,display:s.text,description:`Often follows ${n} (${(s.score*100).toFixed(0)}%)`,type:"command",score:.6+s.score*.4,source:"markov"})):[]}function KN(e){if(!ze.enableLearning)return 0;let t=ni.filter(r=>r.text===e);if(t.length===0)return 0;let n=t.reduce((r,s)=>r+s.usageCount,0);return n<ze.minUsageForBoost?0:Math.min(.5,Math.log(1+n)*.1)}function o0e(e,t,n){let r=new Map;for(let i of e){let o=r.get(i.text);(!o||i.score>o.score)&&r.set(i.text,i)}return Array.from(r.values()).map(i=>{let o=i.score;return i.text.toLowerCase().startsWith(t.toLowerCase())&&(o+=ze.exactPrefixWeight),{...i,score:o}}).sort((i,o)=>o.score-i.score)}function JN(e){let n=(Date.now()-e)/(3600*1e3);if(n<1)return"just now";if(n<24)return`${Math.round(n)}h ago`;let r=n/24;return r<30?`${Math.round(r)}d ago`:`${Math.round(r/30)}mo ago`}function YN(e){return qve("md5").update(e).digest("hex").slice(0,12)}function a0e(e,t,n){if(!ze.enableLearning)return;let r=n?.projectPath?YN(n.projectPath):void 0,s=ni.find(i=>i.text===e&&i.projectHash===r);s?(s.usageCount++,s.lastUsed=Date.now()):ni.push({text:e,type:t,context:n?.previousCommand||"",timestamp:Date.now(),projectHash:r,usageCount:1,lastUsed:Date.now(),timeOfDay:new Date().getHours()}),n?.previousCommand&&Yve(n.previousCommand,e),ni.length>ze.maxHistoryEntries&&ni.shift(),Hn.totalAccepted++,WN()}function c0e(e){for(let t of e)mR.insert(t,{text:t,display:t,type:"symbol",score:.8,source:"symbols"})}function l0e(){mR.clear()}function u0e(e){Vve.insert(e,{text:e,display:e,type:"prior_query",score:.5,source:"queries",metadata:{timestamp:Date.now()}})}function d0e(){return{...ze}}function f0e(e){ze={...ze,...e},zve()}function p0e(){return{...Hn}}function m0e(e=100){return ni.slice(-e).reverse()}function g0e(){ni.length=0,Vi.clear(),WN()}function h0e(){Md.clear()}function y0e(){let e=0,t=[];for(let[n,r]of Vi)for(let[s,i]of r)e+=i,t.push({from:n,to:s,count:i});return t.sort((n,r)=>r.count-n.count),{totalChains:Vi.size,totalTransitions:e,topChains:t.slice(0,10)}}function b0e(e){return e.length===0?"No completions":e.map((t,n)=>{let r=String(n+1).padStart(2),s={command:"\u2318",argument:"\u2192",file_path:"\u{1F4C4}",symbol:"\u{1F523}",prior_query:"?",env_var:"$",shell_command:"$",snippet:"\u2702",flag:"-"},i=(t.score*100).toFixed(0).padStart(3),o=t.description?` \u2014 ${t.description}`:"";return`${r}. ${s[t.type]} [${i}%] ${t.display||t.text}${o} (${t.source})`}).join(`
1574
+ `)}var Uve,ze,tg,cR,lR,uR,dR,ni,Vi,Md,Hn,Gve,Wc,i0,fR,o0,mR,Vve,zN,GN,rg=w(()=>{"use strict";Uve={enabled:!0,enableLearning:!0,decayHalfLifeDays:30,minUsageForBoost:2,enableHistorySource:!0,enableProjectSource:!0,enableSymbolSource:!0,enableMarkov:!0,enableFuzzyMatch:!0,recencyWeight:.3,frequencyWeight:.4,contextMatchWeight:.2,exactPrefixWeight:.1,maxResults:10,maxLatencyMs:50,cacheEnabled:!0,cacheTTLMs:6e4,maxHistoryEntries:5e3,enablePersistence:!0},ze={...Uve},tg=Ed(Nve(),".aiaca","autocomplete"),cR=Ed(tg,"history.json"),lR=Ed(tg,"markov.json"),uR=Ed(tg,"config.json"),dR=Ed(tg,"stats.json");ni=[],Vi=new Map,Md=new Map,Hn={totalCompletions:0,totalAccepted:0,averageLatencyMs:0,cacheHits:0,cacheMisses:0,byType:{},bySource:{}};Hve();Gve=[{name:"help",aliases:["?"],description:"Show available commands"},{name:"clear",aliases:["c"],description:"Clear conversation"},{name:"exit",aliases:["quit","q"],description:"Exit AIACA"},{name:"model",aliases:["m"],description:"Switch model"},{name:"init",aliases:[],description:"Initialize project"},{name:"index",aliases:["idx"],description:"Build code index",subActions:["build","stats","search","force","clear"]},{name:"nlsearch",aliases:["nl","find"],description:"Natural language search",subActions:["index","stats","parse","clear","on","off"]},{name:"graph",aliases:["eg"],description:"Entity graph",subActions:["build","stats","impact","callers","callees","hubs","dead","cycles"]},{name:"preview",aliases:["diff-preview"],description:"Diff preview",subActions:["file","stats","format","on","off"]},{name:"gate",aliases:["hitl"],description:"Approval gates",subActions:["pending","approve","deny","policy","audit","stats"]},{name:"checkpoint",aliases:["cp"],description:"Checkpoint & rollback",subActions:["list","create","rollback","preview","diff","tag","stats"]},{name:"state",aliases:["fsm"],description:"Agent state machine",subActions:["list","show","new","transition","gates","abort"]},{name:"specialist",aliases:["spec"],description:"Specialist agents",subActions:["list","active","history","concurrent","config"]},{name:"dag",aliases:["tasks"],description:"Task DAG",subActions:["list","show","status","critical","topological"]},{name:"pr",aliases:["pull-request"],description:"PR autopilot",subActions:["list","create","show","comment","merge","ready","stats"]},{name:"ci",aliases:["build"],description:"CI/CD pipeline",subActions:["detect","trigger","monitor","show","diagnose","list","stats"]},{name:"issue",aliases:["ticket"],description:"Issue tracker",subActions:["detect","show","comment","status","search","auth"]},{name:"sandbox",aliases:["sb"],description:"Sandbox exec",subActions:["detect","run","stats","cleanup","pull","config"]},{name:"observe",aliases:["obs"],description:"Observability",subActions:["tail","tail-docker","tail-k8s","logs","anomalies","stats"]},{name:"secret",aliases:["vault"],description:"Secret manager",subActions:["status","check","policies","audit","stats"]},{name:"board",aliases:["bb"],description:"Shared blackboard",subActions:["list","get","set","delete","stats","namespaces"]},{name:"ac",aliases:["autocomplete"],description:"Autocomplete settings",subActions:["stats","history","on","off","config"]}],Wc=class{root={children:new Map,entries:[]};insert(t,n){let r=this.root;for(let s of t.toLowerCase())r.children.has(s)||r.children.set(s,{children:new Map,entries:[]}),r=r.children.get(s);r.entries.push(n)}searchPrefix(t,n=100){let r=this.root;for(let i of t.toLowerCase()){if(!r.children.has(i))return[];r=r.children.get(i)}let s=[];return this.collect(r,s,n),s}collect(t,n,r){if(!(n.length>=r)){for(let s of t.entries)n.length<r&&n.push(s);for(let s of t.children.values())this.collect(s,n,r)}}clear(){this.root={children:new Map,entries:[]}}},i0=new Wc,fR=new Map,o0=new Wc,mR=new Wc,Vve=new Wc;Jve();zN=null,GN=0});var wR={};$(wR,{clearCache:()=>U0e,clearProfile:()=>H0e,configure:()=>O0e,detectTarget:()=>e2,explain:()=>r2,formatExplanation:()=>F0e,getConfig:()=>L0e,getSkillProfile:()=>j0e,getStats:()=>N0e,inferSkillLevel:()=>ZN,refine:()=>D0e,resetStats:()=>q0e,setSkillLevel:()=>B0e,updateSkillProfile:()=>XN});import{existsSync as gR,mkdirSync as v0e,readFileSync as hR,writeFileSync as yR}from"fs";import{join as sg}from"path";import{homedir as S0e}from"os";function QN(){v0e(ig,{recursive:!0})}function k0e(){if(QN(),gR(bR))try{Nt={...Nt,...JSON.parse(hR(bR,"utf-8"))}}catch{}if(gR(SR))try{Yt={...Yt,...JSON.parse(hR(SR,"utf-8"))}}catch{}if(gR(vR))try{let e=JSON.parse(hR(vR,"utf-8"));for(let t of e)Date.now()-t.cachedAt<Qn.cacheTTLMs&&Zo.set(t.key,{explanation:t.explanation,cachedAt:t.cachedAt})}catch{}}function Kc(){QN();try{if(yR(bR,JSON.stringify(Nt,null,2),"utf-8"),yR(SR,JSON.stringify(Yt,null,2),"utf-8"),Qn.cacheEnabled){let e=Array.from(Zo.entries()).map(([t,n])=>({key:t,...n}));yR(vR,JSON.stringify(e.slice(-200)),"utf-8")}}catch{}}function ZN(e){let t=e.toLowerCase(),n=e.split(/\s+/).filter(Boolean).length,r=/```|^[\s\S]*\b(function|const|let|var|class|def)\s+\w+/m.test(e),s=x0e.filter(d=>t.includes(d)),i=$0e.filter(d=>d.test(e)).length,o=C0e.filter(d=>d.test(e)).length,a=(e.match(/\b[A-Z]{2,}\b/g)||[]).length,c={...Nt.signals};c.queryComplexity=c.queryComplexity*.7+Math.min(1,n/30)*.3,c.technicalVocabulary=c.technicalVocabulary*.7+Math.min(1,o/5+s.length*.3)*.3,c.abbreviationsUsed+=a,r&&c.codeIncludedInQueries++;for(let d of s)c.advancedConceptsAsked.includes(d)||c.advancedConceptsAsked.push(d);c.beginnerQuestionsAsked+=i;let l=0;l+=c.technicalVocabulary*.4,l+=c.queryComplexity*.2,l+=Math.min(1,c.codeIncludedInQueries/10)*.15,l+=Math.min(1,c.advancedConceptsAsked.length/8)*.2,l-=Math.min(.5,c.beginnerQuestionsAsked/20)*.4,l=Math.max(0,Math.min(1,l));let u="intermediate";return l<.3?u="beginner":l<.55?u="intermediate":l<.8?u="advanced":u="expert",{level:u,signals:c}}function XN(e){if(!Qn.autoDetectSkillLevel)return;let t=ZN(e);Nt.signals=t.signals,Nt.level=t.level,Nt.lastUpdated=Date.now(),Kc()}function e2(e){return/\bat\s+\S+\s*\(.+:\d+:\d+\)/.test(e)||/Traceback \(most recent call last\)/.test(e)?"trace":/^\s*(Error|Exception|Fatal):/im.test(e)||/\b(TypeError|ReferenceError|SyntaxError|RangeError)\b/.test(e)?"error":/^@@\s+-\d+/m.test(e)||/^[\+\-]{3}\s+/m.test(e)?"diff":/<tool_result\b/.test(e)||/Exit code:\s*\d+/.test(e)?"tool_output":/[{};]\s*$|^\s+[a-z_]+\s*[:=]/m.test(e)&&e.split(`
1575
+ `).length>2?"code":/^[\$#>]\s+\S/.test(e)||/^(npm|yarn|pnpm|pip|git|docker|kubectl|cargo)\s+\S/.test(e.trim())?"command":/^\d{4}-\d{2}-\d{2}/m.test(e)||/\[(?:INFO|DEBUG|WARN|ERROR|FATAL)\]/.test(e)?"log":"concept"}function T0e(e){if(!Qn.enableConceptDetection)return[];let t=e.toLowerCase(),n=[];for(let[r,s]of Object.entries(A0e))new RegExp(`\\b${r.replace(/\s+/g,"\\s+")}\\b`,"i").test(t)&&n.push(s);return n.slice(0,5)}function R0e(e){if(!Qn.enableRootCauseAnalysis)return null;for(let t of _0e)if(t.pattern.test(e))return{rootCause:t.rootCause,suggestedFix:t.fix};return null}function P0e(e,t){if(!Qn.enableExecutionFlowReconstruction)return[];let n=[];if(t==="trace"){let r=e.match(/at\s+([^\s(]+)\s*\(([^)]+):(\d+):(\d+)\)/g)||e.match(/File\s+"([^"]+)",\s+line\s+(\d+),\s+in\s+(\S+)/g);if(r){n.push("Stack frames (most recent last):");for(let s of r.reverse().slice(0,6))n.push(` ${s}`)}}if(t==="tool_output"){let r=e.matchAll(/<tool_result\s+name="([^"]+)"[^>]*>([\s\S]*?)<\/tool_result>/g);for(let s of r)n.push(`Tool: ${s[1]} \u2192 ${s[2].slice(0,100).split(`
1566
1576
  `)[0]}`)}if(t==="log"){let r=e.split(`
1567
- `).filter(s=>s.trim()).slice(0,8);n.push(...r.map(s=>s.length>120?s.slice(0,120)+"...":s))}return n}async function P0e(e,t,n,r,s,i,o,a){let c={beginner:"Explain like I have basic programming knowledge but I am new to this technology. Avoid jargon. Use analogies. Define terms.",intermediate:"I know programming well but may not know this specific tool/concept. Use precise terms but explain unusual ones.",advanced:"I am experienced. Be precise and technical. Skip basics. Focus on the non-obvious.",expert:"I am expert-level. Use full technical vocabulary. Focus on subtle implications, edge cases, and tradeoffs."}[n],l={concise:"Use 1-2 short paragraphs. Get to the point.",detailed:"Give a thorough breakdown. Cover the what, why, and how.",step_by_step:"Use numbered steps. Each step describes one logical action.",tldr:"Single sentence summary only.",analogy:"Use a real-world analogy to make the concept clear.",pros_cons:"Discuss the tradeoffs, what is good, what is bad, alternatives.",eli5:"Explain like I am 5 years old. Use simple words. Avoid all jargon."}[r],u={error:"Explain what went wrong, why it happened, and how to fix it.",code:"Explain what this code does, line by line if helpful, and any non-obvious aspects.",tool_output:"Explain what just happened: which tool ran, what it did, what the output means.",command:"Explain what this command does, each flag/argument, and what to expect.",diff:"Explain what was changed, why the change matters, and any risks.",trace:"Explain the call sequence that led to this error, identifying the root cause frame.",log:"Explain what these log lines indicate about system behavior.",concept:"Explain this concept clearly.",auto:"Explain in the most useful way for the content."}[t],d=[];s&&d.push(`Root cause analysis: ${s.rootCause}
1577
+ `).filter(s=>s.trim()).slice(0,8);n.push(...r.map(s=>s.length>120?s.slice(0,120)+"...":s))}return n}async function I0e(e,t,n,r,s,i,o,a){let c={beginner:"Explain like I have basic programming knowledge but I am new to this technology. Avoid jargon. Use analogies. Define terms.",intermediate:"I know programming well but may not know this specific tool/concept. Use precise terms but explain unusual ones.",advanced:"I am experienced. Be precise and technical. Skip basics. Focus on the non-obvious.",expert:"I am expert-level. Use full technical vocabulary. Focus on subtle implications, edge cases, and tradeoffs."}[n],l={concise:"Use 1-2 short paragraphs. Get to the point.",detailed:"Give a thorough breakdown. Cover the what, why, and how.",step_by_step:"Use numbered steps. Each step describes one logical action.",tldr:"Single sentence summary only.",analogy:"Use a real-world analogy to make the concept clear.",pros_cons:"Discuss the tradeoffs, what is good, what is bad, alternatives.",eli5:"Explain like I am 5 years old. Use simple words. Avoid all jargon."}[r],u={error:"Explain what went wrong, why it happened, and how to fix it.",code:"Explain what this code does, line by line if helpful, and any non-obvious aspects.",tool_output:"Explain what just happened: which tool ran, what it did, what the output means.",command:"Explain what this command does, each flag/argument, and what to expect.",diff:"Explain what was changed, why the change matters, and any risks.",trace:"Explain the call sequence that led to this error, identifying the root cause frame.",log:"Explain what these log lines indicate about system behavior.",concept:"Explain this concept clearly.",auto:"Explain in the most useful way for the content."}[t],d=[];s&&d.push(`Root cause analysis: ${s.rootCause}
1568
1578
  Suggested fix: ${s.suggestedFix}`),i.length>0&&d.push(`Relevant concepts:
1569
1579
  ${i.map(m=>`- ${m.term}: ${m.definition}`).join(`
1570
1580
  `)}`),o.length>0&&d.push(`Execution flow:
@@ -1599,26 +1609,26 @@ Output JSON only:
1599
1609
  `)[0].slice(0,200);return{error:`An error occurred: "${n}"`,code:`Code snippet: ${n}`,tool_output:`Tool output starting with: "${n}"`,command:`Command: ${n}`,diff:"Diff with changes (see detailed for breakdown).",trace:`Stack trace from: ${n}`,log:`Log starting: ${n}`,concept:`Topic: ${n}`,auto:n}[t]||n}function n2(e,t,n,r){let s=[];if(s.push(`This appears to be ${t.replace("_"," ")} content.`),n&&(s.push(`
1600
1610
  Root cause: ${n.rootCause}`),s.push(`Suggested fix: ${n.suggestedFix}`)),r.length>0){s.push(`
1601
1611
  Key concepts to know:`);for(let i of r)s.push(`- ${i.term}: ${i.definition}`)}return s.join(`
1602
- `)}async function r2(e,t){let n=Date.now();if(!Qn.enabled)return{summary:"Explain mode disabled",detailed:"Explain mode is currently disabled. Enable with /explain on",concepts:[],skillLevel:Nt.level,style:"concise",generatedAt:Date.now(),durationMs:0};e.context?.userQuery&&XN(e.context.userQuery);let r=I0e(e);if(Qn.cacheEnabled){let m=Zo.get(r);if(m&&Date.now()-m.cachedAt<Qn.cacheTTLMs)return Yt.cacheHits++,m.explanation;Yt.cacheMisses++}let s=e.target==="auto"||!e.target?e2(e.content):e.target,i=e.forceLevel||Nt.level,o=e.style||Qn.defaultStyle,a=A0e(e.content),c=s==="error"||s==="trace"?_0e(e.content):null,l=R0e(e.content,s),u="",d="",f;if(t){let m=await P0e(e,s,i,o,c,a,l,t);u=m.summary,d=m.detailed,f=m.nextSteps}else u=t2(e.content,s),d=n2(e.content,s,c,a),c&&(f=[c.suggestedFix]);let p={summary:u,detailed:d,rootCause:c?.rootCause,executionFlow:l.length>0?l:void 0,concepts:a,nextSteps:f,references:M0e(e.content),skillLevel:i,style:o,generatedAt:Date.now(),durationMs:Date.now()-n};if(Qn.cacheEnabled&&(Zo.set(r,{explanation:p,cachedAt:Date.now()}),Zo.size>200)){let m=[...Zo.entries()].sort((g,h)=>g[1].cachedAt-h[1].cachedAt)[0];m&&Zo.delete(m[0])}return Yt.totalExplanations++,Yt.byTarget[s]=(Yt.byTarget[s]||0)+1,Yt.byStyle[o]=(Yt.byStyle[o]||0)+1,Yt.byLevel[i]=(Yt.byLevel[i]||0)+1,Yt.averageDurationMs=(Yt.averageDurationMs*(Yt.totalExplanations-1)+p.durationMs)/Yt.totalExplanations,Nt.history.push({timestamp:Date.now(),style:o,target:s}),Nt.history.length>100&&Nt.history.shift(),Kc(),p}function I0e(e){return fl("crypto").createHash("md5").update(e.content.slice(0,5e3)).update(e.target||"").update(e.style||"").update(e.forceLevel||Nt.level).digest("hex").slice(0,16)}function M0e(e){let t=[];for(let n of e.matchAll(/(?:^|\s)([\w./-]+\.\w{2,4})(?::(\d+))?/g))n[1].length>5&&t.push({type:"file",label:n[1],location:n[2]?`${n[1]}:${n[2]}`:n[1]});return t.slice(0,5)}async function E0e(e,t,n){let r=e.original.skillLevel,s=e.original.style;if(e.feedback==="too_simple"){let i=["beginner","intermediate","advanced","expert"],o=i.indexOf(r);r=i[Math.min(i.length-1,o+1)]}else if(e.feedback==="too_complex"){let i=["beginner","intermediate","advanced","expert"],o=i.indexOf(r);r=i[Math.max(0,o-1)],s="analogy"}else if(e.feedback==="unclear")s="step_by_step";else if(e.feedback==="helpful")return Yt.helpfulCount++,Nt.history[Nt.history.length-1]?.helpful,Kc(),e.original;return e.feedback==="wrong"&&Yt.notHelpfulCount++,(e.feedback==="too_simple"||e.feedback==="too_complex")&&(Nt.level=r),Kc(),r2({...t,forceLevel:r,style:s},n)}function D0e(e){let t=[],n={beginner:"\u{1F4D8}",intermediate:"\u{1F4D7}",advanced:"\u{1F4D9}",expert:"\u{1F4D5}"}[e.skillLevel];if(t.push(`${n} **Explanation** (${e.skillLevel} level, ${e.style})`),t.push(""),t.push("## Summary"),t.push(e.summary),t.push(""),t.push("## Details"),t.push(e.detailed),t.push(""),e.rootCause&&(t.push("## \u{1F50D} Root Cause"),t.push(e.rootCause),t.push("")),e.executionFlow&&e.executionFlow.length>0){t.push("## \u26A1 Execution Flow");for(let r of e.executionFlow)t.push(` ${r}`);t.push("")}if(e.concepts.length>0){t.push("## \u{1F4A1} Key Concepts");for(let r of e.concepts)t.push(`- **${r.term}** [${r.importance}]: ${r.definition}`);t.push("")}if(e.nextSteps&&e.nextSteps.length>0){t.push("## \u27A1\uFE0F Next Steps");for(let r=0;r<e.nextSteps.length;r++)t.push(`${r+1}. ${e.nextSteps[r]}`);t.push("")}if(e.references&&e.references.length>0){t.push("## \u{1F4DA} References");for(let r of e.references)t.push(`- [${r.type}] ${r.label}`)}return t.join(`
1603
- `)}function F0e(){return{...Qn}}function L0e(e){Qn={...Qn,...e}}function O0e(){return JSON.parse(JSON.stringify(Nt))}function j0e(e){Nt.level=e,Nt.lastUpdated=Date.now(),Kc()}function B0e(){return{...Yt}}function N0e(){Yt={totalExplanations:0,byTarget:{},byStyle:{},byLevel:{},averageDurationMs:0,cacheHits:0,cacheMisses:0,helpfulCount:0,notHelpfulCount:0},Kc()}function q0e(){Zo.clear()}function U0e(){Nt={level:"intermediate",signals:{queryComplexity:.5,technicalVocabulary:.5,abbreviationsUsed:0,codeIncludedInQueries:0,advancedConceptsAsked:[],beginnerQuestionsAsked:0},history:[],lastUpdated:Date.now()},Kc()}var S0e,Qn,ig,bR,lDe,vR,SR,Nt,Zo,Yt,k0e,x0e,$0e,C0e,T0e,kR=w(()=>{"use strict";S0e={enabled:!0,defaultStyle:"detailed",autoDetectSkillLevel:!0,enablePersonalization:!0,enableConceptDetection:!0,enableRootCauseAnalysis:!0,enableExecutionFlowReconstruction:!0,cacheEnabled:!0,cacheTTLMs:1800*1e3,maxContentLength:2e4},Qn={...S0e},ig=sg(v0e(),".aiaca","explain"),bR=sg(ig,"skill-profile.json"),lDe=sg(ig,"history.json"),vR=sg(ig,"cache.json"),SR=sg(ig,"stats.json"),Nt={level:"intermediate",signals:{queryComplexity:.5,technicalVocabulary:.5,abbreviationsUsed:0,codeIncludedInQueries:0,advancedConceptsAsked:[],beginnerQuestionsAsked:0},history:[],lastUpdated:Date.now()},Zo=new Map,Yt={totalExplanations:0,byTarget:{},byStyle:{},byLevel:{},averageDurationMs:0,cacheHits:0,cacheMisses:0,helpfulCount:0,notHelpfulCount:0};w0e();k0e=["big-o","time complexity","space complexity","memoization","currying","monad","functor","closure","hoisting","prototype chain","event loop","tail call","cps","continuation","transducer","kernel","syscall","hash collision","backpressure","idempotent","consensus","crdt","consistent hashing","paxos","raft","mvcc","wal","lsm tree","b-tree","eventual consistency","cap theorem","bloom filter","merkle","eviction policy","arity","variadic","generic","covariance","contravariance","reified","thunk","memoize","lazy evaluation","eager","partial application"],x0e=[/\bwhat is\b/i,/\bhow do i\b/i,/\bcan you explain\b/i,/\bwhat does this mean\b/i,/\bnot sure\b/i,/\bnew to\b/i,/\bjust started\b/i,/\bdon't understand\b/i,/\bwhy doesn't this work\b/i],$0e=[/\b(O\(.+?\))\b/,/\b(npm|pip|cargo|go mod)\b/,/\b(class|interface|trait|struct)\b/,/\b(async|await|promise|future|callback)\b/,/\b(thread|mutex|atomic|lock)\b/,/\b(SIGTERM|SIGKILL|EOF|stderr|stdout)\b/,/\b(stack trace|heap|gc)\b/];C0e={async:{term:"async",definition:"A function marked async returns a Promise and can use await to pause execution until other Promises resolve.",importance:"critical"},await:{term:"await",definition:"Pauses async function execution until the Promise resolves, then returns its value.",importance:"critical"},closure:{term:"closure",definition:"A function that captures variables from its surrounding scope, even after that scope has exited.",importance:"helpful"},promise:{term:"Promise",definition:"An object representing the eventual completion (or failure) of an asynchronous operation.",importance:"critical"},callback:{term:"callback",definition:"A function passed as an argument to be called later, often after async work completes.",importance:"helpful"},mutex:{term:"mutex",definition:"Mutual exclusion lock \u2014 ensures only one thread accesses a shared resource at a time.",importance:"helpful"},"race condition":{term:"race condition",definition:"A bug where the result depends on the timing of concurrent operations executing in unpredictable order.",importance:"critical"},memoization:{term:"memoization",definition:"Caching results of expensive function calls so repeated calls with same inputs return cached value.",importance:"helpful"},idempotent:{term:"idempotent",definition:"An operation that produces the same result when applied multiple times. Safe to retry.",importance:"helpful"},"event loop":{term:"event loop",definition:"Node.js's mechanism for handling async operations: a queue of callbacks processed in order.",importance:"critical"},middleware:{term:"middleware",definition:"Code that runs between a request and response (or any pipeline stage), often for auth, logging, validation.",importance:"helpful"},orm:{term:"ORM",definition:"Object-Relational Mapping \u2014 maps database tables to programming-language objects.",importance:"helpful"},jwt:{term:"JWT",definition:"JSON Web Token \u2014 a signed token format for representing claims (e.g., user identity) in a compact, URL-safe way.",importance:"critical"},cors:{term:"CORS",definition:"Cross-Origin Resource Sharing \u2014 browser security feature that controls which origins can access an API.",importance:"helpful"}};T0e=[{pattern:/Cannot find module ['"]([^'"]+)['"]/,rootCause:"Missing dependency: the imported module is not installed or path is wrong.",fix:"Install the package or fix the import path."},{pattern:/Cannot read propert(?:y|ies) (?:'([^']+)'|"([^"]+)") of (null|undefined)/,rootCause:"Trying to access a property on null/undefined. The expected object was not properly initialized.",fix:"Add a null check before accessing the property, or ensure the object is initialized before use."},{pattern:/TypeError: (\S+) is not a function/,rootCause:"Trying to call something that is not callable (e.g., undefined or wrong type).",fix:"Verify the variable is actually a function. Check imports and typos."},{pattern:/SyntaxError/,rootCause:"Invalid code syntax \u2014 typo, mismatched brackets, missing semicolon, etc.",fix:"Read the line indicated, check for unbalanced parens/braces and typos."},{pattern:/UnhandledPromiseRejection/,rootCause:"A Promise rejected and was not handled with .catch() or try/await.",fix:"Add error handling: wrap awaited calls in try/catch or chain .catch()."},{pattern:/ECONNREFUSED|ETIMEDOUT|ENOTFOUND/,rootCause:"Network error: target is unreachable, slow, or DNS failed.",fix:"Check the URL, server status, network connectivity, and firewall rules."},{pattern:/EACCES|EPERM/,rootCause:"Permission denied for the requested file/operation.",fix:"Check file permissions, run with appropriate privileges, or use a path you own."},{pattern:/Maximum call stack size exceeded/,rootCause:"Infinite recursion \u2014 a function calls itself without a proper base case.",fix:"Add a termination condition. Verify recursive call simplifies the input."},{pattern:/Out of memory|JavaScript heap out of memory/,rootCause:"Process tried to allocate more memory than available.",fix:"Find the memory leak (often unbounded arrays or caches). Increase --max-old-space-size as a stopgap."},{pattern:/port (\d+) (?:is\s+)?already in use|EADDRINUSE/,rootCause:"Another process is using the same port.",fix:"Kill the existing process (lsof -i :PORT) or use a different port."},{pattern:/AssertionError/,rootCause:"A test assertion or invariant check failed \u2014 actual value did not match expected.",fix:"Compare expected vs actual values; either update the test or fix the code."},{pattern:/CORS|Cross-Origin/,rootCause:"Browser blocked the request because the API origin does not match the page origin.",fix:"Configure CORS headers on the server (Access-Control-Allow-Origin) or use a proxy."}]});var IR={};$(IR,{cleanupAll:()=>_R,configure:()=>oSe,detectAvailableRuntimes:()=>a2,execute:()=>sSe,formatResult:()=>fSe,getActiveContainers:()=>uSe,getAuditLog:()=>dSe,getConfig:()=>iSe,getEvents:()=>lSe,getStats:()=>aSe,resetStats:()=>cSe});import{existsSync as RR,mkdirSync as H0e,readFileSync as i2,writeFileSync as Ld,unlinkSync as CR}from"fs";import{join as Yc,basename as o2}from"path";import{homedir as z0e,tmpdir as a0,platform as G0e}from"os";import{execSync as Xo,spawn as PR}from"child_process";import{randomBytes as Fd}from"crypto";import{EventEmitter as V0e}from"events";function l0(){H0e(c0,{recursive:!0})}function W0e(){if(l0(),RR(TR))try{he={...he,...JSON.parse(i2(TR,"utf-8"))}}catch{}}function u0(){l0();try{Ld(TR,JSON.stringify(he,null,2),"utf-8")}catch{}}function K0e(e){if(st.enableAuditLog){l0();try{Ld(AR,JSON.stringify({...e,timestamp:Date.now()})+`
1604
- `,{flag:"a"})}catch{}}}function Q0e(){return l0(),RR(xR)||Ld(xR,JSON.stringify(Y0e,null,2),"utf-8"),xR}function a2(e=!1){if($R&&!e)return $R;let t=new Set;return Ji("docker")&&t.add("docker"),Ji("podman")&&t.add("podman"),Ji("runsc")&&t.add("gvisor"),Ji("firecracker")&&t.add("firecracker"),(Ji("wasmtime")||Ji("wasmer")||Ji("deno"))&&t.add("wasm"),t.add("process"),$R=t,t}function Ji(e){try{return Xo(G0e()==="win32"?`where ${e}`:`which ${e}`,{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}function Z0e(e){let t=a2();switch(e){case"maximum":if(t.has("gvisor"))return"gvisor";if(t.has("firecracker"))return"firecracker";if(t.has("docker"))return"docker";if(t.has("wasm"))return"wasm";break;case"high":if(t.has("firecracker"))return"firecracker";if(t.has("docker"))return"docker";if(t.has("podman"))return"podman";break;case"standard":if(t.has("docker"))return"docker";if(t.has("podman"))return"podman";break;case"lightweight":if(t.has("podman"))return"podman";if(t.has("docker"))return"docker";if(t.has("wasm"))return"wasm";break;case"minimal":if(t.has("wasm"))return"wasm";break;case"process":return"process"}return t.has("docker")?"docker":t.has("podman")?"podman":t.has("wasm")?"wasm":"process"}function c2(e,t){switch(e){case"python":return{entrypoint:["python","-c",t],needsFile:!1};case"node":case"javascript":return{entrypoint:["node","-e",t],needsFile:!1};case"typescript":return{entrypoint:["npx","tsx","/sandbox/code.ts"],needsFile:!0,filename:"/sandbox/code.ts"};case"go":return{entrypoint:["sh","-c","cd /sandbox && go run code.go"],needsFile:!0,filename:"/sandbox/code.go"};case"rust":return{entrypoint:["sh","-c","cd /sandbox && rustc code.rs -o /tmp/out && /tmp/out"],needsFile:!0,filename:"/sandbox/code.rs"};case"java":return{entrypoint:["sh","-c","cd /sandbox && javac Main.java && java -cp /sandbox Main"],needsFile:!0,filename:"/sandbox/Main.java"};case"ruby":return{entrypoint:["ruby","-e",t],needsFile:!1};case"shell":return{entrypoint:["sh","-c",t],needsFile:!1};case"cpp":return{entrypoint:["sh","-c","cd /sandbox && g++ code.cpp -o /tmp/out && /tmp/out"],needsFile:!0,filename:"/sandbox/code.cpp"};case"php":return{entrypoint:["php","-r",t],needsFile:!1};default:return{entrypoint:["sh","-c",t],needsFile:!1}}}function X0e(e,t,n,r){let s=["run","--rm","--name",n,"-i"];s.push("--memory",`${e.memoryMb||st.defaultMemoryMb}m`),s.push("--memory-swap",`${e.memoryMb||st.defaultMemoryMb}m`),s.push("--cpus",`${(e.cpuQuotaPercent||st.defaultCpuQuotaPercent)/100}`),s.push("--pids-limit",String(e.pidsLimit||st.defaultPidsLimit));let i=e.allowNetwork??st.allowNetworkByDefault;i?s.push("--network","bridge"):s.push("--network","none"),s.push("--read-only");let o=Math.min(e.diskMb||st.defaultDiskMb,256);if(s.push("--tmpfs",`/tmp:rw,noexec,nosuid,size=${o}m`),s.push("--tmpfs",`/sandbox:rw,noexec,nosuid,size=${o}m`),s.push("--tmpfs","/var/tmp:rw,noexec,nosuid,size=10m"),st.dropAllCapabilities&&s.push("--cap-drop","ALL"),st.enableNoNewPrivs&&s.push("--security-opt","no-new-privileges"),st.enableSeccomp&&t!=="gvisor")try{let a=Q0e();s.push("--security-opt",`seccomp=${a}`)}catch{}return st.enableAppArmor&&process.platform==="linux"&&s.push("--security-opt","apparmor=docker-default"),st.enableUserNamespaceRemap&&s.push("-u","65534:65534"),t==="gvisor"&&s.push("--runtime","runsc"),s.push("--ipc","private"),s.push("--pid","private"),s.push("-e","HOME=/tmp"),s.push("-e","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"),s.push("--hostname","sandbox"),i||s.push("--dns","127.0.0.1"),s.push("-w","/sandbox"),s.push(r),s}async function eSe(e,t,n){let r=Date.now(),s=`aiaca-vm-${Fd(8).toString("hex")}`,i=s2[e.language]||s2.unknown;if(Dd.add(s),st.pullPolicy==="always"||st.pullPolicy==="if_not_present"&&!await tSe(t,i))try{Xo(`${t==="gvisor"?"docker":t} pull ${i}`,{stdio:"pipe",timeout:18e4})}catch{}let o=t==="gvisor"?"docker":t,a=X0e(e,t,s,i),c=c2(e.language,e.code),l=null;return c.needsFile&&c.filename&&(l=Yc(a0(),`aiaca-vm-${Fd(6).toString("hex")}-${o2(c.filename)}`),Ld(l,e.code),a.splice(a.length-1,0,"-v",`${l}:${c.filename}:ro`)),a.push(...c.entrypoint),new Promise(u=>{let d=[],f="",p="",m=!1,g=!1,h=!1,v=PR(o,a,{stdio:["pipe","pipe","pipe"]});e.stdin&&v.stdin.write(e.stdin),v.stdin.end(),v.stdout.on("data",k=>{let S=k.toString();f+=S.slice(0,1024*1024),/Operation not permitted/i.test(S)&&d.push({type:"syscall_blocked",severity:"info",message:"Syscall blocked by seccomp",timestamp:Date.now()})}),v.stderr.on("data",k=>{let S=k.toString();p+=S.slice(0,1024*1024),/network is unreachable|name resolution failed|getaddrinfo/i.test(S)&&(d.push({type:"network_attempt",severity:"warn",message:"Network access blocked",timestamp:Date.now()}),he.totalNetworkBlocks++),/permission denied/i.test(S)&&d.push({type:"fs_violation",severity:"warn",message:"Filesystem access blocked",timestamp:Date.now()}),/operation not permitted/i.test(S)&&d.push({type:"capability_attempt",severity:"warn",message:"Capability escalation blocked",timestamp:Date.now()})});let y=e.timeoutMs||st.defaultTimeoutMs,b=setTimeout(()=>{g=!0,he.totalTimeouts++;try{Xo(`${o} kill ${s}`,{stdio:"pipe"})}catch{}v.kill("SIGKILL"),m=!0},y);v.on("close",k=>{clearTimeout(b);let S=Date.now()-r;Dd.delete(s);let x={};try{let j=Xo(`${o} inspect ${s} --format '{{json .State}}' 2>/dev/null`,{stdio:"pipe",encoding:"utf-8"});JSON.parse(j).OOMKilled&&(h=!0,he.totalOomKilled++,d.push({type:"oom",severity:"critical",message:"Container killed by OOM killer",timestamp:Date.now()}))}catch{}let A=!1;if(st.alwaysFreshContainer||st.cleanupOnExit)try{Xo(`${o} rm -f ${s} 2>/dev/null`,{stdio:"pipe"}),A=!0}catch{A=!0}if(l)try{CR(l)}catch{}he.totalExecutions++,he.byRuntime[t]=(he.byRuntime[t]||0)+1,he.byIsolation[n]=(he.byIsolation[n]||0)+1,he.byLanguage[e.language]=(he.byLanguage[e.language]||0)+1,he.totalSecurityEvents+=d.length,he.averageDurationMs=(he.averageDurationMs*(he.totalExecutions-1)+S)/he.totalExecutions,u0(),K0e({runtime:t,isolation:n,language:e.language,codeLength:e.code.length,duration:S,exitCode:k,success:k===0&&!g,securityEvents:d,timedOut:g,oomKilled:h,agentId:e.agentId,reason:e.reason}),og.emit("execution_complete",{containerId:s,success:k===0});for(let j of d)og.emit("security_event",j),j.severity==="critical"&&og.emit("critical_event",j);u({success:k===0&&!g&&!h,exitCode:k??-1,stdout:f,stderr:p,duration:S,runtime:t,isolationLevel:n,containerId:s,destroyed:A,resourceUsage:x,securityEvents:d,timedOut:g,killed:m,oomKilled:h})}),v.on("error",k=>{if(clearTimeout(b),Dd.delete(s),l)try{CR(l)}catch{}u(ag(r,t,n,s,k.message))})})}async function tSe(e,t){let n=e==="gvisor"?"docker":e;try{return Xo(`${n} image inspect ${t}`,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}async function nSe(e){let t=Date.now(),n=`aiaca-wasm-${Fd(6).toString("hex")}`;if(e.language!=="javascript"&&e.language!=="typescript")return ag(t,"wasm","minimal",n,`WASM only supports JS/TS, got: ${e.language}`);if(!Ji("deno"))return ag(t,"wasm","minimal",n,"Deno not installed");let r=Yc(a0(),`aiaca-deno-${Fd(4).toString("hex")}.${e.language==="typescript"?"ts":"js"}`);Ld(r,e.code);let s=["run","--no-prompt"];return e.allowNetwork&&s.push("--allow-net"),e.allowReadFilesystem&&e.allowReadFilesystem.length>0&&s.push(`--allow-read=${e.allowReadFilesystem.join(",")}`),s.push(r),new Promise(i=>{let o="",a="",c=[],l=!1,u=!1,d=PR("deno",s,{stdio:["pipe","pipe","pipe"]});e.stdin&&d.stdin.write(e.stdin),d.stdin.end(),d.stdout.on("data",p=>{o+=p.toString().slice(0,1024*1024)}),d.stderr.on("data",p=>{let m=p.toString();a+=m.slice(0,1024*1024),/Permission denied|requires.*permission/i.test(m)&&c.push({type:"capability_attempt",severity:"warn",message:"Deno permission denied",timestamp:Date.now()})});let f=setTimeout(()=>{l=!0,he.totalTimeouts++,d.kill("SIGKILL"),u=!0},e.timeoutMs||st.defaultTimeoutMs);d.on("close",p=>{clearTimeout(f);try{CR(r)}catch{}let m=Date.now()-t;he.totalExecutions++,he.byRuntime.wasm=(he.byRuntime.wasm||0)+1,he.byIsolation.minimal=(he.byIsolation.minimal||0)+1,he.byLanguage[e.language]=(he.byLanguage[e.language]||0)+1,u0(),i({success:p===0&&!l,exitCode:p??-1,stdout:o,stderr:a,duration:m,runtime:"wasm",isolationLevel:"minimal",containerId:n,destroyed:!0,resourceUsage:{},securityEvents:c,timedOut:l,killed:u,oomKilled:!1})})})}async function rSe(e){let t=Date.now(),n=`aiaca-proc-${Fd(4).toString("hex")}`,r=c2(e.language,e.code),s;if(r.needsFile&&r.filename){let i=Yc(a0(),`aiaca-proc-${Fd(4).toString("hex")}-${o2(r.filename)}`);Ld(i,e.code),s=r.entrypoint.map(o=>o===r.filename?i:o)}else s=r.entrypoint;return new Promise(i=>{let o="",a="",c=PR(s[0],s.slice(1),{env:{},cwd:a0()});e.stdin&&c.stdin.write(e.stdin),c.stdin.end(),c.stdout.on("data",u=>{o+=u.toString()}),c.stderr.on("data",u=>{a+=u.toString()});let l=setTimeout(()=>c.kill("SIGKILL"),e.timeoutMs||st.defaultTimeoutMs);c.on("close",u=>{clearTimeout(l);let d=Date.now()-t;he.totalExecutions++,he.byRuntime.process=(he.byRuntime.process||0)+1,u0(),i({success:u===0,exitCode:u??-1,stdout:o,stderr:a,duration:d,runtime:"process",isolationLevel:"process",containerId:n,destroyed:!0,resourceUsage:{},securityEvents:[{type:"capability_attempt",severity:"warn",message:"WARNING: Code ran without sandboxing",timestamp:Date.now()}],timedOut:!1,killed:!1,oomKilled:!1,error:"Code ran in unsafe process mode (no isolation)"})})})}function ag(e,t,n,r,s){return{success:!1,exitCode:-1,stdout:"",stderr:"",duration:Date.now()-e,runtime:t,isolationLevel:n,containerId:r,destroyed:!0,resourceUsage:{},securityEvents:[],timedOut:!1,killed:!1,oomKilled:!1,error:s}}async function sSe(e){if(!st.enabled)return ag(Date.now(),"process","process","","Sandbox disabled");let t=e.isolationLevel||st.defaultIsolationLevel,n=Z0e(t),r;try{n==="docker"||n==="podman"||n==="gvisor"?r=await eSe(e,n,t):n==="wasm"?r=await nSe(e):r=await rSe(e)}catch(s){r=ag(Date.now(),n,t,"",s.message)}return r}function _R(){let e=[],t=0;for(let n of["docker","podman"])if(Ji(n))try{let s=Xo(`${n} ps -a --filter "name=aiaca-(vm|wasm|proc)-" --format "{{.Names}}"`,{stdio:"pipe",encoding:"utf-8"}).split(`
1605
- `).filter(Boolean);for(let i of s)try{Xo(`${n} rm -f ${i} 2>/dev/null`,{stdio:"pipe"}),t++}catch(o){e.push(`${i}: ${o.message}`)}}catch{}return Dd.clear(),{destroyed:t,errors:e}}function iSe(){return{...st}}function oSe(e){st={...st,...e}}function aSe(){return{...he}}function cSe(){he={totalExecutions:0,byRuntime:{},byIsolation:{},byLanguage:{},totalSecurityEvents:0,totalEscapeAttempts:0,totalOomKilled:0,totalTimeouts:0,totalNetworkBlocks:0,averageDurationMs:0,averageMemoryMb:0},u0()}function lSe(){return og}function uSe(){return Array.from(Dd)}function dSe(e=100){if(!RR(AR))return[];try{return i2(AR,"utf-8").split(`
1606
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function fSe(e){let t=[],n=e.success?"\u2713":e.timedOut?"\u23F1\uFE0F":e.oomKilled?"\u{1F4A5}":"\u2717";if(t.push(`${n} **Sandbox Execution** (${e.isolationLevel} via ${e.runtime})`),t.push(`Container: ${e.containerId} ${e.destroyed?"[destroyed]":"[ACTIVE]"}`),t.push(`Exit: ${e.exitCode} | Duration: ${e.duration}ms`),e.timedOut&&t.push("\u23F1\uFE0F TIMEOUT"),e.oomKilled&&t.push("\u{1F4A5} OUT OF MEMORY"),e.error&&t.push(`Error: ${e.error}`),t.push(""),e.securityEvents.length>0){t.push(`## \u{1F6E1}\uFE0F Security Events (${e.securityEvents.length})`);for(let r of e.securityEvents.slice(0,10)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="warn"?"\u26A0\uFE0F ":"\u2139\uFE0F ";t.push(`${s} [${r.type}] ${r.message}`)}t.push("")}return e.stdout&&(t.push("## stdout"),t.push("```"),t.push(e.stdout.slice(0,5e3)),e.stdout.length>5e3&&t.push(`... (${e.stdout.length-5e3} more chars)`),t.push("```")),e.stderr&&(t.push("## stderr"),t.push("```"),t.push(e.stderr.slice(0,3e3)),t.push("```")),t.join(`
1607
- `)}var J0e,st,c0,AR,TR,xR,og,he,Dd,Y0e,s2,$R,MR=w(()=>{"use strict";J0e={enabled:!0,defaultIsolationLevel:"maximum",defaultTimeoutMs:3e4,defaultMemoryMb:256,defaultCpuQuotaPercent:50,defaultPidsLimit:64,defaultDiskMb:100,allowNetworkByDefault:!1,enableSeccomp:!0,enableAppArmor:!0,enableSelinux:!1,dropAllCapabilities:!0,enableUserNamespaceRemap:!0,enableNoNewPrivs:!0,alwaysFreshContainer:!0,cleanupOnExit:!0,recyclePoolSize:0,imageRegistry:"docker.io",pullPolicy:"if_not_present",enableAuditLog:!0},st={...J0e},c0=Yc(z0e(),".aiaca","micro-vm"),AR=Yc(c0,"audit.jsonl"),TR=Yc(c0,"stats.json"),xR=Yc(c0,"seccomp-profile.json"),og=new V0e;og.setMaxListeners(50);he={totalExecutions:0,byRuntime:{},byIsolation:{},byLanguage:{},totalSecurityEvents:0,totalEscapeAttempts:0,totalOomKilled:0,totalTimeouts:0,totalNetworkBlocks:0,averageDurationMs:0,averageMemoryMb:0},Dd=new Set;W0e();Y0e={defaultAction:"SCMP_ACT_ERRNO",archMap:[{architecture:"SCMP_ARCH_X86_64",subArchitectures:["SCMP_ARCH_X86","SCMP_ARCH_X32"]}],syscalls:[{names:["read","write","open","openat","close","stat","fstat","lstat","newfstatat","lseek","access","faccessat","readlink","readlinkat","getcwd","mmap","mprotect","munmap","brk","mremap","madvise","execve","execveat","exit","exit_group","getpid","gettid","getuid","geteuid","getgid","getegid","getppid","set_tid_address","arch_prctl","prctl","clone","futex","set_robust_list","get_robust_list","rt_sigaction","rt_sigprocmask","rt_sigreturn","sigaltstack","rt_sigpending","rt_sigsuspend","rt_sigtimedwait","kill","tgkill","select","poll","epoll_create1","epoll_ctl","epoll_wait","epoll_pwait","clock_gettime","gettimeofday","time","nanosleep","clock_nanosleep","getdents","getdents64","pipe","pipe2","dup","dup2","dup3","fcntl","ioctl","fadvise64","sched_yield","getrandom"],action:"SCMP_ACT_ALLOW"}]};s2={python:"python:3.12-slim",node:"node:22-alpine",javascript:"node:22-alpine",typescript:"node:22-alpine",go:"golang:1.22-alpine",rust:"rust:1.78-alpine",java:"openjdk:21-slim",ruby:"ruby:3.3-alpine",shell:"alpine:latest",cpp:"gcc:13",csharp:"mcr.microsoft.com/dotnet/sdk:8.0-alpine",php:"php:8.3-cli-alpine",unknown:"alpine:latest"},$R=null;st.cleanupOnExit&&(process.on("exit",()=>{Dd.size>0&&_R()}),process.on("SIGINT",()=>{_R(),process.exit(0)}))});var qR={};$(qR,{abstractContent:()=>kSe,configure:()=>MSe,decideRoute:()=>CSe,detectLocalModels:()=>wSe,formatBudget:()=>NSe,formatRouteDecision:()=>BSe,generateComplianceReport:()=>jSe,getAuditLog:()=>LSe,getConfig:()=>ISe,getEvents:()=>FSe,getOrCreateBudget:()=>p0,getPreferredLocalModel:()=>cg,getStats:()=>ESe,listBudgets:()=>p2,listLocalModels:()=>f2,queueOfflineRequest:()=>RSe,recordAbstraction:()=>_Se,recordLocalCall:()=>TSe,recordRemoteSend:()=>ASe,resetStats:()=>DSe,setMode:()=>OSe});import{existsSync as jR,mkdirSync as l2,readFileSync as BR,writeFileSync as d0}from"fs";import{join as jd}from"path";import{homedir as pSe}from"os";import{execSync as mSe}from"child_process";import{createCipheriv as gSe,randomBytes as DR}from"crypto";import{EventEmitter as hSe}from"events";function f0(){l2(Bd,{recursive:!0}),l2(bSe,{recursive:!0})}function SSe(){if(f0(),jR(FR))try{it={...it,...JSON.parse(BR(FR,"utf-8"))}}catch{}}function Od(){f0();try{d0(FR,JSON.stringify(it,null,2),"utf-8")}catch{}}function NR(e){if(!ke.enableAuditLog)return;f0();let t={...e};t.content&&(t.content="[REDACTED]"),t.original&&(t.original="[REDACTED]");try{d0(LR,JSON.stringify({...t,timestamp:Date.now()})+`
1608
- `,{flag:"a"})}catch{}}async function wSe(e=!1){if(!e&&Date.now()-u2<300*1e3)return Array.from(ea.values());try{let t=new AbortController,n=setTimeout(()=>t.abort(),2e3),r=await fetch(`${ke.ollamaEndpoint}/api/tags`,{signal:t.signal});if(clearTimeout(n),r.ok){let s=await r.json();for(let i of s.models||[]){let o=`ollama:${i.name}`;ea.set(o,{id:o,name:i.name,type:"ollama",endpoint:ke.ollamaEndpoint,capabilities:i.name.includes("embed")?["embed"]:["chat","code"],available:!0,contextWindow:i.details?.parameter_size?.includes("70")?8192:4096})}}}catch{}try{let t=new AbortController,n=setTimeout(()=>t.abort(),1e3),r=await fetch("http://localhost:8080/health",{signal:t.signal});clearTimeout(n),r.ok&&ea.set("llamacpp:default",{id:"llamacpp:default",name:"llama.cpp server",type:"llamacpp",endpoint:"http://localhost:8080",capabilities:["chat","code"],available:!0})}catch{}if(process.platform==="darwin")try{mSe("which mlx_lm.generate",{stdio:"pipe",timeout:1e3}),ea.set("mlx:available",{id:"mlx:available",name:"MLX (Apple Silicon)",type:"mlx",capabilities:["chat","code"],available:!0})}catch{}return u2=Date.now(),Array.from(ea.values())}function f2(){return Array.from(ea.values()).filter(e=>e.available)}function cg(){if(ke.preferredLocalModel)return ea.get(ke.preferredLocalModel);for(let e of ea.values())if(e.available)return e}function kSe(e,t){if(t==="none")return{original:e,abstracted:e,level:t,reductionRatio:1,bytesRemoved:0,sensitiveSignalsRemoved:0};let n="",r=0;switch(t){case"summary":n=xSe(e);break;case"diff":n=e.length>1e3?d2(e):e;break;case"structure":n=d2(e);break;case"redacted":let s=$Se(e);n=s.text,r=s.removed;break}return{original:e,abstracted:n,level:t,reductionRatio:n.length/e.length,bytesRemoved:e.length-n.length,sensitiveSignalsRemoved:r}}function xSe(e){let n=e.split(`
1612
+ `)}async function r2(e,t){let n=Date.now();if(!Qn.enabled)return{summary:"Explain mode disabled",detailed:"Explain mode is currently disabled. Enable with /explain on",concepts:[],skillLevel:Nt.level,style:"concise",generatedAt:Date.now(),durationMs:0};e.context?.userQuery&&XN(e.context.userQuery);let r=M0e(e);if(Qn.cacheEnabled){let m=Zo.get(r);if(m&&Date.now()-m.cachedAt<Qn.cacheTTLMs)return Yt.cacheHits++,m.explanation;Yt.cacheMisses++}let s=e.target==="auto"||!e.target?e2(e.content):e.target,i=e.forceLevel||Nt.level,o=e.style||Qn.defaultStyle,a=T0e(e.content),c=s==="error"||s==="trace"?R0e(e.content):null,l=P0e(e.content,s),u="",d="",f;if(t){let m=await I0e(e,s,i,o,c,a,l,t);u=m.summary,d=m.detailed,f=m.nextSteps}else u=t2(e.content,s),d=n2(e.content,s,c,a),c&&(f=[c.suggestedFix]);let p={summary:u,detailed:d,rootCause:c?.rootCause,executionFlow:l.length>0?l:void 0,concepts:a,nextSteps:f,references:E0e(e.content),skillLevel:i,style:o,generatedAt:Date.now(),durationMs:Date.now()-n};if(Qn.cacheEnabled&&(Zo.set(r,{explanation:p,cachedAt:Date.now()}),Zo.size>200)){let m=[...Zo.entries()].sort((g,h)=>g[1].cachedAt-h[1].cachedAt)[0];m&&Zo.delete(m[0])}return Yt.totalExplanations++,Yt.byTarget[s]=(Yt.byTarget[s]||0)+1,Yt.byStyle[o]=(Yt.byStyle[o]||0)+1,Yt.byLevel[i]=(Yt.byLevel[i]||0)+1,Yt.averageDurationMs=(Yt.averageDurationMs*(Yt.totalExplanations-1)+p.durationMs)/Yt.totalExplanations,Nt.history.push({timestamp:Date.now(),style:o,target:s}),Nt.history.length>100&&Nt.history.shift(),Kc(),p}function M0e(e){return fl("crypto").createHash("md5").update(e.content.slice(0,5e3)).update(e.target||"").update(e.style||"").update(e.forceLevel||Nt.level).digest("hex").slice(0,16)}function E0e(e){let t=[];for(let n of e.matchAll(/(?:^|\s)([\w./-]+\.\w{2,4})(?::(\d+))?/g))n[1].length>5&&t.push({type:"file",label:n[1],location:n[2]?`${n[1]}:${n[2]}`:n[1]});return t.slice(0,5)}async function D0e(e,t,n){let r=e.original.skillLevel,s=e.original.style;if(e.feedback==="too_simple"){let i=["beginner","intermediate","advanced","expert"],o=i.indexOf(r);r=i[Math.min(i.length-1,o+1)]}else if(e.feedback==="too_complex"){let i=["beginner","intermediate","advanced","expert"],o=i.indexOf(r);r=i[Math.max(0,o-1)],s="analogy"}else if(e.feedback==="unclear")s="step_by_step";else if(e.feedback==="helpful")return Yt.helpfulCount++,Nt.history[Nt.history.length-1]?.helpful,Kc(),e.original;return e.feedback==="wrong"&&Yt.notHelpfulCount++,(e.feedback==="too_simple"||e.feedback==="too_complex")&&(Nt.level=r),Kc(),r2({...t,forceLevel:r,style:s},n)}function F0e(e){let t=[],n={beginner:"\u{1F4D8}",intermediate:"\u{1F4D7}",advanced:"\u{1F4D9}",expert:"\u{1F4D5}"}[e.skillLevel];if(t.push(`${n} **Explanation** (${e.skillLevel} level, ${e.style})`),t.push(""),t.push("## Summary"),t.push(e.summary),t.push(""),t.push("## Details"),t.push(e.detailed),t.push(""),e.rootCause&&(t.push("## \u{1F50D} Root Cause"),t.push(e.rootCause),t.push("")),e.executionFlow&&e.executionFlow.length>0){t.push("## \u26A1 Execution Flow");for(let r of e.executionFlow)t.push(` ${r}`);t.push("")}if(e.concepts.length>0){t.push("## \u{1F4A1} Key Concepts");for(let r of e.concepts)t.push(`- **${r.term}** [${r.importance}]: ${r.definition}`);t.push("")}if(e.nextSteps&&e.nextSteps.length>0){t.push("## \u27A1\uFE0F Next Steps");for(let r=0;r<e.nextSteps.length;r++)t.push(`${r+1}. ${e.nextSteps[r]}`);t.push("")}if(e.references&&e.references.length>0){t.push("## \u{1F4DA} References");for(let r of e.references)t.push(`- [${r.type}] ${r.label}`)}return t.join(`
1613
+ `)}function L0e(){return{...Qn}}function O0e(e){Qn={...Qn,...e}}function j0e(){return JSON.parse(JSON.stringify(Nt))}function B0e(e){Nt.level=e,Nt.lastUpdated=Date.now(),Kc()}function N0e(){return{...Yt}}function q0e(){Yt={totalExplanations:0,byTarget:{},byStyle:{},byLevel:{},averageDurationMs:0,cacheHits:0,cacheMisses:0,helpfulCount:0,notHelpfulCount:0},Kc()}function U0e(){Zo.clear()}function H0e(){Nt={level:"intermediate",signals:{queryComplexity:.5,technicalVocabulary:.5,abbreviationsUsed:0,codeIncludedInQueries:0,advancedConceptsAsked:[],beginnerQuestionsAsked:0},history:[],lastUpdated:Date.now()},Kc()}var w0e,Qn,ig,bR,uDe,vR,SR,Nt,Zo,Yt,x0e,$0e,C0e,A0e,_0e,kR=w(()=>{"use strict";w0e={enabled:!0,defaultStyle:"detailed",autoDetectSkillLevel:!0,enablePersonalization:!0,enableConceptDetection:!0,enableRootCauseAnalysis:!0,enableExecutionFlowReconstruction:!0,cacheEnabled:!0,cacheTTLMs:1800*1e3,maxContentLength:2e4},Qn={...w0e},ig=sg(S0e(),".aiaca","explain"),bR=sg(ig,"skill-profile.json"),uDe=sg(ig,"history.json"),vR=sg(ig,"cache.json"),SR=sg(ig,"stats.json"),Nt={level:"intermediate",signals:{queryComplexity:.5,technicalVocabulary:.5,abbreviationsUsed:0,codeIncludedInQueries:0,advancedConceptsAsked:[],beginnerQuestionsAsked:0},history:[],lastUpdated:Date.now()},Zo=new Map,Yt={totalExplanations:0,byTarget:{},byStyle:{},byLevel:{},averageDurationMs:0,cacheHits:0,cacheMisses:0,helpfulCount:0,notHelpfulCount:0};k0e();x0e=["big-o","time complexity","space complexity","memoization","currying","monad","functor","closure","hoisting","prototype chain","event loop","tail call","cps","continuation","transducer","kernel","syscall","hash collision","backpressure","idempotent","consensus","crdt","consistent hashing","paxos","raft","mvcc","wal","lsm tree","b-tree","eventual consistency","cap theorem","bloom filter","merkle","eviction policy","arity","variadic","generic","covariance","contravariance","reified","thunk","memoize","lazy evaluation","eager","partial application"],$0e=[/\bwhat is\b/i,/\bhow do i\b/i,/\bcan you explain\b/i,/\bwhat does this mean\b/i,/\bnot sure\b/i,/\bnew to\b/i,/\bjust started\b/i,/\bdon't understand\b/i,/\bwhy doesn't this work\b/i],C0e=[/\b(O\(.+?\))\b/,/\b(npm|pip|cargo|go mod)\b/,/\b(class|interface|trait|struct)\b/,/\b(async|await|promise|future|callback)\b/,/\b(thread|mutex|atomic|lock)\b/,/\b(SIGTERM|SIGKILL|EOF|stderr|stdout)\b/,/\b(stack trace|heap|gc)\b/];A0e={async:{term:"async",definition:"A function marked async returns a Promise and can use await to pause execution until other Promises resolve.",importance:"critical"},await:{term:"await",definition:"Pauses async function execution until the Promise resolves, then returns its value.",importance:"critical"},closure:{term:"closure",definition:"A function that captures variables from its surrounding scope, even after that scope has exited.",importance:"helpful"},promise:{term:"Promise",definition:"An object representing the eventual completion (or failure) of an asynchronous operation.",importance:"critical"},callback:{term:"callback",definition:"A function passed as an argument to be called later, often after async work completes.",importance:"helpful"},mutex:{term:"mutex",definition:"Mutual exclusion lock \u2014 ensures only one thread accesses a shared resource at a time.",importance:"helpful"},"race condition":{term:"race condition",definition:"A bug where the result depends on the timing of concurrent operations executing in unpredictable order.",importance:"critical"},memoization:{term:"memoization",definition:"Caching results of expensive function calls so repeated calls with same inputs return cached value.",importance:"helpful"},idempotent:{term:"idempotent",definition:"An operation that produces the same result when applied multiple times. Safe to retry.",importance:"helpful"},"event loop":{term:"event loop",definition:"Node.js's mechanism for handling async operations: a queue of callbacks processed in order.",importance:"critical"},middleware:{term:"middleware",definition:"Code that runs between a request and response (or any pipeline stage), often for auth, logging, validation.",importance:"helpful"},orm:{term:"ORM",definition:"Object-Relational Mapping \u2014 maps database tables to programming-language objects.",importance:"helpful"},jwt:{term:"JWT",definition:"JSON Web Token \u2014 a signed token format for representing claims (e.g., user identity) in a compact, URL-safe way.",importance:"critical"},cors:{term:"CORS",definition:"Cross-Origin Resource Sharing \u2014 browser security feature that controls which origins can access an API.",importance:"helpful"}};_0e=[{pattern:/Cannot find module ['"]([^'"]+)['"]/,rootCause:"Missing dependency: the imported module is not installed or path is wrong.",fix:"Install the package or fix the import path."},{pattern:/Cannot read propert(?:y|ies) (?:'([^']+)'|"([^"]+)") of (null|undefined)/,rootCause:"Trying to access a property on null/undefined. The expected object was not properly initialized.",fix:"Add a null check before accessing the property, or ensure the object is initialized before use."},{pattern:/TypeError: (\S+) is not a function/,rootCause:"Trying to call something that is not callable (e.g., undefined or wrong type).",fix:"Verify the variable is actually a function. Check imports and typos."},{pattern:/SyntaxError/,rootCause:"Invalid code syntax \u2014 typo, mismatched brackets, missing semicolon, etc.",fix:"Read the line indicated, check for unbalanced parens/braces and typos."},{pattern:/UnhandledPromiseRejection/,rootCause:"A Promise rejected and was not handled with .catch() or try/await.",fix:"Add error handling: wrap awaited calls in try/catch or chain .catch()."},{pattern:/ECONNREFUSED|ETIMEDOUT|ENOTFOUND/,rootCause:"Network error: target is unreachable, slow, or DNS failed.",fix:"Check the URL, server status, network connectivity, and firewall rules."},{pattern:/EACCES|EPERM/,rootCause:"Permission denied for the requested file/operation.",fix:"Check file permissions, run with appropriate privileges, or use a path you own."},{pattern:/Maximum call stack size exceeded/,rootCause:"Infinite recursion \u2014 a function calls itself without a proper base case.",fix:"Add a termination condition. Verify recursive call simplifies the input."},{pattern:/Out of memory|JavaScript heap out of memory/,rootCause:"Process tried to allocate more memory than available.",fix:"Find the memory leak (often unbounded arrays or caches). Increase --max-old-space-size as a stopgap."},{pattern:/port (\d+) (?:is\s+)?already in use|EADDRINUSE/,rootCause:"Another process is using the same port.",fix:"Kill the existing process (lsof -i :PORT) or use a different port."},{pattern:/AssertionError/,rootCause:"A test assertion or invariant check failed \u2014 actual value did not match expected.",fix:"Compare expected vs actual values; either update the test or fix the code."},{pattern:/CORS|Cross-Origin/,rootCause:"Browser blocked the request because the API origin does not match the page origin.",fix:"Configure CORS headers on the server (Access-Control-Allow-Origin) or use a proxy."}]});var IR={};$(IR,{cleanupAll:()=>_R,configure:()=>aSe,detectAvailableRuntimes:()=>a2,execute:()=>iSe,formatResult:()=>pSe,getActiveContainers:()=>dSe,getAuditLog:()=>fSe,getConfig:()=>oSe,getEvents:()=>uSe,getStats:()=>cSe,resetStats:()=>lSe});import{existsSync as RR,mkdirSync as z0e,readFileSync as i2,writeFileSync as Ld,unlinkSync as CR}from"fs";import{join as Yc,basename as o2}from"path";import{homedir as G0e,tmpdir as a0,platform as V0e}from"os";import{execSync as Xo,spawn as PR}from"child_process";import{randomBytes as Fd}from"crypto";import{EventEmitter as J0e}from"events";function l0(){z0e(c0,{recursive:!0})}function K0e(){if(l0(),RR(TR))try{ye={...ye,...JSON.parse(i2(TR,"utf-8"))}}catch{}}function u0(){l0();try{Ld(TR,JSON.stringify(ye,null,2),"utf-8")}catch{}}function Y0e(e){if(st.enableAuditLog){l0();try{Ld(AR,JSON.stringify({...e,timestamp:Date.now()})+`
1614
+ `,{flag:"a"})}catch{}}}function Z0e(){return l0(),RR(xR)||Ld(xR,JSON.stringify(Q0e,null,2),"utf-8"),xR}function a2(e=!1){if($R&&!e)return $R;let t=new Set;return Ji("docker")&&t.add("docker"),Ji("podman")&&t.add("podman"),Ji("runsc")&&t.add("gvisor"),Ji("firecracker")&&t.add("firecracker"),(Ji("wasmtime")||Ji("wasmer")||Ji("deno"))&&t.add("wasm"),t.add("process"),$R=t,t}function Ji(e){try{return Xo(V0e()==="win32"?`where ${e}`:`which ${e}`,{stdio:"pipe",timeout:3e3}),!0}catch{return!1}}function X0e(e){let t=a2();switch(e){case"maximum":if(t.has("gvisor"))return"gvisor";if(t.has("firecracker"))return"firecracker";if(t.has("docker"))return"docker";if(t.has("wasm"))return"wasm";break;case"high":if(t.has("firecracker"))return"firecracker";if(t.has("docker"))return"docker";if(t.has("podman"))return"podman";break;case"standard":if(t.has("docker"))return"docker";if(t.has("podman"))return"podman";break;case"lightweight":if(t.has("podman"))return"podman";if(t.has("docker"))return"docker";if(t.has("wasm"))return"wasm";break;case"minimal":if(t.has("wasm"))return"wasm";break;case"process":return"process"}return t.has("docker")?"docker":t.has("podman")?"podman":t.has("wasm")?"wasm":"process"}function c2(e,t){switch(e){case"python":return{entrypoint:["python","-c",t],needsFile:!1};case"node":case"javascript":return{entrypoint:["node","-e",t],needsFile:!1};case"typescript":return{entrypoint:["npx","tsx","/sandbox/code.ts"],needsFile:!0,filename:"/sandbox/code.ts"};case"go":return{entrypoint:["sh","-c","cd /sandbox && go run code.go"],needsFile:!0,filename:"/sandbox/code.go"};case"rust":return{entrypoint:["sh","-c","cd /sandbox && rustc code.rs -o /tmp/out && /tmp/out"],needsFile:!0,filename:"/sandbox/code.rs"};case"java":return{entrypoint:["sh","-c","cd /sandbox && javac Main.java && java -cp /sandbox Main"],needsFile:!0,filename:"/sandbox/Main.java"};case"ruby":return{entrypoint:["ruby","-e",t],needsFile:!1};case"shell":return{entrypoint:["sh","-c",t],needsFile:!1};case"cpp":return{entrypoint:["sh","-c","cd /sandbox && g++ code.cpp -o /tmp/out && /tmp/out"],needsFile:!0,filename:"/sandbox/code.cpp"};case"php":return{entrypoint:["php","-r",t],needsFile:!1};default:return{entrypoint:["sh","-c",t],needsFile:!1}}}function eSe(e,t,n,r){let s=["run","--rm","--name",n,"-i"];s.push("--memory",`${e.memoryMb||st.defaultMemoryMb}m`),s.push("--memory-swap",`${e.memoryMb||st.defaultMemoryMb}m`),s.push("--cpus",`${(e.cpuQuotaPercent||st.defaultCpuQuotaPercent)/100}`),s.push("--pids-limit",String(e.pidsLimit||st.defaultPidsLimit));let i=e.allowNetwork??st.allowNetworkByDefault;i?s.push("--network","bridge"):s.push("--network","none"),s.push("--read-only");let o=Math.min(e.diskMb||st.defaultDiskMb,256);if(s.push("--tmpfs",`/tmp:rw,noexec,nosuid,size=${o}m`),s.push("--tmpfs",`/sandbox:rw,noexec,nosuid,size=${o}m`),s.push("--tmpfs","/var/tmp:rw,noexec,nosuid,size=10m"),st.dropAllCapabilities&&s.push("--cap-drop","ALL"),st.enableNoNewPrivs&&s.push("--security-opt","no-new-privileges"),st.enableSeccomp&&t!=="gvisor")try{let a=Z0e();s.push("--security-opt",`seccomp=${a}`)}catch{}return st.enableAppArmor&&process.platform==="linux"&&s.push("--security-opt","apparmor=docker-default"),st.enableUserNamespaceRemap&&s.push("-u","65534:65534"),t==="gvisor"&&s.push("--runtime","runsc"),s.push("--ipc","private"),s.push("--pid","private"),s.push("-e","HOME=/tmp"),s.push("-e","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"),s.push("--hostname","sandbox"),i||s.push("--dns","127.0.0.1"),s.push("-w","/sandbox"),s.push(r),s}async function tSe(e,t,n){let r=Date.now(),s=`aiaca-vm-${Fd(8).toString("hex")}`,i=s2[e.language]||s2.unknown;if(Dd.add(s),st.pullPolicy==="always"||st.pullPolicy==="if_not_present"&&!await nSe(t,i))try{Xo(`${t==="gvisor"?"docker":t} pull ${i}`,{stdio:"pipe",timeout:18e4})}catch{}let o=t==="gvisor"?"docker":t,a=eSe(e,t,s,i),c=c2(e.language,e.code),l=null;return c.needsFile&&c.filename&&(l=Yc(a0(),`aiaca-vm-${Fd(6).toString("hex")}-${o2(c.filename)}`),Ld(l,e.code),a.splice(a.length-1,0,"-v",`${l}:${c.filename}:ro`)),a.push(...c.entrypoint),new Promise(u=>{let d=[],f="",p="",m=!1,g=!1,h=!1,v=PR(o,a,{stdio:["pipe","pipe","pipe"]});e.stdin&&v.stdin.write(e.stdin),v.stdin.end(),v.stdout.on("data",k=>{let S=k.toString();f+=S.slice(0,1024*1024),/Operation not permitted/i.test(S)&&d.push({type:"syscall_blocked",severity:"info",message:"Syscall blocked by seccomp",timestamp:Date.now()})}),v.stderr.on("data",k=>{let S=k.toString();p+=S.slice(0,1024*1024),/network is unreachable|name resolution failed|getaddrinfo/i.test(S)&&(d.push({type:"network_attempt",severity:"warn",message:"Network access blocked",timestamp:Date.now()}),ye.totalNetworkBlocks++),/permission denied/i.test(S)&&d.push({type:"fs_violation",severity:"warn",message:"Filesystem access blocked",timestamp:Date.now()}),/operation not permitted/i.test(S)&&d.push({type:"capability_attempt",severity:"warn",message:"Capability escalation blocked",timestamp:Date.now()})});let y=e.timeoutMs||st.defaultTimeoutMs,b=setTimeout(()=>{g=!0,ye.totalTimeouts++;try{Xo(`${o} kill ${s}`,{stdio:"pipe"})}catch{}v.kill("SIGKILL"),m=!0},y);v.on("close",k=>{clearTimeout(b);let S=Date.now()-r;Dd.delete(s);let x={};try{let D=Xo(`${o} inspect ${s} --format '{{json .State}}' 2>/dev/null`,{stdio:"pipe",encoding:"utf-8"});JSON.parse(D).OOMKilled&&(h=!0,ye.totalOomKilled++,d.push({type:"oom",severity:"critical",message:"Container killed by OOM killer",timestamp:Date.now()}))}catch{}let A=!1;if(st.alwaysFreshContainer||st.cleanupOnExit)try{Xo(`${o} rm -f ${s} 2>/dev/null`,{stdio:"pipe"}),A=!0}catch{A=!0}if(l)try{CR(l)}catch{}ye.totalExecutions++,ye.byRuntime[t]=(ye.byRuntime[t]||0)+1,ye.byIsolation[n]=(ye.byIsolation[n]||0)+1,ye.byLanguage[e.language]=(ye.byLanguage[e.language]||0)+1,ye.totalSecurityEvents+=d.length,ye.averageDurationMs=(ye.averageDurationMs*(ye.totalExecutions-1)+S)/ye.totalExecutions,u0(),Y0e({runtime:t,isolation:n,language:e.language,codeLength:e.code.length,duration:S,exitCode:k,success:k===0&&!g,securityEvents:d,timedOut:g,oomKilled:h,agentId:e.agentId,reason:e.reason}),og.emit("execution_complete",{containerId:s,success:k===0});for(let D of d)og.emit("security_event",D),D.severity==="critical"&&og.emit("critical_event",D);u({success:k===0&&!g&&!h,exitCode:k??-1,stdout:f,stderr:p,duration:S,runtime:t,isolationLevel:n,containerId:s,destroyed:A,resourceUsage:x,securityEvents:d,timedOut:g,killed:m,oomKilled:h})}),v.on("error",k=>{if(clearTimeout(b),Dd.delete(s),l)try{CR(l)}catch{}u(ag(r,t,n,s,k.message))})})}async function nSe(e,t){let n=e==="gvisor"?"docker":e;try{return Xo(`${n} image inspect ${t}`,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}async function rSe(e){let t=Date.now(),n=`aiaca-wasm-${Fd(6).toString("hex")}`;if(e.language!=="javascript"&&e.language!=="typescript")return ag(t,"wasm","minimal",n,`WASM only supports JS/TS, got: ${e.language}`);if(!Ji("deno"))return ag(t,"wasm","minimal",n,"Deno not installed");let r=Yc(a0(),`aiaca-deno-${Fd(4).toString("hex")}.${e.language==="typescript"?"ts":"js"}`);Ld(r,e.code);let s=["run","--no-prompt"];return e.allowNetwork&&s.push("--allow-net"),e.allowReadFilesystem&&e.allowReadFilesystem.length>0&&s.push(`--allow-read=${e.allowReadFilesystem.join(",")}`),s.push(r),new Promise(i=>{let o="",a="",c=[],l=!1,u=!1,d=PR("deno",s,{stdio:["pipe","pipe","pipe"]});e.stdin&&d.stdin.write(e.stdin),d.stdin.end(),d.stdout.on("data",p=>{o+=p.toString().slice(0,1024*1024)}),d.stderr.on("data",p=>{let m=p.toString();a+=m.slice(0,1024*1024),/Permission denied|requires.*permission/i.test(m)&&c.push({type:"capability_attempt",severity:"warn",message:"Deno permission denied",timestamp:Date.now()})});let f=setTimeout(()=>{l=!0,ye.totalTimeouts++,d.kill("SIGKILL"),u=!0},e.timeoutMs||st.defaultTimeoutMs);d.on("close",p=>{clearTimeout(f);try{CR(r)}catch{}let m=Date.now()-t;ye.totalExecutions++,ye.byRuntime.wasm=(ye.byRuntime.wasm||0)+1,ye.byIsolation.minimal=(ye.byIsolation.minimal||0)+1,ye.byLanguage[e.language]=(ye.byLanguage[e.language]||0)+1,u0(),i({success:p===0&&!l,exitCode:p??-1,stdout:o,stderr:a,duration:m,runtime:"wasm",isolationLevel:"minimal",containerId:n,destroyed:!0,resourceUsage:{},securityEvents:c,timedOut:l,killed:u,oomKilled:!1})})})}async function sSe(e){let t=Date.now(),n=`aiaca-proc-${Fd(4).toString("hex")}`,r=c2(e.language,e.code),s;if(r.needsFile&&r.filename){let i=Yc(a0(),`aiaca-proc-${Fd(4).toString("hex")}-${o2(r.filename)}`);Ld(i,e.code),s=r.entrypoint.map(o=>o===r.filename?i:o)}else s=r.entrypoint;return new Promise(i=>{let o="",a="",c=PR(s[0],s.slice(1),{env:{},cwd:a0()});e.stdin&&c.stdin.write(e.stdin),c.stdin.end(),c.stdout.on("data",u=>{o+=u.toString()}),c.stderr.on("data",u=>{a+=u.toString()});let l=setTimeout(()=>c.kill("SIGKILL"),e.timeoutMs||st.defaultTimeoutMs);c.on("close",u=>{clearTimeout(l);let d=Date.now()-t;ye.totalExecutions++,ye.byRuntime.process=(ye.byRuntime.process||0)+1,u0(),i({success:u===0,exitCode:u??-1,stdout:o,stderr:a,duration:d,runtime:"process",isolationLevel:"process",containerId:n,destroyed:!0,resourceUsage:{},securityEvents:[{type:"capability_attempt",severity:"warn",message:"WARNING: Code ran without sandboxing",timestamp:Date.now()}],timedOut:!1,killed:!1,oomKilled:!1,error:"Code ran in unsafe process mode (no isolation)"})})})}function ag(e,t,n,r,s){return{success:!1,exitCode:-1,stdout:"",stderr:"",duration:Date.now()-e,runtime:t,isolationLevel:n,containerId:r,destroyed:!0,resourceUsage:{},securityEvents:[],timedOut:!1,killed:!1,oomKilled:!1,error:s}}async function iSe(e){if(!st.enabled)return ag(Date.now(),"process","process","","Sandbox disabled");let t=e.isolationLevel||st.defaultIsolationLevel,n=X0e(t),r;try{n==="docker"||n==="podman"||n==="gvisor"?r=await tSe(e,n,t):n==="wasm"?r=await rSe(e):r=await sSe(e)}catch(s){r=ag(Date.now(),n,t,"",s.message)}return r}function _R(){let e=[],t=0;for(let n of["docker","podman"])if(Ji(n))try{let s=Xo(`${n} ps -a --filter "name=aiaca-(vm|wasm|proc)-" --format "{{.Names}}"`,{stdio:"pipe",encoding:"utf-8"}).split(`
1615
+ `).filter(Boolean);for(let i of s)try{Xo(`${n} rm -f ${i} 2>/dev/null`,{stdio:"pipe"}),t++}catch(o){e.push(`${i}: ${o.message}`)}}catch{}return Dd.clear(),{destroyed:t,errors:e}}function oSe(){return{...st}}function aSe(e){st={...st,...e}}function cSe(){return{...ye}}function lSe(){ye={totalExecutions:0,byRuntime:{},byIsolation:{},byLanguage:{},totalSecurityEvents:0,totalEscapeAttempts:0,totalOomKilled:0,totalTimeouts:0,totalNetworkBlocks:0,averageDurationMs:0,averageMemoryMb:0},u0()}function uSe(){return og}function dSe(){return Array.from(Dd)}function fSe(e=100){if(!RR(AR))return[];try{return i2(AR,"utf-8").split(`
1616
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function pSe(e){let t=[],n=e.success?"\u2713":e.timedOut?"\u23F1\uFE0F":e.oomKilled?"\u{1F4A5}":"\u2717";if(t.push(`${n} **Sandbox Execution** (${e.isolationLevel} via ${e.runtime})`),t.push(`Container: ${e.containerId} ${e.destroyed?"[destroyed]":"[ACTIVE]"}`),t.push(`Exit: ${e.exitCode} | Duration: ${e.duration}ms`),e.timedOut&&t.push("\u23F1\uFE0F TIMEOUT"),e.oomKilled&&t.push("\u{1F4A5} OUT OF MEMORY"),e.error&&t.push(`Error: ${e.error}`),t.push(""),e.securityEvents.length>0){t.push(`## \u{1F6E1}\uFE0F Security Events (${e.securityEvents.length})`);for(let r of e.securityEvents.slice(0,10)){let s=r.severity==="critical"?"\u{1F6A8}":r.severity==="warn"?"\u26A0\uFE0F ":"\u2139\uFE0F ";t.push(`${s} [${r.type}] ${r.message}`)}t.push("")}return e.stdout&&(t.push("## stdout"),t.push("```"),t.push(e.stdout.slice(0,5e3)),e.stdout.length>5e3&&t.push(`... (${e.stdout.length-5e3} more chars)`),t.push("```")),e.stderr&&(t.push("## stderr"),t.push("```"),t.push(e.stderr.slice(0,3e3)),t.push("```")),t.join(`
1617
+ `)}var W0e,st,c0,AR,TR,xR,og,ye,Dd,Q0e,s2,$R,MR=w(()=>{"use strict";W0e={enabled:!0,defaultIsolationLevel:"maximum",defaultTimeoutMs:3e4,defaultMemoryMb:256,defaultCpuQuotaPercent:50,defaultPidsLimit:64,defaultDiskMb:100,allowNetworkByDefault:!1,enableSeccomp:!0,enableAppArmor:!0,enableSelinux:!1,dropAllCapabilities:!0,enableUserNamespaceRemap:!0,enableNoNewPrivs:!0,alwaysFreshContainer:!0,cleanupOnExit:!0,recyclePoolSize:0,imageRegistry:"docker.io",pullPolicy:"if_not_present",enableAuditLog:!0},st={...W0e},c0=Yc(G0e(),".aiaca","micro-vm"),AR=Yc(c0,"audit.jsonl"),TR=Yc(c0,"stats.json"),xR=Yc(c0,"seccomp-profile.json"),og=new J0e;og.setMaxListeners(50);ye={totalExecutions:0,byRuntime:{},byIsolation:{},byLanguage:{},totalSecurityEvents:0,totalEscapeAttempts:0,totalOomKilled:0,totalTimeouts:0,totalNetworkBlocks:0,averageDurationMs:0,averageMemoryMb:0},Dd=new Set;K0e();Q0e={defaultAction:"SCMP_ACT_ERRNO",archMap:[{architecture:"SCMP_ARCH_X86_64",subArchitectures:["SCMP_ARCH_X86","SCMP_ARCH_X32"]}],syscalls:[{names:["read","write","open","openat","close","stat","fstat","lstat","newfstatat","lseek","access","faccessat","readlink","readlinkat","getcwd","mmap","mprotect","munmap","brk","mremap","madvise","execve","execveat","exit","exit_group","getpid","gettid","getuid","geteuid","getgid","getegid","getppid","set_tid_address","arch_prctl","prctl","clone","futex","set_robust_list","get_robust_list","rt_sigaction","rt_sigprocmask","rt_sigreturn","sigaltstack","rt_sigpending","rt_sigsuspend","rt_sigtimedwait","kill","tgkill","select","poll","epoll_create1","epoll_ctl","epoll_wait","epoll_pwait","clock_gettime","gettimeofday","time","nanosleep","clock_nanosleep","getdents","getdents64","pipe","pipe2","dup","dup2","dup3","fcntl","ioctl","fadvise64","sched_yield","getrandom"],action:"SCMP_ACT_ALLOW"}]};s2={python:"python:3.12-slim",node:"node:22-alpine",javascript:"node:22-alpine",typescript:"node:22-alpine",go:"golang:1.22-alpine",rust:"rust:1.78-alpine",java:"openjdk:21-slim",ruby:"ruby:3.3-alpine",shell:"alpine:latest",cpp:"gcc:13",csharp:"mcr.microsoft.com/dotnet/sdk:8.0-alpine",php:"php:8.3-cli-alpine",unknown:"alpine:latest"},$R=null;st.cleanupOnExit&&(process.on("exit",()=>{Dd.size>0&&_R()}),process.on("SIGINT",()=>{_R(),process.exit(0)}))});var qR={};$(qR,{abstractContent:()=>xSe,configure:()=>ESe,decideRoute:()=>ASe,detectLocalModels:()=>kSe,formatBudget:()=>qSe,formatRouteDecision:()=>NSe,generateComplianceReport:()=>BSe,getAuditLog:()=>OSe,getConfig:()=>MSe,getEvents:()=>LSe,getOrCreateBudget:()=>p0,getPreferredLocalModel:()=>cg,getStats:()=>DSe,listBudgets:()=>p2,listLocalModels:()=>f2,queueOfflineRequest:()=>PSe,recordAbstraction:()=>RSe,recordLocalCall:()=>_Se,recordRemoteSend:()=>TSe,resetStats:()=>FSe,setMode:()=>jSe});import{existsSync as jR,mkdirSync as l2,readFileSync as BR,writeFileSync as d0}from"fs";import{join as jd}from"path";import{homedir as mSe}from"os";import{execSync as gSe}from"child_process";import{createCipheriv as hSe,randomBytes as DR}from"crypto";import{EventEmitter as ySe}from"events";function f0(){l2(Bd,{recursive:!0}),l2(vSe,{recursive:!0})}function wSe(){if(f0(),jR(FR))try{it={...it,...JSON.parse(BR(FR,"utf-8"))}}catch{}}function Od(){f0();try{d0(FR,JSON.stringify(it,null,2),"utf-8")}catch{}}function NR(e){if(!ke.enableAuditLog)return;f0();let t={...e};t.content&&(t.content="[REDACTED]"),t.original&&(t.original="[REDACTED]");try{d0(LR,JSON.stringify({...t,timestamp:Date.now()})+`
1618
+ `,{flag:"a"})}catch{}}async function kSe(e=!1){if(!e&&Date.now()-u2<300*1e3)return Array.from(ea.values());try{let t=new AbortController,n=setTimeout(()=>t.abort(),2e3),r=await fetch(`${ke.ollamaEndpoint}/api/tags`,{signal:t.signal});if(clearTimeout(n),r.ok){let s=await r.json();for(let i of s.models||[]){let o=`ollama:${i.name}`;ea.set(o,{id:o,name:i.name,type:"ollama",endpoint:ke.ollamaEndpoint,capabilities:i.name.includes("embed")?["embed"]:["chat","code"],available:!0,contextWindow:i.details?.parameter_size?.includes("70")?8192:4096})}}}catch{}try{let t=new AbortController,n=setTimeout(()=>t.abort(),1e3),r=await fetch("http://localhost:8080/health",{signal:t.signal});clearTimeout(n),r.ok&&ea.set("llamacpp:default",{id:"llamacpp:default",name:"llama.cpp server",type:"llamacpp",endpoint:"http://localhost:8080",capabilities:["chat","code"],available:!0})}catch{}if(process.platform==="darwin")try{gSe("which mlx_lm.generate",{stdio:"pipe",timeout:1e3}),ea.set("mlx:available",{id:"mlx:available",name:"MLX (Apple Silicon)",type:"mlx",capabilities:["chat","code"],available:!0})}catch{}return u2=Date.now(),Array.from(ea.values())}function f2(){return Array.from(ea.values()).filter(e=>e.available)}function cg(){if(ke.preferredLocalModel)return ea.get(ke.preferredLocalModel);for(let e of ea.values())if(e.available)return e}function xSe(e,t){if(t==="none")return{original:e,abstracted:e,level:t,reductionRatio:1,bytesRemoved:0,sensitiveSignalsRemoved:0};let n="",r=0;switch(t){case"summary":n=$Se(e);break;case"diff":n=e.length>1e3?d2(e):e;break;case"structure":n=d2(e);break;case"redacted":let s=CSe(e);n=s.text,r=s.removed;break}return{original:e,abstracted:n,level:t,reductionRatio:n.length/e.length,bytesRemoved:e.length-n.length,sensitiveSignalsRemoved:r}}function $Se(e){let n=e.split(`
1609
1619
  `).length,r=e.split(/\s+/).length,s=[];/^(function|const|let|var|class|interface|type)\s/m.test(e)&&s.push("JavaScript/TypeScript"),/^def\s|^class\s|^import\s/m.test(e)&&s.push("Python"),/^package\s|^func\s/m.test(e)&&s.push("Go"),/^fn\s|^use\s/m.test(e)&&s.push("Rust");let i=[],o=[/(?:function|def|class|interface|type|fn)\s+(\w+)/g];for(let a of o){let c;for(;(c=a.exec(e))!==null&&i.length<20;)i.push(c[1])}return["[ABSTRACTED SUMMARY]",`Lines: ${n} | Words: ${r} | Bytes: ${e.length}`,s.length>0?`Language hints: ${s.join(", ")}`:"",i.length>0?`Symbols: ${i.join(", ")}`:"","","First 500 chars:",e.slice(0,500),e.length>500?`
1610
1620
  [... ${e.length-500} bytes elided ...]`:""].filter(Boolean).join(`
1611
1621
  `)}function d2(e){let t=[],n=e.split(`
1612
1622
  `);for(let r of n)/^(\s*)(function|class|interface|type|def|fn|impl|trait|public|private|export)\s/.test(r)&&t.push(r.trim()),/^(\s*)(\/\/|\/\*|#|<!--)/.test(r)&&r.length<200&&t.push(r.trim());return["[STRUCTURE-ONLY ABSTRACTION]",`Original: ${e.length} bytes, ${n.length} lines`,`Structure: ${t.length} significant elements`,"",...t.slice(0,100)].join(`
1613
- `)}function $Se(e){let t=0,n=e,r=[{pat:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,name:"EMAIL"},{pat:/\b\d{3}-\d{2}-\d{4}\b/g,name:"SSN"},{pat:/\b(?:\d{4}[\s\-]?){3}\d{4}\b/g,name:"CARD"},{pat:/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,name:"AWS_KEY"},{pat:/\bAIza[0-9A-Za-z\-_]{35}\b/g,name:"GCP_KEY"},{pat:/\bghp_[A-Za-z0-9]{36}\b/g,name:"GITHUB_TOKEN"},{pat:/\bsk-[A-Za-z0-9]{32,}\b/g,name:"OPENAI_KEY"},{pat:/\beyJ[A-Za-z0-9_=\-]+\.eyJ[A-Za-z0-9_=\-]+\.[A-Za-z0-9_\-+/=]+\b/g,name:"JWT"},{pat:/-----BEGIN [^-]+-----[\s\S]+?-----END [^-]+-----/g,name:"PEM_KEY"},{pat:/\b(?:[a-z]{3,8}\s+){11}[a-z]{3,8}\b/gi,name:"MNEMONIC"}];for(let{pat:s,name:i}of r)n=n.replace(s,()=>(t++,`[REDACTED:${i}]`));return{text:n,removed:t}}function CSe(e){if(!ke.enabled)return{decision:"remote",reason:"Local-first disabled"};switch(it.totalRequests++,it.byMode[ke.privacyMode]=(it.byMode[ke.privacyMode]||0)+1,ke.privacyMode){case"full_remote":return{decision:"remote",reason:"Full remote mode"};case"offline":return{decision:"queue_offline",reason:"Offline mode active"};case"local_only":{let t=cg();return t?{decision:"local",reason:`Local-only routed to ${t.name}`,modelHint:t.id}:{decision:"reject",reason:"No local model available"}}case"abstracted":return{decision:"abstracted_remote",reason:"Abstracted mode",abstractionLevel:ke.defaultAbstractionLevel};default:{if(ke.routeByClassification){if(e.classification==="secret"){let t=cg();return t?{decision:"local",reason:"Secret data routed local",modelHint:t.id}:{decision:"reject",reason:"Secret data + no local model"}}if(e.classification==="confidential"){let t=cg();return t?{decision:"local",reason:"Confidential routed local",modelHint:t.id}:{decision:"abstracted_remote",reason:"Confidential abstracted (no local)",abstractionLevel:"redacted"}}}if(e.isSensitive&&ke.localForSensitive){let t=cg();if(t)return{decision:"local",reason:"Sensitive routed local",modelHint:t.id}}return{decision:"remote",reason:"Hybrid: routed to remote"}}}}function p0(e){let t=OR.get(e);return t||(t={sessionId:e,bytesSentTotal:0,bytesAbstractedAway:0,remoteCallsCount:0,localCallsCount:0,maxBytesPerSession:ke.maxBytesPerSession,warningThreshold:Math.floor(ke.maxBytesPerSession*(ke.warnAtPercent/100))},OR.set(e,t)),t}function ASe(e,t){if(!ke.enableBudget)return{allowed:!0,reason:"Budget disabled"};let n=p0(e);return n.bytesSentTotal+t>n.maxBytesPerSession?(it.totalBudgetBlocks++,Od(),NR({event:"budget_exceeded",sessionId:e,attempted:t,used:n.bytesSentTotal,max:n.maxBytesPerSession}),lg.emit("budget_exceeded",{sessionId:e,bytes:t,budget:n}),{allowed:!1,reason:`Privacy budget exceeded: ${n.bytesSentTotal}+${t} > ${n.maxBytesPerSession}`}):(n.bytesSentTotal+=t,n.remoteCallsCount++,it.totalRemoteRouted++,it.totalBytesSent+=t,n.bytesSentTotal>n.warningThreshold&&n.bytesSentTotal-t<=n.warningThreshold&&(it.totalBudgetWarnings++,lg.emit("budget_warning",{sessionId:e,used:n.bytesSentTotal,max:n.maxBytesPerSession})),Od(),{allowed:!0,reason:"OK"})}function TSe(e){let t=p0(e);t.localCallsCount++,it.totalLocalRouted++,Od()}function _Se(e,t){let n=p0(e);n.bytesAbstractedAway+=t,it.totalAbstracted++,it.totalBytesAbstractedAway+=t,Od()}function p2(){return Array.from(OR.values())}function RSe(e,t){let n=DR(8).toString("hex");f0();let r={prompt:t};if(ke.encryptLocalCache){let i=PSe(),o=DR(12),a=gSe("aes-256-gcm",i,o),c=Buffer.concat([a.update(t,"utf-8"),a.final()]);r={iv:o.toString("hex"),authTag:a.getAuthTag().toString("hex"),ciphertext:c.toString("base64")}}let s={id:n,sessionId:e,prompt:ke.encryptLocalCache?"":t,queuedAt:Date.now(),encrypted:ke.encryptLocalCache};try{d0(vSe,JSON.stringify({...s,payload:r})+`
1614
- `,{flag:"a"})}catch{}return it.totalOfflineQueued++,Od(),NR({event:"offline_queued",id:n,sessionId:e}),{id:n}}function PSe(){if(jR(ER))try{return Buffer.from(BR(ER,"utf-8").trim(),"hex")}catch{}let e=DR(32);try{d0(ER,e.toString("hex"),{encoding:"utf-8",mode:384})}catch{}return e}function ISe(){return{...ke}}function MSe(e){ke={...ke,...e}}function ESe(){return{...it}}function DSe(){it={totalRequests:0,totalLocalRouted:0,totalRemoteRouted:0,totalAbstracted:0,totalBytesAbstractedAway:0,totalBytesSent:0,totalBudgetWarnings:0,totalBudgetBlocks:0,totalOfflineQueued:0,byMode:{},byAbstractionLevel:{}},Od()}function FSe(){return lg}function LSe(e=100){if(!jR(LR))return[];try{return BR(LR,"utf-8").split(`
1615
- `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function OSe(e){ke.privacyMode=e,NR({event:"mode_changed",mode:e}),lg.emit("mode_changed",{mode:e})}function jSe(){let e=[],t=f2(),n=p2();e.push("# Local-First Data Mode Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Current Mode"),e.push(`- Privacy mode: ${ke.privacyMode}`),e.push(`- Local models available: ${t.length}`);for(let r of t)e.push(` - ${r.name} (${r.type})`);e.push(""),e.push("## Statistics"),e.push(`- Total requests: ${it.totalRequests}`),e.push(`- \u{1F3E0} Local routed: ${it.totalLocalRouted}`),e.push(`- \u{1F310} Remote routed: ${it.totalRemoteRouted}`),e.push(`- \u{1F3AD} Abstracted: ${it.totalAbstracted}`),e.push(`- \u{1F4E4} Total bytes sent: ${(it.totalBytesSent/1024).toFixed(1)}KB`),e.push(`- \u{1F6E1}\uFE0F Bytes abstracted away: ${(it.totalBytesAbstractedAway/1024).toFixed(1)}KB`),e.push(`- \u26A0\uFE0F Budget warnings: ${it.totalBudgetWarnings}`),e.push(`- \u{1F6AB} Budget blocks: ${it.totalBudgetBlocks}`),e.push(`- \u{1F4E5} Offline queued: ${it.totalOfflineQueued}`),e.push(""),e.push("## Active Privacy Budgets");for(let r of n){let s=(r.bytesSentTotal/r.maxBytesPerSession*100).toFixed(1);e.push(`- ${r.sessionId}: ${(r.bytesSentTotal/1024).toFixed(1)}KB / ${(r.maxBytesPerSession/1024).toFixed(1)}KB (${s}%) | ${r.localCallsCount}L/${r.remoteCallsCount}R`)}return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 4 privacy modes (full_remote/abstracted/local_only/hybrid)"),e.push("- \u2713 Local model preference (Ollama/llama.cpp/MLX)"),e.push("- \u2713 Client-side abstraction (summary/diff/structure/redacted)"),e.push(`- ${ke.routeByClassification?"\u2713":"\u2717"} Route by data classification`),e.push(`- ${ke.localForSensitive?"\u2713":"\u2717"} Local for sensitive data`),e.push(`- ${ke.enableBudget?"\u2713":"\u2717"} Privacy budget per session`),e.push(`- ${ke.encryptLocalCache?"\u2713":"\u2717"} Encrypted local cache (AES-256-GCM)`),e.push(`- ${ke.enableOfflineQueue?"\u2713":"\u2717"} Offline queue`),e.push(`- Max bytes/session: ${(ke.maxBytesPerSession/1024).toFixed(0)}KB`),e.join(`
1616
- `)}function BSe(e){let t=e.decision==="local"?"\u{1F3E0}":e.decision==="remote"?"\u{1F310}":e.decision==="abstracted_remote"?"\u{1F3AD}":e.decision==="queue_offline"?"\u{1F4E5}":"\u{1F6AB}",n=[];return n.push(`${t} **${e.decision.toUpperCase()}**`),n.push(`Reason: ${e.reason}`),e.abstractionLevel&&n.push(`Abstraction level: ${e.abstractionLevel}`),e.modelHint&&n.push(`Model: ${e.modelHint}`),n.join(`
1617
- `)}function NSe(e){let t=e.bytesSentTotal/e.maxBytesPerSession*100,n=qSe(t);return[`Session: ${e.sessionId}`,` ${n} ${t.toFixed(1)}%`,` Sent: ${(e.bytesSentTotal/1024).toFixed(1)}KB`,` Abstracted: ${(e.bytesAbstractedAway/1024).toFixed(1)}KB`,` Local calls: ${e.localCallsCount}`,` Remote calls: ${e.remoteCallsCount}`,` Limit: ${(e.maxBytesPerSession/1024).toFixed(1)}KB`].join(`
1618
- `)}function qSe(e){let t=Math.min(20,Math.floor(e/5));return"["+"\u2588".repeat(t)+"\u2591".repeat(20-t)+"]"}var ySe,ke,Bd,FR,LR,ER,bSe,vSe,lg,ea,OR,u2,it,UR=w(()=>{"use strict";ySe={enabled:!0,privacyMode:"hybrid",ollamaEndpoint:"http://localhost:11434",localForSensitive:!0,routeByClassification:!0,defaultAbstractionLevel:"summary",enableBudget:!0,maxBytesPerSession:10*1024*1024,warnAtPercent:75,encryptLocalCache:!0,enableOfflineQueue:!0,enableAuditLog:!0},ke={...ySe},Bd=jd(pSe(),".aiaca","local-first"),FR=jd(Bd,"stats.json"),LR=jd(Bd,"audit.jsonl"),ER=jd(Bd,"cache.key"),bSe=jd(Bd,"cache"),vSe=jd(Bd,"offline-queue.jsonl"),lg=new hSe;lg.setMaxListeners(50);ea=new Map,OR=new Map,u2=0,it={totalRequests:0,totalLocalRouted:0,totalRemoteRouted:0,totalAbstracted:0,totalBytesAbstractedAway:0,totalBytesSent:0,totalBudgetWarnings:0,totalBudgetBlocks:0,totalOfflineQueued:0,byMode:{},byAbstractionLevel:{}};SSe()});import{execSync as m2}from"child_process";import{readFileSync as USe,writeFileSync as HSe}from"fs";import{resolve as zSe}from"path";import*as g2 from"readline";var HR,zR,GR,VR,JR,WR,KR,YR,QR,ZR,XR,e1,t1,n1,r1,s1,i1,o1,h2,y2,b2,v2,S2,w2,k2,x2,$2,C2,A2,T2,_2,R2,P2,I2,M2,E2,D2,F2,L2,O2,j2,B2,N2,q2,U2,H2,z2,G2,V2,J2,W2,K2,Y2,Q2,Z2,X2,eq,tq,nq,rq,sq,iq,oq,aq,cq,lq,uq,dq,fq,pq,mq,gq,hq,yq,bq,vq,Sq,wq,kq,xq,$q,Cq,Aq=w(()=>{"use strict";mu();HR={definition:{name:"task_stop",description:"Stop a running background task.",parameters:[{name:"id",type:"string",description:"Task ID to stop",required:!0}],requiresPermission:!0},handler:async e=>wy(e.id)?`Task ${e.id} stopped.`:`Task ${e.id} not found or not running.`},zR={definition:{name:"task_update",description:"Send a message/update to a running task.",parameters:[{name:"id",type:"string",description:"Task ID",required:!0},{name:"message",type:"string",description:"Message to send",required:!0}]},handler:async e=>{let t=pu(e.id);return t?(t.output+=`
1619
- [Update]: ${e.message}`,`Update sent to task ${e.id}.`):`Task ${e.id} not found.`}},GR={definition:{name:"task_output",description:"Read the full output of a task.",parameters:[{name:"id",type:"string",description:"Task ID",required:!0}]},handler:async e=>{let t=pu(e.id);return t?t.output||"(no output)":`Task ${e.id} not found.`}},VR={definition:{name:"notebook_edit",description:"Edit a Jupyter notebook cell.",parameters:[{name:"path",type:"string",description:"Notebook file path",required:!0},{name:"cell_index",type:"number",description:"Cell index (0-based)",required:!0},{name:"new_source",type:"string",description:"New cell source content",required:!0},{name:"cell_type",type:"string",description:"Cell type: code or markdown",required:!1}],requiresPermission:!0},handler:async(e,t)=>{let n=zSe(t.cwd,e.path);try{let r=JSON.parse(USe(n,"utf-8")),s=e.cell_index;return s<0||s>=r.cells.length?`Error: cell index ${s} out of range (0-${r.cells.length-1})`:(r.cells[s].source=e.new_source.split(`
1623
+ `)}function CSe(e){let t=0,n=e,r=[{pat:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,name:"EMAIL"},{pat:/\b\d{3}-\d{2}-\d{4}\b/g,name:"SSN"},{pat:/\b(?:\d{4}[\s\-]?){3}\d{4}\b/g,name:"CARD"},{pat:/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,name:"AWS_KEY"},{pat:/\bAIza[0-9A-Za-z\-_]{35}\b/g,name:"GCP_KEY"},{pat:/\bghp_[A-Za-z0-9]{36}\b/g,name:"GITHUB_TOKEN"},{pat:/\bsk-[A-Za-z0-9]{32,}\b/g,name:"OPENAI_KEY"},{pat:/\beyJ[A-Za-z0-9_=\-]+\.eyJ[A-Za-z0-9_=\-]+\.[A-Za-z0-9_\-+/=]+\b/g,name:"JWT"},{pat:/-----BEGIN [^-]+-----[\s\S]+?-----END [^-]+-----/g,name:"PEM_KEY"},{pat:/\b(?:[a-z]{3,8}\s+){11}[a-z]{3,8}\b/gi,name:"MNEMONIC"}];for(let{pat:s,name:i}of r)n=n.replace(s,()=>(t++,`[REDACTED:${i}]`));return{text:n,removed:t}}function ASe(e){if(!ke.enabled)return{decision:"remote",reason:"Local-first disabled"};switch(it.totalRequests++,it.byMode[ke.privacyMode]=(it.byMode[ke.privacyMode]||0)+1,ke.privacyMode){case"full_remote":return{decision:"remote",reason:"Full remote mode"};case"offline":return{decision:"queue_offline",reason:"Offline mode active"};case"local_only":{let t=cg();return t?{decision:"local",reason:`Local-only routed to ${t.name}`,modelHint:t.id}:{decision:"reject",reason:"No local model available"}}case"abstracted":return{decision:"abstracted_remote",reason:"Abstracted mode",abstractionLevel:ke.defaultAbstractionLevel};default:{if(ke.routeByClassification){if(e.classification==="secret"){let t=cg();return t?{decision:"local",reason:"Secret data routed local",modelHint:t.id}:{decision:"reject",reason:"Secret data + no local model"}}if(e.classification==="confidential"){let t=cg();return t?{decision:"local",reason:"Confidential routed local",modelHint:t.id}:{decision:"abstracted_remote",reason:"Confidential abstracted (no local)",abstractionLevel:"redacted"}}}if(e.isSensitive&&ke.localForSensitive){let t=cg();if(t)return{decision:"local",reason:"Sensitive routed local",modelHint:t.id}}return{decision:"remote",reason:"Hybrid: routed to remote"}}}}function p0(e){let t=OR.get(e);return t||(t={sessionId:e,bytesSentTotal:0,bytesAbstractedAway:0,remoteCallsCount:0,localCallsCount:0,maxBytesPerSession:ke.maxBytesPerSession,warningThreshold:Math.floor(ke.maxBytesPerSession*(ke.warnAtPercent/100))},OR.set(e,t)),t}function TSe(e,t){if(!ke.enableBudget)return{allowed:!0,reason:"Budget disabled"};let n=p0(e);return n.bytesSentTotal+t>n.maxBytesPerSession?(it.totalBudgetBlocks++,Od(),NR({event:"budget_exceeded",sessionId:e,attempted:t,used:n.bytesSentTotal,max:n.maxBytesPerSession}),lg.emit("budget_exceeded",{sessionId:e,bytes:t,budget:n}),{allowed:!1,reason:`Privacy budget exceeded: ${n.bytesSentTotal}+${t} > ${n.maxBytesPerSession}`}):(n.bytesSentTotal+=t,n.remoteCallsCount++,it.totalRemoteRouted++,it.totalBytesSent+=t,n.bytesSentTotal>n.warningThreshold&&n.bytesSentTotal-t<=n.warningThreshold&&(it.totalBudgetWarnings++,lg.emit("budget_warning",{sessionId:e,used:n.bytesSentTotal,max:n.maxBytesPerSession})),Od(),{allowed:!0,reason:"OK"})}function _Se(e){let t=p0(e);t.localCallsCount++,it.totalLocalRouted++,Od()}function RSe(e,t){let n=p0(e);n.bytesAbstractedAway+=t,it.totalAbstracted++,it.totalBytesAbstractedAway+=t,Od()}function p2(){return Array.from(OR.values())}function PSe(e,t){let n=DR(8).toString("hex");f0();let r={prompt:t};if(ke.encryptLocalCache){let i=ISe(),o=DR(12),a=hSe("aes-256-gcm",i,o),c=Buffer.concat([a.update(t,"utf-8"),a.final()]);r={iv:o.toString("hex"),authTag:a.getAuthTag().toString("hex"),ciphertext:c.toString("base64")}}let s={id:n,sessionId:e,prompt:ke.encryptLocalCache?"":t,queuedAt:Date.now(),encrypted:ke.encryptLocalCache};try{d0(SSe,JSON.stringify({...s,payload:r})+`
1624
+ `,{flag:"a"})}catch{}return it.totalOfflineQueued++,Od(),NR({event:"offline_queued",id:n,sessionId:e}),{id:n}}function ISe(){if(jR(ER))try{return Buffer.from(BR(ER,"utf-8").trim(),"hex")}catch{}let e=DR(32);try{d0(ER,e.toString("hex"),{encoding:"utf-8",mode:384})}catch{}return e}function MSe(){return{...ke}}function ESe(e){ke={...ke,...e}}function DSe(){return{...it}}function FSe(){it={totalRequests:0,totalLocalRouted:0,totalRemoteRouted:0,totalAbstracted:0,totalBytesAbstractedAway:0,totalBytesSent:0,totalBudgetWarnings:0,totalBudgetBlocks:0,totalOfflineQueued:0,byMode:{},byAbstractionLevel:{}},Od()}function LSe(){return lg}function OSe(e=100){if(!jR(LR))return[];try{return BR(LR,"utf-8").split(`
1625
+ `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function jSe(e){ke.privacyMode=e,NR({event:"mode_changed",mode:e}),lg.emit("mode_changed",{mode:e})}function BSe(){let e=[],t=f2(),n=p2();e.push("# Local-First Data Mode Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Current Mode"),e.push(`- Privacy mode: ${ke.privacyMode}`),e.push(`- Local models available: ${t.length}`);for(let r of t)e.push(` - ${r.name} (${r.type})`);e.push(""),e.push("## Statistics"),e.push(`- Total requests: ${it.totalRequests}`),e.push(`- \u{1F3E0} Local routed: ${it.totalLocalRouted}`),e.push(`- \u{1F310} Remote routed: ${it.totalRemoteRouted}`),e.push(`- \u{1F3AD} Abstracted: ${it.totalAbstracted}`),e.push(`- \u{1F4E4} Total bytes sent: ${(it.totalBytesSent/1024).toFixed(1)}KB`),e.push(`- \u{1F6E1}\uFE0F Bytes abstracted away: ${(it.totalBytesAbstractedAway/1024).toFixed(1)}KB`),e.push(`- \u26A0\uFE0F Budget warnings: ${it.totalBudgetWarnings}`),e.push(`- \u{1F6AB} Budget blocks: ${it.totalBudgetBlocks}`),e.push(`- \u{1F4E5} Offline queued: ${it.totalOfflineQueued}`),e.push(""),e.push("## Active Privacy Budgets");for(let r of n){let s=(r.bytesSentTotal/r.maxBytesPerSession*100).toFixed(1);e.push(`- ${r.sessionId}: ${(r.bytesSentTotal/1024).toFixed(1)}KB / ${(r.maxBytesPerSession/1024).toFixed(1)}KB (${s}%) | ${r.localCallsCount}L/${r.remoteCallsCount}R`)}return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 4 privacy modes (full_remote/abstracted/local_only/hybrid)"),e.push("- \u2713 Local model preference (Ollama/llama.cpp/MLX)"),e.push("- \u2713 Client-side abstraction (summary/diff/structure/redacted)"),e.push(`- ${ke.routeByClassification?"\u2713":"\u2717"} Route by data classification`),e.push(`- ${ke.localForSensitive?"\u2713":"\u2717"} Local for sensitive data`),e.push(`- ${ke.enableBudget?"\u2713":"\u2717"} Privacy budget per session`),e.push(`- ${ke.encryptLocalCache?"\u2713":"\u2717"} Encrypted local cache (AES-256-GCM)`),e.push(`- ${ke.enableOfflineQueue?"\u2713":"\u2717"} Offline queue`),e.push(`- Max bytes/session: ${(ke.maxBytesPerSession/1024).toFixed(0)}KB`),e.join(`
1626
+ `)}function NSe(e){let t=e.decision==="local"?"\u{1F3E0}":e.decision==="remote"?"\u{1F310}":e.decision==="abstracted_remote"?"\u{1F3AD}":e.decision==="queue_offline"?"\u{1F4E5}":"\u{1F6AB}",n=[];return n.push(`${t} **${e.decision.toUpperCase()}**`),n.push(`Reason: ${e.reason}`),e.abstractionLevel&&n.push(`Abstraction level: ${e.abstractionLevel}`),e.modelHint&&n.push(`Model: ${e.modelHint}`),n.join(`
1627
+ `)}function qSe(e){let t=e.bytesSentTotal/e.maxBytesPerSession*100,n=USe(t);return[`Session: ${e.sessionId}`,` ${n} ${t.toFixed(1)}%`,` Sent: ${(e.bytesSentTotal/1024).toFixed(1)}KB`,` Abstracted: ${(e.bytesAbstractedAway/1024).toFixed(1)}KB`,` Local calls: ${e.localCallsCount}`,` Remote calls: ${e.remoteCallsCount}`,` Limit: ${(e.maxBytesPerSession/1024).toFixed(1)}KB`].join(`
1628
+ `)}function USe(e){let t=Math.min(20,Math.floor(e/5));return"["+"\u2588".repeat(t)+"\u2591".repeat(20-t)+"]"}var bSe,ke,Bd,FR,LR,ER,vSe,SSe,lg,ea,OR,u2,it,UR=w(()=>{"use strict";bSe={enabled:!0,privacyMode:"hybrid",ollamaEndpoint:"http://localhost:11434",localForSensitive:!0,routeByClassification:!0,defaultAbstractionLevel:"summary",enableBudget:!0,maxBytesPerSession:10*1024*1024,warnAtPercent:75,encryptLocalCache:!0,enableOfflineQueue:!0,enableAuditLog:!0},ke={...bSe},Bd=jd(mSe(),".aiaca","local-first"),FR=jd(Bd,"stats.json"),LR=jd(Bd,"audit.jsonl"),ER=jd(Bd,"cache.key"),vSe=jd(Bd,"cache"),SSe=jd(Bd,"offline-queue.jsonl"),lg=new ySe;lg.setMaxListeners(50);ea=new Map,OR=new Map,u2=0,it={totalRequests:0,totalLocalRouted:0,totalRemoteRouted:0,totalAbstracted:0,totalBytesAbstractedAway:0,totalBytesSent:0,totalBudgetWarnings:0,totalBudgetBlocks:0,totalOfflineQueued:0,byMode:{},byAbstractionLevel:{}};wSe()});import{execSync as m2}from"child_process";import{readFileSync as HSe,writeFileSync as zSe}from"fs";import{resolve as GSe}from"path";import*as g2 from"readline";var HR,zR,GR,VR,JR,WR,KR,YR,QR,ZR,XR,e1,t1,n1,r1,s1,i1,o1,h2,y2,b2,v2,S2,w2,k2,x2,$2,C2,A2,T2,_2,R2,P2,I2,M2,E2,D2,F2,L2,O2,j2,B2,N2,q2,U2,H2,z2,G2,V2,J2,W2,K2,Y2,Q2,Z2,X2,eq,tq,nq,rq,sq,iq,oq,aq,cq,lq,uq,dq,fq,pq,mq,gq,hq,yq,bq,vq,Sq,wq,kq,xq,$q,Cq,Aq=w(()=>{"use strict";mu();HR={definition:{name:"task_stop",description:"Stop a running background task.",parameters:[{name:"id",type:"string",description:"Task ID to stop",required:!0}],requiresPermission:!0},handler:async e=>wy(e.id)?`Task ${e.id} stopped.`:`Task ${e.id} not found or not running.`},zR={definition:{name:"task_update",description:"Send a message/update to a running task.",parameters:[{name:"id",type:"string",description:"Task ID",required:!0},{name:"message",type:"string",description:"Message to send",required:!0}]},handler:async e=>{let t=pu(e.id);return t?(t.output+=`
1629
+ [Update]: ${e.message}`,`Update sent to task ${e.id}.`):`Task ${e.id} not found.`}},GR={definition:{name:"task_output",description:"Read the full output of a task.",parameters:[{name:"id",type:"string",description:"Task ID",required:!0}]},handler:async e=>{let t=pu(e.id);return t?t.output||"(no output)":`Task ${e.id} not found.`}},VR={definition:{name:"notebook_edit",description:"Edit a Jupyter notebook cell.",parameters:[{name:"path",type:"string",description:"Notebook file path",required:!0},{name:"cell_index",type:"number",description:"Cell index (0-based)",required:!0},{name:"new_source",type:"string",description:"New cell source content",required:!0},{name:"cell_type",type:"string",description:"Cell type: code or markdown",required:!1}],requiresPermission:!0},handler:async(e,t)=>{let n=GSe(t.cwd,e.path);try{let r=JSON.parse(HSe(n,"utf-8")),s=e.cell_index;return s<0||s>=r.cells.length?`Error: cell index ${s} out of range (0-${r.cells.length-1})`:(r.cells[s].source=e.new_source.split(`
1620
1630
  `).map((i,o,a)=>o<a.length-1?i+`
1621
- `:i),e.cell_type&&(r.cells[s].cell_type=e.cell_type),HSe(n,JSON.stringify(r,null,1),"utf-8"),`Cell ${s} updated in ${n}`)}catch(r){return`Error: ${r.message}`}}},JR={definition:{name:"ask_user",description:"Ask the user a question and wait for their response.",parameters:[{name:"question",type:"string",description:"Question to ask",required:!0}]},handler:async e=>{let t=g2.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(`
1631
+ `:i),e.cell_type&&(r.cells[s].cell_type=e.cell_type),zSe(n,JSON.stringify(r,null,1),"utf-8"),`Cell ${s} updated in ${n}`)}catch(r){return`Error: ${r.message}`}}},JR={definition:{name:"ask_user",description:"Ask the user a question and wait for their response.",parameters:[{name:"question",type:"string",description:"Question to ask",required:!0}]},handler:async e=>{let t=g2.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(`
1622
1632
  \u2753 ${e.question}
1623
1633
  > `,r=>{t.close(),n(r.trim())})})}},WR={definition:{name:"tool_search",description:"Search available tools by name or description.",parameters:[{name:"query",type:"string",description:"Search query",required:!0}]},handler:async(e,t)=>{let{getTools:n}=await Promise.resolve().then(()=>(Ls(),Tq)),r=e.query.toLowerCase(),s=n().filter(i=>i.definition.name.includes(r)||i.definition.description.toLowerCase().includes(r));return s.length?s.map(i=>`${i.definition.name}: ${i.definition.description}`).join(`
1624
1634
  `):"No matching tools found."}},KR={definition:{name:"enter_plan_mode",description:"Enter plan mode (read-only). No file writes or shell commands allowed.",parameters:[]},handler:async(e,t)=>(t.permissions.mode="plan","\u{1F4CB} Plan mode activated. Only read operations allowed.")},YR={definition:{name:"exit_plan_mode",description:"Exit plan mode and return to normal permissions.",parameters:[]},handler:async(e,t)=>(t.permissions.mode="ask","\u270F\uFE0F Plan mode deactivated. Normal permissions restored.")},QR={definition:{name:"enter_worktree",description:"Create and enter a git worktree for isolated work.",parameters:[{name:"branch",type:"string",description:"Branch name for worktree",required:!0},{name:"path",type:"string",description:"Worktree path (default: ../<branch>)",required:!1}],requiresPermission:!0},handler:async(e,t)=>{let n=e.branch,r=e.path||`../${n}`;try{return m2(`git worktree add "${r}" -b "${n}"`,{cwd:t.cwd,encoding:"utf-8"}),`Worktree created at ${r} on branch ${n}`}catch(s){return`Error: ${s.message}`}}},ZR={definition:{name:"exit_worktree",description:"Remove a git worktree.",parameters:[{name:"path",type:"string",description:"Worktree path to remove",required:!0}],requiresPermission:!0},handler:async(e,t)=>{try{return m2(`git worktree remove "${e.path}"`,{cwd:t.cwd,encoding:"utf-8"}),`Worktree at ${e.path} removed.`}catch(n){return`Error: ${n.message}`}}},XR={definition:{name:"team_create",description:"Create a teammate agent with a specific role.",parameters:[{name:"name",type:"string",description:"Teammate name",required:!0},{name:"role",type:"string",description:"Role description",required:!0}],requiresPermission:!0,permissionCategory:"agent"},handler:async e=>{let{createTask:t}=await Promise.resolve().then(()=>(mu(),Ax)),n=t("agent",{prompt:`[Team: ${e.name}] Role: ${e.role}`});return`Teammate "${e.name}" created (task ${n.id}). Role: ${e.role}`}},e1={definition:{name:"team_delete",description:"Delete a teammate agent.",parameters:[{name:"name",type:"string",description:"Teammate name or task ID",required:!0}]},handler:async e=>{let n=Ao().find(r=>r.prompt?.includes(`[Team: ${e.name}]`)||r.id===e.name);return n?(wy(n.id),`Teammate "${e.name}" deleted.`):`Teammate "${e.name}" not found.`}},t1={definition:{name:"send_message",description:"Send a message to another agent/teammate.",parameters:[{name:"to",type:"string",description:"Recipient agent name or ID",required:!0},{name:"message",type:"string",description:"Message content",required:!0}]},handler:async e=>{let n=Ao().find(r=>r.prompt?.includes(`[Team: ${e.to}]`)||r.id===e.to);return n?(n.output+=`
@@ -1865,15 +1875,15 @@ ${n.formatRule(s)}`}if(r==="remove"&&e.rule_id)return n.removeRule(String(e.rule
1865
1875
  `)}if(r==="budget"&&e.session_id){let s=n.getOrCreateBudget(String(e.session_id));return n.formatBudget(s)}if(r==="budgets"){let s=n.listBudgets();return s.length===0?"No active budgets.":s.map(i=>n.formatBudget(i)).join(`
1866
1876
 
1867
1877
  `)}if(r==="stats"){let s=n.getStats();return["Local-First Stats:",` Total requests: ${s.totalRequests}`,` \u{1F3E0} Local: ${s.totalLocalRouted}`,` \u{1F310} Remote: ${s.totalRemoteRouted}`,` \u{1F3AD} Abstracted: ${s.totalAbstracted}`,` \u{1F4E4} Bytes sent: ${(s.totalBytesSent/1024).toFixed(1)}KB`,` \u{1F6E1}\uFE0F Bytes saved: ${(s.totalBytesAbstractedAway/1024).toFixed(1)}KB`,` \u26A0\uFE0F Budget warnings: ${s.totalBudgetWarnings}`,` \u{1F6AB} Budget blocks: ${s.totalBudgetBlocks}`].join(`
1868
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}}});import{writeFileSync as Rq,mkdirSync as GSe,createWriteStream as VSe}from"fs";import{resolve as JSe,dirname as WSe}from"path";import{Document as KSe,Packer as YSe,Paragraph as ug,HeadingLevel as m0,TextRun as a1}from"docx";import QSe from"pptxgenjs";import ZSe from"exceljs";import XSe from"pdfkit";function ewe(e,t){if(e&&g0[e.toLowerCase()])return g0[e.toLowerCase()];let n=Object.keys(g0),r=0;for(let s=0;s<t.length;s++)r=r*31+t.charCodeAt(s)|0;return g0[n[Math.abs(r)%n.length]]}async function twe(e,t,n,r){let s=[new ug({heading:m0.TITLE,children:[new a1({text:t,color:r.primary,bold:!0})]})];for(let a of n.split(`
1869
- `)){let c=a.replace(/\r$/,""),l=c.match(/^(#{1,6})\s+(.*)/);if(l){let u=l[1].length,d=u===1?m0.HEADING_1:u===2?m0.HEADING_2:m0.HEADING_3;s.push(new ug({heading:d,children:[new a1({text:Wi(l[2]),color:r.primary,bold:!0})]}))}else/^\s*[-*]\s+/.test(c)?s.push(new ug({text:Wi(c.replace(/^\s*[-*]\s+/,"")),bullet:{level:0}})):c.trim()?s.push(new ug({children:[new a1(Wi(c))]})):s.push(new ug({}))}let i=new KSe({sections:[{children:s}]}),o=await YSe.toBuffer(i);Rq(e,o)}async function nwe(e,t,n,r){let s=new QSe;s.defineLayout({name:"AIACA_WIDE",width:13.333,height:7.5}),s.layout="AIACA_WIDE";let i=13.333,o=7.5,a=n.split(/^\s*---\s*$/m).map(l=>l.trim()).filter(Boolean),c=s.addSlide();c.background={color:r.primary},c.addShape(s.ShapeType.rect,{x:0,y:0,w:.35,h:o,fill:{color:r.accent}}),c.addText(Wi(t),{x:1,y:2.6,w:i-2,h:1.6,fontSize:44,bold:!0,color:r.onDark,align:"left",fontFace:"Georgia"}),c.addText("AiCraftAlchemy \xB7 AIACA",{x:1,y:4.3,w:i-2,h:.5,fontSize:14,color:r.secondary,align:"left"}),a.forEach((l,u)=>{let d=l.split(`
1870
- `).filter(v=>v.trim());if(!d.length)return;let f="",p=[];for(let v of d.slice(1)){let y=v.match(/^note:\s*(.*)/i);y?f+=y[1]+" ":p.push(v)}let m=d[0].replace(/^#+\s*/,""),g=s.addSlide();g.background={color:r.lightBg},g.addShape(s.ShapeType.rect,{x:0,y:0,w:.22,h:o,fill:{color:r.accent}}),g.addShape(s.ShapeType.rect,{x:.22,y:0,w:i-.22,h:1.25,fill:{color:r.primary}}),g.addText(Wi(m),{x:.7,y:.2,w:i-1.2,h:.85,fontSize:28,bold:!0,color:r.onDark,align:"left",fontFace:"Georgia",valign:"middle"});let h=p.map(v=>({text:Wi(v.replace(/^[-*]\s*/,"")),options:{bullet:{code:"2022"},fontSize:18,color:r.onLight,paraSpaceAfter:10}}));h.length&&g.addText(h,{x:.9,y:1.7,w:i-1.8,h:o-2.4,align:"left",valign:"top"}),g.addText(String(u+1),{x:i-1,y:o-.55,w:.7,h:.35,fontSize:11,color:r.secondary,align:"right"}),f.trim()&&g.addNotes(f.trim())}),await s.writeFile({fileName:e})}async function rwe(e,t,n){let r=new ZSe.Workbook,s=r.addWorksheet(t.slice(0,31)||"Sheet1");n.split(`
1871
- `).filter(o=>o.trim()&&!/^\s*\|?\s*-+\s*\|/.test(o)).map(o=>o.replace(/^\||\|$/g,"").split(/\s*[|,\t]\s*/).map(a=>a.trim()).filter((a,c,l)=>l.length>1||a!=="")).forEach((o,a)=>{let c=s.addRow(o);a===0&&(c.font={bold:!0,color:{argb:"FFFFFFFF"}},c.fill={type:"pattern",pattern:"solid",fgColor:{argb:"FF4472C4"}})}),s.columns.forEach(o=>{o.width=20}),await r.xlsx.writeFile(e)}function swe(e,t,n,r){return new Promise((s,i)=>{let o="#"+r.primary,a=new XSe({margin:50}),c=VSe(e);c.on("finish",()=>s()),c.on("error",i),a.pipe(c),a.fontSize(24).fillColor(o).text(t,{underline:!1}),a.moveDown(.5);let l=!1;for(let u of n.split(`
1878
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}}});import{writeFileSync as Rq,mkdirSync as VSe,createWriteStream as JSe}from"fs";import{resolve as WSe,dirname as KSe}from"path";import{Document as YSe,Packer as QSe,Paragraph as ug,HeadingLevel as m0,TextRun as a1}from"docx";import ZSe from"pptxgenjs";import XSe from"exceljs";import ewe from"pdfkit";function twe(e,t){if(e&&g0[e.toLowerCase()])return g0[e.toLowerCase()];let n=Object.keys(g0),r=0;for(let s=0;s<t.length;s++)r=r*31+t.charCodeAt(s)|0;return g0[n[Math.abs(r)%n.length]]}async function nwe(e,t,n,r){let s=[new ug({heading:m0.TITLE,children:[new a1({text:t,color:r.primary,bold:!0})]})];for(let a of n.split(`
1879
+ `)){let c=a.replace(/\r$/,""),l=c.match(/^(#{1,6})\s+(.*)/);if(l){let u=l[1].length,d=u===1?m0.HEADING_1:u===2?m0.HEADING_2:m0.HEADING_3;s.push(new ug({heading:d,children:[new a1({text:Wi(l[2]),color:r.primary,bold:!0})]}))}else/^\s*[-*]\s+/.test(c)?s.push(new ug({text:Wi(c.replace(/^\s*[-*]\s+/,"")),bullet:{level:0}})):c.trim()?s.push(new ug({children:[new a1(Wi(c))]})):s.push(new ug({}))}let i=new YSe({sections:[{children:s}]}),o=await QSe.toBuffer(i);Rq(e,o)}async function rwe(e,t,n,r){let s=new ZSe;s.defineLayout({name:"AIACA_WIDE",width:13.333,height:7.5}),s.layout="AIACA_WIDE";let i=13.333,o=7.5,a=n.split(/^\s*---\s*$/m).map(l=>l.trim()).filter(Boolean),c=s.addSlide();c.background={color:r.primary},c.addShape(s.ShapeType.rect,{x:0,y:0,w:.35,h:o,fill:{color:r.accent}}),c.addText(Wi(t),{x:1,y:2.6,w:i-2,h:1.6,fontSize:44,bold:!0,color:r.onDark,align:"left",fontFace:"Georgia"}),c.addText("AiCraftAlchemy \xB7 AIACA",{x:1,y:4.3,w:i-2,h:.5,fontSize:14,color:r.secondary,align:"left"}),a.forEach((l,u)=>{let d=l.split(`
1880
+ `).filter(v=>v.trim());if(!d.length)return;let f="",p=[];for(let v of d.slice(1)){let y=v.match(/^note:\s*(.*)/i);y?f+=y[1]+" ":p.push(v)}let m=d[0].replace(/^#+\s*/,""),g=s.addSlide();g.background={color:r.lightBg},g.addShape(s.ShapeType.rect,{x:0,y:0,w:.22,h:o,fill:{color:r.accent}}),g.addShape(s.ShapeType.rect,{x:.22,y:0,w:i-.22,h:1.25,fill:{color:r.primary}}),g.addText(Wi(m),{x:.7,y:.2,w:i-1.2,h:.85,fontSize:28,bold:!0,color:r.onDark,align:"left",fontFace:"Georgia",valign:"middle"});let h=p.map(v=>({text:Wi(v.replace(/^[-*]\s*/,"")),options:{bullet:{code:"2022"},fontSize:18,color:r.onLight,paraSpaceAfter:10}}));h.length&&g.addText(h,{x:.9,y:1.7,w:i-1.8,h:o-2.4,align:"left",valign:"top"}),g.addText(String(u+1),{x:i-1,y:o-.55,w:.7,h:.35,fontSize:11,color:r.secondary,align:"right"}),f.trim()&&g.addNotes(f.trim())}),await s.writeFile({fileName:e})}async function swe(e,t,n){let r=new XSe.Workbook,s=r.addWorksheet(t.slice(0,31)||"Sheet1");n.split(`
1881
+ `).filter(o=>o.trim()&&!/^\s*\|?\s*-+\s*\|/.test(o)).map(o=>o.replace(/^\||\|$/g,"").split(/\s*[|,\t]\s*/).map(a=>a.trim()).filter((a,c,l)=>l.length>1||a!=="")).forEach((o,a)=>{let c=s.addRow(o);a===0&&(c.font={bold:!0,color:{argb:"FFFFFFFF"}},c.fill={type:"pattern",pattern:"solid",fgColor:{argb:"FF4472C4"}})}),s.columns.forEach(o=>{o.width=20}),await r.xlsx.writeFile(e)}function iwe(e,t,n,r){return new Promise((s,i)=>{let o="#"+r.primary,a=new ewe({margin:50}),c=JSe(e);c.on("finish",()=>s()),c.on("error",i),a.pipe(c),a.fontSize(24).fillColor(o).text(t,{underline:!1}),a.moveDown(.5);let l=!1;for(let u of n.split(`
1872
1882
  `)){let d=u.replace(/\r$/,"");if(d.startsWith("```")){l=!l,a.moveDown(.3);continue}if(l){a.font("Courier").fontSize(10).fillColor("#333").text(d);continue}a.font("Helvetica");let f=d.match(/^(#{1,6})\s+(.*)/);if(f){let p=f[1].length===1?18:f[1].length===2?15:13;a.moveDown(.4).fontSize(p).fillColor(o).text(Wi(f[2]))}else/^\s*[-*]\s+/.test(d)?a.fontSize(11).fillColor("#000").text("\u2022 "+Wi(d.replace(/^\s*[-*]\s+/,"")),{indent:16}):d.trim()?a.fontSize(11).fillColor("#000").text(Wi(d)):a.moveDown(.4)}a.end()})}function _q(e,t,n){let r=`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${ta(t)}</title>
1873
1883
  <style>body{font-family:system-ui,sans-serif;max-width:800px;margin:40px auto;padding:20px;line-height:1.6;color:#333}
1874
1884
  h1,h2,h3{color:#1a1a2e}code{background:#f0f0f0;padding:2px 5px;border-radius:3px}
1875
1885
  pre{background:#1e1e2e;color:#cdd6f4;padding:16px;border-radius:8px;overflow-x:auto}</style>
1876
- </head><body>${iwe(t,n)}</body></html>`;Rq(e,r,"utf-8")}function iwe(e,t){let n=`<h1>${ta(e)}</h1>
1886
+ </head><body>${owe(t,n)}</body></html>`;Rq(e,r,"utf-8")}function owe(e,t){let n=`<h1>${ta(e)}</h1>
1877
1887
  `,r=!1,s=!1;for(let i of t.split(`
1878
1888
  `)){if(i.startsWith("```")){n+=r?`</code></pre>
1879
1889
  `:"<pre><code>",r=!r;continue}if(r){n+=ta(i)+`
@@ -1888,11 +1898,11 @@ pre{background:#1e1e2e;color:#cdd6f4;padding:16px;border-radius:8px;overflow-x:a
1888
1898
  `;continue}n+=`<p>${ta(i)}</p>
1889
1899
  `}return s&&(n+=`</ul>
1890
1900
  `),r&&(n+=`</code></pre>
1891
- `),n}function Wi(e){return e.replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/`(.+?)`/g,"$1")}function ta(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var c1,g0,Pq=w(()=>{"use strict";c1={definition:{name:"doc_create",description:"Create REAL, presentation-grade document files (.docx, .pptx, .xlsx, .pdf, .html) from markdown. Produces genuine Office/PDF files that open natively. Decks and reports are auto-styled with a cohesive color theme, typography, and layout \u2014 not plain bullets.",parameters:[{name:"path",type:"string",description:"Output file path (e.g. notes.docx, slides.pptx, report.pdf, data.xlsx)",required:!0},{name:"content",type:"string",description:'Document content in markdown. For slides, separate each slide with a line containing only "---"; the first line of each block is the slide title, following lines are bullets. For spreadsheets, use markdown tables or CSV rows. Optionally end a slide with a line "note: ..." for speaker notes.',required:!0},{name:"title",type:"string",description:"Document title",required:!1},{name:"theme",type:"string",description:"Visual theme for decks/PDFs. One of: midnight, forest, coral, ocean, teal, berry, charcoal, cherry. Omit to auto-pick a topic-appropriate palette.",required:!1}],requiresPermission:!0},handler:async(e,t)=>{let n=JSe(t.cwd,e.path),r=String(e.content??""),s=e.title||"Document",i=ewe(e.theme,s+" "+r),o=n.split(".").pop()?.toLowerCase();GSe(WSe(n),{recursive:!0});try{switch(o){case"docx":await twe(n,s,r,i);break;case"pptx":await nwe(n,s,r,i);break;case"xlsx":await rwe(n,s,r);break;case"pdf":await swe(n,s,r,i);break;case"html":_q(n,s,r);break;default:_q(n,s,r);break}}catch(a){return`Error creating ${o} document: ${a.message}`}return`Created ${n} (genuine ${(o||"html").toUpperCase()} file, theme: ${i.name})`}},g0={midnight:{name:"midnight",primary:"1E2761",secondary:"408EC6",accent:"7A2048",lightBg:"F4F6FB",onDark:"FFFFFF",onLight:"1E2761"},forest:{name:"forest",primary:"2C5F2D",secondary:"97BC62",accent:"D98E04",lightBg:"F5F7F0",onDark:"FFFFFF",onLight:"23401F"},coral:{name:"coral",primary:"2F3C7E",secondary:"F96167",accent:"F9E795",lightBg:"FFF8F0",onDark:"FFFFFF",onLight:"2F3C7E"},ocean:{name:"ocean",primary:"065A82",secondary:"1C7293",accent:"00A896",lightBg:"EEF6F8",onDark:"FFFFFF",onLight:"07314A"},teal:{name:"teal",primary:"028090",secondary:"00A896",accent:"F0A202",lightBg:"EDF7F6",onDark:"FFFFFF",onLight:"023E48"},berry:{name:"berry",primary:"6D2E46",secondary:"A26769",accent:"D5B942",lightBg:"FAF4EF",onDark:"FFFFFF",onLight:"4A1F30"},charcoal:{name:"charcoal",primary:"2D3142",secondary:"4F5D75",accent:"EF8354",lightBg:"F5F5F7",onDark:"FFFFFF",onLight:"2D3142"},cherry:{name:"cherry",primary:"990011",secondary:"CC5803",accent:"2F3C7E",lightBg:"FCF6F5",onDark:"FFFFFF",onLight:"5A0009"}}});var Bq={};$(Bq,{addRegistry:()=>mwe,buildSkillPrompt:()=>b1,fetchRegistry:()=>g1,getSkill:()=>Nd,getSkillStats:()=>vwe,installFromRegistry:()=>ywe,installSkill:()=>Lq,listAllSkills:()=>m1,loadRegistries:()=>Zc,rateSkill:()=>bwe,removeRegistry:()=>gwe,saveRegistries:()=>mg,searchRemote:()=>hwe,searchSkills:()=>p1,trackSkillUse:()=>y1,uninstallSkill:()=>fwe});import{existsSync as fg,mkdirSync as Iq,readFileSync as y0,writeFileSync as f1,readdirSync as Mq,unlinkSync as owe}from"fs";import{join as ri}from"path";import{homedir as awe}from"os";import{createHash as cwe}from"crypto";function Qc(){Iq(pg,{recursive:!0}),Iq(dg,{recursive:!0})}function uwe(){let e=m1(),t=new Map,n=new Map,r=[],s=new Map;for(let i of e){t.set(i.name,i);for(let a of i.tags)n.has(a)||n.set(a,[]),n.get(a).push(i);let o=Fq(`${i.name} ${i.description} ${i.tags.join(" ")} ${i.examples?.join(" ")||""}`);r.push({skill:i,tokens:o});for(let a of new Set(o))s.set(a,(s.get(a)||0)+1)}return{byName:t,byTag:n,documents:r,docFrequency:s}}function Dq(){return h0||(h0=uwe()),h0}function b0(){h0=null}function Fq(e){return e.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/).filter(t=>t.length>1&&!dwe.has(t))}function p1(e,t={}){let n=Dq(),r=n.documents;if(t.source&&(r=r.filter(a=>a.skill.source===t.source)),t.tags?.length&&(r=r.filter(a=>t.tags.some(c=>a.skill.tags.includes(c)))),t.minRating!==void 0&&(r=r.filter(a=>(a.skill.rating||0)>=t.minRating)),!e.trim())return r.map(a=>a.skill).sort((a,c)=>c.usageCount-a.usageCount).slice(0,t.limit||10);let s=Fq(e),i=r.length||1;return r.map(({skill:a,tokens:c})=>{let l=new Map;for(let d of c)l.set(d,(l.get(d)||0)+1);let u=0;for(let d of s){a.name.includes(d)&&(u+=5),a.tags.includes(d)&&(u+=3);let f=(l.get(d)||0)/Math.max(1,c.length),p=n.docFrequency.get(d)||1,m=Math.log(i/p)+1;u+=f*m}return u*=1+a.usageCount*.05,a.rating&&(u*=1+(a.rating-3)*.1),{skill:a,score:u}}).filter(a=>a.score>0).sort((a,c)=>c.score-a.score).slice(0,t.limit||10).map(a=>a.skill)}function m1(){Qc();let e=[];for(let n of lwe)e.push(Eq(n,"bundled","<bundled>"));if(fg(dg)){for(let n of Mq(dg))if(n.endsWith(".json"))try{let r=ri(dg,n),s=JSON.parse(y0(r,"utf-8"));s.installPath=r,e.push(s)}catch{}}let t=ri(process.cwd(),".aiaca","skills");if(fg(t)){for(let n of Mq(t))if(n.endsWith(".json"))try{let r=JSON.parse(y0(ri(t,n),"utf-8"));e.push(Eq(r,"project",ri(t,n)))}catch{}}return e}function Eq(e,t,n){let r=h1(),s=`${e.name}@${e.version}`;return{...e,id:s,source:t,installedAt:r[s]?.installedAt||new Date().toISOString(),installPath:n,usageCount:r[s]?.usageCount||0,rating:r[s]?.rating,lastUsedAt:r[s]?.lastUsedAt,checksum:Oq(e)}}function Nd(e){return Dq().byName.get(e)||null}function Lq(e,t="local",n){Qc(),pwe(e);let r=`${e.name}@${e.version}`,s=ri(dg,`${r.replace(/[^a-zA-Z0-9.-]/g,"_")}.json`),i={...e,id:r,source:t,installedAt:new Date().toISOString(),installPath:s,usageCount:0,registryUrl:n,checksum:Oq(e)};return f1(s,JSON.stringify(i,null,2),"utf-8"),b0(),i}function fwe(e){Qc();let t=Nd(e);if(!t||t.source==="bundled"||!fg(t.installPath))return!1;try{return owe(t.installPath),b0(),!0}catch{return!1}}function pwe(e){if(!e.name||typeof e.name!="string")throw new Error("Invalid skill: missing name");if(!e.version)throw new Error("Invalid skill: missing version");if(!e.description)throw new Error("Invalid skill: missing description");if(!e.prompt)throw new Error("Invalid skill: missing prompt");Array.isArray(e.tags)||(e.tags=[]),Array.isArray(e.parameters)||(e.parameters=[])}function Oq(e){let t=JSON.stringify({name:e.name,version:e.version,prompt:e.prompt});return cwe("sha256").update(t).digest("hex").slice(0,16)}function Zc(){if(Qc(),!fg(u1))return mg(l1),l1;try{return JSON.parse(y0(u1,"utf-8"))}catch{return l1}}function mg(e){Qc(),f1(u1,JSON.stringify(e,null,2),"utf-8")}function mwe(e,t,n=!1){let r=Zc();if(r.some(s=>s.name===e))throw new Error(`Registry "${e}" already exists`);r.push({name:e,url:t,trusted:n}),mg(r)}function gwe(e){let t=Zc(),n=t.filter(r=>r.name!==e);return n.length===t.length?!1:(mg(n),!0)}async function g1(e){let t=Zc(),n=t.find(r=>r.name===e);if(!n)return{skills:[],error:`Registry "${e}" not found`};try{let r=await fetch(n.url,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"AIACA/1.0"}});if(!r.ok)return{skills:[],error:`HTTP ${r.status}`};let s=await r.json(),i=Array.isArray(s)?s:s.skills||[];return n.skills=i,n.lastFetched=new Date().toISOString(),mg(t),{skills:i}}catch(r){return{skills:[],error:r.message}}}async function hwe(e,t={}){let n=Zc(),r=[];for(let s of n){if(!s.skills){let{skills:i}=await g1(s.name);s.skills=i}for(let i of s.skills||[])(i.name.toLowerCase().includes(e.toLowerCase())||i.description.toLowerCase().includes(e.toLowerCase())||i.tags.some(a=>a.toLowerCase().includes(e.toLowerCase())))&&(t.tags?.length&&!t.tags.some(a=>i.tags.includes(a))||r.push({skill:i,registry:s.name}))}return r.slice(0,t.limit||20)}async function ywe(e,t){let{skills:n,error:r}=await g1(t);if(r)return{error:r};let s=n.find(i=>i.name===e);return s?Lq(s,"remote",Zc().find(i=>i.name===t)?.url):{error:`Skill "${e}" not found in registry "${t}"`}}function h1(){if(Qc(),!fg(d1))return{};try{return JSON.parse(y0(d1,"utf-8"))}catch{return{}}}function jq(e){Qc(),f1(d1,JSON.stringify(e,null,2),"utf-8")}function y1(e){let t=Nd(e);if(!t)return;let n=h1();n[t.id]||(n[t.id]={installedAt:t.installedAt,usageCount:0}),n[t.id].usageCount++,n[t.id].lastUsedAt=new Date().toISOString(),jq(n),b0()}function bwe(e,t){let n=Nd(e);if(!n||t<1||t>5)return!1;let r=h1();return r[n.id]||(r[n.id]={installedAt:n.installedAt,usageCount:0}),r[n.id].rating=t,jq(r),b0(),!0}function b1(e,t){let n=e.prompt;for(let[s,i]of Object.entries(t))n=n.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),String(i));let r=e.parameters.filter(s=>t[s.name]!==void 0&&!e.prompt.includes(`{{${s.name}}}`)).map(s=>`${s.name}: ${t[s.name]}`).join(`
1901
+ `),n}function Wi(e){return e.replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/`(.+?)`/g,"$1")}function ta(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var c1,g0,Pq=w(()=>{"use strict";c1={definition:{name:"doc_create",description:"Create REAL, presentation-grade document files (.docx, .pptx, .xlsx, .pdf, .html) from markdown. Produces genuine Office/PDF files that open natively. Decks and reports are auto-styled with a cohesive color theme, typography, and layout \u2014 not plain bullets.",parameters:[{name:"path",type:"string",description:"Output file path (e.g. notes.docx, slides.pptx, report.pdf, data.xlsx)",required:!0},{name:"content",type:"string",description:'Document content in markdown. For slides, separate each slide with a line containing only "---"; the first line of each block is the slide title, following lines are bullets. For spreadsheets, use markdown tables or CSV rows. Optionally end a slide with a line "note: ..." for speaker notes.',required:!0},{name:"title",type:"string",description:"Document title",required:!1},{name:"theme",type:"string",description:"Visual theme for decks/PDFs. One of: midnight, forest, coral, ocean, teal, berry, charcoal, cherry. Omit to auto-pick a topic-appropriate palette.",required:!1}],requiresPermission:!0},handler:async(e,t)=>{let n=WSe(t.cwd,e.path),r=String(e.content??""),s=e.title||"Document",i=twe(e.theme,s+" "+r),o=n.split(".").pop()?.toLowerCase();VSe(KSe(n),{recursive:!0});try{switch(o){case"docx":await nwe(n,s,r,i);break;case"pptx":await rwe(n,s,r,i);break;case"xlsx":await swe(n,s,r);break;case"pdf":await iwe(n,s,r,i);break;case"html":_q(n,s,r);break;default:_q(n,s,r);break}}catch(a){return`Error creating ${o} document: ${a.message}`}return`Created ${n} (genuine ${(o||"html").toUpperCase()} file, theme: ${i.name})`}},g0={midnight:{name:"midnight",primary:"1E2761",secondary:"408EC6",accent:"7A2048",lightBg:"F4F6FB",onDark:"FFFFFF",onLight:"1E2761"},forest:{name:"forest",primary:"2C5F2D",secondary:"97BC62",accent:"D98E04",lightBg:"F5F7F0",onDark:"FFFFFF",onLight:"23401F"},coral:{name:"coral",primary:"2F3C7E",secondary:"F96167",accent:"F9E795",lightBg:"FFF8F0",onDark:"FFFFFF",onLight:"2F3C7E"},ocean:{name:"ocean",primary:"065A82",secondary:"1C7293",accent:"00A896",lightBg:"EEF6F8",onDark:"FFFFFF",onLight:"07314A"},teal:{name:"teal",primary:"028090",secondary:"00A896",accent:"F0A202",lightBg:"EDF7F6",onDark:"FFFFFF",onLight:"023E48"},berry:{name:"berry",primary:"6D2E46",secondary:"A26769",accent:"D5B942",lightBg:"FAF4EF",onDark:"FFFFFF",onLight:"4A1F30"},charcoal:{name:"charcoal",primary:"2D3142",secondary:"4F5D75",accent:"EF8354",lightBg:"F5F5F7",onDark:"FFFFFF",onLight:"2D3142"},cherry:{name:"cherry",primary:"990011",secondary:"CC5803",accent:"2F3C7E",lightBg:"FCF6F5",onDark:"FFFFFF",onLight:"5A0009"}}});var Bq={};$(Bq,{addRegistry:()=>gwe,buildSkillPrompt:()=>b1,fetchRegistry:()=>g1,getSkill:()=>Nd,getSkillStats:()=>Swe,installFromRegistry:()=>bwe,installSkill:()=>Lq,listAllSkills:()=>m1,loadRegistries:()=>Zc,rateSkill:()=>vwe,removeRegistry:()=>hwe,saveRegistries:()=>mg,searchRemote:()=>ywe,searchSkills:()=>p1,trackSkillUse:()=>y1,uninstallSkill:()=>pwe});import{existsSync as fg,mkdirSync as Iq,readFileSync as y0,writeFileSync as f1,readdirSync as Mq,unlinkSync as awe}from"fs";import{join as ri}from"path";import{homedir as cwe}from"os";import{createHash as lwe}from"crypto";function Qc(){Iq(pg,{recursive:!0}),Iq(dg,{recursive:!0})}function dwe(){let e=m1(),t=new Map,n=new Map,r=[],s=new Map;for(let i of e){t.set(i.name,i);for(let a of i.tags)n.has(a)||n.set(a,[]),n.get(a).push(i);let o=Fq(`${i.name} ${i.description} ${i.tags.join(" ")} ${i.examples?.join(" ")||""}`);r.push({skill:i,tokens:o});for(let a of new Set(o))s.set(a,(s.get(a)||0)+1)}return{byName:t,byTag:n,documents:r,docFrequency:s}}function Dq(){return h0||(h0=dwe()),h0}function b0(){h0=null}function Fq(e){return e.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/).filter(t=>t.length>1&&!fwe.has(t))}function p1(e,t={}){let n=Dq(),r=n.documents;if(t.source&&(r=r.filter(a=>a.skill.source===t.source)),t.tags?.length&&(r=r.filter(a=>t.tags.some(c=>a.skill.tags.includes(c)))),t.minRating!==void 0&&(r=r.filter(a=>(a.skill.rating||0)>=t.minRating)),!e.trim())return r.map(a=>a.skill).sort((a,c)=>c.usageCount-a.usageCount).slice(0,t.limit||10);let s=Fq(e),i=r.length||1;return r.map(({skill:a,tokens:c})=>{let l=new Map;for(let d of c)l.set(d,(l.get(d)||0)+1);let u=0;for(let d of s){a.name.includes(d)&&(u+=5),a.tags.includes(d)&&(u+=3);let f=(l.get(d)||0)/Math.max(1,c.length),p=n.docFrequency.get(d)||1,m=Math.log(i/p)+1;u+=f*m}return u*=1+a.usageCount*.05,a.rating&&(u*=1+(a.rating-3)*.1),{skill:a,score:u}}).filter(a=>a.score>0).sort((a,c)=>c.score-a.score).slice(0,t.limit||10).map(a=>a.skill)}function m1(){Qc();let e=[];for(let n of uwe)e.push(Eq(n,"bundled","<bundled>"));if(fg(dg)){for(let n of Mq(dg))if(n.endsWith(".json"))try{let r=ri(dg,n),s=JSON.parse(y0(r,"utf-8"));s.installPath=r,e.push(s)}catch{}}let t=ri(process.cwd(),".aiaca","skills");if(fg(t)){for(let n of Mq(t))if(n.endsWith(".json"))try{let r=JSON.parse(y0(ri(t,n),"utf-8"));e.push(Eq(r,"project",ri(t,n)))}catch{}}return e}function Eq(e,t,n){let r=h1(),s=`${e.name}@${e.version}`;return{...e,id:s,source:t,installedAt:r[s]?.installedAt||new Date().toISOString(),installPath:n,usageCount:r[s]?.usageCount||0,rating:r[s]?.rating,lastUsedAt:r[s]?.lastUsedAt,checksum:Oq(e)}}function Nd(e){return Dq().byName.get(e)||null}function Lq(e,t="local",n){Qc(),mwe(e);let r=`${e.name}@${e.version}`,s=ri(dg,`${r.replace(/[^a-zA-Z0-9.-]/g,"_")}.json`),i={...e,id:r,source:t,installedAt:new Date().toISOString(),installPath:s,usageCount:0,registryUrl:n,checksum:Oq(e)};return f1(s,JSON.stringify(i,null,2),"utf-8"),b0(),i}function pwe(e){Qc();let t=Nd(e);if(!t||t.source==="bundled"||!fg(t.installPath))return!1;try{return awe(t.installPath),b0(),!0}catch{return!1}}function mwe(e){if(!e.name||typeof e.name!="string")throw new Error("Invalid skill: missing name");if(!e.version)throw new Error("Invalid skill: missing version");if(!e.description)throw new Error("Invalid skill: missing description");if(!e.prompt)throw new Error("Invalid skill: missing prompt");Array.isArray(e.tags)||(e.tags=[]),Array.isArray(e.parameters)||(e.parameters=[])}function Oq(e){let t=JSON.stringify({name:e.name,version:e.version,prompt:e.prompt});return lwe("sha256").update(t).digest("hex").slice(0,16)}function Zc(){if(Qc(),!fg(u1))return mg(l1),l1;try{return JSON.parse(y0(u1,"utf-8"))}catch{return l1}}function mg(e){Qc(),f1(u1,JSON.stringify(e,null,2),"utf-8")}function gwe(e,t,n=!1){let r=Zc();if(r.some(s=>s.name===e))throw new Error(`Registry "${e}" already exists`);r.push({name:e,url:t,trusted:n}),mg(r)}function hwe(e){let t=Zc(),n=t.filter(r=>r.name!==e);return n.length===t.length?!1:(mg(n),!0)}async function g1(e){let t=Zc(),n=t.find(r=>r.name===e);if(!n)return{skills:[],error:`Registry "${e}" not found`};try{let r=await fetch(n.url,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"AIACA/1.0"}});if(!r.ok)return{skills:[],error:`HTTP ${r.status}`};let s=await r.json(),i=Array.isArray(s)?s:s.skills||[];return n.skills=i,n.lastFetched=new Date().toISOString(),mg(t),{skills:i}}catch(r){return{skills:[],error:r.message}}}async function ywe(e,t={}){let n=Zc(),r=[];for(let s of n){if(!s.skills){let{skills:i}=await g1(s.name);s.skills=i}for(let i of s.skills||[])(i.name.toLowerCase().includes(e.toLowerCase())||i.description.toLowerCase().includes(e.toLowerCase())||i.tags.some(a=>a.toLowerCase().includes(e.toLowerCase())))&&(t.tags?.length&&!t.tags.some(a=>i.tags.includes(a))||r.push({skill:i,registry:s.name}))}return r.slice(0,t.limit||20)}async function bwe(e,t){let{skills:n,error:r}=await g1(t);if(r)return{error:r};let s=n.find(i=>i.name===e);return s?Lq(s,"remote",Zc().find(i=>i.name===t)?.url):{error:`Skill "${e}" not found in registry "${t}"`}}function h1(){if(Qc(),!fg(d1))return{};try{return JSON.parse(y0(d1,"utf-8"))}catch{return{}}}function jq(e){Qc(),f1(d1,JSON.stringify(e,null,2),"utf-8")}function y1(e){let t=Nd(e);if(!t)return;let n=h1();n[t.id]||(n[t.id]={installedAt:t.installedAt,usageCount:0}),n[t.id].usageCount++,n[t.id].lastUsedAt=new Date().toISOString(),jq(n),b0()}function vwe(e,t){let n=Nd(e);if(!n||t<1||t>5)return!1;let r=h1();return r[n.id]||(r[n.id]={installedAt:n.installedAt,usageCount:0}),r[n.id].rating=t,jq(r),b0(),!0}function b1(e,t){let n=e.prompt;for(let[s,i]of Object.entries(t))n=n.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),String(i));let r=e.parameters.filter(s=>t[s.name]!==void 0&&!e.prompt.includes(`{{${s.name}}}`)).map(s=>`${s.name}: ${t[s.name]}`).join(`
1892
1902
  `);return r&&(n+=`
1893
1903
 
1894
1904
  Parameters:
1895
- `+r),n}function vwe(){let e=m1(),t=Zc(),n=[...e].sort((r,s)=>s.usageCount-r.usageCount).slice(0,5).map(r=>({name:r.name,uses:r.usageCount}));return{totalInstalled:e.length,bundled:e.filter(r=>r.source==="bundled").length,localInstalled:e.filter(r=>r.source==="local"||r.source==="remote").length,project:e.filter(r=>r.source==="project").length,totalRegistries:t.length,topUsed:n}}var pg,dg,u1,WDe,d1,lwe,h0,dwe,l1,v1=w(()=>{"use strict";pg=ri(awe(),".aiaca","skills"),dg=ri(pg,"installed"),u1=ri(pg,"registries.json"),WDe=ri(pg,"index.json"),d1=ri(pg,"stats.json");lwe=[{name:"code-review",version:"1.0.0",description:"Perform a thorough code review of changes",tags:["review","quality","git"],parameters:[{name:"scope",type:"string",description:"What to review (file/diff/branch)",required:!1}],prompt:"Review the code carefully for: bugs, security issues, performance, maintainability, style. Use git diff for recent changes if no scope given. Provide actionable feedback with file:line references.",tools:["file_read","grep","bash"],examples:["Review my last commit","Review changes to src/auth/"]},{name:"test-writer",version:"1.0.0",description:"Generate comprehensive tests for code",tags:["testing","quality"],parameters:[{name:"file",type:"string",description:"File to test",required:!0}],prompt:"Generate comprehensive unit tests including edge cases, error handling, and happy path. Match the project's existing test framework and style.",tools:["file_read","file_write","bash","glob"],examples:["Write tests for src/utils/parser.ts"]},{name:"refactor",version:"1.0.0",description:"Refactor code for clarity and maintainability",tags:["refactor","quality"],parameters:[{name:"target",type:"string",description:"File or function to refactor",required:!0}],prompt:"Refactor while preserving exact behavior. Improve: naming, structure, abstractions, type safety. Write tests first if missing. Verify tests pass after.",tools:["file_read","file_edit","bash","grep"],examples:["Refactor the auth module"]},{name:"doc-generator",version:"1.0.0",description:"Generate documentation from code",tags:["docs","readme"],parameters:[{name:"type",type:"string",description:"readme/api/architecture",required:!1}],prompt:"Generate clear, structured documentation. Include: overview, setup, usage, examples, architecture. Use proper Markdown formatting.",tools:["file_read","glob","doc_create","file_write"],examples:["Generate a README","Document the API"]},{name:"bug-hunter",version:"1.0.0",description:"Find and fix bugs in the codebase",tags:["debug","bugs"],parameters:[{name:"description",type:"string",description:"Bug description",required:!0}],prompt:"Reproduce the bug, identify root cause, fix it, and verify with tests. Don't suppress symptoms \u2014 fix the underlying issue.",tools:["file_read","file_edit","bash","grep","glob"],examples:["Fix the login error","Find why the build is failing"]},{name:"security-audit",version:"1.0.0",description:"Audit code for security vulnerabilities",tags:["security","audit"],parameters:[],prompt:"Audit for: SQL injection, XSS, CSRF, secrets in code, weak crypto, auth bypasses, unsafe deserialization, race conditions, unsafe regex. Report findings with severity and fix recommendations.",tools:["grep","glob","file_read","web_search"],examples:["Audit my authentication code"]},{name:"perf-optimize",version:"1.0.0",description:"Profile and optimize code performance",tags:["performance","optimization"],parameters:[{name:"target",type:"string",description:"What to optimize",required:!1}],prompt:"Profile the code, identify bottlenecks (algorithmic, I/O, memory), implement optimizations, and benchmark to verify improvements.",tools:["file_read","file_edit","bash","grep"],examples:["Optimize the database queries"]},{name:"migration",version:"1.0.0",description:"Migrate code between frameworks/versions",tags:["migration","upgrade"],parameters:[{name:"from",type:"string",description:"Source (e.g. react-17)",required:!0},{name:"to",type:"string",description:"Target (e.g. react-18)",required:!0}],prompt:"Plan the migration step-by-step. Update dependencies, code, tests. Handle breaking changes. Verify after each step.",tools:["file_read","file_edit","bash","web_search","glob"],examples:["Migrate from CommonJS to ESM"]},{name:"api-design",version:"1.0.0",description:"Design REST/GraphQL APIs",tags:["api","design","architecture"],parameters:[{name:"description",type:"string",description:"API requirements",required:!0}],prompt:"Design a clean API: endpoints, request/response schemas, error handling, auth, versioning, pagination. Generate OpenAPI/GraphQL schema.",tools:["file_write","doc_create","web_search"],examples:["Design a user management API"]},{name:"database-design",version:"1.0.0",description:"Design database schemas",tags:["database","schema"],parameters:[{name:"requirements",type:"string",description:"Domain requirements",required:!0}],prompt:"Design a normalized schema with proper relationships, indexes, constraints. Include migration scripts. Consider query patterns.",tools:["file_write","web_search"],examples:["Design a schema for an e-commerce app"]}],h0=null;dwe=new Set(["a","an","the","and","or","for","in","on","at","to","of","with","is","are"]);l1=[]});var Nq,qq,Uq=w(()=>{"use strict";v1();Nq={definition:{name:"skill",description:"Invoke a registered skill (reusable agent capability). Use skill_search to find skills first.",parameters:[{name:"name",type:"string",description:'Skill name (e.g. "code-review")',required:!0},{name:"params",type:"object",description:"Skill parameters as JSON object",required:!1}]},handler:async(e,t)=>{let n=String(e.name||"");if(!n)return"Error: skill name required";let r=Nd(n);if(!r)return`Error: skill "${n}" not found. Use skill_search to find available skills.`;let s=e.params||{},i=r.parameters.filter(a=>a.required&&s[a.name]===void 0);if(i.length>0)return`Error: missing required parameters: ${i.map(a=>a.name).join(", ")}`;y1(n);let o=b1(r,s);return`[Skill: ${r.name} v${r.version}]
1905
+ `+r),n}function Swe(){let e=m1(),t=Zc(),n=[...e].sort((r,s)=>s.usageCount-r.usageCount).slice(0,5).map(r=>({name:r.name,uses:r.usageCount}));return{totalInstalled:e.length,bundled:e.filter(r=>r.source==="bundled").length,localInstalled:e.filter(r=>r.source==="local"||r.source==="remote").length,project:e.filter(r=>r.source==="project").length,totalRegistries:t.length,topUsed:n}}var pg,dg,u1,KDe,d1,uwe,h0,fwe,l1,v1=w(()=>{"use strict";pg=ri(cwe(),".aiaca","skills"),dg=ri(pg,"installed"),u1=ri(pg,"registries.json"),KDe=ri(pg,"index.json"),d1=ri(pg,"stats.json");uwe=[{name:"code-review",version:"1.0.0",description:"Perform a thorough code review of changes",tags:["review","quality","git"],parameters:[{name:"scope",type:"string",description:"What to review (file/diff/branch)",required:!1}],prompt:"Review the code carefully for: bugs, security issues, performance, maintainability, style. Use git diff for recent changes if no scope given. Provide actionable feedback with file:line references.",tools:["file_read","grep","bash"],examples:["Review my last commit","Review changes to src/auth/"]},{name:"test-writer",version:"1.0.0",description:"Generate comprehensive tests for code",tags:["testing","quality"],parameters:[{name:"file",type:"string",description:"File to test",required:!0}],prompt:"Generate comprehensive unit tests including edge cases, error handling, and happy path. Match the project's existing test framework and style.",tools:["file_read","file_write","bash","glob"],examples:["Write tests for src/utils/parser.ts"]},{name:"refactor",version:"1.0.0",description:"Refactor code for clarity and maintainability",tags:["refactor","quality"],parameters:[{name:"target",type:"string",description:"File or function to refactor",required:!0}],prompt:"Refactor while preserving exact behavior. Improve: naming, structure, abstractions, type safety. Write tests first if missing. Verify tests pass after.",tools:["file_read","file_edit","bash","grep"],examples:["Refactor the auth module"]},{name:"doc-generator",version:"1.0.0",description:"Generate documentation from code",tags:["docs","readme"],parameters:[{name:"type",type:"string",description:"readme/api/architecture",required:!1}],prompt:"Generate clear, structured documentation. Include: overview, setup, usage, examples, architecture. Use proper Markdown formatting.",tools:["file_read","glob","doc_create","file_write"],examples:["Generate a README","Document the API"]},{name:"bug-hunter",version:"1.0.0",description:"Find and fix bugs in the codebase",tags:["debug","bugs"],parameters:[{name:"description",type:"string",description:"Bug description",required:!0}],prompt:"Reproduce the bug, identify root cause, fix it, and verify with tests. Don't suppress symptoms \u2014 fix the underlying issue.",tools:["file_read","file_edit","bash","grep","glob"],examples:["Fix the login error","Find why the build is failing"]},{name:"security-audit",version:"1.0.0",description:"Audit code for security vulnerabilities",tags:["security","audit"],parameters:[],prompt:"Audit for: SQL injection, XSS, CSRF, secrets in code, weak crypto, auth bypasses, unsafe deserialization, race conditions, unsafe regex. Report findings with severity and fix recommendations.",tools:["grep","glob","file_read","web_search"],examples:["Audit my authentication code"]},{name:"perf-optimize",version:"1.0.0",description:"Profile and optimize code performance",tags:["performance","optimization"],parameters:[{name:"target",type:"string",description:"What to optimize",required:!1}],prompt:"Profile the code, identify bottlenecks (algorithmic, I/O, memory), implement optimizations, and benchmark to verify improvements.",tools:["file_read","file_edit","bash","grep"],examples:["Optimize the database queries"]},{name:"migration",version:"1.0.0",description:"Migrate code between frameworks/versions",tags:["migration","upgrade"],parameters:[{name:"from",type:"string",description:"Source (e.g. react-17)",required:!0},{name:"to",type:"string",description:"Target (e.g. react-18)",required:!0}],prompt:"Plan the migration step-by-step. Update dependencies, code, tests. Handle breaking changes. Verify after each step.",tools:["file_read","file_edit","bash","web_search","glob"],examples:["Migrate from CommonJS to ESM"]},{name:"api-design",version:"1.0.0",description:"Design REST/GraphQL APIs",tags:["api","design","architecture"],parameters:[{name:"description",type:"string",description:"API requirements",required:!0}],prompt:"Design a clean API: endpoints, request/response schemas, error handling, auth, versioning, pagination. Generate OpenAPI/GraphQL schema.",tools:["file_write","doc_create","web_search"],examples:["Design a user management API"]},{name:"database-design",version:"1.0.0",description:"Design database schemas",tags:["database","schema"],parameters:[{name:"requirements",type:"string",description:"Domain requirements",required:!0}],prompt:"Design a normalized schema with proper relationships, indexes, constraints. Include migration scripts. Consider query patterns.",tools:["file_write","web_search"],examples:["Design a schema for an e-commerce app"]}],h0=null;fwe=new Set(["a","an","the","and","or","for","in","on","at","to","of","with","is","are"]);l1=[]});var Nq,qq,Uq=w(()=>{"use strict";v1();Nq={definition:{name:"skill",description:"Invoke a registered skill (reusable agent capability). Use skill_search to find skills first.",parameters:[{name:"name",type:"string",description:'Skill name (e.g. "code-review")',required:!0},{name:"params",type:"object",description:"Skill parameters as JSON object",required:!1}]},handler:async(e,t)=>{let n=String(e.name||"");if(!n)return"Error: skill name required";let r=Nd(n);if(!r)return`Error: skill "${n}" not found. Use skill_search to find available skills.`;let s=e.params||{},i=r.parameters.filter(a=>a.required&&s[a.name]===void 0);if(i.length>0)return`Error: missing required parameters: ${i.map(a=>a.name).join(", ")}`;y1(n);let o=b1(r,s);return`[Skill: ${r.name} v${r.version}]
1896
1906
  ${r.description}
1897
1907
 
1898
1908
  FOLLOW THESE INSTRUCTIONS:
@@ -1903,25 +1913,25 @@ Required tools: ${r.tools?.join(", ")||"any"}`}},qq={definition:{name:"skill_sea
1903
1913
  Tags: ${i.tags.join(", ")}
1904
1914
  Params: ${i.parameters.map(o=>`${o.name}${o.required?"*":""}`).join(", ")||"(none)"}`).join(`
1905
1915
 
1906
- `)}}});var Tq={};$(Tq,{findTool:()=>wr,getToolDefinitions:()=>Jm,getToolNames:()=>hg,getTools:()=>e_,getToolsByCategory:()=>wwe});function e_(){return gg}function Jm(e){if(e&&e.length>0){let t=new Set(e);return gg.filter(n=>t.has(n.definition.name)).map(n=>n.definition)}return gg.filter(t=>Swe.has(t.definition.name)).map(t=>t.definition)}function wr(e){return gg.find(t=>t.definition.name===e)}function hg(){return gg.map(e=>e.definition.name)}function wwe(){return{"File Operations":[_w,tx,rx,VR,c1],Search:[sx,ox],Shell:[nw,...process.platform==="win32"?[gx]:[]],Web:[px,mx],Image:[Nb,qb],"Tasks & Agents":[Tx,_x,Rx,Px,HR,zR,GR],Modes:[KR,YR,QR,ZR],Team:[XR,e1,t1],Productivity:[$x,JR,WR,n1],System:[r1,s1,i1,o1]}}var gg,Swe,Ls=w(()=>{"use strict";OI();yM();FD();UD();KD();tF();fF();pF();mF();hF();yF();Aq();Pq();Lm();Uq();gg=[_w,tx,rx,VR,c1,sx,ox,h2,y2,b2,v2,S2,w2,k2,x2,$2,C2,A2,T2,_2,R2,P2,I2,M2,E2,D2,F2,L2,O2,j2,B2,N2,q2,U2,H2,z2,G2,V2,J2,W2,K2,Y2,Q2,Z2,X2,eq,tq,nq,rq,sq,iq,oq,aq,cq,lq,uq,dq,fq,pq,mq,gq,hq,yq,bq,vq,Sq,wq,kq,xq,$q,Cq,nw,...process.platform==="win32"?[gx]:[],px,mx,Nb,qb,Nq,qq,Tx,_x,Rx,Px,HR,zR,GR,$x,JR,WR,KR,YR,QR,ZR,XR,e1,t1,n1,r1,s1,i1,o1];Swe=new Set(["file_read","file_write","file_edit","notebook_edit","glob","grep","code_search","code_index","code_references","find_callers","impact_analysis","nl_search","tool_search","bash","powershell","web_fetch","web_search","search_past_work","analyze_code","detect_smells","generate_tests","find_untested","infer_types","doc_create","spawn_specialist","spawn_pipeline","agent","todo_write","enter_plan_mode","exit_plan_mode","task_create","task_get","task_list","task_update","task_output","task_stop","skill","skill_search","ask_user","image_read","clipboard_image","diff_preview","explain","cron_create","cron_list","cron_delete"])});var a5={};$(a5,{addInterceptor:()=>Bwe,compareCassettes:()=>Uwe,createCassette:()=>k1,deleteCassette:()=>Lwe,exportCassetteAsJSONL:()=>qwe,findReplay:()=>bg,getActiveCassette:()=>jwe,getCassetteStats:()=>Nwe,getMode:()=>Owe,getVCRDir:()=>Hwe,listCassettes:()=>Fwe,loadCassette:()=>qd,record:()=>Xc,saveCassette:()=>A1,setMode:()=>i5,shouldRecord:()=>el,shouldReplay:()=>vg,withCassette:()=>zwe});import{existsSync as r5,mkdirSync as Pwe,readFileSync as s5,writeFileSync as x1,readdirSync as Iwe,statSync as Mwe}from"fs";import{join as $1}from"path";import{homedir as Ewe}from"os";import{createHash as Dwe}from"crypto";function C1(){Pwe(yg,{recursive:!0})}function k1(e,t={}){let n={name:e,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),episodes:[],metadata:t};return A1(n),n}function qd(e){C1();let t=T1(e);if(!r5(t))return null;try{return JSON.parse(s5(t,"utf-8"))}catch{return null}}function A1(e){C1(),e.updatedAt=new Date().toISOString(),x1(T1(e.name),JSON.stringify(e,null,2),"utf-8")}function Fwe(){return C1(),Iwe(yg).filter(e=>e.endsWith(".json")).map(e=>{try{let t=$1(yg,e),n=JSON.parse(s5(t,"utf-8")),r=Mwe(t);return{name:n.name,episodeCount:n.episodes.length,sizeKB:Math.round(r.size/1024),createdAt:n.createdAt,updatedAt:n.updatedAt}}catch{return null}}).filter(Boolean)}function Lwe(e){let t=T1(e);if(!r5(t))return!1;try{return x1(t,"","utf-8"),!0}catch{return!1}}function i5(e,t){if(Gr=e,e==="passthrough"){Ar=null;return}if(!t)throw new Error(`VCR mode "${e}" requires a cassette name`);let n=qd(t);if(e==="record")Ar=n||k1(t),Ar.episodes=[];else if(e==="replay"){if(!n)throw new Error(`Cassette "${t}" not found for replay`);Ar=n}else e==="new_episodes"&&(Ar=n||k1(t))}function Owe(){return Gr}function jwe(){return Ar}function Xc(e,t){let n={id:`ep_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,request:e,response:t,requestHash:o5(e)};Ar&&(Gr==="record"||Gr==="new_episodes")&&(Ar.episodes.push(n),A1(Ar));for(let r of S0)try{r(n)}catch{}return n}function bg(e){if(!Ar||Gr==="passthrough"||Gr==="record")return null;let t=o5(e),n=Ar.episodes.find(r=>r.requestHash===t);return n?n.response:null}function vg(){return Gr==="replay"||Gr==="new_episodes"}function el(){return Gr==="record"||Gr==="new_episodes"}function o5(e){let t={provider:e.provider,model:e.model,systemPrompt:e.systemPrompt,messages:e.messages.map(n=>({role:n.role,content:n.content})),tools:[...e.tools].sort()};return Dwe("sha256").update(JSON.stringify(t)).digest("hex").slice(0,32)}function Bwe(e){return S0.push(e),()=>{let t=S0.indexOf(e);t!==-1&&S0.splice(t,1)}}function Nwe(e){let t=qd(e);if(!t)return null;let n=0,r=0,s=0,i=0;for(let o of t.episodes)n+=o.response.durationMs,r+=o.response.usage?.inputTokens||0,s+=o.response.usage?.outputTokens||0,i+=o.response.toolCalls.length;return{episodes:t.episodes.length,totalDurationMs:n,avgDurationMs:t.episodes.length?Math.round(n/t.episodes.length):0,totalInputTokens:r,totalOutputTokens:s,toolCallCount:i}}function qwe(e,t){let n=qd(e);if(!n)return!1;try{let r=n.episodes.map(s=>JSON.stringify(s));return x1(t,r.join(`
1907
- `),"utf-8"),!0}catch{return!1}}function Uwe(e,t){let n=qd(e),r=qd(t);if(!n||!r)return{matching:0,differing:0,only1:0,only2:0,differences:[]};let s=new Map(n.episodes.map(d=>[d.requestHash,d])),i=new Map(r.episodes.map(d=>[d.requestHash,d])),o=0,a=0,c=[];for(let[d,f]of s){let p=i.get(d);p&&(f.response.content===p.response.content?o++:(a++,c.push({requestHash:d,reason:"Response content differs"})))}let l=[...s.keys()].filter(d=>!i.has(d)).length,u=[...i.keys()].filter(d=>!s.has(d)).length;return{matching:o,differing:a,only1:l,only2:u,differences:c}}function T1(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return $1(yg,`${t}.json`)}function Hwe(){return yg}function zwe(e,t,n){let r=Gr,s=Ar;return i5(t,e),n().finally(()=>{Gr=r,Ar=s})}var yg,Gr,Ar,S0,w0=w(()=>{"use strict";yg=$1(Ewe(),".aiaca","cassettes"),Gr="passthrough",Ar=null,S0=[]});var $0={};$($0,{captureSnapshot:()=>d5,clearAllSnapshots:()=>mke,clearProjectSnapshots:()=>pke,computeDiff:()=>m5,diffSinceLastSession:()=>dke,formatBriefing:()=>M1,getDiffTrackerStats:()=>fke,getLastSnapshot:()=>f5,listSnapshots:()=>ake,loadSnapshot:()=>p5});import{existsSync as Tr,mkdirSync as Gwe,readFileSync as si,writeFileSync as c5,readdirSync as k0,unlinkSync as P1,statSync as Vwe}from"fs";import{join as Zn,resolve as Ud,relative as Jwe}from"path";import{homedir as Wwe}from"os";import{createHash as Sg}from"crypto";import{execSync as na}from"child_process";import{glob as Kwe}from"glob";function Ywe(e){return Sg("sha256").update(Ud(e)).digest("hex").slice(0,16)}function x0(e){return Zn(tl,Ywe(e))}function l5(e){Gwe(x0(e),{recursive:!0})}function R1(e,t){return Zn(x0(e),`${t}.json`)}function u5(e){return Zn(x0(e),"index.json")}async function tke(e){let t=[];for(let l of Qwe)try{let u=await Kwe(l,{cwd:e,absolute:!0,ignore:Zwe,nodir:!0});t.push(...u)}catch{}let n={},r={},s=new Set,i=[],o=0,a=t.map(l=>{try{return{f:l,stat:Vwe(l)}}catch{return null}}).filter(l=>l!==null&&!l.stat.isDirectory()).sort((l,u)=>u.stat.mtimeMs-l.stat.mtimeMs),c=0;for(let{f:l,stat:u}of a){let d=Jwe(e,l).replace(/\\/g,"/"),f=(d.match(/\.([^./\\]+)$/)||["","noext"])[1].toLowerCase();n[f]=(n[f]||0)+1,o+=u.size;let p=d.split("/")[0];if(p&&s.add(p),i.length<20&&i.push({path:d,mtime:u.mtimeMs}),c<Xwe&&u.size<eke)try{let m=si(l),g=Sg("sha256").update(m).digest("hex").slice(0,16),h=m.toString("utf-8",0,Math.min(m.length,1e5)).split(`
1908
- `).length;r[d]={hash:g,size:u.size,mtime:u.mtimeMs,lines:h},c++}catch{}}return{totalCount:t.length,byExtension:n,topLevelDirs:Array.from(s).sort(),totalSizeKB:Math.round(o/1024),trackedFiles:r,recentlyModified:i}}function nke(e){let t={isRepo:!1,isDirty:!1,modifiedFiles:[],untrackedFiles:[],stashCount:0,recentCommits:[]};try{na("git rev-parse --git-dir",{cwd:e,stdio:"pipe"}),t.isRepo=!0}catch{return t}try{t.branch=na("git rev-parse --abbrev-ref HEAD",{cwd:e,stdio:"pipe"}).toString().trim()}catch{}try{t.head=na("git rev-parse HEAD",{cwd:e,stdio:"pipe"}).toString().trim().slice(0,12)}catch{}try{let r=na("git status --porcelain",{cwd:e,stdio:"pipe"}).toString().split(`
1916
+ `)}}});var Tq={};$(Tq,{findTool:()=>wr,getToolDefinitions:()=>Jm,getToolNames:()=>hg,getTools:()=>e_,getToolsByCategory:()=>kwe});function e_(){return gg}function Jm(e){if(e&&e.length>0){let t=new Set(e);return gg.filter(n=>t.has(n.definition.name)).map(n=>n.definition)}return gg.filter(t=>wwe.has(t.definition.name)).map(t=>t.definition)}function wr(e){return gg.find(t=>t.definition.name===e)}function hg(){return gg.map(e=>e.definition.name)}function kwe(){return{"File Operations":[_w,tx,rx,VR,c1],Search:[sx,ox],Shell:[nw,...process.platform==="win32"?[gx]:[]],Web:[px,mx],Image:[Nb,qb],"Tasks & Agents":[Tx,_x,Rx,Px,HR,zR,GR],Modes:[KR,YR,QR,ZR],Team:[XR,e1,t1],Productivity:[$x,JR,WR,n1],System:[r1,s1,i1,o1]}}var gg,wwe,Ls=w(()=>{"use strict";OI();yM();FD();UD();KD();tF();fF();pF();mF();hF();yF();Aq();Pq();Lm();Uq();gg=[_w,tx,rx,VR,c1,sx,ox,h2,y2,b2,v2,S2,w2,k2,x2,$2,C2,A2,T2,_2,R2,P2,I2,M2,E2,D2,F2,L2,O2,j2,B2,N2,q2,U2,H2,z2,G2,V2,J2,W2,K2,Y2,Q2,Z2,X2,eq,tq,nq,rq,sq,iq,oq,aq,cq,lq,uq,dq,fq,pq,mq,gq,hq,yq,bq,vq,Sq,wq,kq,xq,$q,Cq,nw,...process.platform==="win32"?[gx]:[],px,mx,Nb,qb,Nq,qq,Tx,_x,Rx,Px,HR,zR,GR,$x,JR,WR,KR,YR,QR,ZR,XR,e1,t1,n1,r1,s1,i1,o1];wwe=new Set(["file_read","file_write","file_edit","notebook_edit","glob","grep","code_search","code_index","code_references","find_callers","impact_analysis","nl_search","tool_search","bash","powershell","web_fetch","web_search","search_past_work","analyze_code","detect_smells","generate_tests","find_untested","infer_types","doc_create","spawn_specialist","spawn_pipeline","agent","todo_write","enter_plan_mode","exit_plan_mode","task_create","task_get","task_list","task_update","task_output","task_stop","skill","skill_search","ask_user","image_read","clipboard_image","diff_preview","explain","cron_create","cron_list","cron_delete"])});var a5={};$(a5,{addInterceptor:()=>Nwe,compareCassettes:()=>Hwe,createCassette:()=>k1,deleteCassette:()=>Owe,exportCassetteAsJSONL:()=>Uwe,findReplay:()=>bg,getActiveCassette:()=>Bwe,getCassetteStats:()=>qwe,getMode:()=>jwe,getVCRDir:()=>zwe,listCassettes:()=>Lwe,loadCassette:()=>qd,record:()=>Xc,saveCassette:()=>A1,setMode:()=>i5,shouldRecord:()=>el,shouldReplay:()=>vg,withCassette:()=>Gwe});import{existsSync as r5,mkdirSync as Iwe,readFileSync as s5,writeFileSync as x1,readdirSync as Mwe,statSync as Ewe}from"fs";import{join as $1}from"path";import{homedir as Dwe}from"os";import{createHash as Fwe}from"crypto";function C1(){Iwe(yg,{recursive:!0})}function k1(e,t={}){let n={name:e,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),episodes:[],metadata:t};return A1(n),n}function qd(e){C1();let t=T1(e);if(!r5(t))return null;try{return JSON.parse(s5(t,"utf-8"))}catch{return null}}function A1(e){C1(),e.updatedAt=new Date().toISOString(),x1(T1(e.name),JSON.stringify(e,null,2),"utf-8")}function Lwe(){return C1(),Mwe(yg).filter(e=>e.endsWith(".json")).map(e=>{try{let t=$1(yg,e),n=JSON.parse(s5(t,"utf-8")),r=Ewe(t);return{name:n.name,episodeCount:n.episodes.length,sizeKB:Math.round(r.size/1024),createdAt:n.createdAt,updatedAt:n.updatedAt}}catch{return null}}).filter(Boolean)}function Owe(e){let t=T1(e);if(!r5(t))return!1;try{return x1(t,"","utf-8"),!0}catch{return!1}}function i5(e,t){if(Gr=e,e==="passthrough"){Ar=null;return}if(!t)throw new Error(`VCR mode "${e}" requires a cassette name`);let n=qd(t);if(e==="record")Ar=n||k1(t),Ar.episodes=[];else if(e==="replay"){if(!n)throw new Error(`Cassette "${t}" not found for replay`);Ar=n}else e==="new_episodes"&&(Ar=n||k1(t))}function jwe(){return Gr}function Bwe(){return Ar}function Xc(e,t){let n={id:`ep_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,request:e,response:t,requestHash:o5(e)};Ar&&(Gr==="record"||Gr==="new_episodes")&&(Ar.episodes.push(n),A1(Ar));for(let r of S0)try{r(n)}catch{}return n}function bg(e){if(!Ar||Gr==="passthrough"||Gr==="record")return null;let t=o5(e),n=Ar.episodes.find(r=>r.requestHash===t);return n?n.response:null}function vg(){return Gr==="replay"||Gr==="new_episodes"}function el(){return Gr==="record"||Gr==="new_episodes"}function o5(e){let t={provider:e.provider,model:e.model,systemPrompt:e.systemPrompt,messages:e.messages.map(n=>({role:n.role,content:n.content})),tools:[...e.tools].sort()};return Fwe("sha256").update(JSON.stringify(t)).digest("hex").slice(0,32)}function Nwe(e){return S0.push(e),()=>{let t=S0.indexOf(e);t!==-1&&S0.splice(t,1)}}function qwe(e){let t=qd(e);if(!t)return null;let n=0,r=0,s=0,i=0;for(let o of t.episodes)n+=o.response.durationMs,r+=o.response.usage?.inputTokens||0,s+=o.response.usage?.outputTokens||0,i+=o.response.toolCalls.length;return{episodes:t.episodes.length,totalDurationMs:n,avgDurationMs:t.episodes.length?Math.round(n/t.episodes.length):0,totalInputTokens:r,totalOutputTokens:s,toolCallCount:i}}function Uwe(e,t){let n=qd(e);if(!n)return!1;try{let r=n.episodes.map(s=>JSON.stringify(s));return x1(t,r.join(`
1917
+ `),"utf-8"),!0}catch{return!1}}function Hwe(e,t){let n=qd(e),r=qd(t);if(!n||!r)return{matching:0,differing:0,only1:0,only2:0,differences:[]};let s=new Map(n.episodes.map(d=>[d.requestHash,d])),i=new Map(r.episodes.map(d=>[d.requestHash,d])),o=0,a=0,c=[];for(let[d,f]of s){let p=i.get(d);p&&(f.response.content===p.response.content?o++:(a++,c.push({requestHash:d,reason:"Response content differs"})))}let l=[...s.keys()].filter(d=>!i.has(d)).length,u=[...i.keys()].filter(d=>!s.has(d)).length;return{matching:o,differing:a,only1:l,only2:u,differences:c}}function T1(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return $1(yg,`${t}.json`)}function zwe(){return yg}function Gwe(e,t,n){let r=Gr,s=Ar;return i5(t,e),n().finally(()=>{Gr=r,Ar=s})}var yg,Gr,Ar,S0,w0=w(()=>{"use strict";yg=$1(Dwe(),".aiaca","cassettes"),Gr="passthrough",Ar=null,S0=[]});var $0={};$($0,{captureSnapshot:()=>d5,clearAllSnapshots:()=>gke,clearProjectSnapshots:()=>mke,computeDiff:()=>m5,diffSinceLastSession:()=>fke,formatBriefing:()=>M1,getDiffTrackerStats:()=>pke,getLastSnapshot:()=>f5,listSnapshots:()=>cke,loadSnapshot:()=>p5});import{existsSync as Tr,mkdirSync as Vwe,readFileSync as si,writeFileSync as c5,readdirSync as k0,unlinkSync as P1,statSync as Jwe}from"fs";import{join as Zn,resolve as Ud,relative as Wwe}from"path";import{homedir as Kwe}from"os";import{createHash as Sg}from"crypto";import{execSync as na}from"child_process";import{glob as Ywe}from"glob";function Qwe(e){return Sg("sha256").update(Ud(e)).digest("hex").slice(0,16)}function x0(e){return Zn(tl,Qwe(e))}function l5(e){Vwe(x0(e),{recursive:!0})}function R1(e,t){return Zn(x0(e),`${t}.json`)}function u5(e){return Zn(x0(e),"index.json")}async function nke(e){let t=[];for(let l of Zwe)try{let u=await Ywe(l,{cwd:e,absolute:!0,ignore:Xwe,nodir:!0});t.push(...u)}catch{}let n={},r={},s=new Set,i=[],o=0,a=t.map(l=>{try{return{f:l,stat:Jwe(l)}}catch{return null}}).filter(l=>l!==null&&!l.stat.isDirectory()).sort((l,u)=>u.stat.mtimeMs-l.stat.mtimeMs),c=0;for(let{f:l,stat:u}of a){let d=Wwe(e,l).replace(/\\/g,"/"),f=(d.match(/\.([^./\\]+)$/)||["","noext"])[1].toLowerCase();n[f]=(n[f]||0)+1,o+=u.size;let p=d.split("/")[0];if(p&&s.add(p),i.length<20&&i.push({path:d,mtime:u.mtimeMs}),c<eke&&u.size<tke)try{let m=si(l),g=Sg("sha256").update(m).digest("hex").slice(0,16),h=m.toString("utf-8",0,Math.min(m.length,1e5)).split(`
1918
+ `).length;r[d]={hash:g,size:u.size,mtime:u.mtimeMs,lines:h},c++}catch{}}return{totalCount:t.length,byExtension:n,topLevelDirs:Array.from(s).sort(),totalSizeKB:Math.round(o/1024),trackedFiles:r,recentlyModified:i}}function rke(e){let t={isRepo:!1,isDirty:!1,modifiedFiles:[],untrackedFiles:[],stashCount:0,recentCommits:[]};try{na("git rev-parse --git-dir",{cwd:e,stdio:"pipe"}),t.isRepo=!0}catch{return t}try{t.branch=na("git rev-parse --abbrev-ref HEAD",{cwd:e,stdio:"pipe"}).toString().trim()}catch{}try{t.head=na("git rev-parse HEAD",{cwd:e,stdio:"pipe"}).toString().trim().slice(0,12)}catch{}try{let r=na("git status --porcelain",{cwd:e,stdio:"pipe"}).toString().split(`
1909
1919
  `).filter(Boolean);for(let s of r){let i=s.slice(0,2),o=s.slice(3);i.startsWith("??")?t.untrackedFiles.push(o):t.modifiedFiles.push(o)}t.isDirty=r.length>0}catch{}try{let n=na("git stash list",{cwd:e,stdio:"pipe"}).toString();t.stashCount=n.split(`
1910
1920
  `).filter(Boolean).length}catch{}try{let n=na("git log -10 --pretty=format:%H|%s|%an|%aI",{cwd:e,stdio:"pipe"}).toString();t.recentCommits=n.split(`
1911
- `).filter(Boolean).map(r=>{let[s,i,o,a]=r.split("|");return{sha:s.slice(0,12),message:i,author:o,date:a}})}catch{}try{t.remoteUrl=na("git config --get remote.origin.url",{cwd:e,stdio:"pipe"}).toString().trim()}catch{}try{let n=na("git rev-list --left-right --count HEAD...@{u}",{cwd:e,stdio:"pipe"}).toString().trim(),[r,s]=n.split(" ").map(i=>parseInt(i,10));t.ahead=isFinite(r)?r:0,t.behind=isFinite(s)?s:0}catch{}return t}function rke(e){let t={},n=Zn(e,"package.json");if(Tr(n))try{let o=JSON.parse(si(n,"utf-8"));t.packageJson={version:o.version||"",dependencies:o.dependencies||{},devDependencies:o.devDependencies||{},scripts:o.scripts||{}}}catch{}for(let o of["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb"]){let a=Zn(e,o);if(Tr(a))try{let c=si(a);t.lockfileHash=Sg("md5").update(c).digest("hex").slice(0,16);break}catch{}}let r=Zn(e,"requirements.txt");if(Tr(r))try{let o=si(r,"utf-8").split(`
1921
+ `).filter(Boolean).map(r=>{let[s,i,o,a]=r.split("|");return{sha:s.slice(0,12),message:i,author:o,date:a}})}catch{}try{t.remoteUrl=na("git config --get remote.origin.url",{cwd:e,stdio:"pipe"}).toString().trim()}catch{}try{let n=na("git rev-list --left-right --count HEAD...@{u}",{cwd:e,stdio:"pipe"}).toString().trim(),[r,s]=n.split(" ").map(i=>parseInt(i,10));t.ahead=isFinite(r)?r:0,t.behind=isFinite(s)?s:0}catch{}return t}function ske(e){let t={},n=Zn(e,"package.json");if(Tr(n))try{let o=JSON.parse(si(n,"utf-8"));t.packageJson={version:o.version||"",dependencies:o.dependencies||{},devDependencies:o.devDependencies||{},scripts:o.scripts||{}}}catch{}for(let o of["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb"]){let a=Zn(e,o);if(Tr(a))try{let c=si(a);t.lockfileHash=Sg("md5").update(c).digest("hex").slice(0,16);break}catch{}}let r=Zn(e,"requirements.txt");if(Tr(r))try{let o=si(r,"utf-8").split(`
1912
1922
  `),a={};for(let c of o){let l=c.match(/^([\w_-]+)([=<>!]+.+)?/);l&&(a[l[1]]=l[2]||"*")}t.pythonRequirements=a}catch{}let s=Zn(e,"go.mod");if(Tr(s))try{let o=si(s,"utf-8"),a=o.match(/^module\s+(\S+)/m),c={},l=o.match(/require\s*\(([\s\S]*?)\)/)?.[1]||"";for(let u of l.split(`
1913
1923
  `)){let d=u.trim().match(/^(\S+)\s+(\S+)/);d&&(c[d[1]]=d[2])}t.goMod={module:a?.[1]||"",deps:c}}catch{}let i=Zn(e,"Cargo.toml");if(Tr(i))try{let o=si(i,"utf-8"),a=o.match(/^\s*name\s*=\s*"([^"]+)"/m),c=o.match(/^\s*version\s*=\s*"([^"]+)"/m),l={},u=o.match(/\[dependencies\]([\s\S]*?)(?=\n\[|$)/)?.[1]||"";for(let d of u.split(`
1914
- `)){let f=d.match(/^\s*([\w_-]+)\s*=\s*["']?([^"'\n]+)/);f&&(l[f[1]]=f[2].trim())}t.cargoToml={name:a?.[1]||"",version:c?.[1]||"",deps:l}}catch{}return t}function ske(e){let t={configFiles:{},envFiles:[]},n=[".aiaca.json","tsconfig.json",".eslintrc.json",".eslintrc.js",".eslintrc.cjs",".prettierrc",".prettierrc.json",".prettierrc.js","jest.config.js","vitest.config.ts","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","rollup.config.js","docker-compose.yml","docker-compose.yaml","pyproject.toml","setup.py","setup.cfg","go.work"];for(let r of n){let s=Zn(e,r);if(Tr(s))try{let i=si(s);if(t.configFiles[r]=Sg("md5").update(i).digest("hex").slice(0,12),r===".aiaca.json")try{t.aiacaConfig=JSON.parse(i.toString("utf-8"))}catch{}}catch{}}for(let r of[".env",".env.local",".env.development",".env.production"]){let s=Zn(e,r);Tr(s)&&t.envFiles.push(r)}return t}function ike(e){let t=["NODE_ENV","PYTHON_VERSION","GO_VERSION","RUST_VERSION","CI","PATH"],n={};for(let r of t)process.env[r]&&(n[r]=r==="PATH"?process.env[r].split(/[;:]/).slice(0,5).join(";")+"...":process.env[r]);return{cwd:e,hostname:process.env.COMPUTERNAME||process.env.HOSTNAME,user:process.env.USER||process.env.USERNAME,shell:process.env.SHELL||process.env.ComSpec,relevantEnv:n}}async function d5(e,t,n=""){l5(e);let r=Date.now(),s=Ud(e),[i,o,a,c]=await Promise.all([tke(s),Promise.resolve(nke(s)),Promise.resolve(rke(s)),Promise.resolve(ske(s))]),l=ike(s),u={id:Sg("sha256").update(`${t}:${Date.now()}:${Math.random()}`).digest("hex").slice(0,16),projectPath:s,sessionId:t,capturedAt:Date.now(),capturedAtISO:new Date().toISOString(),summary:n,files:i,git:o,dependencies:a,config:c,environment:l,stats:{filesScanned:i.totalCount,filesHashed:Object.keys(i.trackedFiles).length,scanDurationMs:Date.now()-r,totalSizeKB:i.totalSizeKB},metadata:{nodeVersion:process.version,platform:process.platform}};c5(R1(s,u.id),JSON.stringify(u),"utf-8");let d=I1(s);if(d.snapshots.push({id:u.id,sessionId:t,capturedAt:u.capturedAt,summary:n}),d.snapshots.length>_1){let f=d.snapshots.slice(0,d.snapshots.length-_1);for(let p of f)try{P1(R1(s,p.id))}catch{}d.snapshots=d.snapshots.slice(-_1)}return oke(s,d),u}function I1(e){let t=u5(e);if(!Tr(t))return{snapshots:[]};try{return JSON.parse(si(t,"utf-8"))}catch{return{snapshots:[]}}}function oke(e,t){l5(e),c5(u5(e),JSON.stringify(t,null,2),"utf-8")}function f5(e){let t=I1(Ud(e));if(t.snapshots.length===0)return null;let n=t.snapshots[t.snapshots.length-1];return p5(e,n.id)}function p5(e,t){let n=R1(Ud(e),t);if(!Tr(n))return null;try{return JSON.parse(si(n,"utf-8"))}catch{return null}}function ake(e){return I1(Ud(e)).snapshots}function m5(e,t){let n=new Set(Object.keys(e.files.trackedFiles)),r=new Set(Object.keys(t.files.trackedFiles)),s=[...r].filter(T=>!n.has(T)),i=[...n].filter(T=>!r.has(T)),o=[];for(let T of r)n.has(T)&&e.files.trackedFiles[T].hash!==t.files.trackedFiles[T].hash&&o.push(T);let a=[],c=new Map(i.map(T=>[e.files.trackedFiles[T].hash,T])),l=[];for(let T of s){let ce=c.get(t.files.trackedFiles[T].hash);if(ce){a.push({from:ce,to:T});let se=i.indexOf(ce);se>=0&&i.splice(se,1)}else l.push(T)}let u=e.git.branch!==t.git.branch&&e.git.branch&&t.git.branch?{from:e.git.branch,to:t.git.branch}:void 0,d=new Set(e.git.recentCommits.map(T=>T.sha)),f=t.git.recentCommits.filter(T=>!d.has(T.sha)),p=new Set(e.git.modifiedFiles),m=new Set(t.git.modifiedFiles),g=[...m].filter(T=>!p.has(T)),h=[...p].filter(T=>!m.has(T)),v={},y=[],b=[];if(e.dependencies.packageJson&&t.dependencies.packageJson){let T={...e.dependencies.packageJson.dependencies,...e.dependencies.packageJson.devDependencies},ce={...t.dependencies.packageJson.dependencies,...t.dependencies.packageJson.devDependencies};for(let[se,C]of Object.entries(ce))se in T?T[se]!==C&&b.push({name:se,from:T[se],to:C}):v[se]=C;for(let se of Object.keys(T))se in ce||y.push(se)}let k=[];if(e.dependencies.packageJson&&t.dependencies.packageJson){let T=e.dependencies.packageJson.scripts||{},ce=t.dependencies.packageJson.scripts||{},se=new Set([...Object.keys(T),...Object.keys(ce)]);for(let C of se)T[C]!==ce[C]&&k.push({name:C,from:T[C],to:ce[C]})}let S=new Set(Object.keys(e.config.configFiles)),x=new Set(Object.keys(t.config.configFiles)),A=[...x].filter(T=>!S.has(T)),j=[...S].filter(T=>!x.has(T)),I=[];for(let T of x)S.has(T)&&e.config.configFiles[T]!==t.config.configFiles[T]&&I.push(T);let ye;if(e.config.aiacaConfig&&t.config.aiacaConfig){ye={};let T=new Set([...Object.keys(e.config.aiacaConfig),...Object.keys(t.config.aiacaConfig)]);for(let ce of T){let se=e.config.aiacaConfig[ce],C=t.config.aiacaConfig[ce];JSON.stringify(se)!==JSON.stringify(C)&&(ye[ce]={from:se,to:C})}Object.keys(ye).length===0&&(ye=void 0)}let Ne={};for(let T of new Set([...Object.keys(e.environment.relevantEnv),...Object.keys(t.environment.relevantEnv)]))e.environment.relevantEnv[T]!==t.environment.relevantEnv[T]&&(Ne[T]={from:e.environment.relevantEnv[T]||"",to:t.environment.relevantEnv[T]||""});let mn=l.length+i.length+o.length+a.length,nn="none";mn+f.length+Object.keys(v).length+y.length+b.length>0&&(mn>50||f.length>5||u?nn="major":mn>10||b.length>0?nn="moderate":nn="minor");let De=t.capturedAt-e.capturedAt,Et=uke(De),gn={fromSnapshotId:e.id,toSnapshotId:t.id,fromTimestamp:e.capturedAt,toTimestamp:t.capturedAt,durationMs:De,durationFormatted:Et,filesAdded:l,filesRemoved:i,filesModified:o,filesRenamed:a,totalFileChanges:mn,branchChanged:u,commitsAdded:f,dirtyChanged:{wasDirty:e.git.isDirty,isDirty:t.git.isDirty},modifiedFilesChanged:{added:g,removed:h},dependenciesAdded:v,dependenciesRemoved:y,dependenciesUpdated:b,scriptsChanged:k,lockfileChanged:e.dependencies.lockfileHash!==t.dependencies.lockfileHash,configFilesChanged:I,configFilesAdded:A,configFilesRemoved:j,aiacaConfigChanges:ye,envChanges:Ne,significance:nn,briefing:""};return gn.briefing=M1(gn,{format:"markdown",detail:"detailed"}),gn}function M1(e,t={}){let n=t.format||"markdown",r=t.detail||"detailed",s=t.maxFileChanges||20,i=t.maxCommits||10,o=t.maxDeps||15;if(n==="xml")return cke(e,t);if(n==="plain")return lke(e,t);let a=[];if(a.push(`# Session Diff \u2014 ${e.durationFormatted} since last session`),a.push(""),a.push(`**Significance:** ${e.significance}`),e.totalFileChanges===0&&e.commitsAdded.length===0&&Object.keys(e.dependenciesAdded).length===0&&e.dependenciesUpdated.length===0)return a.push(""),a.push("No significant changes since last session."),a.join(`
1924
+ `)){let f=d.match(/^\s*([\w_-]+)\s*=\s*["']?([^"'\n]+)/);f&&(l[f[1]]=f[2].trim())}t.cargoToml={name:a?.[1]||"",version:c?.[1]||"",deps:l}}catch{}return t}function ike(e){let t={configFiles:{},envFiles:[]},n=[".aiaca.json","tsconfig.json",".eslintrc.json",".eslintrc.js",".eslintrc.cjs",".prettierrc",".prettierrc.json",".prettierrc.js","jest.config.js","vitest.config.ts","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","rollup.config.js","docker-compose.yml","docker-compose.yaml","pyproject.toml","setup.py","setup.cfg","go.work"];for(let r of n){let s=Zn(e,r);if(Tr(s))try{let i=si(s);if(t.configFiles[r]=Sg("md5").update(i).digest("hex").slice(0,12),r===".aiaca.json")try{t.aiacaConfig=JSON.parse(i.toString("utf-8"))}catch{}}catch{}}for(let r of[".env",".env.local",".env.development",".env.production"]){let s=Zn(e,r);Tr(s)&&t.envFiles.push(r)}return t}function oke(e){let t=["NODE_ENV","PYTHON_VERSION","GO_VERSION","RUST_VERSION","CI","PATH"],n={};for(let r of t)process.env[r]&&(n[r]=r==="PATH"?process.env[r].split(/[;:]/).slice(0,5).join(";")+"...":process.env[r]);return{cwd:e,hostname:process.env.COMPUTERNAME||process.env.HOSTNAME,user:process.env.USER||process.env.USERNAME,shell:process.env.SHELL||process.env.ComSpec,relevantEnv:n}}async function d5(e,t,n=""){l5(e);let r=Date.now(),s=Ud(e),[i,o,a,c]=await Promise.all([nke(s),Promise.resolve(rke(s)),Promise.resolve(ske(s)),Promise.resolve(ike(s))]),l=oke(s),u={id:Sg("sha256").update(`${t}:${Date.now()}:${Math.random()}`).digest("hex").slice(0,16),projectPath:s,sessionId:t,capturedAt:Date.now(),capturedAtISO:new Date().toISOString(),summary:n,files:i,git:o,dependencies:a,config:c,environment:l,stats:{filesScanned:i.totalCount,filesHashed:Object.keys(i.trackedFiles).length,scanDurationMs:Date.now()-r,totalSizeKB:i.totalSizeKB},metadata:{nodeVersion:process.version,platform:process.platform}};c5(R1(s,u.id),JSON.stringify(u),"utf-8");let d=I1(s);if(d.snapshots.push({id:u.id,sessionId:t,capturedAt:u.capturedAt,summary:n}),d.snapshots.length>_1){let f=d.snapshots.slice(0,d.snapshots.length-_1);for(let p of f)try{P1(R1(s,p.id))}catch{}d.snapshots=d.snapshots.slice(-_1)}return ake(s,d),u}function I1(e){let t=u5(e);if(!Tr(t))return{snapshots:[]};try{return JSON.parse(si(t,"utf-8"))}catch{return{snapshots:[]}}}function ake(e,t){l5(e),c5(u5(e),JSON.stringify(t,null,2),"utf-8")}function f5(e){let t=I1(Ud(e));if(t.snapshots.length===0)return null;let n=t.snapshots[t.snapshots.length-1];return p5(e,n.id)}function p5(e,t){let n=R1(Ud(e),t);if(!Tr(n))return null;try{return JSON.parse(si(n,"utf-8"))}catch{return null}}function cke(e){return I1(Ud(e)).snapshots}function m5(e,t){let n=new Set(Object.keys(e.files.trackedFiles)),r=new Set(Object.keys(t.files.trackedFiles)),s=[...r].filter(T=>!n.has(T)),i=[...n].filter(T=>!r.has(T)),o=[];for(let T of r)n.has(T)&&e.files.trackedFiles[T].hash!==t.files.trackedFiles[T].hash&&o.push(T);let a=[],c=new Map(i.map(T=>[e.files.trackedFiles[T].hash,T])),l=[];for(let T of s){let le=c.get(t.files.trackedFiles[T].hash);if(le){a.push({from:le,to:T});let ie=i.indexOf(le);ie>=0&&i.splice(ie,1)}else l.push(T)}let u=e.git.branch!==t.git.branch&&e.git.branch&&t.git.branch?{from:e.git.branch,to:t.git.branch}:void 0,d=new Set(e.git.recentCommits.map(T=>T.sha)),f=t.git.recentCommits.filter(T=>!d.has(T.sha)),p=new Set(e.git.modifiedFiles),m=new Set(t.git.modifiedFiles),g=[...m].filter(T=>!p.has(T)),h=[...p].filter(T=>!m.has(T)),v={},y=[],b=[];if(e.dependencies.packageJson&&t.dependencies.packageJson){let T={...e.dependencies.packageJson.dependencies,...e.dependencies.packageJson.devDependencies},le={...t.dependencies.packageJson.dependencies,...t.dependencies.packageJson.devDependencies};for(let[ie,C]of Object.entries(le))ie in T?T[ie]!==C&&b.push({name:ie,from:T[ie],to:C}):v[ie]=C;for(let ie of Object.keys(T))ie in le||y.push(ie)}let k=[];if(e.dependencies.packageJson&&t.dependencies.packageJson){let T=e.dependencies.packageJson.scripts||{},le=t.dependencies.packageJson.scripts||{},ie=new Set([...Object.keys(T),...Object.keys(le)]);for(let C of ie)T[C]!==le[C]&&k.push({name:C,from:T[C],to:le[C]})}let S=new Set(Object.keys(e.config.configFiles)),x=new Set(Object.keys(t.config.configFiles)),A=[...x].filter(T=>!S.has(T)),D=[...S].filter(T=>!x.has(T)),M=[];for(let T of x)S.has(T)&&e.config.configFiles[T]!==t.config.configFiles[T]&&M.push(T);let ee;if(e.config.aiacaConfig&&t.config.aiacaConfig){ee={};let T=new Set([...Object.keys(e.config.aiacaConfig),...Object.keys(t.config.aiacaConfig)]);for(let le of T){let ie=e.config.aiacaConfig[le],C=t.config.aiacaConfig[le];JSON.stringify(ie)!==JSON.stringify(C)&&(ee[le]={from:ie,to:C})}Object.keys(ee).length===0&&(ee=void 0)}let Ne={};for(let T of new Set([...Object.keys(e.environment.relevantEnv),...Object.keys(t.environment.relevantEnv)]))e.environment.relevantEnv[T]!==t.environment.relevantEnv[T]&&(Ne[T]={from:e.environment.relevantEnv[T]||"",to:t.environment.relevantEnv[T]||""});let mn=l.length+i.length+o.length+a.length,nn="none";mn+f.length+Object.keys(v).length+y.length+b.length>0&&(mn>50||f.length>5||u?nn="major":mn>10||b.length>0?nn="moderate":nn="minor");let De=t.capturedAt-e.capturedAt,Et=dke(De),gn={fromSnapshotId:e.id,toSnapshotId:t.id,fromTimestamp:e.capturedAt,toTimestamp:t.capturedAt,durationMs:De,durationFormatted:Et,filesAdded:l,filesRemoved:i,filesModified:o,filesRenamed:a,totalFileChanges:mn,branchChanged:u,commitsAdded:f,dirtyChanged:{wasDirty:e.git.isDirty,isDirty:t.git.isDirty},modifiedFilesChanged:{added:g,removed:h},dependenciesAdded:v,dependenciesRemoved:y,dependenciesUpdated:b,scriptsChanged:k,lockfileChanged:e.dependencies.lockfileHash!==t.dependencies.lockfileHash,configFilesChanged:M,configFilesAdded:A,configFilesRemoved:D,aiacaConfigChanges:ee,envChanges:Ne,significance:nn,briefing:""};return gn.briefing=M1(gn,{format:"markdown",detail:"detailed"}),gn}function M1(e,t={}){let n=t.format||"markdown",r=t.detail||"detailed",s=t.maxFileChanges||20,i=t.maxCommits||10,o=t.maxDeps||15;if(n==="xml")return lke(e,t);if(n==="plain")return uke(e,t);let a=[];if(a.push(`# Session Diff \u2014 ${e.durationFormatted} since last session`),a.push(""),a.push(`**Significance:** ${e.significance}`),e.totalFileChanges===0&&e.commitsAdded.length===0&&Object.keys(e.dependenciesAdded).length===0&&e.dependenciesUpdated.length===0)return a.push(""),a.push("No significant changes since last session."),a.join(`
1915
1925
  `);if(e.totalFileChanges>0){if(a.push(""),a.push(`## File Changes (${e.totalFileChanges})`),e.filesAdded.length>0){a.push(""),a.push(`### Added (${e.filesAdded.length})`);for(let l of e.filesAdded.slice(0,s))a.push(`- ${l}`);e.filesAdded.length>s&&a.push(`- \u2026 +${e.filesAdded.length-s} more`)}if(e.filesModified.length>0){a.push(""),a.push(`### Modified (${e.filesModified.length})`);for(let l of e.filesModified.slice(0,s))a.push(`- ${l}`);e.filesModified.length>s&&a.push(`- \u2026 +${e.filesModified.length-s} more`)}if(e.filesRemoved.length>0){a.push(""),a.push(`### Removed (${e.filesRemoved.length})`);for(let l of e.filesRemoved.slice(0,s))a.push(`- ${l}`)}if(e.filesRenamed.length>0){a.push(""),a.push(`### Renamed (${e.filesRenamed.length})`);for(let l of e.filesRenamed.slice(0,s))a.push(`- ${l.from} \u2192 ${l.to}`)}}if(e.branchChanged||e.commitsAdded.length>0||e.dirtyChanged.wasDirty!==e.dirtyChanged.isDirty){if(a.push(""),a.push("## Git"),e.branchChanged&&a.push(`- Branch: ${e.branchChanged.from} \u2192 ${e.branchChanged.to}`),e.commitsAdded.length>0){a.push(`- New commits (${e.commitsAdded.length}):`);for(let l of e.commitsAdded.slice(0,i))a.push(` - ${l.sha} ${l.message} (${l.author})`)}e.dirtyChanged.wasDirty&&!e.dirtyChanged.isDirty&&a.push("- Working tree was cleaned"),!e.dirtyChanged.wasDirty&&e.dirtyChanged.isDirty&&a.push("- Working tree is now dirty")}if(Object.keys(e.dependenciesAdded).length>0||e.dependenciesRemoved.length>0||e.dependenciesUpdated.length>0){if(a.push(""),a.push("## Dependencies"),Object.keys(e.dependenciesAdded).length>0){a.push(""),a.push("### Added");for(let[l,u]of Object.entries(e.dependenciesAdded).slice(0,o))a.push(`- ${l}@${u}`)}if(e.dependenciesUpdated.length>0){a.push(""),a.push("### Updated");for(let l of e.dependenciesUpdated.slice(0,o))a.push(`- ${l.name}: ${l.from} \u2192 ${l.to}`)}if(e.dependenciesRemoved.length>0){a.push(""),a.push("### Removed");for(let l of e.dependenciesRemoved.slice(0,o))a.push(`- ${l}`)}e.lockfileChanged&&a.push("- Lockfile changed")}if(e.scriptsChanged.length>0){a.push(""),a.push("## Scripts Changed");for(let l of e.scriptsChanged.slice(0,10))l.from?l.to?a.push(`- ${l.name}: ${l.from} \u2192 ${l.to}`):a.push(`- - ${l.name}: ${l.from}`):a.push(`- + ${l.name}: ${l.to}`)}if((e.configFilesChanged.length>0||e.configFilesAdded.length>0||e.configFilesRemoved.length>0||e.aiacaConfigChanges)&&(a.push(""),a.push("## Config"),e.configFilesAdded.length>0&&a.push(`- Added: ${e.configFilesAdded.join(", ")}`),e.configFilesChanged.length>0&&a.push(`- Changed: ${e.configFilesChanged.join(", ")}`),e.configFilesRemoved.length>0&&a.push(`- Removed: ${e.configFilesRemoved.join(", ")}`),e.aiacaConfigChanges)){a.push("- AIACA config changes:");for(let[l,u]of Object.entries(e.aiacaConfigChanges))a.push(` - ${l}: ${JSON.stringify(u.from)} \u2192 ${JSON.stringify(u.to)}`)}if(t.includeEnv&&Object.keys(e.envChanges).length>0){a.push(""),a.push("## Environment");for(let[l,u]of Object.entries(e.envChanges))a.push(`- ${l}: ${u.from||"(unset)"} \u2192 ${u.to||"(unset)"}`)}return a.join(`
1916
- `)}function cke(e,t){let n=[];if(n.push(`<session_diff duration="${e.durationFormatted}" significance="${e.significance}">`),e.totalFileChanges>0){n.push(` <files added="${e.filesAdded.length}" modified="${e.filesModified.length}" removed="${e.filesRemoved.length}" renamed="${e.filesRenamed.length}">`);for(let r of e.filesModified.slice(0,30))n.push(` <modified>${r}</modified>`);for(let r of e.filesAdded.slice(0,30))n.push(` <added>${r}</added>`);for(let r of e.filesRemoved.slice(0,30))n.push(` <removed>${r}</removed>`);n.push(" </files>")}if(e.commitsAdded.length>0){n.push(` <new_commits count="${e.commitsAdded.length}">`);for(let r of e.commitsAdded.slice(0,10))n.push(` <commit sha="${r.sha}" author="${r.author}">${r.message}</commit>`);n.push(" </new_commits>")}if(e.branchChanged&&n.push(` <branch_change from="${e.branchChanged.from}" to="${e.branchChanged.to}"/>`),e.dependenciesUpdated.length>0){n.push(" <dependency_updates>");for(let r of e.dependenciesUpdated.slice(0,15))n.push(` <update name="${r.name}" from="${r.from}" to="${r.to}"/>`);n.push(" </dependency_updates>")}return n.push("</session_diff>"),n.join(`
1917
- `)}function lke(e,t){if(e.totalFileChanges===0&&e.commitsAdded.length===0)return`No significant changes since last session (${e.durationFormatted} ago).`;let n=[];return n.push(`Since last session (${e.durationFormatted} ago):`),e.totalFileChanges>0&&n.push(`${e.totalFileChanges} files changed`),e.commitsAdded.length>0&&n.push(`${e.commitsAdded.length} new commits`),e.branchChanged&&n.push(`branch ${e.branchChanged.from}\u2192${e.branchChanged.to}`),e.dependenciesUpdated.length>0&&n.push(`${e.dependenciesUpdated.length} deps updated`),Object.keys(e.dependenciesAdded).length>0&&n.push(`${Object.keys(e.dependenciesAdded).length} deps added`),n.join(", ")+"."}function uke(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60),s=Math.floor(r/24);return s>0?`${s}d ${r%24}h`:r>0?`${r}h ${n%60}m`:n>0?`${n}m`:`${t}s`}async function dke(e,t,n={}){let r=f5(e),s=await d5(e,t,"");if(!r)return{briefing:"First session for this project \u2014 no previous state to diff against.",diff:null,snapshot:s};let i=m5(r,s);return{briefing:M1(i,n),diff:i,snapshot:s}}function fke(){if(!Tr(tl))return{totalSnapshots:0,totalDiffs:0,totalProjects:0,averageSessionDurationMs:0,totalFileChangesTracked:0,totalCommitsTracked:0,oldestSnapshotAt:0,newestSnapshotAt:0,perProjectSnapshots:{}};let e=0,t=0,n=Date.now(),r=0,s={};try{let i=k0(tl);for(let o of i){let a=Zn(tl,o,"index.json");if(Tr(a))try{let c=JSON.parse(si(a,"utf-8"));e+=c.snapshots.length,t++,s[o]=c.snapshots.length;for(let l of c.snapshots)l.capturedAt<n&&(n=l.capturedAt),l.capturedAt>r&&(r=l.capturedAt)}catch{}}}catch{}return{totalSnapshots:e,totalDiffs:Math.max(0,e-t),totalProjects:t,averageSessionDurationMs:0,totalFileChangesTracked:0,totalCommitsTracked:0,oldestSnapshotAt:n,newestSnapshotAt:r,perProjectSnapshots:s}}function pke(e){let t=x0(Ud(e));if(!Tr(t))return!1;try{for(let n of k0(t))try{P1(Zn(t,n))}catch{}return!0}catch{return!1}}function mke(){if(!Tr(tl))return!0;try{for(let e of k0(tl)){let t=Zn(tl,e);try{for(let n of k0(t))P1(Zn(t,n))}catch{}}return!0}catch{return!1}}var tl,_1,Qwe,Zwe,Xwe,eke,C0=w(()=>{"use strict";tl=Zn(Wwe(),".aiaca","session-diff"),_1=30;Qwe=["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/*.{py,java,go,rs,c,cpp,h,hpp}","**/*.{json,yaml,yml,toml,xml}","**/*.{md,txt,rst}","**/*.{html,css,scss,sass}","**/*.{sh,ps1,bat,cmd}","**/*.sql","**/Makefile","**/Dockerfile*"],Zwe=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.cache/**","**/coverage/**","**/target/**","**/.next/**","**/.nuxt/**","**/__pycache__/**","**/.venv/**","**/venv/**","**/vendor/**","**/*.min.js","**/*.lock"],Xwe=2e3,eke=1024*1024});var b5={};$(b5,{addCustomTip:()=>Rke,buildContext:()=>Fke,checkContextualTriggers:()=>$ke,dismissTip:()=>Ake,formatTip:()=>Lke,getAllTipsForBrowsing:()=>Oke,getPreferences:()=>Mke,getTipForTrigger:()=>bs,getTipsStats:()=>Dke,rateTip:()=>Tke,recordQuery:()=>_ke,recordTipShown:()=>Cke,removeCustomTip:()=>Pke,resetTips:()=>Eke,setPreferences:()=>Ike});import{existsSync as gke,readFileSync as hke,writeFileSync as yke,mkdirSync as bke}from"fs";import{join as g5}from"path";import{homedir as vke}from"os";function y5(){bke(h5,{recursive:!0})}function wke(){if(y5(),!gke(E1)){Ki();return}try{V={...V,...JSON.parse(hke(E1,"utf-8"))}}catch{}}function Ki(){y5(),yke(E1,JSON.stringify(V,null,2),"utf-8")}function D1(){return[...Ske,...V.customTips]}function kke(e,t){if(V.dismissed.includes(e.id)||!V.preferences.enabled||V.preferences.showFrequency==="off"||V.preferences.categories.length>0&&!V.preferences.categories.includes(e.category)||V.preferences.tags.length>0&&!e.tags.some(i=>V.preferences.tags.includes(i)))return!1;let n={beginner:0,intermediate:1,advanced:2};if(n[e.difficulty]<n[V.preferences.minDifficulty])return!1;let r=V.shown[e.id]||[];if(e.showOnce&&r.length>0)return!1;let s=r.filter(i=>Date.now()-new Date(i.shownAt).getTime()<t.sessionAge);if(e.maxShowsPerSession&&s.length>=e.maxShowsPerSession)return!1;if(e.cooldownMs&&r.length>0){let i=r[r.length-1];if(Date.now()-new Date(i.shownAt).getTime()<e.cooldownMs)return!1}return!(e.triggerCondition&&!e.triggerCondition(t))}function xke(e,t){return D1().filter(n=>n.trigger===e).filter(n=>kke(n,t)).sort((n,r)=>r.priority-n.priority)}function bs(e,t){let n=xke(e,t);if(n.length===0)return null;let r=V.preferences.showFrequency;if(r==="rare"&&Math.random()>.3||r==="normal"&&Math.random()>.6)return null;let s=n.slice(0,3);return s[Math.floor(Math.random()*s.length)]}function $ke(e){if(e.isFirstRun){let n=bs("first_run",e);if(n)return n}if(e.errorCount>=3){let n=bs("multiple_failures",e);if(n)return n}else if(e.errorCount>0){let n=bs("after_error",e);if(n)return n}if(e.sessionAge>1800*1e3){let n=bs("long_session",e);if(n)return n}if(e.contextTokens>5e4){let n=bs("large_context",e);if(n)return n}if(e.totalCost>1){let n=bs("high_cost",e);if(n)return n}if([10,50,100,500,1e3,5e3].includes(e.totalQueriesEver)){let n=bs("milestone",e);if(n)return n}if(e.filesModified.length>0){let n=bs("file_modified",e);if(n)return n}if(e.toolUseCount===1){let n=bs("first_tool_use",e);if(n)return n}if(e.idleTimeMs>600*1e3){let n=bs("idle",e);if(n)return n}return null}function Cke(e,t){V.shown[e]||(V.shown[e]=[]),V.shown[e].push({tipId:e,trigger:t,shownAt:new Date().toISOString(),dismissed:!1}),Ki()}function Ake(e){V.dismissed.includes(e)||V.dismissed.push(e),Ki()}function Tke(e,t){let n=V.shown[e];n&&n.length>0&&(n[n.length-1].rated=t,Ki())}function _ke(){V.totalQueriesEver++,Ki()}function Rke(e){V.customTips.push(e),Ki()}function Pke(e){let t=V.customTips.length;return V.customTips=V.customTips.filter(n=>n.id!==e),Ki(),V.customTips.length<t}function Ike(e){V.preferences={...V.preferences,...e},Ki()}function Mke(){return{...V.preferences}}function Eke(){V.shown={},V.dismissed=[],Ki()}function Dke(){let e=new Map(D1().map(i=>[i.id,i])),t=0,n=0,r=0,s=[];for(let[i,o]of Object.entries(V.shown))t+=o.length,n+=o.filter(a=>a.rated==="helpful").length,r+=o.filter(a=>a.rated==="not_helpful").length,s.push({id:i,shows:o.length});return s.sort((i,o)=>o.shows-i.shows),{totalShows:t,uniqueTipsShown:Object.keys(V.shown).length,dismissedCount:V.dismissed.length,helpfulCount:n,notHelpfulCount:r,customTipsCount:V.customTips.length,totalQueries:V.totalQueriesEver,topShownTips:s.slice(0,10).map(i=>({id:i.id,message:e.get(i.id)?.message||"?",shows:i.shows}))}}function Fke(e,t){let n=Date.now(),r=t.sessionStartTime?n-t.sessionStartTime:0,s=0,i=0,o=[],a=[],c=[];for(let l of e){if(l.role==="assistant"&&l.toolCalls)for(let u of l.toolCalls)s++,c.push(u.name),(u.name==="file_write"||u.name==="file_edit")&&a.push(String(u.input?.path));if(l.role==="user"&&/<tool_result.*error="true"|Error:|Exit code:/.test(l.content)){i++;let u=l.content.match(/Error: ([^\n]+)/);u&&o.push(u[1])}}return{sessionAge:r,messageCount:e.length,toolUseCount:s,errorCount:i,recentErrors:o.slice(-5),filesModified:[...new Set(a)],totalCost:t.totalCost||0,contextTokens:t.contextTokens||0,isFirstRun:V.totalQueriesEver===0,totalQueriesEver:V.totalQueriesEver,lastUsedTools:c.slice(-10),idleTimeMs:t.idleTimeMs||0}}function Lke(e){return`${e.difficulty==="beginner"?"\u{1F4A1}":e.difficulty==="intermediate"?"\u2728":"\u{1F393}"} Tip: ${e.message}`}function Oke(e){let t=D1();return e?.category&&(t=t.filter(n=>n.category===e.category)),e?.difficulty&&(t=t.filter(n=>n.difficulty===e.difficulty)),t.sort((n,r)=>r.priority-n.priority)}var Ske,h5,E1,V,v5=w(()=>{"use strict";Ske=[{id:"gs_help",message:"Type /help to see all available commands",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:9,tags:["basics"]},{id:"gs_init",message:"Create AIACA.md in your project root with /init to give persistent project context",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:8,tags:["memory"]},{id:"gs_model",message:"Use /model to switch between Claude and Gemini models for different tasks",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:7,tags:["models"]},{id:"gs_first_run",message:'Welcome to AIACA! Try asking it to "explain this codebase" to get started',category:"getting_started",difficulty:"beginner",trigger:"first_run",showOnce:!0,priority:10,tags:["welcome"]},{id:"prod_compact",message:"Use /compact to summarize long conversations and free up context window",category:"productivity",difficulty:"intermediate",trigger:"large_context",showOnce:!1,priority:9,cooldownMs:1800*1e3,tags:["context"]},{id:"prod_collapse",message:"Use /collapse for lossless context compression \u2014 preserves all info while shrinking tool results",category:"productivity",difficulty:"intermediate",trigger:"large_context",showOnce:!1,priority:8,tags:["context","efficiency"]},{id:"prod_recall",message:"Use /recall extract to save important facts from this session for future use",category:"productivity",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:7,tags:["memory"]},{id:"prod_skill",message:"Browse pre-built skills with /skill list \u2014 they save typing for common tasks",category:"productivity",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:6,tags:["skills"]},{id:"cmd_resume",message:"Continue past sessions with /resume \u2014 your conversation history persists",category:"commands",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:6,tags:["session"]},{id:"cmd_export",message:"Save conversations as markdown with /export",category:"commands",difficulty:"beginner",trigger:"long_session",showOnce:!0,priority:5,tags:["export"]},{id:"cmd_diff",message:"Use /diff to see git changes inline",category:"commands",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:4,tags:["git"]},{id:"cmd_search",message:"Search past conversations with /search <query>",category:"commands",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:5,tags:["search"]},{id:"tool_first_bash",message:'Tip: AIACA can run any shell command via the bash tool \u2014 say "run npm install"',category:"tools",difficulty:"beginner",trigger:"first_tool_use",showOnce:!0,priority:7,tags:["shell"]},{id:"tool_image",message:'Copy an image to clipboard then ask AIACA to "look at this" \u2014 it auto-detects',category:"tools",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:6,tags:["vision"]},{id:"tool_doc",message:"Generate .docx, .pptx, .pdf files using natural language \u2014 AIACA handles formatting",category:"tools",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:5,tags:["docs"]},{id:"tool_agent",message:"Spawn parallel sub-agents with the agent tool for independent subtasks",category:"tools",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["agents"]},{id:"eff_plan_mode",message:"Use /plan for read-only exploration \u2014 prevents accidental writes",category:"efficiency",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:6,tags:["safety"]},{id:"eff_perm_auto",message:'Set permission mode to "auto" with /permissions auto for fewer interruptions on safe ops',category:"efficiency",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:7,tags:["permissions"]},{id:"eff_cache",message:"Enable response caching with /cache on for faster repeated queries",category:"efficiency",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:5,tags:["cache"]},{id:"eff_vcr",message:"Record + replay API calls with /vcr \u2014 perfect for testing and debugging",category:"efficiency",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["testing"]},{id:"qual_review",message:"Run /review or use the code-review skill before committing changes",category:"quality",difficulty:"intermediate",trigger:"file_modified",showOnce:!1,priority:7,cooldownMs:3600*1e3,tags:["review"]},{id:"qual_test",message:"Use the test-writer skill to generate comprehensive tests automatically",category:"quality",difficulty:"intermediate",trigger:"file_modified",showOnce:!1,priority:6,cooldownMs:3600*1e3,tags:["testing"]},{id:"qual_security",message:"Run /skill security-audit periodically to catch vulnerabilities",category:"quality",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:6,tags:["security"]},{id:"qual_docs",message:"Generate documentation automatically with /docs readme --ai --write",category:"quality",difficulty:"intermediate",trigger:"opportunity",showOnce:!0,priority:5,tags:["docs"]},{id:"safe_perm",message:'Default permission mode "ask" prompts before destructive operations \u2014 safer for production',category:"safety",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:6,tags:["permissions"]},{id:"safe_undo",message:"File edits are auto-snapshotted \u2014 recovery available via fileHistory",category:"safety",difficulty:"intermediate",trigger:"file_modified",showOnce:!0,priority:7,tags:["safety"]},{id:"safe_worktree",message:"Use /worktree for isolated git operations without affecting main branch",category:"safety",difficulty:"advanced",trigger:"startup",showOnce:!0,priority:5,tags:["git"]},{id:"cost_haiku",message:"Use /model gemini-2.5-flash-lite for cheap/fast simple queries",category:"cost_savings",difficulty:"intermediate",trigger:"high_cost",showOnce:!1,priority:8,cooldownMs:3600*1e3,tags:["cost"]},{id:"cost_compact",message:"Compact context regularly \u2014 saves tokens on long sessions",category:"cost_savings",difficulty:"intermediate",trigger:"high_cost",showOnce:!1,priority:7,cooldownMs:1800*1e3,tags:["cost"]},{id:"cost_cache",message:"Enable /cache for repeated similar queries \u2014 cuts cost dramatically",category:"cost_savings",difficulty:"advanced",trigger:"high_cost",showOnce:!0,priority:8,tags:["cost","cache"]},{id:"collab_team",message:"Sync memories across machines with /team start \u2014 knowledge persists across devices",category:"collaboration",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["team"]},{id:"collab_mcp",message:"Connect external tools via Model Context Protocol \u2014 see /mcp",category:"collaboration",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["mcp"]},{id:"collab_share",message:"Share session transcripts via /share for collaboration",category:"collaboration",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:4,tags:["share"]},{id:"wf_init_first",message:"For new projects, run /init to scaffold an AIACA.md instructions file",category:"workflows",difficulty:"beginner",trigger:"first_run",showOnce:!0,priority:8,tags:["setup"]},{id:"wf_research",message:"For research tasks, web_search + web_fetch combination works great",category:"workflows",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:5,tags:["research"]},{id:"wf_refactor",message:"For refactoring: use the refactor skill with target file specified",category:"workflows",difficulty:"intermediate",trigger:"workflow_pattern",showOnce:!0,priority:6,tags:["refactor"]},{id:"wf_bug_hunt",message:"For bugs: describe the symptom, AIACA traces from observable to root cause",category:"workflows",difficulty:"intermediate",trigger:"after_failure",showOnce:!1,priority:7,cooldownMs:1800*1e3,tags:["debug"]},{id:"adv_dream",message:"Run /dream periodically \u2014 consolidates memories like REM sleep, generates insights",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["memory"]},{id:"adv_diag",message:"Track performance with /diagnose metrics \u2014 identify bottlenecks",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:3,tags:["perf"]},{id:"adv_hooks",message:"Add custom hooks (/hooks) to run shell commands on tool events",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["hooks"]},{id:"ts_doctor",message:"Run /doctor to diagnose configuration issues",category:"troubleshooting",difficulty:"beginner",trigger:"after_error",showOnce:!1,priority:8,cooldownMs:1800*1e3,tags:["debug"]},{id:"ts_retry",message:"AIACA auto-retries on rate limits with exponential backoff",category:"troubleshooting",difficulty:"beginner",trigger:"after_error",showOnce:!0,priority:7,tags:["errors"]},{id:"ts_logs",message:"Inspect detailed logs with /diagnose logs",category:"troubleshooting",difficulty:"intermediate",trigger:"multiple_failures",showOnce:!1,priority:8,cooldownMs:3600*1e3,tags:["debug"]},{id:"ts_clear",message:"If things get weird, /clear resets the conversation",category:"troubleshooting",difficulty:"beginner",trigger:"multiple_failures",showOnce:!1,priority:6,cooldownMs:3600*1e3,tags:["reset"]},{id:"ms_10",message:"\u{1F389} You've made 10 queries! Try /skill list to discover pre-built workflows",category:"getting_started",difficulty:"beginner",trigger:"milestone",showOnce:!0,priority:6,triggerCondition:e=>e.totalQueriesEver===10,tags:["milestone"]},{id:"ms_100",message:"\u{1F680} 100 queries! You're a power user. Have you tried /dream for memory consolidation?",category:"advanced",difficulty:"advanced",trigger:"milestone",showOnce:!0,priority:5,triggerCondition:e=>e.totalQueriesEver===100,tags:["milestone"]},{id:"ms_1000",message:"\u{1F3C6} 1000 queries! You're officially an AIACA expert. Consider sharing skills with the community via /skill registry",category:"advanced",difficulty:"advanced",trigger:"milestone",showOnce:!0,priority:4,triggerCondition:e=>e.totalQueriesEver===1e3,tags:["milestone"]},{id:"nf_image",message:"NEW: AIACA now supports image inputs \u2014 paste from clipboard or reference file paths",category:"productivity",difficulty:"intermediate",trigger:"new_feature",showOnce:!0,priority:7,tags:["vision"]},{id:"nf_team",message:"NEW: Team memory sync lets multiple agents share knowledge \u2014 try /team start",category:"collaboration",difficulty:"advanced",trigger:"new_feature",showOnce:!0,priority:5,tags:["team"]},{id:"opp_no_tests",message:"I notice no test framework \u2014 consider adding one (jest, vitest, pytest)",category:"quality",difficulty:"intermediate",trigger:"opportunity",showOnce:!0,priority:6,tags:["testing"]},{id:"opp_no_readme",message:"No README found \u2014 generate one with /docs readme --ai --write",category:"quality",difficulty:"beginner",trigger:"opportunity",showOnce:!0,priority:7,tags:["docs"]},{id:"opp_no_git",message:'Not a git repo \u2014 initialize with "git init" to track changes',category:"quality",difficulty:"beginner",trigger:"opportunity",showOnce:!0,priority:6,tags:["git"]}],h5=g5(vke(),".aiaca","tips"),E1=g5(h5,"state.json"),V={installedAt:new Date().toISOString(),totalQueriesEver:0,shown:{},dismissed:[],preferences:{enabled:!0,showFrequency:"normal",minDifficulty:"beginner",categories:[],tags:[]},customTips:[]};wke()});var j1={};$(j1,{clearTeamMemory:()=>Zke,discoverAgents:()=>k5,getAgentPresence:()=>x5,getOrCreateIdentity:()=>ii,getTeamSyncStats:()=>Qke,loadTeamConfig:()=>Yke,manualSync:()=>exe,pruneOldData:()=>Xke,receiveMemories:()=>A0,registerPresence:()=>L1,saveTeamConfig:()=>C5,shareMemories:()=>O1,startAutoSync:()=>Vke,startFileWatcher:()=>Wke,stopAutoSync:()=>Jke,stopFileWatcher:()=>Kke,updateIdentity:()=>$g});import{existsSync as Vr,readFileSync as sl,writeFileSync as ra,mkdirSync as Hd,readdirSync as il,statSync as jke,watch as Bke,unlinkSync as xg}from"fs";import{join as Mt}from"path";import{homedir as Nke,hostname as S5}from"os";import{createHash as qke,randomUUID as Uke}from"crypto";function Jr(){Hd(ol,{recursive:!0}),Hd(Yi,{recursive:!0}),Hd(Gd,{recursive:!0}),Hd(Qi,{recursive:!0})}function ii(e){if(Jr(),_r)return _r;if(Vr(nl))try{return _r=JSON.parse(sl(nl,"utf-8")),_r.lastSeenAt=new Date().toISOString(),ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}catch{}return _r={id:`agent_${Uke()}`,name:e||`aiaca-${S5()}-${Date.now().toString(36).slice(-6)}`,hostname:S5(),startedAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),capabilities:["memory_sync","conflict_resolution","crdt"],syncMode:"manual",factsShared:0,factsReceived:0},ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}function $g(e){return _r={...ii(),...e,lastSeenAt:new Date().toISOString()},ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}function L1(){Jr();let e=ii();e.lastSeenAt=new Date().toISOString(),ra(Mt(Yi,`${e.id}.json`),JSON.stringify(e,null,2),"utf-8")}function k5(){if(Jr(),!Vr(Yi))return[];let e=ii().id,t=Date.now()-1440*60*1e3,n=[];for(let r of il(Yi))if(r.endsWith(".json"))try{let s=JSON.parse(sl(Mt(Yi,r),"utf-8"));if(s.id===e)continue;if(new Date(s.lastSeenAt).getTime()<t){xg(Mt(Yi,r));continue}n.push(s)}catch{}return n}function x5(e){Jr();let t=Mt(Yi,`${e}.json`);if(!Vr(t))return"offline";try{let n=JSON.parse(sl(t,"utf-8")),r=Date.now()-new Date(n.lastSeenAt).getTime();return r<300*1e3?"online":r<3600*1e3?"recent":"offline"}catch{return"offline"}}function Hke(e,t){let n=new Set([...Object.keys(e),...Object.keys(t)]),r=!1,s=!1;for(let i of n){let o=e[i]||0,a=t[i]||0;o>a&&(r=!0),a>o&&(s=!0)}return r&&s?"concurrent":r?"after":s?"before":"equal"}function zke(e,t){let n={...e};for(let[r,s]of Object.entries(t))n[r]=Math.max(n[r]||0,s);return n}function Gke(e,t="team"){let n=ii().id;return{...e,scope:t,ownerId:n,vectorClock:{[n]:1},signature:$5(e)}}function $5(e){return qke("sha256").update(`${e.id}:${e.content}:${e.category}`).digest("hex").slice(0,16)}function O1(e={}){Jr();let t=ii(),r=Jn().filter(o=>!(e.scope&&o.scope&&o.scope==="private"||e.categories&&!e.categories.includes(o.category)||e.minConfidence&&o.confidence<e.minConfidence||e.minImportance&&o.importance<e.minImportance));if(e.maxFacts&&(r=r.slice(0,e.maxFacts)),r.length===0)return{sharedCount:0,envelope:null};let s=r.map(o=>Gke(o,e.scope||"team")),i={fromAgent:t.id,toAgent:e.toAgentId,timestamp:new Date().toISOString(),facts:s,metadata:{syncRound:t.factsShared,totalFacts:s.length}};if(e.toAgentId){let o=Mt(Gd,e.toAgentId);Hd(o,{recursive:!0});let a=Mt(o,`${i.timestamp.replace(/[:.]/g,"_")}_${t.id.slice(-6)}.json`);ra(a,JSON.stringify(i,null,2),"utf-8")}else{let o=Mt(Qi,`${i.timestamp.replace(/[:.]/g,"_")}_${t.id.slice(-6)}.json`);ra(o,JSON.stringify(i,null,2),"utf-8")}return $g({factsShared:t.factsShared+s.length}),{sharedCount:s.length,envelope:i}}function A0(){Jr();let e=ii(),t=[],n=Mt(Gd,e.id);if(Vr(n)){for(let r of il(n))if(r.endsWith(".json"))try{let s=JSON.parse(sl(Mt(n,r),"utf-8")),i=w5(s);t.push(i),xg(Mt(n,r))}catch(s){t.push({added:0,updated:0,conflicts:0,rejected:0,totalReceived:0,errors:[s.message],durationMs:0})}}if(Vr(Qi))for(let r of il(Qi)){if(!r.endsWith(".json"))continue;let s=Mt(Qi,r);try{let i=JSON.parse(sl(s,"utf-8"));if(i.fromAgent===e.id)continue;let o=Mt(ol,`last_processed_${e.id}.json`),a={};if(Vr(o))try{a=JSON.parse(sl(o,"utf-8"))}catch{}if(a[i.fromAgent]&&a[i.fromAgent]>=i.timestamp)continue;let c=w5(i);t.push(c),a[i.fromAgent]=i.timestamp,ra(o,JSON.stringify(a,null,2),"utf-8")}catch{}}return t}function w5(e){let t=Date.now(),n=ii(),r=0,s=0,i=0,o=0,a=[],c=Jn(),l=new Map(c.map(u=>[u.id,u]));for(let u of e.facts)try{if(u.signature&&u.signature!==$5(u)){o++,a.push(`Bad signature on ${u.id}`);continue}let d=l.get(u.id);if(d){let f=Hke(d.vectorClock||{},u.vectorClock||{});f==="before"?(Nr(d.id),us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,metadata:{...u.metadata,syncedFrom:e.fromAgent}}),s++):f==="concurrent"&&(i++,u.confidence>d.confidence&&(Nr(d.id),us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,metadata:{...u.metadata,syncedFrom:e.fromAgent,mergedClock:zke(d.vectorClock||{},u.vectorClock||{})}}),s++))}else{let f=u.vectorClock||{[e.fromAgent]:1};us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,tags:[...u.tags||[],`from:${e.fromAgent.slice(-8)}`],metadata:{...u.metadata,syncedFrom:e.fromAgent,vectorClock:f,scope:u.scope}}),r++}}catch(d){a.push(`Error merging ${u.id}: ${d.message}`),o++}return $g({factsReceived:n.factsReceived+r+s}),{added:r,updated:s,conflicts:i,rejected:o,totalReceived:e.facts.length,errors:a,fromAgent:e.fromAgent,durationMs:Date.now()-t}}function Vke(e=300*1e3,t="auto"){rl&&clearInterval(rl),$g({syncMode:t}),rl=setInterval(()=>{try{L1(),A0(),(t==="realtime"||t==="auto")&&O1({minConfidence:.75,minImportance:.6,maxFacts:50})}catch{}},e),rl.unref()}function Jke(){rl&&(clearInterval(rl),rl=null),$g({syncMode:"manual"})}function Wke(){if(kg)return;Jr();let e=ii(),t=Mt(Gd,e.id);Hd(t,{recursive:!0});try{kg=Bke(t,n=>{n==="rename"&&setTimeout(()=>A0(),100)})}catch{}}function Kke(){kg&&(kg.close(),kg=null)}function Yke(){if(Jr(),!Vr(F1))return C5(wg),wg;try{let e=JSON.parse(sl(F1,"utf-8"));return zd={...wg,...e},zd}catch{return wg}}function C5(e){return Jr(),zd={...zd,...e},ra(F1,JSON.stringify(zd,null,2),"utf-8"),zd}function Qke(){Jr();let e=ii(),t=k5(),n=t.filter(o=>x5(o.id)==="online").length,r=Mt(Gd,e.id),s=0;Vr(r)&&(s=il(r).filter(o=>o.endsWith(".json")).length);let i=0;return Vr(Qi)&&(i=il(Qi).filter(o=>o.endsWith(".json")).length),{myAgent:e,knownAgents:t.length,onlineAgents:n,totalFactsShared:e.factsShared,totalFactsReceived:e.factsReceived,inboxPending:s,sharedQueueSize:i,syncMode:e.syncMode}}function Zke(){Jr();for(let e of[Yi,Gd,Qi])if(Vr(e))for(let t of il(e))try{xg(Mt(e,t))}catch{}if(Vr(nl))try{xg(nl)}catch{}_r=null}function Xke(){Jr();let e=Date.now()-10080*60*1e3;for(let t of[Qi,Yi])if(Vr(t))for(let n of il(t))try{let r=Mt(t,n);jke(r).mtimeMs<e&&xg(r)}catch{}}async function exe(){L1();let e=O1({minConfidence:.75,minImportance:.6}),t=A0(),n=t.reduce((r,s)=>r+s.added+s.updated,0);return{shared:e.sharedCount,received:n,results:t}}var ol,Yi,Gd,Qi,nl,F1,_r,rl,kg,wg,zd,B1=w(()=>{"use strict";xu();ol=Mt(Nke(),".aiaca","team-memory"),Yi=Mt(ol,"agents"),Gd=Mt(ol,"inbox"),Qi=Mt(ol,"shared"),nl=Mt(ol,"identity.json"),F1=Mt(ol,"config.json");_r=null;rl=null;kg=null;wg={enabled:!1,mode:"manual",intervalMs:300*1e3,shareScope:"team",minConfidence:.75,minImportance:.6,maxFactsPerSync:50,enableFileWatcher:!1},zd={...wg}});var N5={};$(N5,{analyzeProject:()=>U1,categorizeCommits:()=>M5,extractSymbols:()=>H1,generateAPIDocs:()=>D5,generateAllDocs:()=>bxe,generateArchitecture:()=>L5,generateChangelog:()=>F5,generateDoc:()=>O5,generateReadme:()=>N1,getDocSuggestion:()=>vxe,getGitChangelog:()=>I5,renderFileTree:()=>Vd});import{existsSync as qt,readFileSync as q1,writeFileSync as T0,readdirSync as txe,statSync as nxe}from"fs";import{join as pt,basename as _5,extname as rxe,relative as Cg,dirname as sxe}from"path";import{execSync as ixe}from"child_process";import{globSync as R5}from"glob";function U1(e){let t=axe(e),n=cxe(e),r=lxe(e,t),s=P5(e,e),i=uxe(e,t);return{name:t?.name||_5(e),description:t?.description,version:t?.version,language:n,framework:r,dependencies:t?.dependencies?Object.keys(t.dependencies):[],devDependencies:t?.devDependencies?Object.keys(t.devDependencies):[],scripts:t?.scripts||{},fileTree:s,entryPoint:t?.main||dxe(e,n),hasTests:!!i,testFramework:i}}function axe(e){let t=pt(e,"package.json");if(!qt(t))return null;try{return JSON.parse(q1(t,"utf-8"))}catch{return null}}function cxe(e){return qt(pt(e,"package.json"))?"JavaScript/TypeScript":qt(pt(e,"Cargo.toml"))?"Rust":qt(pt(e,"go.mod"))?"Go":qt(pt(e,"pyproject.toml"))||qt(pt(e,"requirements.txt"))?"Python":qt(pt(e,"pom.xml"))||qt(pt(e,"build.gradle"))?"Java":qt(pt(e,"Gemfile"))?"Ruby":qt(pt(e,"*.csproj"))?"C#":"Unknown"}function lxe(e,t){if(!t?.dependencies&&!t?.devDependencies)return;let n={...t.dependencies,...t.devDependencies};if(n.react)return"React";if(n.vue)return"Vue";if(n["@angular/core"])return"Angular";if(n.svelte)return"Svelte";if(n.next)return"Next.js";if(n.nuxt)return"Nuxt";if(n.express)return"Express";if(n.fastify)return"Fastify";if(n["@nestjs/core"])return"NestJS";if(n.ink)return"Ink (CLI)"}function uxe(e,t){if(!t)return;let n={...t.dependencies,...t.devDependencies};if(n.jest)return"Jest";if(n.vitest)return"Vitest";if(n.mocha)return"Mocha";if(n.cypress)return"Cypress";if(n.playwright)return"Playwright";if(qt(pt(e,"pytest.ini"))||qt(pt(e,"pyproject.toml")))return"pytest"}function dxe(e,t){let n=["src/index.ts","src/index.js","src/main.ts","index.ts","index.js","main.py","main.go","src/main.rs"];for(let r of n)if(qt(pt(e,r)))return r}function P5(e,t,n=0,r=4){let s=_5(t)||t,i=nxe(t);if(!i.isDirectory())return{name:s,type:"file",path:Cg(e,t),size:i.size};let o={name:s,type:"dir",path:Cg(e,t),children:[]};if(n>=r)return o;try{let a=txe(t);for(let c of a){if(c.startsWith(".")&&!A5.has(c)||oxe.has(c))continue;let l=pt(t,c);try{let u=P5(e,l,n+1,r);A5.has(c)&&(u.important=!0),o.children.push(u)}catch{}}}catch{}return o}function H1(e){if(!qt(e))return[];let t=rxe(e);if(![".ts",".tsx",".js",".jsx",".mjs"].includes(t))return[];let n=q1(e,"utf-8"),r=[];for(let[s,i]of Object.entries(fxe)){i.lastIndex=0;let o;for(;(o=i.exec(n))!==null;){let a=n.slice(0,o.index).split(`
1918
- `).length,c=pxe(s,o,e,a,n);c&&r.push(c)}}return gxe(r)}function pxe(e,t,n,r,s){let i=!!t[2]?.includes("export"),o,a=t[0].trim().replace(/\s+/g," ").slice(0,200);switch(e){case"function":o=t[4];break;case"arrowFunction":o=t[3];break;case"class":o=t[4];break;case"interface":o=t[3];break;case"type":o=t[3];break;case"enum":o=t[3];break;case"const":o=t[3];break}if(!o)return null;let c=mxe(s,t.index);return{name:o,kind:e==="arrowFunction"?"function":e==="method"?"method":e,file:n,line:r,signature:a,isExported:i,isAsync:!!t[3]?.includes("async")||!!t[5]?.includes("async"),jsdoc:c}}function mxe(e,t){let r=e.slice(0,t).split(`
1926
+ `)}function lke(e,t){let n=[];if(n.push(`<session_diff duration="${e.durationFormatted}" significance="${e.significance}">`),e.totalFileChanges>0){n.push(` <files added="${e.filesAdded.length}" modified="${e.filesModified.length}" removed="${e.filesRemoved.length}" renamed="${e.filesRenamed.length}">`);for(let r of e.filesModified.slice(0,30))n.push(` <modified>${r}</modified>`);for(let r of e.filesAdded.slice(0,30))n.push(` <added>${r}</added>`);for(let r of e.filesRemoved.slice(0,30))n.push(` <removed>${r}</removed>`);n.push(" </files>")}if(e.commitsAdded.length>0){n.push(` <new_commits count="${e.commitsAdded.length}">`);for(let r of e.commitsAdded.slice(0,10))n.push(` <commit sha="${r.sha}" author="${r.author}">${r.message}</commit>`);n.push(" </new_commits>")}if(e.branchChanged&&n.push(` <branch_change from="${e.branchChanged.from}" to="${e.branchChanged.to}"/>`),e.dependenciesUpdated.length>0){n.push(" <dependency_updates>");for(let r of e.dependenciesUpdated.slice(0,15))n.push(` <update name="${r.name}" from="${r.from}" to="${r.to}"/>`);n.push(" </dependency_updates>")}return n.push("</session_diff>"),n.join(`
1927
+ `)}function uke(e,t){if(e.totalFileChanges===0&&e.commitsAdded.length===0)return`No significant changes since last session (${e.durationFormatted} ago).`;let n=[];return n.push(`Since last session (${e.durationFormatted} ago):`),e.totalFileChanges>0&&n.push(`${e.totalFileChanges} files changed`),e.commitsAdded.length>0&&n.push(`${e.commitsAdded.length} new commits`),e.branchChanged&&n.push(`branch ${e.branchChanged.from}\u2192${e.branchChanged.to}`),e.dependenciesUpdated.length>0&&n.push(`${e.dependenciesUpdated.length} deps updated`),Object.keys(e.dependenciesAdded).length>0&&n.push(`${Object.keys(e.dependenciesAdded).length} deps added`),n.join(", ")+"."}function dke(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60),s=Math.floor(r/24);return s>0?`${s}d ${r%24}h`:r>0?`${r}h ${n%60}m`:n>0?`${n}m`:`${t}s`}async function fke(e,t,n={}){let r=f5(e),s=await d5(e,t,"");if(!r)return{briefing:"First session for this project \u2014 no previous state to diff against.",diff:null,snapshot:s};let i=m5(r,s);return{briefing:M1(i,n),diff:i,snapshot:s}}function pke(){if(!Tr(tl))return{totalSnapshots:0,totalDiffs:0,totalProjects:0,averageSessionDurationMs:0,totalFileChangesTracked:0,totalCommitsTracked:0,oldestSnapshotAt:0,newestSnapshotAt:0,perProjectSnapshots:{}};let e=0,t=0,n=Date.now(),r=0,s={};try{let i=k0(tl);for(let o of i){let a=Zn(tl,o,"index.json");if(Tr(a))try{let c=JSON.parse(si(a,"utf-8"));e+=c.snapshots.length,t++,s[o]=c.snapshots.length;for(let l of c.snapshots)l.capturedAt<n&&(n=l.capturedAt),l.capturedAt>r&&(r=l.capturedAt)}catch{}}}catch{}return{totalSnapshots:e,totalDiffs:Math.max(0,e-t),totalProjects:t,averageSessionDurationMs:0,totalFileChangesTracked:0,totalCommitsTracked:0,oldestSnapshotAt:n,newestSnapshotAt:r,perProjectSnapshots:s}}function mke(e){let t=x0(Ud(e));if(!Tr(t))return!1;try{for(let n of k0(t))try{P1(Zn(t,n))}catch{}return!0}catch{return!1}}function gke(){if(!Tr(tl))return!0;try{for(let e of k0(tl)){let t=Zn(tl,e);try{for(let n of k0(t))P1(Zn(t,n))}catch{}}return!0}catch{return!1}}var tl,_1,Zwe,Xwe,eke,tke,C0=w(()=>{"use strict";tl=Zn(Kwe(),".aiaca","session-diff"),_1=30;Zwe=["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/*.{py,java,go,rs,c,cpp,h,hpp}","**/*.{json,yaml,yml,toml,xml}","**/*.{md,txt,rst}","**/*.{html,css,scss,sass}","**/*.{sh,ps1,bat,cmd}","**/*.sql","**/Makefile","**/Dockerfile*"],Xwe=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.cache/**","**/coverage/**","**/target/**","**/.next/**","**/.nuxt/**","**/__pycache__/**","**/.venv/**","**/venv/**","**/vendor/**","**/*.min.js","**/*.lock"],eke=2e3,tke=1024*1024});var b5={};$(b5,{addCustomTip:()=>Pke,buildContext:()=>Lke,checkContextualTriggers:()=>Cke,dismissTip:()=>Tke,formatTip:()=>Oke,getAllTipsForBrowsing:()=>jke,getPreferences:()=>Eke,getTipForTrigger:()=>bs,getTipsStats:()=>Fke,rateTip:()=>_ke,recordQuery:()=>Rke,recordTipShown:()=>Ake,removeCustomTip:()=>Ike,resetTips:()=>Dke,setPreferences:()=>Mke});import{existsSync as hke,readFileSync as yke,writeFileSync as bke,mkdirSync as vke}from"fs";import{join as g5}from"path";import{homedir as Ske}from"os";function y5(){vke(h5,{recursive:!0})}function kke(){if(y5(),!hke(E1)){Ki();return}try{V={...V,...JSON.parse(yke(E1,"utf-8"))}}catch{}}function Ki(){y5(),bke(E1,JSON.stringify(V,null,2),"utf-8")}function D1(){return[...wke,...V.customTips]}function xke(e,t){if(V.dismissed.includes(e.id)||!V.preferences.enabled||V.preferences.showFrequency==="off"||V.preferences.categories.length>0&&!V.preferences.categories.includes(e.category)||V.preferences.tags.length>0&&!e.tags.some(i=>V.preferences.tags.includes(i)))return!1;let n={beginner:0,intermediate:1,advanced:2};if(n[e.difficulty]<n[V.preferences.minDifficulty])return!1;let r=V.shown[e.id]||[];if(e.showOnce&&r.length>0)return!1;let s=r.filter(i=>Date.now()-new Date(i.shownAt).getTime()<t.sessionAge);if(e.maxShowsPerSession&&s.length>=e.maxShowsPerSession)return!1;if(e.cooldownMs&&r.length>0){let i=r[r.length-1];if(Date.now()-new Date(i.shownAt).getTime()<e.cooldownMs)return!1}return!(e.triggerCondition&&!e.triggerCondition(t))}function $ke(e,t){return D1().filter(n=>n.trigger===e).filter(n=>xke(n,t)).sort((n,r)=>r.priority-n.priority)}function bs(e,t){let n=$ke(e,t);if(n.length===0)return null;let r=V.preferences.showFrequency;if(r==="rare"&&Math.random()>.3||r==="normal"&&Math.random()>.6)return null;let s=n.slice(0,3);return s[Math.floor(Math.random()*s.length)]}function Cke(e){if(e.isFirstRun){let n=bs("first_run",e);if(n)return n}if(e.errorCount>=3){let n=bs("multiple_failures",e);if(n)return n}else if(e.errorCount>0){let n=bs("after_error",e);if(n)return n}if(e.sessionAge>1800*1e3){let n=bs("long_session",e);if(n)return n}if(e.contextTokens>5e4){let n=bs("large_context",e);if(n)return n}if(e.totalCost>1){let n=bs("high_cost",e);if(n)return n}if([10,50,100,500,1e3,5e3].includes(e.totalQueriesEver)){let n=bs("milestone",e);if(n)return n}if(e.filesModified.length>0){let n=bs("file_modified",e);if(n)return n}if(e.toolUseCount===1){let n=bs("first_tool_use",e);if(n)return n}if(e.idleTimeMs>600*1e3){let n=bs("idle",e);if(n)return n}return null}function Ake(e,t){V.shown[e]||(V.shown[e]=[]),V.shown[e].push({tipId:e,trigger:t,shownAt:new Date().toISOString(),dismissed:!1}),Ki()}function Tke(e){V.dismissed.includes(e)||V.dismissed.push(e),Ki()}function _ke(e,t){let n=V.shown[e];n&&n.length>0&&(n[n.length-1].rated=t,Ki())}function Rke(){V.totalQueriesEver++,Ki()}function Pke(e){V.customTips.push(e),Ki()}function Ike(e){let t=V.customTips.length;return V.customTips=V.customTips.filter(n=>n.id!==e),Ki(),V.customTips.length<t}function Mke(e){V.preferences={...V.preferences,...e},Ki()}function Eke(){return{...V.preferences}}function Dke(){V.shown={},V.dismissed=[],Ki()}function Fke(){let e=new Map(D1().map(i=>[i.id,i])),t=0,n=0,r=0,s=[];for(let[i,o]of Object.entries(V.shown))t+=o.length,n+=o.filter(a=>a.rated==="helpful").length,r+=o.filter(a=>a.rated==="not_helpful").length,s.push({id:i,shows:o.length});return s.sort((i,o)=>o.shows-i.shows),{totalShows:t,uniqueTipsShown:Object.keys(V.shown).length,dismissedCount:V.dismissed.length,helpfulCount:n,notHelpfulCount:r,customTipsCount:V.customTips.length,totalQueries:V.totalQueriesEver,topShownTips:s.slice(0,10).map(i=>({id:i.id,message:e.get(i.id)?.message||"?",shows:i.shows}))}}function Lke(e,t){let n=Date.now(),r=t.sessionStartTime?n-t.sessionStartTime:0,s=0,i=0,o=[],a=[],c=[];for(let l of e){if(l.role==="assistant"&&l.toolCalls)for(let u of l.toolCalls)s++,c.push(u.name),(u.name==="file_write"||u.name==="file_edit")&&a.push(String(u.input?.path));if(l.role==="user"&&/<tool_result.*error="true"|Error:|Exit code:/.test(l.content)){i++;let u=l.content.match(/Error: ([^\n]+)/);u&&o.push(u[1])}}return{sessionAge:r,messageCount:e.length,toolUseCount:s,errorCount:i,recentErrors:o.slice(-5),filesModified:[...new Set(a)],totalCost:t.totalCost||0,contextTokens:t.contextTokens||0,isFirstRun:V.totalQueriesEver===0,totalQueriesEver:V.totalQueriesEver,lastUsedTools:c.slice(-10),idleTimeMs:t.idleTimeMs||0}}function Oke(e){return`${e.difficulty==="beginner"?"\u{1F4A1}":e.difficulty==="intermediate"?"\u2728":"\u{1F393}"} Tip: ${e.message}`}function jke(e){let t=D1();return e?.category&&(t=t.filter(n=>n.category===e.category)),e?.difficulty&&(t=t.filter(n=>n.difficulty===e.difficulty)),t.sort((n,r)=>r.priority-n.priority)}var wke,h5,E1,V,v5=w(()=>{"use strict";wke=[{id:"gs_help",message:"Type /help to see all available commands",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:9,tags:["basics"]},{id:"gs_init",message:"Create AIACA.md in your project root with /init to give persistent project context",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:8,tags:["memory"]},{id:"gs_model",message:"Use /model to switch between Claude and Gemini models for different tasks",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:7,tags:["models"]},{id:"gs_first_run",message:'Welcome to AIACA! Try asking it to "explain this codebase" to get started',category:"getting_started",difficulty:"beginner",trigger:"first_run",showOnce:!0,priority:10,tags:["welcome"]},{id:"prod_compact",message:"Use /compact to summarize long conversations and free up context window",category:"productivity",difficulty:"intermediate",trigger:"large_context",showOnce:!1,priority:9,cooldownMs:1800*1e3,tags:["context"]},{id:"prod_collapse",message:"Use /collapse for lossless context compression \u2014 preserves all info while shrinking tool results",category:"productivity",difficulty:"intermediate",trigger:"large_context",showOnce:!1,priority:8,tags:["context","efficiency"]},{id:"prod_recall",message:"Use /recall extract to save important facts from this session for future use",category:"productivity",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:7,tags:["memory"]},{id:"prod_skill",message:"Browse pre-built skills with /skill list \u2014 they save typing for common tasks",category:"productivity",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:6,tags:["skills"]},{id:"cmd_resume",message:"Continue past sessions with /resume \u2014 your conversation history persists",category:"commands",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:6,tags:["session"]},{id:"cmd_export",message:"Save conversations as markdown with /export",category:"commands",difficulty:"beginner",trigger:"long_session",showOnce:!0,priority:5,tags:["export"]},{id:"cmd_diff",message:"Use /diff to see git changes inline",category:"commands",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:4,tags:["git"]},{id:"cmd_search",message:"Search past conversations with /search <query>",category:"commands",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:5,tags:["search"]},{id:"tool_first_bash",message:'Tip: AIACA can run any shell command via the bash tool \u2014 say "run npm install"',category:"tools",difficulty:"beginner",trigger:"first_tool_use",showOnce:!0,priority:7,tags:["shell"]},{id:"tool_image",message:'Copy an image to clipboard then ask AIACA to "look at this" \u2014 it auto-detects',category:"tools",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:6,tags:["vision"]},{id:"tool_doc",message:"Generate .docx, .pptx, .pdf files using natural language \u2014 AIACA handles formatting",category:"tools",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:5,tags:["docs"]},{id:"tool_agent",message:"Spawn parallel sub-agents with the agent tool for independent subtasks",category:"tools",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["agents"]},{id:"eff_plan_mode",message:"Use /plan for read-only exploration \u2014 prevents accidental writes",category:"efficiency",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:6,tags:["safety"]},{id:"eff_perm_auto",message:'Set permission mode to "auto" with /permissions auto for fewer interruptions on safe ops',category:"efficiency",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:7,tags:["permissions"]},{id:"eff_cache",message:"Enable response caching with /cache on for faster repeated queries",category:"efficiency",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:5,tags:["cache"]},{id:"eff_vcr",message:"Record + replay API calls with /vcr \u2014 perfect for testing and debugging",category:"efficiency",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["testing"]},{id:"qual_review",message:"Run /review or use the code-review skill before committing changes",category:"quality",difficulty:"intermediate",trigger:"file_modified",showOnce:!1,priority:7,cooldownMs:3600*1e3,tags:["review"]},{id:"qual_test",message:"Use the test-writer skill to generate comprehensive tests automatically",category:"quality",difficulty:"intermediate",trigger:"file_modified",showOnce:!1,priority:6,cooldownMs:3600*1e3,tags:["testing"]},{id:"qual_security",message:"Run /skill security-audit periodically to catch vulnerabilities",category:"quality",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:6,tags:["security"]},{id:"qual_docs",message:"Generate documentation automatically with /docs readme --ai --write",category:"quality",difficulty:"intermediate",trigger:"opportunity",showOnce:!0,priority:5,tags:["docs"]},{id:"safe_perm",message:'Default permission mode "ask" prompts before destructive operations \u2014 safer for production',category:"safety",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:6,tags:["permissions"]},{id:"safe_undo",message:"File edits are auto-snapshotted \u2014 recovery available via fileHistory",category:"safety",difficulty:"intermediate",trigger:"file_modified",showOnce:!0,priority:7,tags:["safety"]},{id:"safe_worktree",message:"Use /worktree for isolated git operations without affecting main branch",category:"safety",difficulty:"advanced",trigger:"startup",showOnce:!0,priority:5,tags:["git"]},{id:"cost_haiku",message:"Use /model gemini-2.5-flash-lite for cheap/fast simple queries",category:"cost_savings",difficulty:"intermediate",trigger:"high_cost",showOnce:!1,priority:8,cooldownMs:3600*1e3,tags:["cost"]},{id:"cost_compact",message:"Compact context regularly \u2014 saves tokens on long sessions",category:"cost_savings",difficulty:"intermediate",trigger:"high_cost",showOnce:!1,priority:7,cooldownMs:1800*1e3,tags:["cost"]},{id:"cost_cache",message:"Enable /cache for repeated similar queries \u2014 cuts cost dramatically",category:"cost_savings",difficulty:"advanced",trigger:"high_cost",showOnce:!0,priority:8,tags:["cost","cache"]},{id:"collab_team",message:"Sync memories across machines with /team start \u2014 knowledge persists across devices",category:"collaboration",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["team"]},{id:"collab_mcp",message:"Connect external tools via Model Context Protocol \u2014 see /mcp",category:"collaboration",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["mcp"]},{id:"collab_share",message:"Share session transcripts via /share for collaboration",category:"collaboration",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:4,tags:["share"]},{id:"wf_init_first",message:"For new projects, run /init to scaffold an AIACA.md instructions file",category:"workflows",difficulty:"beginner",trigger:"first_run",showOnce:!0,priority:8,tags:["setup"]},{id:"wf_research",message:"For research tasks, web_search + web_fetch combination works great",category:"workflows",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:5,tags:["research"]},{id:"wf_refactor",message:"For refactoring: use the refactor skill with target file specified",category:"workflows",difficulty:"intermediate",trigger:"workflow_pattern",showOnce:!0,priority:6,tags:["refactor"]},{id:"wf_bug_hunt",message:"For bugs: describe the symptom, AIACA traces from observable to root cause",category:"workflows",difficulty:"intermediate",trigger:"after_failure",showOnce:!1,priority:7,cooldownMs:1800*1e3,tags:["debug"]},{id:"adv_dream",message:"Run /dream periodically \u2014 consolidates memories like REM sleep, generates insights",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["memory"]},{id:"adv_diag",message:"Track performance with /diagnose metrics \u2014 identify bottlenecks",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:3,tags:["perf"]},{id:"adv_hooks",message:"Add custom hooks (/hooks) to run shell commands on tool events",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["hooks"]},{id:"ts_doctor",message:"Run /doctor to diagnose configuration issues",category:"troubleshooting",difficulty:"beginner",trigger:"after_error",showOnce:!1,priority:8,cooldownMs:1800*1e3,tags:["debug"]},{id:"ts_retry",message:"AIACA auto-retries on rate limits with exponential backoff",category:"troubleshooting",difficulty:"beginner",trigger:"after_error",showOnce:!0,priority:7,tags:["errors"]},{id:"ts_logs",message:"Inspect detailed logs with /diagnose logs",category:"troubleshooting",difficulty:"intermediate",trigger:"multiple_failures",showOnce:!1,priority:8,cooldownMs:3600*1e3,tags:["debug"]},{id:"ts_clear",message:"If things get weird, /clear resets the conversation",category:"troubleshooting",difficulty:"beginner",trigger:"multiple_failures",showOnce:!1,priority:6,cooldownMs:3600*1e3,tags:["reset"]},{id:"ms_10",message:"\u{1F389} You've made 10 queries! Try /skill list to discover pre-built workflows",category:"getting_started",difficulty:"beginner",trigger:"milestone",showOnce:!0,priority:6,triggerCondition:e=>e.totalQueriesEver===10,tags:["milestone"]},{id:"ms_100",message:"\u{1F680} 100 queries! You're a power user. Have you tried /dream for memory consolidation?",category:"advanced",difficulty:"advanced",trigger:"milestone",showOnce:!0,priority:5,triggerCondition:e=>e.totalQueriesEver===100,tags:["milestone"]},{id:"ms_1000",message:"\u{1F3C6} 1000 queries! You're officially an AIACA expert. Consider sharing skills with the community via /skill registry",category:"advanced",difficulty:"advanced",trigger:"milestone",showOnce:!0,priority:4,triggerCondition:e=>e.totalQueriesEver===1e3,tags:["milestone"]},{id:"nf_image",message:"NEW: AIACA now supports image inputs \u2014 paste from clipboard or reference file paths",category:"productivity",difficulty:"intermediate",trigger:"new_feature",showOnce:!0,priority:7,tags:["vision"]},{id:"nf_team",message:"NEW: Team memory sync lets multiple agents share knowledge \u2014 try /team start",category:"collaboration",difficulty:"advanced",trigger:"new_feature",showOnce:!0,priority:5,tags:["team"]},{id:"opp_no_tests",message:"I notice no test framework \u2014 consider adding one (jest, vitest, pytest)",category:"quality",difficulty:"intermediate",trigger:"opportunity",showOnce:!0,priority:6,tags:["testing"]},{id:"opp_no_readme",message:"No README found \u2014 generate one with /docs readme --ai --write",category:"quality",difficulty:"beginner",trigger:"opportunity",showOnce:!0,priority:7,tags:["docs"]},{id:"opp_no_git",message:'Not a git repo \u2014 initialize with "git init" to track changes',category:"quality",difficulty:"beginner",trigger:"opportunity",showOnce:!0,priority:6,tags:["git"]}],h5=g5(Ske(),".aiaca","tips"),E1=g5(h5,"state.json"),V={installedAt:new Date().toISOString(),totalQueriesEver:0,shown:{},dismissed:[],preferences:{enabled:!0,showFrequency:"normal",minDifficulty:"beginner",categories:[],tags:[]},customTips:[]};kke()});var j1={};$(j1,{clearTeamMemory:()=>Xke,discoverAgents:()=>k5,getAgentPresence:()=>x5,getOrCreateIdentity:()=>ii,getTeamSyncStats:()=>Zke,loadTeamConfig:()=>Qke,manualSync:()=>txe,pruneOldData:()=>exe,receiveMemories:()=>A0,registerPresence:()=>L1,saveTeamConfig:()=>C5,shareMemories:()=>O1,startAutoSync:()=>Jke,startFileWatcher:()=>Kke,stopAutoSync:()=>Wke,stopFileWatcher:()=>Yke,updateIdentity:()=>$g});import{existsSync as Vr,readFileSync as sl,writeFileSync as ra,mkdirSync as Hd,readdirSync as il,statSync as Bke,watch as Nke,unlinkSync as xg}from"fs";import{join as Mt}from"path";import{homedir as qke,hostname as S5}from"os";import{createHash as Uke,randomUUID as Hke}from"crypto";function Jr(){Hd(ol,{recursive:!0}),Hd(Yi,{recursive:!0}),Hd(Gd,{recursive:!0}),Hd(Qi,{recursive:!0})}function ii(e){if(Jr(),_r)return _r;if(Vr(nl))try{return _r=JSON.parse(sl(nl,"utf-8")),_r.lastSeenAt=new Date().toISOString(),ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}catch{}return _r={id:`agent_${Hke()}`,name:e||`aiaca-${S5()}-${Date.now().toString(36).slice(-6)}`,hostname:S5(),startedAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),capabilities:["memory_sync","conflict_resolution","crdt"],syncMode:"manual",factsShared:0,factsReceived:0},ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}function $g(e){return _r={...ii(),...e,lastSeenAt:new Date().toISOString()},ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}function L1(){Jr();let e=ii();e.lastSeenAt=new Date().toISOString(),ra(Mt(Yi,`${e.id}.json`),JSON.stringify(e,null,2),"utf-8")}function k5(){if(Jr(),!Vr(Yi))return[];let e=ii().id,t=Date.now()-1440*60*1e3,n=[];for(let r of il(Yi))if(r.endsWith(".json"))try{let s=JSON.parse(sl(Mt(Yi,r),"utf-8"));if(s.id===e)continue;if(new Date(s.lastSeenAt).getTime()<t){xg(Mt(Yi,r));continue}n.push(s)}catch{}return n}function x5(e){Jr();let t=Mt(Yi,`${e}.json`);if(!Vr(t))return"offline";try{let n=JSON.parse(sl(t,"utf-8")),r=Date.now()-new Date(n.lastSeenAt).getTime();return r<300*1e3?"online":r<3600*1e3?"recent":"offline"}catch{return"offline"}}function zke(e,t){let n=new Set([...Object.keys(e),...Object.keys(t)]),r=!1,s=!1;for(let i of n){let o=e[i]||0,a=t[i]||0;o>a&&(r=!0),a>o&&(s=!0)}return r&&s?"concurrent":r?"after":s?"before":"equal"}function Gke(e,t){let n={...e};for(let[r,s]of Object.entries(t))n[r]=Math.max(n[r]||0,s);return n}function Vke(e,t="team"){let n=ii().id;return{...e,scope:t,ownerId:n,vectorClock:{[n]:1},signature:$5(e)}}function $5(e){return Uke("sha256").update(`${e.id}:${e.content}:${e.category}`).digest("hex").slice(0,16)}function O1(e={}){Jr();let t=ii(),r=Jn().filter(o=>!(e.scope&&o.scope&&o.scope==="private"||e.categories&&!e.categories.includes(o.category)||e.minConfidence&&o.confidence<e.minConfidence||e.minImportance&&o.importance<e.minImportance));if(e.maxFacts&&(r=r.slice(0,e.maxFacts)),r.length===0)return{sharedCount:0,envelope:null};let s=r.map(o=>Vke(o,e.scope||"team")),i={fromAgent:t.id,toAgent:e.toAgentId,timestamp:new Date().toISOString(),facts:s,metadata:{syncRound:t.factsShared,totalFacts:s.length}};if(e.toAgentId){let o=Mt(Gd,e.toAgentId);Hd(o,{recursive:!0});let a=Mt(o,`${i.timestamp.replace(/[:.]/g,"_")}_${t.id.slice(-6)}.json`);ra(a,JSON.stringify(i,null,2),"utf-8")}else{let o=Mt(Qi,`${i.timestamp.replace(/[:.]/g,"_")}_${t.id.slice(-6)}.json`);ra(o,JSON.stringify(i,null,2),"utf-8")}return $g({factsShared:t.factsShared+s.length}),{sharedCount:s.length,envelope:i}}function A0(){Jr();let e=ii(),t=[],n=Mt(Gd,e.id);if(Vr(n)){for(let r of il(n))if(r.endsWith(".json"))try{let s=JSON.parse(sl(Mt(n,r),"utf-8")),i=w5(s);t.push(i),xg(Mt(n,r))}catch(s){t.push({added:0,updated:0,conflicts:0,rejected:0,totalReceived:0,errors:[s.message],durationMs:0})}}if(Vr(Qi))for(let r of il(Qi)){if(!r.endsWith(".json"))continue;let s=Mt(Qi,r);try{let i=JSON.parse(sl(s,"utf-8"));if(i.fromAgent===e.id)continue;let o=Mt(ol,`last_processed_${e.id}.json`),a={};if(Vr(o))try{a=JSON.parse(sl(o,"utf-8"))}catch{}if(a[i.fromAgent]&&a[i.fromAgent]>=i.timestamp)continue;let c=w5(i);t.push(c),a[i.fromAgent]=i.timestamp,ra(o,JSON.stringify(a,null,2),"utf-8")}catch{}}return t}function w5(e){let t=Date.now(),n=ii(),r=0,s=0,i=0,o=0,a=[],c=Jn(),l=new Map(c.map(u=>[u.id,u]));for(let u of e.facts)try{if(u.signature&&u.signature!==$5(u)){o++,a.push(`Bad signature on ${u.id}`);continue}let d=l.get(u.id);if(d){let f=zke(d.vectorClock||{},u.vectorClock||{});f==="before"?(Nr(d.id),us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,metadata:{...u.metadata,syncedFrom:e.fromAgent}}),s++):f==="concurrent"&&(i++,u.confidence>d.confidence&&(Nr(d.id),us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,metadata:{...u.metadata,syncedFrom:e.fromAgent,mergedClock:Gke(d.vectorClock||{},u.vectorClock||{})}}),s++))}else{let f=u.vectorClock||{[e.fromAgent]:1};us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,tags:[...u.tags||[],`from:${e.fromAgent.slice(-8)}`],metadata:{...u.metadata,syncedFrom:e.fromAgent,vectorClock:f,scope:u.scope}}),r++}}catch(d){a.push(`Error merging ${u.id}: ${d.message}`),o++}return $g({factsReceived:n.factsReceived+r+s}),{added:r,updated:s,conflicts:i,rejected:o,totalReceived:e.facts.length,errors:a,fromAgent:e.fromAgent,durationMs:Date.now()-t}}function Jke(e=300*1e3,t="auto"){rl&&clearInterval(rl),$g({syncMode:t}),rl=setInterval(()=>{try{L1(),A0(),(t==="realtime"||t==="auto")&&O1({minConfidence:.75,minImportance:.6,maxFacts:50})}catch{}},e),rl.unref()}function Wke(){rl&&(clearInterval(rl),rl=null),$g({syncMode:"manual"})}function Kke(){if(kg)return;Jr();let e=ii(),t=Mt(Gd,e.id);Hd(t,{recursive:!0});try{kg=Nke(t,n=>{n==="rename"&&setTimeout(()=>A0(),100)})}catch{}}function Yke(){kg&&(kg.close(),kg=null)}function Qke(){if(Jr(),!Vr(F1))return C5(wg),wg;try{let e=JSON.parse(sl(F1,"utf-8"));return zd={...wg,...e},zd}catch{return wg}}function C5(e){return Jr(),zd={...zd,...e},ra(F1,JSON.stringify(zd,null,2),"utf-8"),zd}function Zke(){Jr();let e=ii(),t=k5(),n=t.filter(o=>x5(o.id)==="online").length,r=Mt(Gd,e.id),s=0;Vr(r)&&(s=il(r).filter(o=>o.endsWith(".json")).length);let i=0;return Vr(Qi)&&(i=il(Qi).filter(o=>o.endsWith(".json")).length),{myAgent:e,knownAgents:t.length,onlineAgents:n,totalFactsShared:e.factsShared,totalFactsReceived:e.factsReceived,inboxPending:s,sharedQueueSize:i,syncMode:e.syncMode}}function Xke(){Jr();for(let e of[Yi,Gd,Qi])if(Vr(e))for(let t of il(e))try{xg(Mt(e,t))}catch{}if(Vr(nl))try{xg(nl)}catch{}_r=null}function exe(){Jr();let e=Date.now()-10080*60*1e3;for(let t of[Qi,Yi])if(Vr(t))for(let n of il(t))try{let r=Mt(t,n);Bke(r).mtimeMs<e&&xg(r)}catch{}}async function txe(){L1();let e=O1({minConfidence:.75,minImportance:.6}),t=A0(),n=t.reduce((r,s)=>r+s.added+s.updated,0);return{shared:e.sharedCount,received:n,results:t}}var ol,Yi,Gd,Qi,nl,F1,_r,rl,kg,wg,zd,B1=w(()=>{"use strict";xu();ol=Mt(qke(),".aiaca","team-memory"),Yi=Mt(ol,"agents"),Gd=Mt(ol,"inbox"),Qi=Mt(ol,"shared"),nl=Mt(ol,"identity.json"),F1=Mt(ol,"config.json");_r=null;rl=null;kg=null;wg={enabled:!1,mode:"manual",intervalMs:300*1e3,shareScope:"team",minConfidence:.75,minImportance:.6,maxFactsPerSync:50,enableFileWatcher:!1},zd={...wg}});var N5={};$(N5,{analyzeProject:()=>U1,categorizeCommits:()=>M5,extractSymbols:()=>H1,generateAPIDocs:()=>D5,generateAllDocs:()=>vxe,generateArchitecture:()=>L5,generateChangelog:()=>F5,generateDoc:()=>O5,generateReadme:()=>N1,getDocSuggestion:()=>Sxe,getGitChangelog:()=>I5,renderFileTree:()=>Vd});import{existsSync as qt,readFileSync as q1,writeFileSync as T0,readdirSync as nxe,statSync as rxe}from"fs";import{join as pt,basename as _5,extname as sxe,relative as Cg,dirname as ixe}from"path";import{execSync as oxe}from"child_process";import{globSync as R5}from"glob";function U1(e){let t=cxe(e),n=lxe(e),r=uxe(e,t),s=P5(e,e),i=dxe(e,t);return{name:t?.name||_5(e),description:t?.description,version:t?.version,language:n,framework:r,dependencies:t?.dependencies?Object.keys(t.dependencies):[],devDependencies:t?.devDependencies?Object.keys(t.devDependencies):[],scripts:t?.scripts||{},fileTree:s,entryPoint:t?.main||fxe(e,n),hasTests:!!i,testFramework:i}}function cxe(e){let t=pt(e,"package.json");if(!qt(t))return null;try{return JSON.parse(q1(t,"utf-8"))}catch{return null}}function lxe(e){return qt(pt(e,"package.json"))?"JavaScript/TypeScript":qt(pt(e,"Cargo.toml"))?"Rust":qt(pt(e,"go.mod"))?"Go":qt(pt(e,"pyproject.toml"))||qt(pt(e,"requirements.txt"))?"Python":qt(pt(e,"pom.xml"))||qt(pt(e,"build.gradle"))?"Java":qt(pt(e,"Gemfile"))?"Ruby":qt(pt(e,"*.csproj"))?"C#":"Unknown"}function uxe(e,t){if(!t?.dependencies&&!t?.devDependencies)return;let n={...t.dependencies,...t.devDependencies};if(n.react)return"React";if(n.vue)return"Vue";if(n["@angular/core"])return"Angular";if(n.svelte)return"Svelte";if(n.next)return"Next.js";if(n.nuxt)return"Nuxt";if(n.express)return"Express";if(n.fastify)return"Fastify";if(n["@nestjs/core"])return"NestJS";if(n.ink)return"Ink (CLI)"}function dxe(e,t){if(!t)return;let n={...t.dependencies,...t.devDependencies};if(n.jest)return"Jest";if(n.vitest)return"Vitest";if(n.mocha)return"Mocha";if(n.cypress)return"Cypress";if(n.playwright)return"Playwright";if(qt(pt(e,"pytest.ini"))||qt(pt(e,"pyproject.toml")))return"pytest"}function fxe(e,t){let n=["src/index.ts","src/index.js","src/main.ts","index.ts","index.js","main.py","main.go","src/main.rs"];for(let r of n)if(qt(pt(e,r)))return r}function P5(e,t,n=0,r=4){let s=_5(t)||t,i=rxe(t);if(!i.isDirectory())return{name:s,type:"file",path:Cg(e,t),size:i.size};let o={name:s,type:"dir",path:Cg(e,t),children:[]};if(n>=r)return o;try{let a=nxe(t);for(let c of a){if(c.startsWith(".")&&!A5.has(c)||axe.has(c))continue;let l=pt(t,c);try{let u=P5(e,l,n+1,r);A5.has(c)&&(u.important=!0),o.children.push(u)}catch{}}}catch{}return o}function H1(e){if(!qt(e))return[];let t=sxe(e);if(![".ts",".tsx",".js",".jsx",".mjs"].includes(t))return[];let n=q1(e,"utf-8"),r=[];for(let[s,i]of Object.entries(pxe)){i.lastIndex=0;let o;for(;(o=i.exec(n))!==null;){let a=n.slice(0,o.index).split(`
1928
+ `).length,c=mxe(s,o,e,a,n);c&&r.push(c)}}return hxe(r)}function mxe(e,t,n,r,s){let i=!!t[2]?.includes("export"),o,a=t[0].trim().replace(/\s+/g," ").slice(0,200);switch(e){case"function":o=t[4];break;case"arrowFunction":o=t[3];break;case"class":o=t[4];break;case"interface":o=t[3];break;case"type":o=t[3];break;case"enum":o=t[3];break;case"const":o=t[3];break}if(!o)return null;let c=gxe(s,t.index);return{name:o,kind:e==="arrowFunction"?"function":e==="method"?"method":e,file:n,line:r,signature:a,isExported:i,isAsync:!!t[3]?.includes("async")||!!t[5]?.includes("async"),jsdoc:c}}function gxe(e,t){let r=e.slice(0,t).split(`
1919
1929
  `),s=[];for(let i=r.length-1;i>=0;i--){let o=r[i].trim();if(!(o===""&&s.length===0))if(o.startsWith("//")||o.startsWith("*")||o.startsWith("/**")||o.startsWith("*/"))s.unshift(o.replace(/^[/*]+\s?/,"").replace(/\s*\*\/$/,""));else break}return s.length>0?s.join(`
1920
- `).trim():void 0}function gxe(e){let t=new Set;return e.filter(n=>{let r=`${n.file}:${n.name}:${n.kind}`;return t.has(r)?!1:(t.add(r),!0)})}function Vd(e,t="",n=!0){let r=[],s=t===""?"":n?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",i=e.important?" \u2B50":"";if(r.push(`${t}${s}${e.name}${e.type==="dir"?"/":""}${i}`),e.children&&e.children.length>0){let o=t+(t===""?"":n?" ":"\u2502 ");for(let a=0;a<e.children.length;a++){let c=a===e.children.length-1;r.push(Vd(e.children[a],o,c))}}return r.join(`
1921
- `)}function I5(e,t){try{let n=t?`${t}..HEAD`:"-30";return ixe(`git log ${n} --pretty=format:"%h|%s|%an|%ar"`,{cwd:e,encoding:"utf-8",timeout:5e3}).trim().split(`
1922
- `).filter(Boolean)}catch{return[]}}function M5(e){let t={Features:[],"Bug Fixes":[],Performance:[],Documentation:[],Refactoring:[],Tests:[],Other:[]};for(let n of e){let[r,s,i,o]=n.split("|"),a=`${s} (${r})`;/^(feat|feature)[:\(]/i.test(s)?t.Features.push(a):/^(fix|bugfix)[:\(]/i.test(s)?t["Bug Fixes"].push(a):/^perf[:\(]/i.test(s)?t.Performance.push(a):/^docs?[:\(]/i.test(s)?t.Documentation.push(a):/^refactor[:\(]/i.test(s)?t.Refactoring.push(a):/^test[:\(]/i.test(s)?t.Tests.push(a):t.Other.push(a)}return t}async function N1(e,t){let n=Date.now(),r=U1(e.cwd),s,i=0;return t&&e.detail!=="brief"?(s=await hxe(r,e,t),i++):s=E5(r,e),e.outputPath&&T0(e.outputPath,s,"utf-8"),{type:"readme",content:s,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:j5(r.fileTree),symbolsAnalyzed:0,metadata:{aiCalls:i,confidence:i>0?.95:.8,sections:B5(s)}}}function E5(e,t){let n=[];if(n.push(`# ${e.name}`),n.push(""),e.description&&n.push(e.description,""),e.version&&n.push(`**Version:** ${e.version}`,""),n.push("## Tech Stack"),n.push(`- **Language:** ${e.language}`),e.framework&&n.push(`- **Framework:** ${e.framework}`),e.testFramework&&n.push(`- **Testing:** ${e.testFramework}`),n.push(""),e.dependencies.length>0&&(n.push("## Dependencies"),n.push(e.dependencies.slice(0,15).map(r=>`- ${r}`).join(`
1930
+ `).trim():void 0}function hxe(e){let t=new Set;return e.filter(n=>{let r=`${n.file}:${n.name}:${n.kind}`;return t.has(r)?!1:(t.add(r),!0)})}function Vd(e,t="",n=!0){let r=[],s=t===""?"":n?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",i=e.important?" \u2B50":"";if(r.push(`${t}${s}${e.name}${e.type==="dir"?"/":""}${i}`),e.children&&e.children.length>0){let o=t+(t===""?"":n?" ":"\u2502 ");for(let a=0;a<e.children.length;a++){let c=a===e.children.length-1;r.push(Vd(e.children[a],o,c))}}return r.join(`
1931
+ `)}function I5(e,t){try{let n=t?`${t}..HEAD`:"-30";return oxe(`git log ${n} --pretty=format:"%h|%s|%an|%ar"`,{cwd:e,encoding:"utf-8",timeout:5e3}).trim().split(`
1932
+ `).filter(Boolean)}catch{return[]}}function M5(e){let t={Features:[],"Bug Fixes":[],Performance:[],Documentation:[],Refactoring:[],Tests:[],Other:[]};for(let n of e){let[r,s,i,o]=n.split("|"),a=`${s} (${r})`;/^(feat|feature)[:\(]/i.test(s)?t.Features.push(a):/^(fix|bugfix)[:\(]/i.test(s)?t["Bug Fixes"].push(a):/^perf[:\(]/i.test(s)?t.Performance.push(a):/^docs?[:\(]/i.test(s)?t.Documentation.push(a):/^refactor[:\(]/i.test(s)?t.Refactoring.push(a):/^test[:\(]/i.test(s)?t.Tests.push(a):t.Other.push(a)}return t}async function N1(e,t){let n=Date.now(),r=U1(e.cwd),s,i=0;return t&&e.detail!=="brief"?(s=await yxe(r,e,t),i++):s=E5(r,e),e.outputPath&&T0(e.outputPath,s,"utf-8"),{type:"readme",content:s,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:j5(r.fileTree),symbolsAnalyzed:0,metadata:{aiCalls:i,confidence:i>0?.95:.8,sections:B5(s)}}}function E5(e,t){let n=[];if(n.push(`# ${e.name}`),n.push(""),e.description&&n.push(e.description,""),e.version&&n.push(`**Version:** ${e.version}`,""),n.push("## Tech Stack"),n.push(`- **Language:** ${e.language}`),e.framework&&n.push(`- **Framework:** ${e.framework}`),e.testFramework&&n.push(`- **Testing:** ${e.testFramework}`),n.push(""),e.dependencies.length>0&&(n.push("## Dependencies"),n.push(e.dependencies.slice(0,15).map(r=>`- ${r}`).join(`
1923
1933
  `)),e.dependencies.length>15&&n.push(`- *...and ${e.dependencies.length-15} more*`),n.push("")),Object.keys(e.scripts).length>0){n.push("## Scripts"),n.push("```bash");for(let[r,s]of Object.entries(e.scripts))n.push(`npm run ${r} # ${s}`);n.push("```"),n.push("")}return t.includeTOC&&n.splice(2,0,"## Table of Contents","","- [Tech Stack](#tech-stack)","- [Dependencies](#dependencies)","- [Scripts](#scripts)","- [Project Structure](#project-structure)",""),n.push("## Project Structure"),n.push("```"),n.push(Vd(e.fileTree).slice(0,3e3)),n.push("```"),n.push(""),n.push("## Getting Started"),n.push("```bash"),e.language.includes("JavaScript")?n.push("npm install",e.scripts.dev?"npm run dev":"npm start"):e.language==="Python"?n.push("pip install -r requirements.txt",`python ${e.entryPoint||"main.py"}`):e.language==="Rust"?n.push("cargo build","cargo run"):e.language==="Go"&&n.push("go mod download","go run ."),n.push("```"),n.join(`
1924
- `)}async function hxe(e,t,n){let r=E5(e,t),s=t.detail||"standard",i="";e.entryPoint&&qt(pt(t.cwd,e.entryPoint))&&(i=q1(pt(t.cwd,e.entryPoint),"utf-8").slice(0,3e3));let o=`Generate a professional README.md for this project.
1934
+ `)}async function yxe(e,t,n){let r=E5(e,t),s=t.detail||"standard",i="";e.entryPoint&&qt(pt(t.cwd,e.entryPoint))&&(i=q1(pt(t.cwd,e.entryPoint),"utf-8").slice(0,3e3));let o=`Generate a professional README.md for this project.
1925
1935
 
1926
1936
  PROJECT INFO:
1927
1937
  - Name: ${e.name}
@@ -1952,7 +1962,7 @@ ${s==="comprehensive"?`
1952
1962
  10. Contributing
1953
1963
  11. License`:""}
1954
1964
 
1955
- Use proper Markdown. Be specific to this project, not generic. Output ONLY the README content, no explanations.`;try{return(await n.sendMessage([{role:"user",content:o,timestamp:new Date().toISOString()}],"You are a technical writing expert. Generate clean, professional README files.",[],void 0)).content.trim()}catch{return r}}async function D5(e,t){let n=Date.now(),r=e.files||R5("src/**/*.{ts,tsx,js,jsx}",{cwd:e.cwd,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**"]}),s=[];for(let o of r.slice(0,50)){let a=pt(e.cwd,o),c=H1(a);s.push(...c.filter(l=>l.isExported))}let i=await yxe(s,e,t);return e.outputPath&&T0(e.outputPath,i,"utf-8"),{type:"api",content:i,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:r.length,symbolsAnalyzed:s.length,metadata:{aiCalls:t?1:0,confidence:.85,sections:["API Reference"]}}}async function yxe(e,t,n){let r=["# API Reference",""],s=new Map;for(let i of e){let o=Cg(t.cwd,i.file);s.has(o)||s.set(o,[]),s.get(o).push(i)}for(let[i,o]of s){r.push(`## \`${i}\``),r.push("");for(let a of o){let c=a.kind==="function"?"\u0192":a.kind==="class"?"C":a.kind==="interface"?"I":a.kind==="type"?"T":"\u2022";r.push(`### ${c} \`${a.name}\``),r.push(""),r.push(`**Kind:** ${a.kind}${a.isAsync?" (async)":""}${a.isExported?" \xB7 exported":""}`),r.push(`**Location:** \`${i}:${a.line}\``),r.push(""),r.push("```typescript"),r.push(a.signature),r.push("```"),r.push(""),a.jsdoc&&(r.push(a.jsdoc),r.push("")),r.push("---"),r.push("")}}return r.join(`
1965
+ Use proper Markdown. Be specific to this project, not generic. Output ONLY the README content, no explanations.`;try{return(await n.sendMessage([{role:"user",content:o,timestamp:new Date().toISOString()}],"You are a technical writing expert. Generate clean, professional README files.",[],void 0)).content.trim()}catch{return r}}async function D5(e,t){let n=Date.now(),r=e.files||R5("src/**/*.{ts,tsx,js,jsx}",{cwd:e.cwd,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**"]}),s=[];for(let o of r.slice(0,50)){let a=pt(e.cwd,o),c=H1(a);s.push(...c.filter(l=>l.isExported))}let i=await bxe(s,e,t);return e.outputPath&&T0(e.outputPath,i,"utf-8"),{type:"api",content:i,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:r.length,symbolsAnalyzed:s.length,metadata:{aiCalls:t?1:0,confidence:.85,sections:["API Reference"]}}}async function bxe(e,t,n){let r=["# API Reference",""],s=new Map;for(let i of e){let o=Cg(t.cwd,i.file);s.has(o)||s.set(o,[]),s.get(o).push(i)}for(let[i,o]of s){r.push(`## \`${i}\``),r.push("");for(let a of o){let c=a.kind==="function"?"\u0192":a.kind==="class"?"C":a.kind==="interface"?"I":a.kind==="type"?"T":"\u2022";r.push(`### ${c} \`${a.name}\``),r.push(""),r.push(`**Kind:** ${a.kind}${a.isAsync?" (async)":""}${a.isExported?" \xB7 exported":""}`),r.push(`**Location:** \`${i}:${a.line}\``),r.push(""),r.push("```typescript"),r.push(a.signature),r.push("```"),r.push(""),a.jsdoc&&(r.push(a.jsdoc),r.push("")),r.push("---"),r.push("")}}return r.join(`
1956
1966
  `)}async function F5(e,t){let n=Date.now(),r=I5(e.cwd),s=M5(r),i=["# Changelog","",`## ${new Date().toISOString().slice(0,10)}`,""];for(let[a,c]of Object.entries(s))if(c.length!==0){i.push(`### ${a}`);for(let l of c)i.push(`- ${l}`);i.push("")}let o=i.join(`
1957
1967
  `);return e.outputPath&&T0(e.outputPath,o,"utf-8"),{type:"changelog",content:o,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:0,symbolsAnalyzed:0,metadata:{aiCalls:0,confidence:.9,sections:Object.keys(s)}}}async function L5(e,t){let n=Date.now(),r=U1(e.cwd),s=R5("src/**/*.{ts,tsx,js,jsx,py}",{cwd:e.cwd,ignore:["**/*.test.*","**/node_modules/**"]}).slice(0,30),i=[];for(let c of s)i.push(...H1(pt(e.cwd,c)).filter(l=>l.isExported));let o="",a=0;if(t){let c=`Generate an architecture document for this project.
1958
1968
 
@@ -1975,9 +1985,9 @@ Generate ARCHITECTURE.md covering:
1975
1985
  5. Extension points
1976
1986
  6. Design decisions
1977
1987
 
1978
- Use Markdown. Output only the document content.`;try{o=(await t.sendMessage([{role:"user",content:c,timestamp:new Date().toISOString()}],"You are a software architect. Generate clear architecture documentation.",[],void 0)).content.trim(),a=1}catch{o=T5(r,i,e.cwd)}}else o=T5(r,i,e.cwd);return e.outputPath&&T0(e.outputPath,o,"utf-8"),{type:"architecture",content:o,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:s.length,symbolsAnalyzed:i.length,metadata:{aiCalls:a,confidence:a>0?.9:.75,sections:B5(o)}}}function T5(e,t,n){let r=["# Architecture","","## Overview",`${e.name} is a ${e.language} ${e.framework?`${e.framework} `:""}application.`,"","## Module Organization","```",Vd(e.fileTree),"```","","## Key Components"],s=new Map;for(let i of t){let o=sxe(Cg(n,i.file));s.has(o)||s.set(o,[]),s.get(o).push(i)}for(let[i,o]of s){r.push(`### \`${i}/\``),r.push(`Contains ${o.length} exported symbol(s):`);for(let a of o.slice(0,10))r.push(`- **${a.kind}** \`${a.name}\``);r.push("")}return r.join(`
1979
- `)}async function O5(e,t){switch(e.type){case"readme":return N1(e,t);case"api":case"reference":return D5(e,t);case"architecture":case"overview":return L5(e,t);case"changelog":return F5(e,t);default:return N1(e,t)}}async function bxe(e,t){let n=["readme","api","architecture","changelog"],r=[];for(let s of n)try{let i=await O5({type:s,cwd:e,detail:"standard"},t);r.push(i)}catch{}return r}function j5(e){return e.type==="file"?1:(e.children||[]).reduce((t,n)=>t+j5(n),0)}function B5(e){let t=[];for(let n of e.split(`
1980
- `))n.startsWith("## ")&&t.push(n.slice(3).trim());return t}function vxe(e){return qt(pt(e,"README.md"))?qt(pt(e,"CHANGELOG.md"))?!qt(pt(e,"docs/architecture.md"))&&!qt(pt(e,"ARCHITECTURE.md"))?"architecture":!qt(pt(e,"docs/api.md"))&&!qt(pt(e,"API.md"))?"api":null:"changelog":"readme"}var oxe,A5,fxe,q5=w(()=>{"use strict";oxe=new Set(["node_modules",".git","dist","build",".next","target","venv",".venv","__pycache__",".cache"]),A5=new Set(["README.md","package.json","tsconfig.json","Cargo.toml","pyproject.toml","requirements.txt","go.mod","index.ts","index.js","main.py","main.go","main.rs","src/index.ts","src/main.ts"]);fxe={function:/^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*(<[^>]+>)?\s*\(([^)]*)\)(\s*:\s*([^{]+))?/gm,arrowFunction:/^(\s*)(export\s+)?const\s+(\w+)\s*(:\s*[^=]+)?\s*=\s*(async\s+)?(\([^)]*\)|[^=]+)\s*=>/gm,class:/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)(\s+extends\s+\w+)?(\s+implements\s+[^{]+)?/gm,interface:/^(\s*)(export\s+)?interface\s+(\w+)(\s*<[^>]+>)?(\s+extends\s+[^{]+)?/gm,type:/^(\s*)(export\s+)?type\s+(\w+)(\s*<[^>]+>)?\s*=/gm,enum:/^(\s*)(export\s+)?enum\s+(\w+)/gm,const:/^(\s*)(export\s+)?const\s+(\w+)\s*[:=]/gm}});async function Jd(e,t={}){let n={...Sxe,...t},r=null;for(let s=0;s<=n.maxRetries;s++)try{return await e()}catch(i){r=i;let o=i.status||i.statusCode||i.code;if(!(n.retryableStatuses.includes(o)||i.message?.includes("ECONNRESET")||i.message?.includes("ETIMEDOUT")||i.message?.includes("overloaded"))||s===n.maxRetries)throw i;let c=Math.random()*.3+.85,l=Math.min(n.baseDelayMs*Math.pow(2,s)*c,n.maxDelayMs),u=i.headers?.["retry-after"],d=u?parseInt(u)*1e3:l;n.onRetry?.(s+1,i,d),await wxe(d)}throw r}function wxe(e){return new Promise(t=>setTimeout(t,e))}var Sxe,z1=w(()=>{"use strict";Sxe={maxRetries:3,baseDelayMs:1e3,maxDelayMs:6e4,retryableStatuses:[429,500,502,503,529]}});import kxe from"@anthropic-ai/sdk";var _0,U5=w(()=>{"use strict";z1();w0();_0=class{constructor(t,n){this.apiKey=t;this.model=n;this.client=new kxe({apiKey:t,maxRetries:0})}apiKey;model;name="claude";client;async sendMessage(t,n,r,s){if(vg()){let u=bg({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:""});if(u){if(s&&u.content){for(let d of u.content.match(/.{1,40}/g)||[u.content])s({type:"text",text:d});s({type:"done"})}return{content:u.content,toolCalls:u.toolCalls,usage:u.usage}}}let i=Date.now(),o=t.map(u=>({role:u.role,content:u.content})),a=r.map(u=>({name:u.name,description:u.description,input_schema:{type:"object",properties:Object.fromEntries(u.parameters.map(d=>[d.name,{type:d.type,description:d.description}])),required:u.parameters.filter(d=>d.required).map(d=>d.name)}}));if(s){let u=await this.streamWithRetry(o,n,a,s);return el()&&Xc({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:new Date().toISOString()},{content:u.content,toolCalls:u.toolCalls,usage:u.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),u}let c=s||(()=>{}),l=await Jd(()=>this.doSend(o,n,a),{onRetry:(u,d,f)=>{c({type:"error",error:`Retry ${u} in ${Math.round(f/1e3)}s: ${d.message}`})}});return el()&&Xc({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(u=>u.name),timestamp:new Date().toISOString()},{content:l.content,toolCalls:l.toolCalls,usage:l.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),l}async doSend(t,n,r){let s=await this.client.messages.create({model:this.model,max_tokens:128e3,system:n,messages:t,tools:r}),i=s.content.filter(a=>a.type==="text").map(a=>a.text).join(""),o=s.content.filter(a=>a.type==="tool_use").map(a=>{let c=a;return{id:c.id,name:c.name,input:c.input}});return{content:i,toolCalls:o,usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens}}}async streamWithRetry(t,n,r,s){return Jd(()=>this.doStream(t,n,r,s),{onRetry:(i,o,a)=>{s({type:"error",error:`Retry ${i} in ${Math.round(a/1e3)}s (${o.message})`})}})}async doStream(t,n,r,s){let i=this.client.messages.stream({model:this.model,max_tokens:128e3,system:n,messages:t,tools:r}),o="",a=[],c=null;for await(let u of i)if(u.type==="content_block_start"){let d=u.content_block;d.type==="tool_use"&&(c={id:d.id,name:d.name,input:{}},s({type:"tool_call_start",toolCall:c}))}else if(u.type==="content_block_delta"){let d=u.delta;d.type==="text_delta"?(o+=d.text,s({type:"text",text:d.text})):d.type==="input_json_delta"&&c&&s({type:"tool_call_delta",text:d.partial_json})}else u.type==="content_block_stop"&&c&&(a.push(c),s({type:"tool_call_end",toolCall:c}),c=null);let l=await i.finalMessage();for(let u of l.content)if(u.type==="tool_use"){let d=a.find(f=>f.id===u.id);d&&(d.input=u.input)}return s({type:"done"}),{content:o,toolCalls:a,usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens}}}}});import{GoogleGenAI as xxe}from"@google/genai";var R0,H5=w(()=>{"use strict";z1();Lm();w0();R0=class{constructor(t,n){this.apiKey=t;this.model=n;let r=process.stderr.write.bind(process.stderr);process.stderr.write=((s,...i)=>(typeof s=="string"?s:s?.toString?.()||"").includes("API key should be set when using the Gemini API")?!0:r(s,...i));try{this.client=new xxe({apiKey:t||"missing"})}finally{process.stderr.write=r}}apiKey;model;name="gemini";client;async sendMessage(t,n,r,s){if(vg()){let u=bg({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:""});if(u){if(s&&u.content){for(let d of u.content.match(/.{1,40}/g)||[u.content])s({type:"text",text:d});s({type:"done"})}return{content:u.content,toolCalls:u.toolCalls,usage:u.usage}}}let i=Date.now(),o=r.length>0?[{functionDeclarations:r.map(u=>({name:u.name,description:u.description,parameters:{type:"OBJECT",properties:Object.fromEntries(u.parameters.map(d=>{let f={type:d.type.toUpperCase(),description:d.description};if(d.type==="array"||d.type.toUpperCase()==="ARRAY"){let p=d.items;f.items=p?{type:String(p.type||"string").toUpperCase()}:{type:"STRING"}}return(d.type==="object"||d.type.toUpperCase()==="OBJECT")&&!d.properties&&(delete f.type,f.type="OBJECT",f.properties=d.properties||{}),[d.name,f]})),required:u.parameters.filter(d=>d.required).map(d=>d.name)}}))}]:[],a=t.map((u,d)=>{let f=[{text:u.content}];if(u.role==="user"&&d===t.length-1&&VA()){for(let p of zA())f.push({inlineData:{mimeType:p.mimeType,data:p.base64}});GA()}return{role:u.role==="assistant"?"model":"user",parts:f}}),c={systemInstruction:n,tools:o};if(s){let u=await Jd(()=>this.doStream(a,c,s),{onRetry:(d,f,p)=>s({type:"error",error:`Retry ${d} in ${Math.round(p/1e3)}s (${f.message})`})});return el()&&Xc({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:new Date().toISOString()},{content:u.content,toolCalls:u.toolCalls,usage:u.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),u}let l=await Jd(()=>this.doSend(a,c));return el()&&Xc({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(u=>u.name),timestamp:new Date().toISOString()},{content:l.content,toolCalls:l.toolCalls,usage:l.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),l}async doSend(t,n){let r=await this.client.models.generateContent({model:this.model,config:n,contents:t}),s="",i=[],o=r.candidates||[];for(let a of o){let c=a?.content?.parts||[];for(let l of c)typeof l?.text=="string"&&l.text&&(s+=l.text),l?.functionCall&&i.push({id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:l.functionCall.name,input:l.functionCall.args||{}})}if(!s&&i.length===0){try{s=r.text||""}catch{}if(r.functionCalls)for(let a of r.functionCalls)i.push({id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:a.name,input:a.args||{}})}return{content:s,toolCalls:i,usage:r.usageMetadata?{inputTokens:r.usageMetadata.promptTokenCount||0,outputTokens:r.usageMetadata.candidatesTokenCount||0}:void 0}}async doStream(t,n,r){let s=await this.client.models.generateContentStream({model:this.model,config:n,contents:t}),i="",o=[];for await(let a of s){let c="",l=a.candidates||[];for(let u of l){let d=u?.content?.parts||[];for(let f of d)if(typeof f?.text=="string"&&f.text&&(c+=f.text),f?.functionCall){let p={id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:f.functionCall.name,input:f.functionCall.args||{}};o.push(p),r({type:"tool_call_start",toolCall:p}),r({type:"tool_call_end",toolCall:p})}}c&&(i+=c,r({type:"text",text:c}))}return r({type:"done"}),{content:i,toolCalls:o,usage:void 0}}}});var sa={};$(sa,{createProvider:()=>Wd});function Wd(e,t,n){switch(e){case"claude":return new _0(t,n);case"gemini":return new R0(t,n);default:throw new Error(`Unknown provider: ${e}`)}}var Zi=w(()=>{"use strict";U5();H5()});var I0={};$(I0,{checkAndDreamIfIdle:()=>W5,formatBrief:()=>Jxe,formatCycleAsMarkdown:()=>Vxe,getDreamConfig:()=>Gxe,getDreamHistory:()=>qxe,getDreamStats:()=>Hxe,getLastDream:()=>Uxe,recordActivity:()=>jxe,runDreamCycle:()=>J5,setDreamConfig:()=>zxe,startAutoDreamScheduler:()=>Bxe,stopAutoDreamScheduler:()=>Nxe});import{existsSync as z5,mkdirSync as $xe,readFileSync as G5,writeFileSync as V5}from"fs";import{join as J1}from"path";import{homedir as Cxe}from"os";function K1(){$xe(W1,{recursive:!0})}function Txe(){if(K1(),!!z5(G1))try{Rr=JSON.parse(G5(G1,"utf-8"))}catch{}}function _xe(){K1();let e=Rr.slice(-50);V5(G1,JSON.stringify(e,null,2),"utf-8")}async function Rxe(){let e=t$(),t=Jn(),n=new Map;for(let s of t){let i=s.content.toLowerCase().trim();n.has(i)||n.set(i,[]),n.get(i).push(s)}let r=0;for(let s of n.values())if(!(s.length<2)){s.sort((i,o)=>o.importance-i.importance);for(let i of s.slice(1))Nr(i.id)&&r++}return{duplicatesRemoved:r,factsPromoted:e.promoted,factsPruned:e.removed,importanceRecalibrated:t.length}}async function Pxe(e){let t=Jn();if(t.length<5)return{};let n=[],r=0,s=new Map;for(let o of t)s.has(o.category)||s.set(o.category,[]),s.get(o.category).push(o);for(let[o,a]of s){if(a.length<2)continue;let c=Ixe(a);for(let l of c){if(l.length<2)continue;let u=Exe(l),d=l.map(p=>p.id);for(let p of l)Nr(p.id);let f=us(u,{category:o,confidence:Math.max(...l.map(p=>p.confidence)),source:"consolidated",tier:"long_term"});n.push({from:l.map(p=>p.content),to:u,mergedFactId:f.id})}}let i=t.filter(o=>o.contradicts&&o.contradicts.length>0);for(let o of i)if(o.contradicts)for(let a of o.contradicts){let c=t.find(u=>u.id===a);if(!c)continue;let l=new Date(o.createdAt).getTime()>new Date(c.createdAt).getTime();l&&o.confidence>=c.confidence?Nr(c.id)&&r++:!l&&c.confidence>o.confidence&&Nr(o.id)&&r++}return{factsMerged:n,contradictionsResolved:r}}function Ixe(e){let t=[],n=new Set;for(let r of e){if(n.has(r.id))continue;let s=[r];n.add(r.id);for(let i of e){if(n.has(i.id))continue;let o=Mxe(r.tokens,i.tokens);o>.5&&o<.95&&(s.push(i),n.add(i.id))}s.length>1&&t.push(s)}return t}function Mxe(e,t){let n=new Set(e),r=new Set(t),s=new Set([...n].filter(o=>r.has(o))),i=new Set([...n,...r]);return i.size===0?0:s.size/i.size}function Exe(e){e.sort((s,i)=>i.content.length-s.content.length);let t=e[0].content,r=e.slice(1).map(s=>s.content).filter(s=>!t.toLowerCase().includes(s.toLowerCase().slice(0,30)));return r.length===0?t:`${t} (also: ${r.slice(0,2).join("; ")})`}async function Dxe(e){let t=Jn();if(t.length<8)return{};let n=[...t].sort((o,a)=>a.importance-o.importance).slice(0,30),r=[],s=[],i=0;if(Wr.enableInsightGeneration&&i<Wr.maxAICallsPerDream){let o=await Fxe(n,e);r.push(...o),i++;for(let a of o.filter(c=>c.confidence>=.8))us(a.content,{category:a.category,confidence:a.confidence,source:"inferred",tier:"long_term",metadata:{dreamGenerated:!0,basedOn:a.basedOn}})}if(Wr.enablePatternDiscovery&&i<Wr.maxAICallsPerDream){let o=await Lxe(n,e);s.push(...o),i++}return{insightsGenerated:r,patternsDiscovered:s}}async function Fxe(e,t){let r=`Analyze these memory facts and generate 3-5 high-level INSIGHTS that:
1988
+ Use Markdown. Output only the document content.`;try{o=(await t.sendMessage([{role:"user",content:c,timestamp:new Date().toISOString()}],"You are a software architect. Generate clear architecture documentation.",[],void 0)).content.trim(),a=1}catch{o=T5(r,i,e.cwd)}}else o=T5(r,i,e.cwd);return e.outputPath&&T0(e.outputPath,o,"utf-8"),{type:"architecture",content:o,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:s.length,symbolsAnalyzed:i.length,metadata:{aiCalls:a,confidence:a>0?.9:.75,sections:B5(o)}}}function T5(e,t,n){let r=["# Architecture","","## Overview",`${e.name} is a ${e.language} ${e.framework?`${e.framework} `:""}application.`,"","## Module Organization","```",Vd(e.fileTree),"```","","## Key Components"],s=new Map;for(let i of t){let o=ixe(Cg(n,i.file));s.has(o)||s.set(o,[]),s.get(o).push(i)}for(let[i,o]of s){r.push(`### \`${i}/\``),r.push(`Contains ${o.length} exported symbol(s):`);for(let a of o.slice(0,10))r.push(`- **${a.kind}** \`${a.name}\``);r.push("")}return r.join(`
1989
+ `)}async function O5(e,t){switch(e.type){case"readme":return N1(e,t);case"api":case"reference":return D5(e,t);case"architecture":case"overview":return L5(e,t);case"changelog":return F5(e,t);default:return N1(e,t)}}async function vxe(e,t){let n=["readme","api","architecture","changelog"],r=[];for(let s of n)try{let i=await O5({type:s,cwd:e,detail:"standard"},t);r.push(i)}catch{}return r}function j5(e){return e.type==="file"?1:(e.children||[]).reduce((t,n)=>t+j5(n),0)}function B5(e){let t=[];for(let n of e.split(`
1990
+ `))n.startsWith("## ")&&t.push(n.slice(3).trim());return t}function Sxe(e){return qt(pt(e,"README.md"))?qt(pt(e,"CHANGELOG.md"))?!qt(pt(e,"docs/architecture.md"))&&!qt(pt(e,"ARCHITECTURE.md"))?"architecture":!qt(pt(e,"docs/api.md"))&&!qt(pt(e,"API.md"))?"api":null:"changelog":"readme"}var axe,A5,pxe,q5=w(()=>{"use strict";axe=new Set(["node_modules",".git","dist","build",".next","target","venv",".venv","__pycache__",".cache"]),A5=new Set(["README.md","package.json","tsconfig.json","Cargo.toml","pyproject.toml","requirements.txt","go.mod","index.ts","index.js","main.py","main.go","main.rs","src/index.ts","src/main.ts"]);pxe={function:/^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*(<[^>]+>)?\s*\(([^)]*)\)(\s*:\s*([^{]+))?/gm,arrowFunction:/^(\s*)(export\s+)?const\s+(\w+)\s*(:\s*[^=]+)?\s*=\s*(async\s+)?(\([^)]*\)|[^=]+)\s*=>/gm,class:/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)(\s+extends\s+\w+)?(\s+implements\s+[^{]+)?/gm,interface:/^(\s*)(export\s+)?interface\s+(\w+)(\s*<[^>]+>)?(\s+extends\s+[^{]+)?/gm,type:/^(\s*)(export\s+)?type\s+(\w+)(\s*<[^>]+>)?\s*=/gm,enum:/^(\s*)(export\s+)?enum\s+(\w+)/gm,const:/^(\s*)(export\s+)?const\s+(\w+)\s*[:=]/gm}});async function Jd(e,t={}){let n={...wxe,...t},r=null;for(let s=0;s<=n.maxRetries;s++)try{return await e()}catch(i){r=i;let o=i.status||i.statusCode||i.code;if(!(n.retryableStatuses.includes(o)||i.message?.includes("ECONNRESET")||i.message?.includes("ETIMEDOUT")||i.message?.includes("overloaded"))||s===n.maxRetries)throw i;let c=Math.random()*.3+.85,l=Math.min(n.baseDelayMs*Math.pow(2,s)*c,n.maxDelayMs),u=i.headers?.["retry-after"],d=u?parseInt(u)*1e3:l;n.onRetry?.(s+1,i,d),await kxe(d)}throw r}function kxe(e){return new Promise(t=>setTimeout(t,e))}var wxe,z1=w(()=>{"use strict";wxe={maxRetries:3,baseDelayMs:1e3,maxDelayMs:6e4,retryableStatuses:[429,500,502,503,529]}});import xxe from"@anthropic-ai/sdk";var _0,U5=w(()=>{"use strict";z1();w0();_0=class{constructor(t,n){this.apiKey=t;this.model=n;this.client=new xxe({apiKey:t,maxRetries:0})}apiKey;model;name="claude";client;async sendMessage(t,n,r,s){if(vg()){let u=bg({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:""});if(u){if(s&&u.content){for(let d of u.content.match(/.{1,40}/g)||[u.content])s({type:"text",text:d});s({type:"done"})}return{content:u.content,toolCalls:u.toolCalls,usage:u.usage}}}let i=Date.now(),o=t.map(u=>({role:u.role,content:u.content})),a=r.map(u=>({name:u.name,description:u.description,input_schema:{type:"object",properties:Object.fromEntries(u.parameters.map(d=>[d.name,{type:d.type,description:d.description}])),required:u.parameters.filter(d=>d.required).map(d=>d.name)}}));if(s){let u=await this.streamWithRetry(o,n,a,s);return el()&&Xc({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:new Date().toISOString()},{content:u.content,toolCalls:u.toolCalls,usage:u.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),u}let c=s||(()=>{}),l=await Jd(()=>this.doSend(o,n,a),{onRetry:(u,d,f)=>{c({type:"error",error:`Retry ${u} in ${Math.round(f/1e3)}s: ${d.message}`})}});return el()&&Xc({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(u=>u.name),timestamp:new Date().toISOString()},{content:l.content,toolCalls:l.toolCalls,usage:l.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),l}async doSend(t,n,r){let s=await this.client.messages.create({model:this.model,max_tokens:128e3,system:n,messages:t,tools:r}),i=s.content.filter(a=>a.type==="text").map(a=>a.text).join(""),o=s.content.filter(a=>a.type==="tool_use").map(a=>{let c=a;return{id:c.id,name:c.name,input:c.input}});return{content:i,toolCalls:o,usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens}}}async streamWithRetry(t,n,r,s){return Jd(()=>this.doStream(t,n,r,s),{onRetry:(i,o,a)=>{s({type:"error",error:`Retry ${i} in ${Math.round(a/1e3)}s (${o.message})`})}})}async doStream(t,n,r,s){let i=this.client.messages.stream({model:this.model,max_tokens:128e3,system:n,messages:t,tools:r}),o="",a=[],c=null;for await(let u of i)if(u.type==="content_block_start"){let d=u.content_block;d.type==="tool_use"&&(c={id:d.id,name:d.name,input:{}},s({type:"tool_call_start",toolCall:c}))}else if(u.type==="content_block_delta"){let d=u.delta;d.type==="text_delta"?(o+=d.text,s({type:"text",text:d.text})):d.type==="input_json_delta"&&c&&s({type:"tool_call_delta",text:d.partial_json})}else u.type==="content_block_stop"&&c&&(a.push(c),s({type:"tool_call_end",toolCall:c}),c=null);let l=await i.finalMessage();for(let u of l.content)if(u.type==="tool_use"){let d=a.find(f=>f.id===u.id);d&&(d.input=u.input)}return s({type:"done"}),{content:o,toolCalls:a,usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens}}}}});import{GoogleGenAI as $xe}from"@google/genai";var R0,H5=w(()=>{"use strict";z1();Lm();w0();R0=class{constructor(t,n){this.apiKey=t;this.model=n;let r=process.stderr.write.bind(process.stderr);process.stderr.write=((s,...i)=>(typeof s=="string"?s:s?.toString?.()||"").includes("API key should be set when using the Gemini API")?!0:r(s,...i));try{this.client=new $xe({apiKey:t||"missing"})}finally{process.stderr.write=r}}apiKey;model;name="gemini";client;async sendMessage(t,n,r,s){if(vg()){let u=bg({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:""});if(u){if(s&&u.content){for(let d of u.content.match(/.{1,40}/g)||[u.content])s({type:"text",text:d});s({type:"done"})}return{content:u.content,toolCalls:u.toolCalls,usage:u.usage}}}let i=Date.now(),o=r.length>0?[{functionDeclarations:r.map(u=>({name:u.name,description:u.description,parameters:{type:"OBJECT",properties:Object.fromEntries(u.parameters.map(d=>{let f={type:d.type.toUpperCase(),description:d.description};if(d.type==="array"||d.type.toUpperCase()==="ARRAY"){let p=d.items;f.items=p?{type:String(p.type||"string").toUpperCase()}:{type:"STRING"}}return(d.type==="object"||d.type.toUpperCase()==="OBJECT")&&!d.properties&&(delete f.type,f.type="OBJECT",f.properties=d.properties||{}),[d.name,f]})),required:u.parameters.filter(d=>d.required).map(d=>d.name)}}))}]:[],a=t.map((u,d)=>{let f=[{text:u.content}];if(u.role==="user"&&d===t.length-1&&VA()){for(let p of zA())f.push({inlineData:{mimeType:p.mimeType,data:p.base64}});GA()}return{role:u.role==="assistant"?"model":"user",parts:f}}),c={systemInstruction:n,tools:o};if(s){let u=await Jd(()=>this.doStream(a,c,s),{onRetry:(d,f,p)=>s({type:"error",error:`Retry ${d} in ${Math.round(p/1e3)}s (${f.message})`})});return el()&&Xc({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:new Date().toISOString()},{content:u.content,toolCalls:u.toolCalls,usage:u.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),u}let l=await Jd(()=>this.doSend(a,c));return el()&&Xc({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(u=>u.name),timestamp:new Date().toISOString()},{content:l.content,toolCalls:l.toolCalls,usage:l.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),l}async doSend(t,n){let r=await this.client.models.generateContent({model:this.model,config:n,contents:t}),s="",i=[],o=r.candidates||[];for(let a of o){let c=a?.content?.parts||[];for(let l of c)typeof l?.text=="string"&&l.text&&(s+=l.text),l?.functionCall&&i.push({id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:l.functionCall.name,input:l.functionCall.args||{}})}if(!s&&i.length===0){try{s=r.text||""}catch{}if(r.functionCalls)for(let a of r.functionCalls)i.push({id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:a.name,input:a.args||{}})}return{content:s,toolCalls:i,usage:r.usageMetadata?{inputTokens:r.usageMetadata.promptTokenCount||0,outputTokens:r.usageMetadata.candidatesTokenCount||0}:void 0}}async doStream(t,n,r){let s=await this.client.models.generateContentStream({model:this.model,config:n,contents:t}),i="",o=[];for await(let a of s){let c="",l=a.candidates||[];for(let u of l){let d=u?.content?.parts||[];for(let f of d)if(typeof f?.text=="string"&&f.text&&(c+=f.text),f?.functionCall){let p={id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:f.functionCall.name,input:f.functionCall.args||{}};o.push(p),r({type:"tool_call_start",toolCall:p}),r({type:"tool_call_end",toolCall:p})}}c&&(i+=c,r({type:"text",text:c}))}return r({type:"done"}),{content:i,toolCalls:o,usage:void 0}}}});var sa={};$(sa,{createProvider:()=>Wd});function Wd(e,t,n){switch(e){case"claude":return new _0(t,n);case"gemini":return new R0(t,n);default:throw new Error(`Unknown provider: ${e}`)}}var Zi=w(()=>{"use strict";U5();H5()});var I0={};$(I0,{checkAndDreamIfIdle:()=>W5,formatBrief:()=>Wxe,formatCycleAsMarkdown:()=>Jxe,getDreamConfig:()=>Vxe,getDreamHistory:()=>Uxe,getDreamStats:()=>zxe,getLastDream:()=>Hxe,recordActivity:()=>Bxe,runDreamCycle:()=>J5,setDreamConfig:()=>Gxe,startAutoDreamScheduler:()=>Nxe,stopAutoDreamScheduler:()=>qxe});import{existsSync as z5,mkdirSync as Cxe,readFileSync as G5,writeFileSync as V5}from"fs";import{join as J1}from"path";import{homedir as Axe}from"os";function K1(){Cxe(W1,{recursive:!0})}function _xe(){if(K1(),!!z5(G1))try{Rr=JSON.parse(G5(G1,"utf-8"))}catch{}}function Rxe(){K1();let e=Rr.slice(-50);V5(G1,JSON.stringify(e,null,2),"utf-8")}async function Pxe(){let e=t$(),t=Jn(),n=new Map;for(let s of t){let i=s.content.toLowerCase().trim();n.has(i)||n.set(i,[]),n.get(i).push(s)}let r=0;for(let s of n.values())if(!(s.length<2)){s.sort((i,o)=>o.importance-i.importance);for(let i of s.slice(1))Nr(i.id)&&r++}return{duplicatesRemoved:r,factsPromoted:e.promoted,factsPruned:e.removed,importanceRecalibrated:t.length}}async function Ixe(e){let t=Jn();if(t.length<5)return{};let n=[],r=0,s=new Map;for(let o of t)s.has(o.category)||s.set(o.category,[]),s.get(o.category).push(o);for(let[o,a]of s){if(a.length<2)continue;let c=Mxe(a);for(let l of c){if(l.length<2)continue;let u=Dxe(l),d=l.map(p=>p.id);for(let p of l)Nr(p.id);let f=us(u,{category:o,confidence:Math.max(...l.map(p=>p.confidence)),source:"consolidated",tier:"long_term"});n.push({from:l.map(p=>p.content),to:u,mergedFactId:f.id})}}let i=t.filter(o=>o.contradicts&&o.contradicts.length>0);for(let o of i)if(o.contradicts)for(let a of o.contradicts){let c=t.find(u=>u.id===a);if(!c)continue;let l=new Date(o.createdAt).getTime()>new Date(c.createdAt).getTime();l&&o.confidence>=c.confidence?Nr(c.id)&&r++:!l&&c.confidence>o.confidence&&Nr(o.id)&&r++}return{factsMerged:n,contradictionsResolved:r}}function Mxe(e){let t=[],n=new Set;for(let r of e){if(n.has(r.id))continue;let s=[r];n.add(r.id);for(let i of e){if(n.has(i.id))continue;let o=Exe(r.tokens,i.tokens);o>.5&&o<.95&&(s.push(i),n.add(i.id))}s.length>1&&t.push(s)}return t}function Exe(e,t){let n=new Set(e),r=new Set(t),s=new Set([...n].filter(o=>r.has(o))),i=new Set([...n,...r]);return i.size===0?0:s.size/i.size}function Dxe(e){e.sort((s,i)=>i.content.length-s.content.length);let t=e[0].content,r=e.slice(1).map(s=>s.content).filter(s=>!t.toLowerCase().includes(s.toLowerCase().slice(0,30)));return r.length===0?t:`${t} (also: ${r.slice(0,2).join("; ")})`}async function Fxe(e){let t=Jn();if(t.length<8)return{};let n=[...t].sort((o,a)=>a.importance-o.importance).slice(0,30),r=[],s=[],i=0;if(Wr.enableInsightGeneration&&i<Wr.maxAICallsPerDream){let o=await Lxe(n,e);r.push(...o),i++;for(let a of o.filter(c=>c.confidence>=.8))us(a.content,{category:a.category,confidence:a.confidence,source:"inferred",tier:"long_term",metadata:{dreamGenerated:!0,basedOn:a.basedOn}})}if(Wr.enablePatternDiscovery&&i<Wr.maxAICallsPerDream){let o=await Oxe(n,e);s.push(...o),i++}return{insightsGenerated:r,patternsDiscovered:s}}async function Lxe(e,t){let r=`Analyze these memory facts and generate 3-5 high-level INSIGHTS that:
1981
1991
  1. Are not directly stated in any single fact
1982
1992
  2. Combine multiple facts to derive a higher-level understanding
1983
1993
  3. Would be useful for the AI in future sessions
@@ -1989,7 +1999,7 @@ ${e.map((s,i)=>`${i+1}. [${s.category}] ${s.content}`).join(`
1989
1999
  Return JSON array (no markdown):
1990
2000
  [{"content": "...", "category": "preference|project|pattern|decision|constraint|fact|goal|context", "confidence": 0.0-1.0, "basedOn": [1, 5, 12]}]
1991
2001
 
1992
- Only return insights with confidence >= 0.7. Return [] if nothing meaningful.`;try{let o=(await t.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You are a precise insight generator. Output only valid JSON.",[],void 0)).content.replace(/```(?:json)?\s*/g,"").replace(/```/g,"").trim().match(/\[[\s\S]*\]/);return o?JSON.parse(o[0]).filter(c=>c.confidence>=.7&&typeof c.content=="string").map(c=>({content:c.content.slice(0,300),category:c.category||"pattern",confidence:Math.max(0,Math.min(1,c.confidence)),basedOn:(c.basedOn||[]).map(l=>e[l-1]?.id).filter(Boolean)})):[]}catch{return[]}}async function Lxe(e,t){let r=`Identify behavioral or contextual PATTERNS in these facts.
2002
+ Only return insights with confidence >= 0.7. Return [] if nothing meaningful.`;try{let o=(await t.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You are a precise insight generator. Output only valid JSON.",[],void 0)).content.replace(/```(?:json)?\s*/g,"").replace(/```/g,"").trim().match(/\[[\s\S]*\]/);return o?JSON.parse(o[0]).filter(c=>c.confidence>=.7&&typeof c.content=="string").map(c=>({content:c.content.slice(0,300),category:c.category||"pattern",confidence:Math.max(0,Math.min(1,c.confidence)),basedOn:(c.basedOn||[]).map(l=>e[l-1]?.id).filter(Boolean)})):[]}catch{return[]}}async function Oxe(e,t){let r=`Identify behavioral or contextual PATTERNS in these facts.
1993
2003
 
1994
2004
  FACTS:
1995
2005
  ${e.map(s=>`[${s.category}] ${s.content}`).join(`
@@ -2005,7 +2015,7 @@ Look for:
2005
2015
  Return JSON array (no markdown):
2006
2016
  [{"description": "...", "type": "temporal|causal|preference|workflow|project", "occurrences": N, "examples": ["..."]}]
2007
2017
 
2008
- Only return clear, well-supported patterns. Return [] if none found.`;try{let o=(await t.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You are a pattern recognition engine. Output only valid JSON.",[],void 0)).content.replace(/```(?:json)?\s*/g,"").replace(/```/g,"").trim().match(/\[[\s\S]*\]/);return o?JSON.parse(o[0]).slice(0,5):[]}catch{return[]}}async function Oxe(e,t){let r=`You just completed a memory consolidation cycle for an AI assistant. Write a 2-sentence reflective narrative about what was learned and consolidated.
2018
+ Only return clear, well-supported patterns. Return [] if none found.`;try{let o=(await t.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You are a pattern recognition engine. Output only valid JSON.",[],void 0)).content.replace(/```(?:json)?\s*/g,"").replace(/```/g,"").trim().match(/\[[\s\S]*\]/);return o?JSON.parse(o[0]).slice(0,5):[]}catch{return[]}}async function jxe(e,t){let r=`You just completed a memory consolidation cycle for an AI assistant. Write a 2-sentence reflective narrative about what was learned and consolidated.
2009
2019
 
2010
2020
  ${`
2011
2021
  Cycle results:
@@ -2020,9 +2030,9 @@ Cycle results:
2020
2030
 
2021
2031
  Insights: ${e.insightsGenerated.slice(0,3).map(s=>s.content).join("; ")}
2022
2032
 
2023
- Write in first person, as if the AI is reflecting on its own consolidation. Be concise.`;try{return(await t.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You are an AI reflecting on memory consolidation. Be concise and insightful.",[],void 0)).content.trim().slice(0,400)}catch{return""}}async function J5(e={}){if(Ag)throw new Error("Dream cycle already in progress");Ag=!0;let t=`dream_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,n=Date.now(),r=Jn().length,s=[],i={duplicatesRemoved:0,factsPruned:0,factsPromoted:0,factsMerged:[],insightsGenerated:[],patternsDiscovered:[],contradictionsResolved:0,importanceRecalibrated:0},o=0;try{let l=await Rxe();if(i={...i,...l},s.push("light_sleep"),r>=Wr.minFactsForDream){let u=await Pxe(e.provider);i={...i,...u},s.push("deep_sleep")}if(!e.skipREM&&e.provider&&r>=8){let u=await Dxe(e.provider);i.insightsGenerated=u.insightsGenerated||[],i.patternsDiscovered=u.patternsDiscovered||[],o+=(u.insightsGenerated?.length?1:0)+(u.patternsDiscovered?.length?1:0),s.push("rem"),Wr.enableNarrativeSynthesis&&e.provider&&(i.insightsGenerated.length>0||i.patternsDiscovered.length>0)&&(i.narrative=await Oxe(i,e.provider),o++)}}finally{Ag=!1}let a=Jn().length,c={id:t,startedAt:new Date(n).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-n,triggeredBy:e.triggeredBy||"manual",phasesRun:s,results:i,metadata:{factsAtStart:r,factsAtEnd:a,aiCallsMade:o}};return Rr.push(c),_xe(),K1(),V5(V1,JSON.stringify(c,null,2),"utf-8"),c}function jxe(){P0=Date.now()}async function W5(e){if(Date.now()-P0<Wr.idleThresholdMs||Ag)return null;let n=Rr[Rr.length-1];return n&&Date.now()-new Date(n.startedAt).getTime()<1800*1e3?null:J5({provider:e,triggeredBy:"idle"})}function Bxe(e,t=1800*1e3){al&&clearInterval(al),al=setInterval(()=>{W5(e).catch(()=>{})},t),al.unref()}function Nxe(){al&&(clearInterval(al),al=null)}function qxe(e=10){return Rr.slice(-e).reverse()}function Uxe(){if(!z5(V1))return null;try{return JSON.parse(G5(V1,"utf-8"))}catch{return null}}function Hxe(){let e=Rr.length,t=Rr.reduce((o,a)=>o+a.durationMs,0),n=Rr.reduce((o,a)=>o+a.results.duplicatesRemoved+a.results.factsPruned+a.results.factsMerged.length+a.results.contradictionsResolved,0),r=Rr.reduce((o,a)=>o+a.results.insightsGenerated.length,0),s=Rr.reduce((o,a)=>o+a.results.patternsDiscovered.length,0),i=Rr[Rr.length-1];return{totalCycles:e,avgDurationMs:e>0?Math.round(t/e):0,totalFactsConsolidated:n,totalInsightsGenerated:r,totalPatternsDiscovered:s,isCurrentlyDreaming:Ag,lastDreamAt:i?.completedAt,nextScheduledIdleDream:P0+Wr.idleThresholdMs>Date.now()?new Date(P0+Wr.idleThresholdMs).toISOString():void 0}}function zxe(e){Wr={...Wr,...e}}function Gxe(){return{...Wr}}function Vxe(e){let t=[];if(t.push(`# \u{1F319} Dream Cycle ${e.id.slice(-8)}`),t.push(""),t.push(`**Triggered by:** ${e.triggeredBy} | **Duration:** ${(e.durationMs/1e3).toFixed(1)}s`),t.push(`**Phases:** ${e.phasesRun.join(" \u2192 ")}`),t.push(`**Memories:** ${e.metadata.factsAtStart} \u2192 ${e.metadata.factsAtEnd}`),t.push(""),e.results.narrative&&(t.push("## Reflection"),t.push(`*${e.results.narrative}*`),t.push("")),t.push("## Consolidation Results"),t.push(`- \u{1F5D1} Duplicates removed: ${e.results.duplicatesRemoved}`),t.push(`- \u2B06 Promoted to long-term: ${e.results.factsPromoted}`),t.push(`- \u2702 Pruned: ${e.results.factsPruned}`),t.push(`- \u{1F517} Merged groups: ${e.results.factsMerged.length}`),t.push(`- \u2696 Contradictions resolved: ${e.results.contradictionsResolved}`),t.push(""),e.results.insightsGenerated.length>0){t.push("## \u2728 New Insights");for(let n of e.results.insightsGenerated)t.push(`- **[${n.category}]** ${n.content} *(confidence: ${(n.confidence*100).toFixed(0)}%)*`);t.push("")}if(e.results.patternsDiscovered.length>0){t.push("## \u{1F50D} Patterns Discovered");for(let n of e.results.patternsDiscovered)t.push(`- **${n.type}**: ${n.description} (${n.occurrences} occurrences)`)}return t.join(`
2024
- `)}function Jxe(e){let t=e.results;return`\u{1F319} Dream cycle: ${t.duplicatesRemoved+t.factsPromoted+t.factsPruned+t.factsMerged.length+t.contradictionsResolved} memory operations, ${t.insightsGenerated.length} insights, ${t.patternsDiscovered.length} patterns (${(e.durationMs/1e3).toFixed(1)}s)`}var Axe,Wr,W1,G1,V1,Ag,Rr,P0,al,M0=w(()=>{"use strict";xu();Axe={idleThresholdMs:600*1e3,minFactsForDream:5,maxAICallsPerDream:3,enableInsightGeneration:!0,enablePatternDiscovery:!0,enableNarrativeSynthesis:!0},Wr={...Axe},W1=J1(Cxe(),".aiaca","dreams"),G1=J1(W1,"history.json"),V1=J1(W1,"last.json");Ag=!1,Rr=[];Txe();P0=Date.now(),al=null});var sU={};$(sU,{buildTimeline:()=>Z5,classifyOutcome:()=>Q5,compactToolUse:()=>Zxe,detectBottlenecks:()=>Y5,detectPatterns:()=>K5,extractInvocations:()=>E0,formatAsBullets:()=>tU,formatAsMarkdown:()=>eU,formatAsNarrative:()=>nU,formatAsStructured:()=>rU,summarizeHeuristic:()=>Kd,summarizeToolUse:()=>Xxe,summarizeWithAI:()=>X5});function E0(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(!(r.role!=="assistant"||!r.toolCalls))for(let s of r.toolCalls){let i=e[n+1],o,a=!0,c;if(i&&i.role==="user"){let l=new RegExp(`<tool_result name="${s.name}"(?:\\s+error="(true|false)")?>([\\s\\S]*?)</tool_result>`,"i"),u=i.content.match(l);u&&(a=u[1]!=="true",o=u[2].trim(),(!a||/^Error:|Exit code: [1-9]/.test(o))&&(a=!1,c=o.split(`
2025
- `)[0]))}t.push({name:s.name,input:s.input,output:o,success:a,errorMessage:c,timestamp:r.timestamp,turnIndex:n})}}return t}function K5(e){let t=[],n=e.map(u=>u.name),r=e.filter(u=>["file_read","grep","glob"].includes(u.name)).length,s=e.filter(u=>["file_write","file_edit"].includes(u.name)).length;r>=3&&s===0&&t.push({type:"investigation",description:`Exploring code (${r} reads/searches with no modifications)`,confidence:Math.min(1,r/5),toolSequence:n.filter(u=>["file_read","grep","glob"].includes(u))});let i=["file_read","file_edit","bash"],o=0;for(let u=0;u<=n.length-3;u++)i.every(d=>n.slice(u,u+3).includes(d))&&o++;o>=2&&t.push({type:"iteration",description:`Iterative development cycle (${o} read-edit-test cycles)`,confidence:Math.min(1,o/3),toolSequence:i});let a=e.filter(u=>!u.success);a.length>=2&&t.push({type:"fix_loop",description:`Debugging session (${a.length} errors encountered)`,confidence:Math.min(1,a.length/3),toolSequence:a.map(u=>u.name)});let c=e.filter(u=>u.name==="bash"&&/\b(test|jest|pytest|vitest|cargo test)\b/.test(String(u.input.command||"")));c.length>=2&&t.push({type:"test_loop",description:`Test-driven cycle (${c.length} test runs)`,confidence:Math.min(1,c.length/3),toolSequence:c.map(u=>u.name)}),n.includes("web_search")&&n.includes("file_write")&&t.push({type:"workflow",description:"Research \u2192 implement workflow",confidence:.8,toolSequence:["web_search","web_fetch","file_write"].filter(u=>n.includes(u))});let l=e.filter(u=>["grep","glob","file_read"].includes(u.name)).length;return l>=5&&s<l/3&&t.push({type:"exploration",description:`Codebase exploration (${l} search/read operations)`,confidence:.85,toolSequence:n.filter(u=>["grep","glob","file_read"].includes(u))}),t}function Y5(e){let t=new Map;for(let n of e){if(!n.durationMs)continue;let r=t.get(n.name)||{total:0,count:0};r.total+=n.durationMs,r.count++,t.set(n.name,r)}return Array.from(t.entries()).map(([n,r])=>({tool:n,totalDurationMs:r.total,callCount:r.count,avgDurationMs:Math.round(r.total/r.count)})).sort((n,r)=>r.totalDurationMs-n.totalDurationMs).slice(0,5)}function Q5(e,t){if(e.length===0)return"unknown";let n=e.filter(o=>!o.success).length/e.length,r=t?.content?.toLowerCase()||"",s=/\b(done|completed|finished|successfully|works|fixed|created)\b/,i=/\b(failed|cannot|unable|error|stuck)\b/;return n>.5?"failure":n>0&&s.test(r)?"partial_success":s.test(r)?"success":i.test(r)?"failure":n===0?"success":"partial_success"}function Z5(e){return e.map(t=>({turnIndex:t.turnIndex,tool:t.name,action:Wxe(t),result:t.success?"success":"failure",durationMs:t.durationMs}))}function Wxe(e){let t=e.input;switch(e.name){case"bash":case"powershell":return`$ ${String(t.command||"").slice(0,60)}`;case"file_read":return`read ${t.path}`;case"file_write":return`wrote ${t.path}`;case"file_edit":return`edited ${t.path}`;case"grep":return`grep "${t.pattern}"`;case"glob":return`glob "${t.pattern}"`;case"web_search":return`searched: ${t.query}`;case"web_fetch":return`fetched ${t.url}`;case"doc_create":return`created doc ${t.path}`;case"image_read":return`analyzed image ${t.path}`;default:return`${e.name}(${JSON.stringify(t).slice(0,40)})`}}function Kd(e,t="turn"){let n=[...new Set(e.filter(g=>g.name==="file_read").map(g=>String(g.input.path)))].filter(Boolean),r=[...new Set(e.filter(g=>g.name==="file_edit").map(g=>String(g.input.path)))].filter(Boolean),s=[...new Set(e.filter(g=>g.name==="file_write"||g.name==="doc_create").map(g=>String(g.input.path)))].filter(Boolean),i=e.filter(g=>g.name==="bash"||g.name==="powershell").map(g=>String(g.input.command||"")),o=e.filter(g=>g.name==="web_fetch").map(g=>String(g.input.url||"")),a=e.filter(g=>!g.success),c=new Map;for(let g of a){let h=`${g.name}:${g.errorMessage||"unknown"}`;c.has(h)?c.get(h).attemptCount++:c.set(h,{tool:g.name,message:g.errorMessage||"Unknown error",recovered:!1,attemptCount:1})}let l=K5(e),u=Z5(e),d=Y5(e),f=e.reduce((g,h)=>g+(h.durationMs||0),0),p=[];s.length&&p.push(`Created ${s.length} file(s): ${s.slice(0,3).join(", ")}${s.length>3?"...":""}`),r.length&&p.push(`Modified ${r.length} file(s): ${r.slice(0,3).join(", ")}${r.length>3?"...":""}`),n.length&&p.push(`Read ${n.length} file(s)`),i.length&&p.push(`Ran ${i.length} command(s)`),o.length&&p.push(`Visited ${o.length} URL(s)`),a.length&&p.push(`Encountered ${a.length} error(s)`);for(let g of l)p.push(`Pattern: ${g.description}`);let m=Kxe({filesCreated:s,filesWritten:r,filesRead:n,commandsRun:i,errors:a,patterns:l});return{level:t,outcome:Q5(e),totalCalls:e.length,successfulCalls:e.filter(g=>g.success).length,failedCalls:a.length,uniqueTools:[...new Set(e.map(g=>g.name))],filesRead:n,filesModified:r,filesCreated:s,commandsRun:i,websVisited:o,errorsEncountered:Array.from(c.values()),patterns:l,timeline:u,totalDurationMs:f,bottlenecks:d,narrative:m,bulletPoints:p,metadata:{messagesAnalyzed:e.length,confidenceScore:e.length>0?.9:.5}}}function Kxe(e){let t=[];return e.patterns.length>0&&t.push(`This was a ${e.patterns[0].type.replace("_"," ")} session.`),e.filesCreated.length>0&&t.push(`Created ${e.filesCreated.length} file${e.filesCreated.length>1?"s":""} (${e.filesCreated.slice(0,2).map(n=>n.split("/").pop()).join(", ")}${e.filesCreated.length>2?`, +${e.filesCreated.length-2} more`:""}).`),e.filesWritten.length>0&&t.push(`Modified ${e.filesWritten.length} file${e.filesWritten.length>1?"s":""}.`),e.commandsRun.length>0&&t.push(`Executed ${e.commandsRun.length} shell command${e.commandsRun.length>1?"s":""}.`),e.errors.length>0&&t.push(`Hit ${e.errors.length} error${e.errors.length>1?"s":""} during execution.`),t.join(" ")||"No significant tool activity."}async function X5(e,t,n,r={}){let s=Kd(e,r.level||"turn");if(e.length===0)return s;let i=e.slice(-30).map((c,l)=>`${l+1}. ${c.name}(${Yxe(c.input)}) \u2192 ${c.success?"OK":"FAIL: "+c.errorMessage}`).join(`
2033
+ Write in first person, as if the AI is reflecting on its own consolidation. Be concise.`;try{return(await t.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You are an AI reflecting on memory consolidation. Be concise and insightful.",[],void 0)).content.trim().slice(0,400)}catch{return""}}async function J5(e={}){if(Ag)throw new Error("Dream cycle already in progress");Ag=!0;let t=`dream_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,n=Date.now(),r=Jn().length,s=[],i={duplicatesRemoved:0,factsPruned:0,factsPromoted:0,factsMerged:[],insightsGenerated:[],patternsDiscovered:[],contradictionsResolved:0,importanceRecalibrated:0},o=0;try{let l=await Pxe();if(i={...i,...l},s.push("light_sleep"),r>=Wr.minFactsForDream){let u=await Ixe(e.provider);i={...i,...u},s.push("deep_sleep")}if(!e.skipREM&&e.provider&&r>=8){let u=await Fxe(e.provider);i.insightsGenerated=u.insightsGenerated||[],i.patternsDiscovered=u.patternsDiscovered||[],o+=(u.insightsGenerated?.length?1:0)+(u.patternsDiscovered?.length?1:0),s.push("rem"),Wr.enableNarrativeSynthesis&&e.provider&&(i.insightsGenerated.length>0||i.patternsDiscovered.length>0)&&(i.narrative=await jxe(i,e.provider),o++)}}finally{Ag=!1}let a=Jn().length,c={id:t,startedAt:new Date(n).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-n,triggeredBy:e.triggeredBy||"manual",phasesRun:s,results:i,metadata:{factsAtStart:r,factsAtEnd:a,aiCallsMade:o}};return Rr.push(c),Rxe(),K1(),V5(V1,JSON.stringify(c,null,2),"utf-8"),c}function Bxe(){P0=Date.now()}async function W5(e){if(Date.now()-P0<Wr.idleThresholdMs||Ag)return null;let n=Rr[Rr.length-1];return n&&Date.now()-new Date(n.startedAt).getTime()<1800*1e3?null:J5({provider:e,triggeredBy:"idle"})}function Nxe(e,t=1800*1e3){al&&clearInterval(al),al=setInterval(()=>{W5(e).catch(()=>{})},t),al.unref()}function qxe(){al&&(clearInterval(al),al=null)}function Uxe(e=10){return Rr.slice(-e).reverse()}function Hxe(){if(!z5(V1))return null;try{return JSON.parse(G5(V1,"utf-8"))}catch{return null}}function zxe(){let e=Rr.length,t=Rr.reduce((o,a)=>o+a.durationMs,0),n=Rr.reduce((o,a)=>o+a.results.duplicatesRemoved+a.results.factsPruned+a.results.factsMerged.length+a.results.contradictionsResolved,0),r=Rr.reduce((o,a)=>o+a.results.insightsGenerated.length,0),s=Rr.reduce((o,a)=>o+a.results.patternsDiscovered.length,0),i=Rr[Rr.length-1];return{totalCycles:e,avgDurationMs:e>0?Math.round(t/e):0,totalFactsConsolidated:n,totalInsightsGenerated:r,totalPatternsDiscovered:s,isCurrentlyDreaming:Ag,lastDreamAt:i?.completedAt,nextScheduledIdleDream:P0+Wr.idleThresholdMs>Date.now()?new Date(P0+Wr.idleThresholdMs).toISOString():void 0}}function Gxe(e){Wr={...Wr,...e}}function Vxe(){return{...Wr}}function Jxe(e){let t=[];if(t.push(`# \u{1F319} Dream Cycle ${e.id.slice(-8)}`),t.push(""),t.push(`**Triggered by:** ${e.triggeredBy} | **Duration:** ${(e.durationMs/1e3).toFixed(1)}s`),t.push(`**Phases:** ${e.phasesRun.join(" \u2192 ")}`),t.push(`**Memories:** ${e.metadata.factsAtStart} \u2192 ${e.metadata.factsAtEnd}`),t.push(""),e.results.narrative&&(t.push("## Reflection"),t.push(`*${e.results.narrative}*`),t.push("")),t.push("## Consolidation Results"),t.push(`- \u{1F5D1} Duplicates removed: ${e.results.duplicatesRemoved}`),t.push(`- \u2B06 Promoted to long-term: ${e.results.factsPromoted}`),t.push(`- \u2702 Pruned: ${e.results.factsPruned}`),t.push(`- \u{1F517} Merged groups: ${e.results.factsMerged.length}`),t.push(`- \u2696 Contradictions resolved: ${e.results.contradictionsResolved}`),t.push(""),e.results.insightsGenerated.length>0){t.push("## \u2728 New Insights");for(let n of e.results.insightsGenerated)t.push(`- **[${n.category}]** ${n.content} *(confidence: ${(n.confidence*100).toFixed(0)}%)*`);t.push("")}if(e.results.patternsDiscovered.length>0){t.push("## \u{1F50D} Patterns Discovered");for(let n of e.results.patternsDiscovered)t.push(`- **${n.type}**: ${n.description} (${n.occurrences} occurrences)`)}return t.join(`
2034
+ `)}function Wxe(e){let t=e.results;return`\u{1F319} Dream cycle: ${t.duplicatesRemoved+t.factsPromoted+t.factsPruned+t.factsMerged.length+t.contradictionsResolved} memory operations, ${t.insightsGenerated.length} insights, ${t.patternsDiscovered.length} patterns (${(e.durationMs/1e3).toFixed(1)}s)`}var Txe,Wr,W1,G1,V1,Ag,Rr,P0,al,M0=w(()=>{"use strict";xu();Txe={idleThresholdMs:600*1e3,minFactsForDream:5,maxAICallsPerDream:3,enableInsightGeneration:!0,enablePatternDiscovery:!0,enableNarrativeSynthesis:!0},Wr={...Txe},W1=J1(Axe(),".aiaca","dreams"),G1=J1(W1,"history.json"),V1=J1(W1,"last.json");Ag=!1,Rr=[];_xe();P0=Date.now(),al=null});var sU={};$(sU,{buildTimeline:()=>Z5,classifyOutcome:()=>Q5,compactToolUse:()=>Xxe,detectBottlenecks:()=>Y5,detectPatterns:()=>K5,extractInvocations:()=>E0,formatAsBullets:()=>tU,formatAsMarkdown:()=>eU,formatAsNarrative:()=>nU,formatAsStructured:()=>rU,summarizeHeuristic:()=>Kd,summarizeToolUse:()=>e$e,summarizeWithAI:()=>X5});function E0(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(!(r.role!=="assistant"||!r.toolCalls))for(let s of r.toolCalls){let i=e[n+1],o,a=!0,c;if(i&&i.role==="user"){let l=new RegExp(`<tool_result name="${s.name}"(?:\\s+error="(true|false)")?>([\\s\\S]*?)</tool_result>`,"i"),u=i.content.match(l);u&&(a=u[1]!=="true",o=u[2].trim(),(!a||/^Error:|Exit code: [1-9]/.test(o))&&(a=!1,c=o.split(`
2035
+ `)[0]))}t.push({name:s.name,input:s.input,output:o,success:a,errorMessage:c,timestamp:r.timestamp,turnIndex:n})}}return t}function K5(e){let t=[],n=e.map(u=>u.name),r=e.filter(u=>["file_read","grep","glob"].includes(u.name)).length,s=e.filter(u=>["file_write","file_edit"].includes(u.name)).length;r>=3&&s===0&&t.push({type:"investigation",description:`Exploring code (${r} reads/searches with no modifications)`,confidence:Math.min(1,r/5),toolSequence:n.filter(u=>["file_read","grep","glob"].includes(u))});let i=["file_read","file_edit","bash"],o=0;for(let u=0;u<=n.length-3;u++)i.every(d=>n.slice(u,u+3).includes(d))&&o++;o>=2&&t.push({type:"iteration",description:`Iterative development cycle (${o} read-edit-test cycles)`,confidence:Math.min(1,o/3),toolSequence:i});let a=e.filter(u=>!u.success);a.length>=2&&t.push({type:"fix_loop",description:`Debugging session (${a.length} errors encountered)`,confidence:Math.min(1,a.length/3),toolSequence:a.map(u=>u.name)});let c=e.filter(u=>u.name==="bash"&&/\b(test|jest|pytest|vitest|cargo test)\b/.test(String(u.input.command||"")));c.length>=2&&t.push({type:"test_loop",description:`Test-driven cycle (${c.length} test runs)`,confidence:Math.min(1,c.length/3),toolSequence:c.map(u=>u.name)}),n.includes("web_search")&&n.includes("file_write")&&t.push({type:"workflow",description:"Research \u2192 implement workflow",confidence:.8,toolSequence:["web_search","web_fetch","file_write"].filter(u=>n.includes(u))});let l=e.filter(u=>["grep","glob","file_read"].includes(u.name)).length;return l>=5&&s<l/3&&t.push({type:"exploration",description:`Codebase exploration (${l} search/read operations)`,confidence:.85,toolSequence:n.filter(u=>["grep","glob","file_read"].includes(u))}),t}function Y5(e){let t=new Map;for(let n of e){if(!n.durationMs)continue;let r=t.get(n.name)||{total:0,count:0};r.total+=n.durationMs,r.count++,t.set(n.name,r)}return Array.from(t.entries()).map(([n,r])=>({tool:n,totalDurationMs:r.total,callCount:r.count,avgDurationMs:Math.round(r.total/r.count)})).sort((n,r)=>r.totalDurationMs-n.totalDurationMs).slice(0,5)}function Q5(e,t){if(e.length===0)return"unknown";let n=e.filter(o=>!o.success).length/e.length,r=t?.content?.toLowerCase()||"",s=/\b(done|completed|finished|successfully|works|fixed|created)\b/,i=/\b(failed|cannot|unable|error|stuck)\b/;return n>.5?"failure":n>0&&s.test(r)?"partial_success":s.test(r)?"success":i.test(r)?"failure":n===0?"success":"partial_success"}function Z5(e){return e.map(t=>({turnIndex:t.turnIndex,tool:t.name,action:Kxe(t),result:t.success?"success":"failure",durationMs:t.durationMs}))}function Kxe(e){let t=e.input;switch(e.name){case"bash":case"powershell":return`$ ${String(t.command||"").slice(0,60)}`;case"file_read":return`read ${t.path}`;case"file_write":return`wrote ${t.path}`;case"file_edit":return`edited ${t.path}`;case"grep":return`grep "${t.pattern}"`;case"glob":return`glob "${t.pattern}"`;case"web_search":return`searched: ${t.query}`;case"web_fetch":return`fetched ${t.url}`;case"doc_create":return`created doc ${t.path}`;case"image_read":return`analyzed image ${t.path}`;default:return`${e.name}(${JSON.stringify(t).slice(0,40)})`}}function Kd(e,t="turn"){let n=[...new Set(e.filter(g=>g.name==="file_read").map(g=>String(g.input.path)))].filter(Boolean),r=[...new Set(e.filter(g=>g.name==="file_edit").map(g=>String(g.input.path)))].filter(Boolean),s=[...new Set(e.filter(g=>g.name==="file_write"||g.name==="doc_create").map(g=>String(g.input.path)))].filter(Boolean),i=e.filter(g=>g.name==="bash"||g.name==="powershell").map(g=>String(g.input.command||"")),o=e.filter(g=>g.name==="web_fetch").map(g=>String(g.input.url||"")),a=e.filter(g=>!g.success),c=new Map;for(let g of a){let h=`${g.name}:${g.errorMessage||"unknown"}`;c.has(h)?c.get(h).attemptCount++:c.set(h,{tool:g.name,message:g.errorMessage||"Unknown error",recovered:!1,attemptCount:1})}let l=K5(e),u=Z5(e),d=Y5(e),f=e.reduce((g,h)=>g+(h.durationMs||0),0),p=[];s.length&&p.push(`Created ${s.length} file(s): ${s.slice(0,3).join(", ")}${s.length>3?"...":""}`),r.length&&p.push(`Modified ${r.length} file(s): ${r.slice(0,3).join(", ")}${r.length>3?"...":""}`),n.length&&p.push(`Read ${n.length} file(s)`),i.length&&p.push(`Ran ${i.length} command(s)`),o.length&&p.push(`Visited ${o.length} URL(s)`),a.length&&p.push(`Encountered ${a.length} error(s)`);for(let g of l)p.push(`Pattern: ${g.description}`);let m=Yxe({filesCreated:s,filesWritten:r,filesRead:n,commandsRun:i,errors:a,patterns:l});return{level:t,outcome:Q5(e),totalCalls:e.length,successfulCalls:e.filter(g=>g.success).length,failedCalls:a.length,uniqueTools:[...new Set(e.map(g=>g.name))],filesRead:n,filesModified:r,filesCreated:s,commandsRun:i,websVisited:o,errorsEncountered:Array.from(c.values()),patterns:l,timeline:u,totalDurationMs:f,bottlenecks:d,narrative:m,bulletPoints:p,metadata:{messagesAnalyzed:e.length,confidenceScore:e.length>0?.9:.5}}}function Yxe(e){let t=[];return e.patterns.length>0&&t.push(`This was a ${e.patterns[0].type.replace("_"," ")} session.`),e.filesCreated.length>0&&t.push(`Created ${e.filesCreated.length} file${e.filesCreated.length>1?"s":""} (${e.filesCreated.slice(0,2).map(n=>n.split("/").pop()).join(", ")}${e.filesCreated.length>2?`, +${e.filesCreated.length-2} more`:""}).`),e.filesWritten.length>0&&t.push(`Modified ${e.filesWritten.length} file${e.filesWritten.length>1?"s":""}.`),e.commandsRun.length>0&&t.push(`Executed ${e.commandsRun.length} shell command${e.commandsRun.length>1?"s":""}.`),e.errors.length>0&&t.push(`Hit ${e.errors.length} error${e.errors.length>1?"s":""} during execution.`),t.join(" ")||"No significant tool activity."}async function X5(e,t,n,r={}){let s=Kd(e,r.level||"turn");if(e.length===0)return s;let i=e.slice(-30).map((c,l)=>`${l+1}. ${c.name}(${Qxe(c.input)}) \u2192 ${c.success?"OK":"FAIL: "+c.errorMessage}`).join(`
2026
2036
  `),a=`Analyze this tool execution sequence and produce a high-quality summary.
2027
2037
 
2028
2038
  USER'S ORIGINAL TASK: ${t.find(c=>c.role==="user"&&!c.content.startsWith("<tool_result"))?.content?.slice(0,300)||"Unknown task"}
@@ -2044,9 +2054,9 @@ Write a 2-3 sentence narrative summary that:
2044
2054
  3. Notes any significant errors, patterns, or gotchas
2045
2055
  4. Uses past tense, professional, concise
2046
2056
 
2047
- Return ONLY the narrative paragraph. No preamble, no markdown, no bullet points.`;try{let l=(await n.sendMessage([{role:"user",content:a,timestamp:new Date().toISOString()}],"You are a precise technical summarizer. Output a single paragraph.",[],void 0)).content.trim().slice(0,1e3);return{...s,narrative:l,metadata:{...s.metadata,confidenceScore:.95}}}catch{return s}}function Yxe(e){return Object.keys(e).slice(0,2).map(n=>{let r=String(e[n]||"").slice(0,40);return`${n}: ${r}`}).join(", ")}function eU(e){let t=["## Tool Use Summary",""];if(t.push(`**Outcome:** ${Qxe(e.outcome)}`),t.push(`**Calls:** ${e.totalCalls} (${e.successfulCalls} \u2713, ${e.failedCalls} \u2717)`),t.push(`**Tools used:** ${e.uniqueTools.join(", ")}`),e.totalDurationMs>0&&t.push(`**Total time:** ${(e.totalDurationMs/1e3).toFixed(1)}s`),t.push(""),t.push("### Narrative"),t.push(e.narrative),t.push(""),(e.filesCreated.length||e.filesModified.length||e.filesRead.length)&&(t.push("### Files"),e.filesCreated.length&&t.push(`- **Created:** ${e.filesCreated.join(", ")}`),e.filesModified.length&&t.push(`- **Modified:** ${e.filesModified.join(", ")}`),e.filesRead.length&&t.push(`- **Read:** ${e.filesRead.slice(0,5).join(", ")}${e.filesRead.length>5?`... +${e.filesRead.length-5}`:""}`),t.push("")),e.commandsRun.length){t.push("### Commands");for(let n of e.commandsRun.slice(0,5))t.push(`- \`${n}\``);t.push("")}if(e.errorsEncountered.length){t.push("### Errors");for(let n of e.errorsEncountered)t.push(`- **${n.tool}**: ${n.message}${n.attemptCount>1?` (${n.attemptCount} attempts)`:""}`);t.push("")}if(e.patterns.length){t.push("### Patterns Detected");for(let n of e.patterns)t.push(`- **${n.type}**: ${n.description} (${Math.round(n.confidence*100)}% confidence)`);t.push("")}if(e.bottlenecks.length&&e.bottlenecks[0].totalDurationMs>1e3){t.push("### Performance");for(let n of e.bottlenecks.slice(0,3))t.push(`- **${n.tool}**: ${n.callCount} calls, ${(n.totalDurationMs/1e3).toFixed(1)}s total (avg ${n.avgDurationMs}ms)`)}return t.join(`
2057
+ Return ONLY the narrative paragraph. No preamble, no markdown, no bullet points.`;try{let l=(await n.sendMessage([{role:"user",content:a,timestamp:new Date().toISOString()}],"You are a precise technical summarizer. Output a single paragraph.",[],void 0)).content.trim().slice(0,1e3);return{...s,narrative:l,metadata:{...s.metadata,confidenceScore:.95}}}catch{return s}}function Qxe(e){return Object.keys(e).slice(0,2).map(n=>{let r=String(e[n]||"").slice(0,40);return`${n}: ${r}`}).join(", ")}function eU(e){let t=["## Tool Use Summary",""];if(t.push(`**Outcome:** ${Zxe(e.outcome)}`),t.push(`**Calls:** ${e.totalCalls} (${e.successfulCalls} \u2713, ${e.failedCalls} \u2717)`),t.push(`**Tools used:** ${e.uniqueTools.join(", ")}`),e.totalDurationMs>0&&t.push(`**Total time:** ${(e.totalDurationMs/1e3).toFixed(1)}s`),t.push(""),t.push("### Narrative"),t.push(e.narrative),t.push(""),(e.filesCreated.length||e.filesModified.length||e.filesRead.length)&&(t.push("### Files"),e.filesCreated.length&&t.push(`- **Created:** ${e.filesCreated.join(", ")}`),e.filesModified.length&&t.push(`- **Modified:** ${e.filesModified.join(", ")}`),e.filesRead.length&&t.push(`- **Read:** ${e.filesRead.slice(0,5).join(", ")}${e.filesRead.length>5?`... +${e.filesRead.length-5}`:""}`),t.push("")),e.commandsRun.length){t.push("### Commands");for(let n of e.commandsRun.slice(0,5))t.push(`- \`${n}\``);t.push("")}if(e.errorsEncountered.length){t.push("### Errors");for(let n of e.errorsEncountered)t.push(`- **${n.tool}**: ${n.message}${n.attemptCount>1?` (${n.attemptCount} attempts)`:""}`);t.push("")}if(e.patterns.length){t.push("### Patterns Detected");for(let n of e.patterns)t.push(`- **${n.type}**: ${n.description} (${Math.round(n.confidence*100)}% confidence)`);t.push("")}if(e.bottlenecks.length&&e.bottlenecks[0].totalDurationMs>1e3){t.push("### Performance");for(let n of e.bottlenecks.slice(0,3))t.push(`- **${n.tool}**: ${n.callCount} calls, ${(n.totalDurationMs/1e3).toFixed(1)}s total (avg ${n.avgDurationMs}ms)`)}return t.join(`
2048
2058
  `)}function tU(e){return e.bulletPoints.map(t=>`\u2022 ${t}`).join(`
2049
- `)}function nU(e){return e.narrative}function rU(e){return JSON.stringify({outcome:e.outcome,totalCalls:e.totalCalls,successfulCalls:e.successfulCalls,failedCalls:e.failedCalls,files:{created:e.filesCreated,modified:e.filesModified,read:e.filesRead.slice(0,10)},commands:e.commandsRun.slice(0,10),errors:e.errorsEncountered,patterns:e.patterns.map(t=>({type:t.type,confidence:t.confidence})),durationMs:e.totalDurationMs},null,2)}function Qxe(e){return{success:"\u2705 Success",partial_success:"\u26A0\uFE0F Partial",failure:"\u274C Failed",in_progress:"\u{1F504} In progress",unknown:"\u2754 Unknown"}[e]}function Zxe(e){let t=Kd(e),n=[];return t.filesCreated.length&&n.push(`created ${t.filesCreated.length} file(s)`),t.filesModified.length&&n.push(`modified ${t.filesModified.length} file(s)`),t.commandsRun.length&&n.push(`ran ${t.commandsRun.length} command(s)`),t.failedCalls>0&&n.push(`${t.failedCalls} error(s)`),`[Tool summary: ${n.join(", ")||"no significant activity"}]`}async function Xxe(e,t={}){let n=E0(e),r=t.useAI&&t.provider?await X5(n,e,t.provider,t):Kd(n,t.level||"turn"),s;switch(t.format){case"narrative":s=nU(r);break;case"bulleted":s=tU(r);break;case"structured":s=rU(r);break;default:s=eU(r)}return{summary:r,formatted:s}}var Y1=w(()=>{"use strict"});var gU={};$(gU,{analyzeFailures:()=>dU,assessGoalAchievement:()=>aU,compareAgents:()=>f$e,extractDecisions:()=>lU,extractDeliverables:()=>cU,extractReasoning:()=>uU,formatAsMarkdown:()=>p$e,formatBrief:()=>m$e,generateHandoffNotes:()=>fU,generateVerificationSuggestions:()=>pU,inferAgentRole:()=>oU,loadAgentSummary:()=>a$e,saveAgentSummary:()=>o$e,summarizeAgentHeuristic:()=>mU,summarizeAgentWithAI:()=>d$e});import{existsSync as e$e,mkdirSync as t$e,readFileSync as n$e,writeFileSync as r$e}from"fs";import{join as Q1}from"path";import{homedir as s$e}from"os";function i$e(){t$e(Z1,{recursive:!0})}function o$e(e){i$e();let t=Q1(Z1,`${e.agentId}.json`);return r$e(t,JSON.stringify(e,null,2),"utf-8"),t}function a$e(e){let t=Q1(Z1,`${e}.json`);if(!e$e(t))return null;try{return JSON.parse(n$e(t,"utf-8"))}catch{return null}}function oU(e,t){let n=e.toLowerCase(),r=t.map(s=>s.name);return/\b(test|jest|pytest|spec)\b/.test(n)?"tester":/\b(review|audit|critique|analyze)\b/.test(n)?"reviewer":/\b(fix|bug|error|debug)\b/.test(n)?"fixer":/\b(research|find|search|investigate)\b/.test(n)?"researcher":/\b(explore|understand|examine)\b/.test(n)||r.filter(s=>["grep","glob","file_read"].includes(s)).length/Math.max(1,r.length)>.7?"explorer":r.includes("file_write")||r.includes("file_edit")?"implementer":"general"}function aU(e,t,n){let r=[],s=[];/\b(done|completed|finished|successfully|works|ready)\b/i.test(n)&&r.push("Agent reported task completion");let i=t.length===0?0:t.filter(u=>u.success).length/t.length;i>.9&&r.push(`High tool success rate (${Math.round(i*100)}%)`);let o=e.toLowerCase();if(/create|write|make/.test(o)){let u=t.filter(d=>d.name==="file_write"||d.name==="doc_create").filter(d=>d.success).length;u>0?r.push(`Created ${u} file(s)`):s.push("Task asked to create files but none were created")}if(/test/.test(o)){let u=t.filter(d=>d.name==="bash"&&/test/.test(String(d.input.command||""))).filter(d=>d.success).length;u>0&&r.push(`Ran ${u} successful test command(s)`)}if(/fix|bug/.test(o)){let u=t.filter(d=>d.name==="file_edit").filter(d=>d.success).length;u>0&&r.push(`Made ${u} edit(s) to fix the issue`)}/\b(failed|cannot|unable|stuck|gave up)\b/i.test(n)&&s.push("Agent indicated failure"),i<.5&&t.length>2&&s.push(`Low tool success rate (${Math.round(i*100)}%)`);let a=t.filter(u=>!u.success).length;a>=3&&s.push(`${a} tool errors encountered`);let c=r.length/Math.max(1,r.length+s.length),l=c>.6;return{goal:e,achieved:l,partialAchievement:l?void 0:r.length>0?"Some progress made but goal not fully achieved":void 0,evidenceOfSuccess:r,evidenceAgainst:s,confidence:c}}function cU(e){let t=[],n=new Set;for(let r of e){if(!r.success)continue;let s=String(r.input.path||"");if(r.name==="file_write"&&s&&!n.has(s))n.add(s),t.push({type:iU(s),description:`Created ${s}`,path:s,status:"created"});else if(r.name==="file_edit"&&s){let i=t.find(o=>o.path===s);i?i.status="modified":(t.push({type:iU(s),description:`Modified ${s}`,path:s,status:"modified"}),n.add(s))}else r.name==="doc_create"&&s?t.push({type:"doc",description:`Created document ${s}`,path:s,status:"created"}):r.name==="bash"&&/test/.test(String(r.input.command||""))&&t.push({type:"test",description:`Test run: ${String(r.input.command).slice(0,60)}`,status:"verified"})}return t}function iU(e){return/\.(test|spec)\./.test(e)?"test":/\.(md|rst|txt)$/i.test(e)?"doc":/\.(json|yaml|yml|toml|ini|env)$/i.test(e)?"config":"file"}function lU(e){let t=[],n=[/\bI('ll| will| chose to| decided to| went with) ([^.!?]+)[.!?]/gi,/\bUsing ([^.!?]+) (because|since|as) ([^.!?]+)[.!?]/gi,/\bI'?m? ([^.!?]+) (instead of|over|rather than) ([^.!?]+)[.!?]/gi];for(let r of e)if(r.role==="assistant")for(let s of n)for(let i of r.content.matchAll(s)){let o=i[2]||i[1],a=i[3]||"";o&&o.length<200&&t.push({description:o.trim().slice(0,200),rationale:a.trim().slice(0,200)||"No rationale stated",reversibility:c$e(o)})}return t.slice(0,10)}function c$e(e){let t=e.toLowerCase();return/delete|remove|drop|destroy/.test(t)||/install|migrate|upgrade/.test(t)?"difficult":(/edit|modify|update|change/.test(t),"reversible")}function uU(e){let t=[],n=[/\bbecause ([^.!?]+)[.!?]/i,/\bso that ([^.!?]+)[.!?]/i,/\bin order to ([^.!?]+)[.!?]/i,/\bfirst,?\s+([^.!?]+)[.!?]/i,/\bnext,?\s+([^.!?]+)[.!?]/i,/\bThe (issue|problem|root cause) is ([^.!?]+)[.!?]/i];for(let r of e)if(r.role==="assistant")for(let s of n){let i=r.content.match(s);i&&i[1]&&i[1].length<200&&t.push(i[1].trim())}return[...new Set(t)].slice(0,8)}function dU(e){let t=[],n=new Map;for(let r=0;r<e.length;r++){let s=e[r];if(s.success)continue;let i=`${s.name}:${s.errorMessage||"unknown"}`;if(n.has(i))n.get(i).count++;else{let o=!1,a;for(let c=r+1;c<Math.min(e.length,r+4);c++)if(e[c].name===s.name&&e[c].success){o=!0,a=`Retried ${s.name} successfully`;break}n.set(i,{count:1,recovered:o,recoveryAction:a})}}for(let[r,s]of n){let[i,...o]=r.split(":");t.push({point:i,cause:o.join(":")||"Unknown",recovered:s.recovered,recoveryAction:s.recoveryAction})}return t.slice(0,5)}function fU(e){let t=[];if(e.outcome==="failed"&&t.push("\u26A0\uFE0F Task did not complete \u2014 review failures before retrying"),e.outcome==="partial"&&t.push("Task partially complete \u2014 see deliverables for what was finished"),e.deliverables&&e.deliverables.some(n=>n.status==="unverified")){let n=e.deliverables.filter(r=>r.status==="unverified");t.push(`${n.length} deliverable(s) not verified \u2014 recommend testing`)}if(e.failures&&e.failures.some(n=>!n.recovered)){let n=e.failures.filter(r=>!r.recovered);t.push(`Unresolved errors: ${n.map(r=>r.cause.slice(0,50)).join("; ")}`)}return e.commandsRun&&e.commandsRun.some(n=>/install|migrate/.test(n))&&t.push("Environment changes were made (installs/migrations) \u2014 verify state"),e.filesModified&&e.filesModified.length>5&&t.push(`Many files modified (${e.filesModified.length}) \u2014 review diff before committing`),t}function pU(e,t){let n=[],r=e.some(a=>a.status==="created"&&a.type==="file"),s=e.some(a=>a.status==="modified"),i=e.some(a=>a.type==="test"),o=t.some(a=>/\b(test|jest|pytest|vitest)\b/.test(a));return(r||s)&&(!i&&!o&&n.push("Run the test suite to verify changes"),n.push("Review the diff before committing")),r&&n.push("Verify new files have proper imports/exports"),t.some(a=>/install/.test(a))&&n.push("Verify package.json/requirements.txt is updated"),e.some(a=>a.type==="config")&&n.push("Verify config changes work in target environment"),n}function mU(e,t,n,r){let s=E0(r),i=Kd(s),o=oU(n,s),a=[...r].reverse().find(x=>x.role==="assistant"&&x.content.trim())?.content||"",c=aU(n,s,a),l=cU(s),u=lU(r),d=uU(r),f=dU(s),p="unclear";c.achieved&&c.confidence>.7?p="completed":c.achieved?p="partial":f.length>=3?p="failed":l.length>0&&(p="partial");let m=r[0]?.timestamp||new Date().toISOString(),g=r[r.length-1]?.timestamp||new Date().toISOString(),h=new Date(g).getTime()-new Date(m).getTime(),v={outcome:p,deliverables:l,failures:f,commandsRun:i.commandsRun,filesModified:i.filesModified},y=fU(v),b=pU(l,i.commandsRun),k=l$e(o,n,p,l,f),S=u$e(o,n,p,i,l,u,f);return{agentId:e,agentName:t,role:o,task:n,outcome:p,startedAt:m,completedAt:g,durationMs:h,iterations:r.filter(x=>x.role==="assistant").length,toolCallCount:s.length,goalAchievement:c,deliverables:l,decisions:u,reasoning:d,failures:f,handoffNotes:y,filesCreated:i.filesCreated,filesModified:i.filesModified,filesRead:i.filesRead,commandsRun:i.commandsRun,errorsEncountered:i.errorsEncountered.map(x=>x.message),patterns:i.patterns,confidenceScore:.85,verificationSuggestions:b,executiveSummary:k,technicalSummary:S,metadata:{messagesAnalyzed:r.length}}}function l$e(e,t,n,r,s){let i={completed:"completed",partial:"partially completed",failed:"failed",aborted:"was aborted",unclear:"finished unclear"},o=r.filter(l=>l.status==="created").length,a=r.filter(l=>l.status==="modified").length,c=s.length>0?` Hit ${s.length} error(s).`:"";return`${e.charAt(0).toUpperCase()+e.slice(1)} agent ${i[n]} the task${o||a?` \u2014 created ${o}, modified ${a} file(s)`:""}.${c}`}function u$e(e,t,n,r,s,i,o){let a=[];if(a.push(`Acting as a ${e}, the agent ${n==="completed"?"completed":"attempted"} the task: "${t.slice(0,100)}".`),r.totalCalls>0&&a.push(`Used ${r.uniqueTools.length} unique tools across ${r.totalCalls} calls.`),s.length>0&&a.push(`Delivered ${s.length} item(s): ${s.slice(0,3).map(c=>c.description).join("; ")}.`),i.length>0&&a.push(`Made ${i.length} key decision(s).`),o.length>0){let c=o.filter(l=>l.recovered).length;a.push(`Encountered ${o.length} failure(s)${c>0?` (${c} recovered)`:""}.`)}return a.join(" ")}async function d$e(e,t,n,r,s){let i=mU(e,t,n,r);if(r.length<3)return i;let o=r.slice(-15).filter(c=>!c.content.startsWith("<tool_result")).map(c=>`[${c.role}] ${c.content.slice(0,400)}`).join(`
2059
+ `)}function nU(e){return e.narrative}function rU(e){return JSON.stringify({outcome:e.outcome,totalCalls:e.totalCalls,successfulCalls:e.successfulCalls,failedCalls:e.failedCalls,files:{created:e.filesCreated,modified:e.filesModified,read:e.filesRead.slice(0,10)},commands:e.commandsRun.slice(0,10),errors:e.errorsEncountered,patterns:e.patterns.map(t=>({type:t.type,confidence:t.confidence})),durationMs:e.totalDurationMs},null,2)}function Zxe(e){return{success:"\u2705 Success",partial_success:"\u26A0\uFE0F Partial",failure:"\u274C Failed",in_progress:"\u{1F504} In progress",unknown:"\u2754 Unknown"}[e]}function Xxe(e){let t=Kd(e),n=[];return t.filesCreated.length&&n.push(`created ${t.filesCreated.length} file(s)`),t.filesModified.length&&n.push(`modified ${t.filesModified.length} file(s)`),t.commandsRun.length&&n.push(`ran ${t.commandsRun.length} command(s)`),t.failedCalls>0&&n.push(`${t.failedCalls} error(s)`),`[Tool summary: ${n.join(", ")||"no significant activity"}]`}async function e$e(e,t={}){let n=E0(e),r=t.useAI&&t.provider?await X5(n,e,t.provider,t):Kd(n,t.level||"turn"),s;switch(t.format){case"narrative":s=nU(r);break;case"bulleted":s=tU(r);break;case"structured":s=rU(r);break;default:s=eU(r)}return{summary:r,formatted:s}}var Y1=w(()=>{"use strict"});var gU={};$(gU,{analyzeFailures:()=>dU,assessGoalAchievement:()=>aU,compareAgents:()=>p$e,extractDecisions:()=>lU,extractDeliverables:()=>cU,extractReasoning:()=>uU,formatAsMarkdown:()=>m$e,formatBrief:()=>g$e,generateHandoffNotes:()=>fU,generateVerificationSuggestions:()=>pU,inferAgentRole:()=>oU,loadAgentSummary:()=>c$e,saveAgentSummary:()=>a$e,summarizeAgentHeuristic:()=>mU,summarizeAgentWithAI:()=>f$e});import{existsSync as t$e,mkdirSync as n$e,readFileSync as r$e,writeFileSync as s$e}from"fs";import{join as Q1}from"path";import{homedir as i$e}from"os";function o$e(){n$e(Z1,{recursive:!0})}function a$e(e){o$e();let t=Q1(Z1,`${e.agentId}.json`);return s$e(t,JSON.stringify(e,null,2),"utf-8"),t}function c$e(e){let t=Q1(Z1,`${e}.json`);if(!t$e(t))return null;try{return JSON.parse(r$e(t,"utf-8"))}catch{return null}}function oU(e,t){let n=e.toLowerCase(),r=t.map(s=>s.name);return/\b(test|jest|pytest|spec)\b/.test(n)?"tester":/\b(review|audit|critique|analyze)\b/.test(n)?"reviewer":/\b(fix|bug|error|debug)\b/.test(n)?"fixer":/\b(research|find|search|investigate)\b/.test(n)?"researcher":/\b(explore|understand|examine)\b/.test(n)||r.filter(s=>["grep","glob","file_read"].includes(s)).length/Math.max(1,r.length)>.7?"explorer":r.includes("file_write")||r.includes("file_edit")?"implementer":"general"}function aU(e,t,n){let r=[],s=[];/\b(done|completed|finished|successfully|works|ready)\b/i.test(n)&&r.push("Agent reported task completion");let i=t.length===0?0:t.filter(u=>u.success).length/t.length;i>.9&&r.push(`High tool success rate (${Math.round(i*100)}%)`);let o=e.toLowerCase();if(/create|write|make/.test(o)){let u=t.filter(d=>d.name==="file_write"||d.name==="doc_create").filter(d=>d.success).length;u>0?r.push(`Created ${u} file(s)`):s.push("Task asked to create files but none were created")}if(/test/.test(o)){let u=t.filter(d=>d.name==="bash"&&/test/.test(String(d.input.command||""))).filter(d=>d.success).length;u>0&&r.push(`Ran ${u} successful test command(s)`)}if(/fix|bug/.test(o)){let u=t.filter(d=>d.name==="file_edit").filter(d=>d.success).length;u>0&&r.push(`Made ${u} edit(s) to fix the issue`)}/\b(failed|cannot|unable|stuck|gave up)\b/i.test(n)&&s.push("Agent indicated failure"),i<.5&&t.length>2&&s.push(`Low tool success rate (${Math.round(i*100)}%)`);let a=t.filter(u=>!u.success).length;a>=3&&s.push(`${a} tool errors encountered`);let c=r.length/Math.max(1,r.length+s.length),l=c>.6;return{goal:e,achieved:l,partialAchievement:l?void 0:r.length>0?"Some progress made but goal not fully achieved":void 0,evidenceOfSuccess:r,evidenceAgainst:s,confidence:c}}function cU(e){let t=[],n=new Set;for(let r of e){if(!r.success)continue;let s=String(r.input.path||"");if(r.name==="file_write"&&s&&!n.has(s))n.add(s),t.push({type:iU(s),description:`Created ${s}`,path:s,status:"created"});else if(r.name==="file_edit"&&s){let i=t.find(o=>o.path===s);i?i.status="modified":(t.push({type:iU(s),description:`Modified ${s}`,path:s,status:"modified"}),n.add(s))}else r.name==="doc_create"&&s?t.push({type:"doc",description:`Created document ${s}`,path:s,status:"created"}):r.name==="bash"&&/test/.test(String(r.input.command||""))&&t.push({type:"test",description:`Test run: ${String(r.input.command).slice(0,60)}`,status:"verified"})}return t}function iU(e){return/\.(test|spec)\./.test(e)?"test":/\.(md|rst|txt)$/i.test(e)?"doc":/\.(json|yaml|yml|toml|ini|env)$/i.test(e)?"config":"file"}function lU(e){let t=[],n=[/\bI('ll| will| chose to| decided to| went with) ([^.!?]+)[.!?]/gi,/\bUsing ([^.!?]+) (because|since|as) ([^.!?]+)[.!?]/gi,/\bI'?m? ([^.!?]+) (instead of|over|rather than) ([^.!?]+)[.!?]/gi];for(let r of e)if(r.role==="assistant")for(let s of n)for(let i of r.content.matchAll(s)){let o=i[2]||i[1],a=i[3]||"";o&&o.length<200&&t.push({description:o.trim().slice(0,200),rationale:a.trim().slice(0,200)||"No rationale stated",reversibility:l$e(o)})}return t.slice(0,10)}function l$e(e){let t=e.toLowerCase();return/delete|remove|drop|destroy/.test(t)||/install|migrate|upgrade/.test(t)?"difficult":(/edit|modify|update|change/.test(t),"reversible")}function uU(e){let t=[],n=[/\bbecause ([^.!?]+)[.!?]/i,/\bso that ([^.!?]+)[.!?]/i,/\bin order to ([^.!?]+)[.!?]/i,/\bfirst,?\s+([^.!?]+)[.!?]/i,/\bnext,?\s+([^.!?]+)[.!?]/i,/\bThe (issue|problem|root cause) is ([^.!?]+)[.!?]/i];for(let r of e)if(r.role==="assistant")for(let s of n){let i=r.content.match(s);i&&i[1]&&i[1].length<200&&t.push(i[1].trim())}return[...new Set(t)].slice(0,8)}function dU(e){let t=[],n=new Map;for(let r=0;r<e.length;r++){let s=e[r];if(s.success)continue;let i=`${s.name}:${s.errorMessage||"unknown"}`;if(n.has(i))n.get(i).count++;else{let o=!1,a;for(let c=r+1;c<Math.min(e.length,r+4);c++)if(e[c].name===s.name&&e[c].success){o=!0,a=`Retried ${s.name} successfully`;break}n.set(i,{count:1,recovered:o,recoveryAction:a})}}for(let[r,s]of n){let[i,...o]=r.split(":");t.push({point:i,cause:o.join(":")||"Unknown",recovered:s.recovered,recoveryAction:s.recoveryAction})}return t.slice(0,5)}function fU(e){let t=[];if(e.outcome==="failed"&&t.push("\u26A0\uFE0F Task did not complete \u2014 review failures before retrying"),e.outcome==="partial"&&t.push("Task partially complete \u2014 see deliverables for what was finished"),e.deliverables&&e.deliverables.some(n=>n.status==="unverified")){let n=e.deliverables.filter(r=>r.status==="unverified");t.push(`${n.length} deliverable(s) not verified \u2014 recommend testing`)}if(e.failures&&e.failures.some(n=>!n.recovered)){let n=e.failures.filter(r=>!r.recovered);t.push(`Unresolved errors: ${n.map(r=>r.cause.slice(0,50)).join("; ")}`)}return e.commandsRun&&e.commandsRun.some(n=>/install|migrate/.test(n))&&t.push("Environment changes were made (installs/migrations) \u2014 verify state"),e.filesModified&&e.filesModified.length>5&&t.push(`Many files modified (${e.filesModified.length}) \u2014 review diff before committing`),t}function pU(e,t){let n=[],r=e.some(a=>a.status==="created"&&a.type==="file"),s=e.some(a=>a.status==="modified"),i=e.some(a=>a.type==="test"),o=t.some(a=>/\b(test|jest|pytest|vitest)\b/.test(a));return(r||s)&&(!i&&!o&&n.push("Run the test suite to verify changes"),n.push("Review the diff before committing")),r&&n.push("Verify new files have proper imports/exports"),t.some(a=>/install/.test(a))&&n.push("Verify package.json/requirements.txt is updated"),e.some(a=>a.type==="config")&&n.push("Verify config changes work in target environment"),n}function mU(e,t,n,r){let s=E0(r),i=Kd(s),o=oU(n,s),a=[...r].reverse().find(x=>x.role==="assistant"&&x.content.trim())?.content||"",c=aU(n,s,a),l=cU(s),u=lU(r),d=uU(r),f=dU(s),p="unclear";c.achieved&&c.confidence>.7?p="completed":c.achieved?p="partial":f.length>=3?p="failed":l.length>0&&(p="partial");let m=r[0]?.timestamp||new Date().toISOString(),g=r[r.length-1]?.timestamp||new Date().toISOString(),h=new Date(g).getTime()-new Date(m).getTime(),v={outcome:p,deliverables:l,failures:f,commandsRun:i.commandsRun,filesModified:i.filesModified},y=fU(v),b=pU(l,i.commandsRun),k=u$e(o,n,p,l,f),S=d$e(o,n,p,i,l,u,f);return{agentId:e,agentName:t,role:o,task:n,outcome:p,startedAt:m,completedAt:g,durationMs:h,iterations:r.filter(x=>x.role==="assistant").length,toolCallCount:s.length,goalAchievement:c,deliverables:l,decisions:u,reasoning:d,failures:f,handoffNotes:y,filesCreated:i.filesCreated,filesModified:i.filesModified,filesRead:i.filesRead,commandsRun:i.commandsRun,errorsEncountered:i.errorsEncountered.map(x=>x.message),patterns:i.patterns,confidenceScore:.85,verificationSuggestions:b,executiveSummary:k,technicalSummary:S,metadata:{messagesAnalyzed:r.length}}}function u$e(e,t,n,r,s){let i={completed:"completed",partial:"partially completed",failed:"failed",aborted:"was aborted",unclear:"finished unclear"},o=r.filter(l=>l.status==="created").length,a=r.filter(l=>l.status==="modified").length,c=s.length>0?` Hit ${s.length} error(s).`:"";return`${e.charAt(0).toUpperCase()+e.slice(1)} agent ${i[n]} the task${o||a?` \u2014 created ${o}, modified ${a} file(s)`:""}.${c}`}function d$e(e,t,n,r,s,i,o){let a=[];if(a.push(`Acting as a ${e}, the agent ${n==="completed"?"completed":"attempted"} the task: "${t.slice(0,100)}".`),r.totalCalls>0&&a.push(`Used ${r.uniqueTools.length} unique tools across ${r.totalCalls} calls.`),s.length>0&&a.push(`Delivered ${s.length} item(s): ${s.slice(0,3).map(c=>c.description).join("; ")}.`),i.length>0&&a.push(`Made ${i.length} key decision(s).`),o.length>0){let c=o.filter(l=>l.recovered).length;a.push(`Encountered ${o.length} failure(s)${c>0?` (${c} recovered)`:""}.`)}return a.join(" ")}async function f$e(e,t,n,r,s){let i=mU(e,t,n,r);if(r.length<3)return i;let o=r.slice(-15).filter(c=>!c.content.startsWith("<tool_result")).map(c=>`[${c.role}] ${c.content.slice(0,400)}`).join(`
2050
2060
  `),a=`Analyze this agent's work and produce a deep summary.
2051
2061
 
2052
2062
  ORIGINAL TASK: ${n}
@@ -2072,8 +2082,8 @@ Produce a JSON response (no markdown) with these fields:
2072
2082
  "additionalReasoning": ["key insight 1", "key insight 2"],
2073
2083
  "additionalHandoffNotes": ["important note 1"],
2074
2084
  "verificationSuggestions": ["specific verification step 1"]
2075
- }`;try{let u=(await s.sendMessage([{role:"user",content:a,timestamp:new Date().toISOString()}],"You are a precise agent work analyzer. Output ONLY valid JSON.",[],void 0)).content.replace(/```(?:json)?\s*/g,"").replace(/```/g,"").trim().match(/\{[\s\S]*\}/);if(!u)return i;let d=JSON.parse(u[0]);return{...i,executiveSummary:d.executiveSummary||i.executiveSummary,technicalSummary:d.technicalSummary||i.technicalSummary,selfReportedConfidence:typeof d.selfReportedConfidence=="number"?d.selfReportedConfidence:void 0,decisions:[...i.decisions,...(d.additionalDecisions||[]).slice(0,5)],reasoning:[...i.reasoning,...(d.additionalReasoning||[]).slice(0,5)],handoffNotes:[...i.handoffNotes,...(d.additionalHandoffNotes||[]).slice(0,3)],verificationSuggestions:[...new Set([...i.verificationSuggestions,...d.verificationSuggestions||[]])],confidenceScore:.95}}catch{return i}}function f$e(e){let t=e.reduce((l,u)=>l+u.durationMs,0),n=Math.max(...e.map(l=>l.durationMs),0),r=e.flatMap(l=>l.deliverables),s=[...new Set(e.flatMap(l=>l.handoffNotes))],i=[];for(let l=0;l<e.length;l++)for(let u=l+1;u<e.length;u++)for(let d of e[l].decisions)for(let f of e[u].decisions){if(d.description.length<20||f.description.length<20)continue;d.description.toLowerCase().split(" ").filter(m=>f.description.toLowerCase().includes(m)).length>3&&d.description!==f.description&&i.push({a:d,b:f,agentIds:[e[l].agentId,e[u].agentId]})}let o=e.filter(l=>l.outcome==="completed").length,a=e.filter(l=>l.outcome==="partial").length,c=e.filter(l=>l.outcome==="failed").length;return{totalAgents:e.length,completed:o,partial:a,failed:c,parallelDurationMs:n,totalDurationMs:t,efficiency:t>0?n/t:1,combinedDeliverables:r,conflictingDecisions:i.slice(0,5),combinedHandoffNotes:s,overallNarrative:`${e.length} agents ran in parallel. ${o} completed, ${a} partial, ${c} failed. Combined deliverables: ${r.length}.`}}function p$e(e){let t={completed:"\u2705",partial:"\u26A0\uFE0F",failed:"\u274C",aborted:"\u{1F6D1}",unclear:"\u2754"},n=[`# Agent: ${e.agentName}`,"",`**Role:** ${e.role} | **Outcome:** ${t[e.outcome]} ${e.outcome} | **Confidence:** ${Math.round(e.confidenceScore*100)}%`,`**Duration:** ${(e.durationMs/1e3).toFixed(1)}s | **Tool calls:** ${e.toolCallCount} | **Iterations:** ${e.iterations}`,"","## Task",e.task,"","## Executive Summary",e.executiveSummary,"","## Technical Summary",e.technicalSummary,""];if(e.deliverables.length>0){n.push("## Deliverables");for(let r of e.deliverables){let s=r.status==="created"?"\u2728":r.status==="modified"?"\u270F\uFE0F":r.status==="verified"?"\u2705":"\u2753";n.push(`- ${s} **[${r.type}]** ${r.description}`)}n.push("")}if(e.decisions.length>0){n.push("## Key Decisions");for(let r of e.decisions)n.push(`- **${r.description}** \u2014 ${r.rationale} (${r.reversibility})`);n.push("")}if(e.failures.length>0){n.push("## Failures");for(let r of e.failures)n.push(`- **${r.point}**: ${r.cause}${r.recovered?" \u2713 recovered":" \u274C unresolved"}`);n.push("")}if(e.handoffNotes.length>0){n.push("## Handoff Notes");for(let r of e.handoffNotes)n.push(`- ${r}`);n.push("")}if(e.verificationSuggestions.length>0){n.push("## Recommended Verification");for(let r of e.verificationSuggestions)n.push(`- ${r}`)}return n.join(`
2076
- `)}function m$e(e){return`${{completed:"\u2705",partial:"\u26A0\uFE0F",failed:"\u274C",aborted:"\u{1F6D1}",unclear:"\u2754"}[e.outcome]} ${e.agentName} (${e.role}): ${e.executiveSummary}`}var Z1,hU=w(()=>{"use strict";Y1();Z1=Q1(s$e(),".aiaca","agent-summaries")});var CU={};$(CU,{analyzeContext:()=>X1,clearPreferences:()=>T$e,clearSpeculativeCache:()=>_$e,generateSpeculative:()=>xU,getCacheStats:()=>R$e,getHybridSuggestions:()=>k$e,getPreferenceStats:()=>A$e,getSuggestions:()=>kU,recordAccepted:()=>x$e,recordRejected:()=>$$e});import{existsSync as bU,readFileSync as g$e,writeFileSync as vU,mkdirSync as h$e}from"fs";import{join as SU}from"path";import{homedir as wU}from"os";function X1(e){let t=[...e].reverse().find(u=>u.role==="user"&&!u.content.startsWith("<tool_result")),n=[...e].reverse().find(u=>u.role==="assistant"&&u.content.trim()),r=[],s=[],i=[],o=[],a=[];for(let u of e.slice(-5)){if(u.role==="assistant"&&u.toolCalls)for(let d of u.toolCalls)r.push(d.name),(d.name==="file_write"||d.name==="file_edit")&&s.push(String(d.input?.path)),d.name==="file_read"&&i.push(String(d.input?.path)),(d.name==="bash"||d.name==="powershell")&&o.push(String(d.input?.command));if(u.role==="user"&&/<tool_result.*error="true"|Error:|Exit code: [1-9]/.test(u.content)){let d=u.content.match(/Error: ([^\n]+)/);d&&a.push(d[1])}}let c=b$e(n?.content||"",r,s,a),l=v$e(n?.content+" "+(t?.content||""));return{lastUserMessage:t,lastAssistantMessage:n,recentTools:r,filesModified:s,filesRead:i,commandsRun:o,errorsEncountered:a,trigger:c,entities:l}}function b$e(e,t,n,r){return r.length>0?"found_error":n.length>0?n[0].endsWith(".test.ts")||n[0].includes("test")?"wrote_test":t.includes("file_write")?"created_file":"edited_file":t.includes("bash")||t.includes("powershell")?"ran_command":t.includes("grep")||t.includes("glob")?"searched":t.includes("web_fetch")||t.includes("web_search")?"browsed_web":/\b(refactor|clean.*up|simplif)/i.test(e)?"refactored":/\b(fixed|resolved|patched)\b/i.test(e)?"fixed_bug":/\b(add(ed)?|implement(ed)?|created)\b.*\b(feature|function|component)\b/i.test(e)?"added_feature":/\b(complete|done|finished)\b/i.test(e)?"completed_task":/\?$/.test(e.trim())?"asked_question":t.length===0?"idle":"completed_task"}function v$e(e){let t=[...new Set(Array.from(e.matchAll(/[\w./-]+\.\w{2,4}\b/g)).map(s=>s[0]))].slice(0,5),n=[...new Set(Array.from(e.matchAll(/\b(npm|pip|cargo|git|docker)\s+\w+/gi)).map(s=>s[0]))].slice(0,5);return{files:t,tools:n,concepts:[]}}function yU(e){return e.split(/[/\\]/).pop()||e}function F(){return new Date().toISOString()}function kU(e,t={}){let n=X1(e),r=t.limit||5,s=t.minConfidence||.5,i=[];for(let u of y$e)if(S$e(u,n)){let d=u.generate(n);for(let f of d)f.confidence*=u.weight,f.trigger=n.trigger,f.reasoning=`Matched pattern: ${u.id}`,i.push(f)}let o=new Set,c=i.filter(u=>o.has(u.text)?!1:(o.add(u.text),!0)).filter(u=>u.confidence>=s);return C$e(c).sort((u,d)=>d.confidence-u.confidence).slice(0,r)}function S$e(e,t){if(typeof e.trigger=="function")return e.trigger(t);if(e.trigger instanceof RegExp){let n=(t.lastAssistantMessage?.content||"")+" "+t.commandsRun.join(" ");return e.trigger.test(n)}return e.trigger===t.trigger}async function xU(e,t){let n=t.cacheKey||e.length.toString(),r=Tg.get(n);if(r&&Date.now()-r.timestamp<w$e)return r.suggestions;let s=X1(e),o=`Based on this conversation, predict the 5 most likely things the user will say next. Be specific and actionable.
2085
+ }`;try{let u=(await s.sendMessage([{role:"user",content:a,timestamp:new Date().toISOString()}],"You are a precise agent work analyzer. Output ONLY valid JSON.",[],void 0)).content.replace(/```(?:json)?\s*/g,"").replace(/```/g,"").trim().match(/\{[\s\S]*\}/);if(!u)return i;let d=JSON.parse(u[0]);return{...i,executiveSummary:d.executiveSummary||i.executiveSummary,technicalSummary:d.technicalSummary||i.technicalSummary,selfReportedConfidence:typeof d.selfReportedConfidence=="number"?d.selfReportedConfidence:void 0,decisions:[...i.decisions,...(d.additionalDecisions||[]).slice(0,5)],reasoning:[...i.reasoning,...(d.additionalReasoning||[]).slice(0,5)],handoffNotes:[...i.handoffNotes,...(d.additionalHandoffNotes||[]).slice(0,3)],verificationSuggestions:[...new Set([...i.verificationSuggestions,...d.verificationSuggestions||[]])],confidenceScore:.95}}catch{return i}}function p$e(e){let t=e.reduce((l,u)=>l+u.durationMs,0),n=Math.max(...e.map(l=>l.durationMs),0),r=e.flatMap(l=>l.deliverables),s=[...new Set(e.flatMap(l=>l.handoffNotes))],i=[];for(let l=0;l<e.length;l++)for(let u=l+1;u<e.length;u++)for(let d of e[l].decisions)for(let f of e[u].decisions){if(d.description.length<20||f.description.length<20)continue;d.description.toLowerCase().split(" ").filter(m=>f.description.toLowerCase().includes(m)).length>3&&d.description!==f.description&&i.push({a:d,b:f,agentIds:[e[l].agentId,e[u].agentId]})}let o=e.filter(l=>l.outcome==="completed").length,a=e.filter(l=>l.outcome==="partial").length,c=e.filter(l=>l.outcome==="failed").length;return{totalAgents:e.length,completed:o,partial:a,failed:c,parallelDurationMs:n,totalDurationMs:t,efficiency:t>0?n/t:1,combinedDeliverables:r,conflictingDecisions:i.slice(0,5),combinedHandoffNotes:s,overallNarrative:`${e.length} agents ran in parallel. ${o} completed, ${a} partial, ${c} failed. Combined deliverables: ${r.length}.`}}function m$e(e){let t={completed:"\u2705",partial:"\u26A0\uFE0F",failed:"\u274C",aborted:"\u{1F6D1}",unclear:"\u2754"},n=[`# Agent: ${e.agentName}`,"",`**Role:** ${e.role} | **Outcome:** ${t[e.outcome]} ${e.outcome} | **Confidence:** ${Math.round(e.confidenceScore*100)}%`,`**Duration:** ${(e.durationMs/1e3).toFixed(1)}s | **Tool calls:** ${e.toolCallCount} | **Iterations:** ${e.iterations}`,"","## Task",e.task,"","## Executive Summary",e.executiveSummary,"","## Technical Summary",e.technicalSummary,""];if(e.deliverables.length>0){n.push("## Deliverables");for(let r of e.deliverables){let s=r.status==="created"?"\u2728":r.status==="modified"?"\u270F\uFE0F":r.status==="verified"?"\u2705":"\u2753";n.push(`- ${s} **[${r.type}]** ${r.description}`)}n.push("")}if(e.decisions.length>0){n.push("## Key Decisions");for(let r of e.decisions)n.push(`- **${r.description}** \u2014 ${r.rationale} (${r.reversibility})`);n.push("")}if(e.failures.length>0){n.push("## Failures");for(let r of e.failures)n.push(`- **${r.point}**: ${r.cause}${r.recovered?" \u2713 recovered":" \u274C unresolved"}`);n.push("")}if(e.handoffNotes.length>0){n.push("## Handoff Notes");for(let r of e.handoffNotes)n.push(`- ${r}`);n.push("")}if(e.verificationSuggestions.length>0){n.push("## Recommended Verification");for(let r of e.verificationSuggestions)n.push(`- ${r}`)}return n.join(`
2086
+ `)}function g$e(e){return`${{completed:"\u2705",partial:"\u26A0\uFE0F",failed:"\u274C",aborted:"\u{1F6D1}",unclear:"\u2754"}[e.outcome]} ${e.agentName} (${e.role}): ${e.executiveSummary}`}var Z1,hU=w(()=>{"use strict";Y1();Z1=Q1(i$e(),".aiaca","agent-summaries")});var CU={};$(CU,{analyzeContext:()=>X1,clearPreferences:()=>_$e,clearSpeculativeCache:()=>R$e,generateSpeculative:()=>xU,getCacheStats:()=>P$e,getHybridSuggestions:()=>x$e,getPreferenceStats:()=>T$e,getSuggestions:()=>kU,recordAccepted:()=>$$e,recordRejected:()=>C$e});import{existsSync as bU,readFileSync as h$e,writeFileSync as vU,mkdirSync as y$e}from"fs";import{join as SU}from"path";import{homedir as wU}from"os";function X1(e){let t=[...e].reverse().find(u=>u.role==="user"&&!u.content.startsWith("<tool_result")),n=[...e].reverse().find(u=>u.role==="assistant"&&u.content.trim()),r=[],s=[],i=[],o=[],a=[];for(let u of e.slice(-5)){if(u.role==="assistant"&&u.toolCalls)for(let d of u.toolCalls)r.push(d.name),(d.name==="file_write"||d.name==="file_edit")&&s.push(String(d.input?.path)),d.name==="file_read"&&i.push(String(d.input?.path)),(d.name==="bash"||d.name==="powershell")&&o.push(String(d.input?.command));if(u.role==="user"&&/<tool_result.*error="true"|Error:|Exit code: [1-9]/.test(u.content)){let d=u.content.match(/Error: ([^\n]+)/);d&&a.push(d[1])}}let c=v$e(n?.content||"",r,s,a),l=S$e(n?.content+" "+(t?.content||""));return{lastUserMessage:t,lastAssistantMessage:n,recentTools:r,filesModified:s,filesRead:i,commandsRun:o,errorsEncountered:a,trigger:c,entities:l}}function v$e(e,t,n,r){return r.length>0?"found_error":n.length>0?n[0].endsWith(".test.ts")||n[0].includes("test")?"wrote_test":t.includes("file_write")?"created_file":"edited_file":t.includes("bash")||t.includes("powershell")?"ran_command":t.includes("grep")||t.includes("glob")?"searched":t.includes("web_fetch")||t.includes("web_search")?"browsed_web":/\b(refactor|clean.*up|simplif)/i.test(e)?"refactored":/\b(fixed|resolved|patched)\b/i.test(e)?"fixed_bug":/\b(add(ed)?|implement(ed)?|created)\b.*\b(feature|function|component)\b/i.test(e)?"added_feature":/\b(complete|done|finished)\b/i.test(e)?"completed_task":/\?$/.test(e.trim())?"asked_question":t.length===0?"idle":"completed_task"}function S$e(e){let t=[...new Set(Array.from(e.matchAll(/[\w./-]+\.\w{2,4}\b/g)).map(s=>s[0]))].slice(0,5),n=[...new Set(Array.from(e.matchAll(/\b(npm|pip|cargo|git|docker)\s+\w+/gi)).map(s=>s[0]))].slice(0,5);return{files:t,tools:n,concepts:[]}}function yU(e){return e.split(/[/\\]/).pop()||e}function L(){return new Date().toISOString()}function kU(e,t={}){let n=X1(e),r=t.limit||5,s=t.minConfidence||.5,i=[];for(let u of b$e)if(w$e(u,n)){let d=u.generate(n);for(let f of d)f.confidence*=u.weight,f.trigger=n.trigger,f.reasoning=`Matched pattern: ${u.id}`,i.push(f)}let o=new Set,c=i.filter(u=>o.has(u.text)?!1:(o.add(u.text),!0)).filter(u=>u.confidence>=s);return A$e(c).sort((u,d)=>d.confidence-u.confidence).slice(0,r)}function w$e(e,t){if(typeof e.trigger=="function")return e.trigger(t);if(e.trigger instanceof RegExp){let n=(t.lastAssistantMessage?.content||"")+" "+t.commandsRun.join(" ");return e.trigger.test(n)}return e.trigger===t.trigger}async function xU(e,t){let n=t.cacheKey||e.length.toString(),r=Tg.get(n);if(r&&Date.now()-r.timestamp<k$e)return r.suggestions;let s=X1(e),o=`Based on this conversation, predict the 5 most likely things the user will say next. Be specific and actionable.
2077
2087
 
2078
2088
  Recent conversation:
2079
2089
  ${e.slice(-4).map(a=>`[${a.role}] ${a.content.slice(0,300)}`).join(`
@@ -2091,19 +2101,19 @@ Return STRICTLY JSON array (no markdown):
2091
2101
  Each suggestion should be:
2092
2102
  - Short (under 80 chars)
2093
2103
  - Specific to this context
2094
- - Natural conversational continuation`;try{let l=(await t.provider.sendMessage([{role:"user",content:o,timestamp:new Date().toISOString()}],"You predict likely next user prompts. Return ONLY valid JSON.",[],void 0)).content.replace(/```(?:json)?\s*/g,"").replace(/```/g,"").trim().match(/\[[\s\S]*\]/);if(!l)return[];let d=JSON.parse(l[0]).filter(f=>f.text&&f.confidence>=.5).slice(0,t.maxSuggestions||5).map(f=>({text:f.text.slice(0,120),category:f.category||"follow_up",confidence:Math.max(0,Math.min(1,f.confidence)),trigger:s.trigger,reasoning:f.reasoning||"AI speculative",generatedAt:F()}));return Tg.set(n,{suggestions:d,timestamp:Date.now()}),d}catch{return[]}}async function k$e(e,t={}){let n=t.limit||5,r=kU(e,{limit:n*2}),s=[];t.useSpeculative!==!1&&t.provider&&e.length>=4&&(s=await xU(e,{provider:t.provider,maxSuggestions:n}));let i=new Map;for(let o of[...s,...r]){let a=o.text.toLowerCase().trim();(!i.has(a)||i.get(a).confidence<o.confidence)&&i.set(a,o)}return Array.from(i.values()).sort((o,a)=>a.confidence-o.confidence).slice(0,n)}function Rg(){if(!bU(_g))return{acceptedSuggestions:{},rejectedSuggestions:{},categoryAffinities:{follow_up:1,related:1,action:1,question:1,verify:1,expand:1,fix:1,iterate:1},triggerHistory:{}};try{return JSON.parse(g$e(_g,"utf-8"))}catch{return Rg()}}function $U(e){h$e(SU(wU(),".aiaca"),{recursive:!0}),vU(_g,JSON.stringify(e,null,2),"utf-8")}function x$e(e){let t=Rg();t.acceptedSuggestions[e.text]=(t.acceptedSuggestions[e.text]||0)+1,t.categoryAffinities[e.category]=(t.categoryAffinities[e.category]||1)*1.05,e.trigger&&(t.triggerHistory[e.trigger]=(t.triggerHistory[e.trigger]||0)+1),$U(t)}function $$e(e){let t=Rg();t.rejectedSuggestions[e.text]=(t.rejectedSuggestions[e.text]||0)+1,t.categoryAffinities[e.category]=(t.categoryAffinities[e.category]||1)*.95,$U(t)}function C$e(e){let t=Rg();return e.map(n=>{let r=t.acceptedSuggestions[n.text]||0,s=t.rejectedSuggestions[n.text]||0,i=t.categoryAffinities[n.category]||1,o=n.confidence*i;return o+=r*.05,o-=s*.1,{...n,confidence:Math.max(0,Math.min(1,o))}})}function A$e(){let e=Rg(),t=Object.values(e.acceptedSuggestions).reduce((i,o)=>i+o,0),n=Object.values(e.rejectedSuggestions).reduce((i,o)=>i+o,0),r=Object.entries(e.categoryAffinities).sort((i,o)=>o[1]-i[1])[0]?.[0]||"action",s=Object.entries(e.acceptedSuggestions).sort((i,o)=>o[1]-i[1]).slice(0,5).map(([i,o])=>({text:i,uses:o}));return{totalAccepted:t,totalRejected:n,topCategory:r,topSuggestions:s}}function T$e(){bU(_g)&&vU(_g,JSON.stringify({acceptedSuggestions:{},rejectedSuggestions:{},categoryAffinities:{follow_up:1,related:1,action:1,question:1,verify:1,expand:1,fix:1,iterate:1},triggerHistory:{}},null,2))}function _$e(){Tg.clear()}function R$e(){let e=Date.now(),t=e;for(let n of Tg.values())n.timestamp<t&&(t=n.timestamp);return{entries:Tg.size,oldestMs:e-t}}var y$e,Tg,w$e,_g,AU=w(()=>{"use strict";y$e=[{id:"after_file_create",trigger:"created_file",weight:.9,generate:e=>{let t=e.filesModified[e.filesModified.length-1]||"this file";return[{text:"Run the tests",category:"action",confidence:.85,generatedAt:F()},{text:"Add error handling",category:"follow_up",confidence:.8,generatedAt:F()},{text:`Write tests for ${yU(t)}`,category:"action",confidence:.85,generatedAt:F()},{text:"Add type definitions",category:"follow_up",confidence:.75,generatedAt:F()},{text:"Document the function/class",category:"expand",confidence:.7,generatedAt:F()}]}},{id:"after_file_edit",trigger:"edited_file",weight:.85,generate:e=>[{text:"Run the tests to verify",category:"verify",confidence:.9,generatedAt:F()},{text:"Show me the full file now",category:"verify",confidence:.8,generatedAt:F()},{text:"What else needs to change?",category:"follow_up",confidence:.75,generatedAt:F()}]},{id:"after_error",trigger:"found_error",weight:1,generate:e=>[{text:"Show me the full error stack trace",category:"question",confidence:.9,generatedAt:F()},{text:"Try a different approach",category:"fix",confidence:.85,generatedAt:F()},{text:"Check the logs",category:"action",confidence:.8,generatedAt:F()},{text:"Search the web for this error",category:"action",confidence:.75,generatedAt:F()},{text:"Add logging to debug",category:"fix",confidence:.7,generatedAt:F()}]},{id:"after_install",trigger:/\b(npm install|pip install|cargo add|yarn add)\b/,weight:.8,generate:()=>[{text:"Update the imports",category:"follow_up",confidence:.85,generatedAt:F()},{text:"Show me how to use it",category:"question",confidence:.8,generatedAt:F()},{text:"Update the documentation",category:"follow_up",confidence:.65,generatedAt:F()}]},{id:"after_test_run",trigger:/\b(test|jest|pytest|cargo test|go test)\b/,weight:.85,generate:()=>[{text:"Fix the failing tests",category:"fix",confidence:.85,generatedAt:F()},{text:"Add more test coverage",category:"expand",confidence:.75,generatedAt:F()},{text:"Show test coverage report",category:"action",confidence:.7,generatedAt:F()}]},{id:"after_commit",trigger:/\b(commit|pushed|merged|pr|pull request)\b/i,weight:.8,generate:()=>[{text:"Create a pull request",category:"action",confidence:.85,generatedAt:F()},{text:"What should we work on next?",category:"question",confidence:.8,generatedAt:F()},{text:"Update the changelog",category:"follow_up",confidence:.7,generatedAt:F()}]},{id:"after_refactor",trigger:/\b(refactor|cleanup|improve|simplif)/i,weight:.85,generate:()=>[{text:"Run the linter",category:"verify",confidence:.9,generatedAt:F()},{text:"Are there other places to improve?",category:"expand",confidence:.8,generatedAt:F()},{text:"Run tests to verify behavior unchanged",category:"verify",confidence:.95,generatedAt:F()}]},{id:"after_explanation",trigger:/\b(explain|what.*does|how.*work|describe)/i,weight:.7,generate:()=>[{text:"Show me an example",category:"follow_up",confidence:.85,generatedAt:F()},{text:"Can you simplify it?",category:"question",confidence:.7,generatedAt:F()},{text:"Walk me through it step by step",category:"expand",confidence:.75,generatedAt:F()}]},{id:"after_search",trigger:"searched",weight:.7,generate:e=>{let t=e.filesRead[e.filesRead.length-1];return[{text:"Show me the most relevant result",category:"follow_up",confidence:.8,generatedAt:F()},...t?[{text:`Open ${yU(t)}`,category:"action",confidence:.75,generatedAt:F()}]:[],{text:"Refine the search",category:"iterate",confidence:.7,generatedAt:F()}]}},{id:"after_web_fetch",trigger:"browsed_web",weight:.6,generate:()=>[{text:"Summarize this for me",category:"follow_up",confidence:.8,generatedAt:F()},{text:"How does this apply to my project?",category:"question",confidence:.75,generatedAt:F()},{text:"Find related resources",category:"expand",confidence:.65,generatedAt:F()}]},{id:"after_fix",trigger:"fixed_bug",weight:.9,generate:()=>[{text:"Add a regression test",category:"action",confidence:.95,generatedAt:F()},{text:"Check for similar bugs elsewhere",category:"expand",confidence:.8,generatedAt:F()},{text:"Document the fix in the changelog",category:"follow_up",confidence:.65,generatedAt:F()}]},{id:"after_feature",trigger:"added_feature",weight:.85,generate:()=>[{text:"Write tests for the new feature",category:"action",confidence:.9,generatedAt:F()},{text:"Update the documentation",category:"follow_up",confidence:.85,generatedAt:F()},{text:"Add it to the changelog",category:"follow_up",confidence:.7,generatedAt:F()},{text:"What edge cases should we handle?",category:"question",confidence:.75,generatedAt:F()}]},{id:"default",trigger:"idle",weight:.3,generate:()=>[{text:"Explain this codebase",category:"question",confidence:.5,generatedAt:F()},{text:"Find and fix bugs",category:"action",confidence:.5,generatedAt:F()},{text:"Add tests",category:"action",confidence:.5,generatedAt:F()},{text:"Review my recent changes",category:"verify",confidence:.6,generatedAt:F()}]}];Tg=new Map,w$e=300*1e3;_g=SU(wU(),".aiaca","suggestion-prefs.json")});var U0={};$(U0,{breakCache:()=>z$e,cleanup:()=>nCe,dedupeRequest:()=>MU,disableCache:()=>B$e,disableLogging:()=>W$e,disablePromptDump:()=>Q$e,dumpPrompt:()=>Z$e,enableCache:()=>j$e,enableLogging:()=>J$e,enablePromptDump:()=>Y$e,executeAPICall:()=>tCe,generateCacheKey:()=>q$e,getCacheStats:()=>H$e,getCached:()=>RU,getCircuitStatus:()=>eCe,getInflightCount:()=>G$e,getRecentLogs:()=>K$e,invalidateCache:()=>U$e,isCacheEnabled:()=>N$e,isCircuitOpen:()=>FU,listDumps:()=>EU,logAPIEvent:()=>L0,recordFailure:()=>OU,recordSuccess:()=>LU,setCached:()=>PU,shouldBreakCache:()=>IU,withRetry:()=>_U});import{existsSync as tP,mkdirSync as D0,readFileSync as nP,writeFileSync as O0,appendFileSync as P$e,readdirSync as B0,statSync as N0,unlinkSync as Pg}from"fs";import{join as Pr}from"path";import{homedir as I$e}from"os";import{createHash as M$e}from"crypto";function Xi(){D0(q0,{recursive:!0}),D0(oi,{recursive:!0}),D0(TU,{recursive:!0}),D0(j0,{recursive:!0})}async function _U(e,t={}){let n={...E$e,...t},r=null;for(let s=0;s<=n.maxRetries;s++)try{return await e()}catch(i){r=i;let o=i.status||i.statusCode||i.response?.status,a=i.message||"";if(!(n.retryableStatuses.includes(o)||n.retryableErrors.some(p=>p.test(a)))||s===n.maxRetries)throw i;let l=D$e(i.headers?.["retry-after"]||i.response?.headers?.["retry-after"]),u=Math.min(n.baseDelayMs*Math.pow(2,s),n.maxDelayMs),d=n.jitter?.85+Math.random()*.3:1,f=l!==null?l:Math.floor(u*d);n.onRetry?.(s+1,i,f),await F$e(f)}throw r}function D$e(e){if(e===void 0)return null;if(typeof e=="number")return e*1e3;let t=parseInt(e,10);if(!isNaN(t))return t*1e3;let n=new Date(e).getTime();return isNaN(n)?null:Math.max(0,n-Date.now())}function F$e(e){return new Promise(t=>setTimeout(t,e))}function j$e(){Mg=!0}function B$e(){Mg=!1}function N$e(){return Mg}function q$e(e,t,n,r,s){let i=JSON.stringify({p:e,m:t,s:n,msgs:r.map(o=>({r:o.role,c:o.content})),t:[...s].sort()});return M$e("sha256").update(i).digest("hex").slice(0,32)}function RU(e){if(!Mg)return null;let t=vs.get(e);if(t&&Date.now()-t.createdAt<t.ttlMs)return t.hits++,t.response;t&&vs.delete(e),Xi();let n=Pr(oi,`${e}.json`);if(!tP(n))return null;try{let r=JSON.parse(nP(n,"utf-8"));if(Date.now()-r.createdAt<r.ttlMs)return vs.set(e,r),r.response;Pg(n)}catch{}return null}function PU(e,t,n=O$e){if(!Mg)return;let r={key:e,response:t,createdAt:Date.now(),ttlMs:n,hits:0};if(vs.set(e,r),vs.size>L$e){let s=vs.keys().next().value;s&&vs.delete(s)}Xi();try{O0(Pr(oi,`${e}.json`),JSON.stringify(r),"utf-8")}catch{}}function U$e(e){if(e){vs.delete(e);let t=Pr(oi,`${e}.json`);if(tP(t))try{Pg(t)}catch{}}else{vs.clear(),Xi();for(let t of B0(oi))try{Pg(Pr(oi,t))}catch{}}}function H$e(){Xi();let e=B0(oi).filter(r=>r.endsWith(".json")),t=e.reduce((r,s)=>{try{return r+N0(Pr(oi,s)).size}catch{return r}},0),n=Array.from(vs.values()).reduce((r,s)=>r+s.hits,0);return{memEntries:vs.size,diskEntries:e.length,totalHits:n,sizeKB:Math.round(t/1024)}}function z$e(){eP=!0}function IU(){return eP?(eP=!1,!0):!1}async function MU(e,t){let n=F0.get(e);if(n)return n;let r=t().finally(()=>F0.delete(e));return F0.set(e,r),r}function G$e(){return F0.size}function J$e(){rP=!0}function W$e(){rP=!1}function L0(e){if(rP){Xi();try{if(N0(cl).size>V$e){let n=cl+"."+Date.now();O0(n,nP(cl)),O0(cl,"")}}catch{}try{P$e(cl,JSON.stringify(e)+`
2095
- `,"utf-8")}catch{}}}function K$e(e=50){if(Xi(),!tP(cl))return[];try{return nP(cl,"utf-8").trim().split(`
2096
- `).slice(-e).map(n=>JSON.parse(n))}catch{return[]}}function Y$e(){sP=!0}function Q$e(){sP=!1}function Z$e(e,t,n={}){if(!sP)return null;Xi();let r=`dump_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,s=Pr(j0,`${r}.txt`);try{let i=["=== METADATA ===",JSON.stringify(n,null,2),"","=== SYSTEM PROMPT ===",e,"","=== MESSAGES ===",...t.map((o,a)=>`--- [${a}] ${o.role} ---
2104
+ - Natural conversational continuation`;try{let l=(await t.provider.sendMessage([{role:"user",content:o,timestamp:new Date().toISOString()}],"You predict likely next user prompts. Return ONLY valid JSON.",[],void 0)).content.replace(/```(?:json)?\s*/g,"").replace(/```/g,"").trim().match(/\[[\s\S]*\]/);if(!l)return[];let d=JSON.parse(l[0]).filter(f=>f.text&&f.confidence>=.5).slice(0,t.maxSuggestions||5).map(f=>({text:f.text.slice(0,120),category:f.category||"follow_up",confidence:Math.max(0,Math.min(1,f.confidence)),trigger:s.trigger,reasoning:f.reasoning||"AI speculative",generatedAt:L()}));return Tg.set(n,{suggestions:d,timestamp:Date.now()}),d}catch{return[]}}async function x$e(e,t={}){let n=t.limit||5,r=kU(e,{limit:n*2}),s=[];t.useSpeculative!==!1&&t.provider&&e.length>=4&&(s=await xU(e,{provider:t.provider,maxSuggestions:n}));let i=new Map;for(let o of[...s,...r]){let a=o.text.toLowerCase().trim();(!i.has(a)||i.get(a).confidence<o.confidence)&&i.set(a,o)}return Array.from(i.values()).sort((o,a)=>a.confidence-o.confidence).slice(0,n)}function Rg(){if(!bU(_g))return{acceptedSuggestions:{},rejectedSuggestions:{},categoryAffinities:{follow_up:1,related:1,action:1,question:1,verify:1,expand:1,fix:1,iterate:1},triggerHistory:{}};try{return JSON.parse(h$e(_g,"utf-8"))}catch{return Rg()}}function $U(e){y$e(SU(wU(),".aiaca"),{recursive:!0}),vU(_g,JSON.stringify(e,null,2),"utf-8")}function $$e(e){let t=Rg();t.acceptedSuggestions[e.text]=(t.acceptedSuggestions[e.text]||0)+1,t.categoryAffinities[e.category]=(t.categoryAffinities[e.category]||1)*1.05,e.trigger&&(t.triggerHistory[e.trigger]=(t.triggerHistory[e.trigger]||0)+1),$U(t)}function C$e(e){let t=Rg();t.rejectedSuggestions[e.text]=(t.rejectedSuggestions[e.text]||0)+1,t.categoryAffinities[e.category]=(t.categoryAffinities[e.category]||1)*.95,$U(t)}function A$e(e){let t=Rg();return e.map(n=>{let r=t.acceptedSuggestions[n.text]||0,s=t.rejectedSuggestions[n.text]||0,i=t.categoryAffinities[n.category]||1,o=n.confidence*i;return o+=r*.05,o-=s*.1,{...n,confidence:Math.max(0,Math.min(1,o))}})}function T$e(){let e=Rg(),t=Object.values(e.acceptedSuggestions).reduce((i,o)=>i+o,0),n=Object.values(e.rejectedSuggestions).reduce((i,o)=>i+o,0),r=Object.entries(e.categoryAffinities).sort((i,o)=>o[1]-i[1])[0]?.[0]||"action",s=Object.entries(e.acceptedSuggestions).sort((i,o)=>o[1]-i[1]).slice(0,5).map(([i,o])=>({text:i,uses:o}));return{totalAccepted:t,totalRejected:n,topCategory:r,topSuggestions:s}}function _$e(){bU(_g)&&vU(_g,JSON.stringify({acceptedSuggestions:{},rejectedSuggestions:{},categoryAffinities:{follow_up:1,related:1,action:1,question:1,verify:1,expand:1,fix:1,iterate:1},triggerHistory:{}},null,2))}function R$e(){Tg.clear()}function P$e(){let e=Date.now(),t=e;for(let n of Tg.values())n.timestamp<t&&(t=n.timestamp);return{entries:Tg.size,oldestMs:e-t}}var b$e,Tg,k$e,_g,AU=w(()=>{"use strict";b$e=[{id:"after_file_create",trigger:"created_file",weight:.9,generate:e=>{let t=e.filesModified[e.filesModified.length-1]||"this file";return[{text:"Run the tests",category:"action",confidence:.85,generatedAt:L()},{text:"Add error handling",category:"follow_up",confidence:.8,generatedAt:L()},{text:`Write tests for ${yU(t)}`,category:"action",confidence:.85,generatedAt:L()},{text:"Add type definitions",category:"follow_up",confidence:.75,generatedAt:L()},{text:"Document the function/class",category:"expand",confidence:.7,generatedAt:L()}]}},{id:"after_file_edit",trigger:"edited_file",weight:.85,generate:e=>[{text:"Run the tests to verify",category:"verify",confidence:.9,generatedAt:L()},{text:"Show me the full file now",category:"verify",confidence:.8,generatedAt:L()},{text:"What else needs to change?",category:"follow_up",confidence:.75,generatedAt:L()}]},{id:"after_error",trigger:"found_error",weight:1,generate:e=>[{text:"Show me the full error stack trace",category:"question",confidence:.9,generatedAt:L()},{text:"Try a different approach",category:"fix",confidence:.85,generatedAt:L()},{text:"Check the logs",category:"action",confidence:.8,generatedAt:L()},{text:"Search the web for this error",category:"action",confidence:.75,generatedAt:L()},{text:"Add logging to debug",category:"fix",confidence:.7,generatedAt:L()}]},{id:"after_install",trigger:/\b(npm install|pip install|cargo add|yarn add)\b/,weight:.8,generate:()=>[{text:"Update the imports",category:"follow_up",confidence:.85,generatedAt:L()},{text:"Show me how to use it",category:"question",confidence:.8,generatedAt:L()},{text:"Update the documentation",category:"follow_up",confidence:.65,generatedAt:L()}]},{id:"after_test_run",trigger:/\b(test|jest|pytest|cargo test|go test)\b/,weight:.85,generate:()=>[{text:"Fix the failing tests",category:"fix",confidence:.85,generatedAt:L()},{text:"Add more test coverage",category:"expand",confidence:.75,generatedAt:L()},{text:"Show test coverage report",category:"action",confidence:.7,generatedAt:L()}]},{id:"after_commit",trigger:/\b(commit|pushed|merged|pr|pull request)\b/i,weight:.8,generate:()=>[{text:"Create a pull request",category:"action",confidence:.85,generatedAt:L()},{text:"What should we work on next?",category:"question",confidence:.8,generatedAt:L()},{text:"Update the changelog",category:"follow_up",confidence:.7,generatedAt:L()}]},{id:"after_refactor",trigger:/\b(refactor|cleanup|improve|simplif)/i,weight:.85,generate:()=>[{text:"Run the linter",category:"verify",confidence:.9,generatedAt:L()},{text:"Are there other places to improve?",category:"expand",confidence:.8,generatedAt:L()},{text:"Run tests to verify behavior unchanged",category:"verify",confidence:.95,generatedAt:L()}]},{id:"after_explanation",trigger:/\b(explain|what.*does|how.*work|describe)/i,weight:.7,generate:()=>[{text:"Show me an example",category:"follow_up",confidence:.85,generatedAt:L()},{text:"Can you simplify it?",category:"question",confidence:.7,generatedAt:L()},{text:"Walk me through it step by step",category:"expand",confidence:.75,generatedAt:L()}]},{id:"after_search",trigger:"searched",weight:.7,generate:e=>{let t=e.filesRead[e.filesRead.length-1];return[{text:"Show me the most relevant result",category:"follow_up",confidence:.8,generatedAt:L()},...t?[{text:`Open ${yU(t)}`,category:"action",confidence:.75,generatedAt:L()}]:[],{text:"Refine the search",category:"iterate",confidence:.7,generatedAt:L()}]}},{id:"after_web_fetch",trigger:"browsed_web",weight:.6,generate:()=>[{text:"Summarize this for me",category:"follow_up",confidence:.8,generatedAt:L()},{text:"How does this apply to my project?",category:"question",confidence:.75,generatedAt:L()},{text:"Find related resources",category:"expand",confidence:.65,generatedAt:L()}]},{id:"after_fix",trigger:"fixed_bug",weight:.9,generate:()=>[{text:"Add a regression test",category:"action",confidence:.95,generatedAt:L()},{text:"Check for similar bugs elsewhere",category:"expand",confidence:.8,generatedAt:L()},{text:"Document the fix in the changelog",category:"follow_up",confidence:.65,generatedAt:L()}]},{id:"after_feature",trigger:"added_feature",weight:.85,generate:()=>[{text:"Write tests for the new feature",category:"action",confidence:.9,generatedAt:L()},{text:"Update the documentation",category:"follow_up",confidence:.85,generatedAt:L()},{text:"Add it to the changelog",category:"follow_up",confidence:.7,generatedAt:L()},{text:"What edge cases should we handle?",category:"question",confidence:.75,generatedAt:L()}]},{id:"default",trigger:"idle",weight:.3,generate:()=>[{text:"Explain this codebase",category:"question",confidence:.5,generatedAt:L()},{text:"Find and fix bugs",category:"action",confidence:.5,generatedAt:L()},{text:"Add tests",category:"action",confidence:.5,generatedAt:L()},{text:"Review my recent changes",category:"verify",confidence:.6,generatedAt:L()}]}];Tg=new Map,k$e=300*1e3;_g=SU(wU(),".aiaca","suggestion-prefs.json")});var U0={};$(U0,{breakCache:()=>G$e,cleanup:()=>rCe,dedupeRequest:()=>MU,disableCache:()=>N$e,disableLogging:()=>K$e,disablePromptDump:()=>Z$e,dumpPrompt:()=>X$e,enableCache:()=>B$e,enableLogging:()=>W$e,enablePromptDump:()=>Q$e,executeAPICall:()=>nCe,generateCacheKey:()=>U$e,getCacheStats:()=>z$e,getCached:()=>RU,getCircuitStatus:()=>tCe,getInflightCount:()=>V$e,getRecentLogs:()=>Y$e,invalidateCache:()=>H$e,isCacheEnabled:()=>q$e,isCircuitOpen:()=>FU,listDumps:()=>EU,logAPIEvent:()=>L0,recordFailure:()=>OU,recordSuccess:()=>LU,setCached:()=>PU,shouldBreakCache:()=>IU,withRetry:()=>_U});import{existsSync as tP,mkdirSync as D0,readFileSync as nP,writeFileSync as O0,appendFileSync as I$e,readdirSync as B0,statSync as N0,unlinkSync as Pg}from"fs";import{join as Pr}from"path";import{homedir as M$e}from"os";import{createHash as E$e}from"crypto";function Xi(){D0(q0,{recursive:!0}),D0(oi,{recursive:!0}),D0(TU,{recursive:!0}),D0(j0,{recursive:!0})}async function _U(e,t={}){let n={...D$e,...t},r=null;for(let s=0;s<=n.maxRetries;s++)try{return await e()}catch(i){r=i;let o=i.status||i.statusCode||i.response?.status,a=i.message||"";if(!(n.retryableStatuses.includes(o)||n.retryableErrors.some(p=>p.test(a)))||s===n.maxRetries)throw i;let l=F$e(i.headers?.["retry-after"]||i.response?.headers?.["retry-after"]),u=Math.min(n.baseDelayMs*Math.pow(2,s),n.maxDelayMs),d=n.jitter?.85+Math.random()*.3:1,f=l!==null?l:Math.floor(u*d);n.onRetry?.(s+1,i,f),await L$e(f)}throw r}function F$e(e){if(e===void 0)return null;if(typeof e=="number")return e*1e3;let t=parseInt(e,10);if(!isNaN(t))return t*1e3;let n=new Date(e).getTime();return isNaN(n)?null:Math.max(0,n-Date.now())}function L$e(e){return new Promise(t=>setTimeout(t,e))}function B$e(){Mg=!0}function N$e(){Mg=!1}function q$e(){return Mg}function U$e(e,t,n,r,s){let i=JSON.stringify({p:e,m:t,s:n,msgs:r.map(o=>({r:o.role,c:o.content})),t:[...s].sort()});return E$e("sha256").update(i).digest("hex").slice(0,32)}function RU(e){if(!Mg)return null;let t=vs.get(e);if(t&&Date.now()-t.createdAt<t.ttlMs)return t.hits++,t.response;t&&vs.delete(e),Xi();let n=Pr(oi,`${e}.json`);if(!tP(n))return null;try{let r=JSON.parse(nP(n,"utf-8"));if(Date.now()-r.createdAt<r.ttlMs)return vs.set(e,r),r.response;Pg(n)}catch{}return null}function PU(e,t,n=j$e){if(!Mg)return;let r={key:e,response:t,createdAt:Date.now(),ttlMs:n,hits:0};if(vs.set(e,r),vs.size>O$e){let s=vs.keys().next().value;s&&vs.delete(s)}Xi();try{O0(Pr(oi,`${e}.json`),JSON.stringify(r),"utf-8")}catch{}}function H$e(e){if(e){vs.delete(e);let t=Pr(oi,`${e}.json`);if(tP(t))try{Pg(t)}catch{}}else{vs.clear(),Xi();for(let t of B0(oi))try{Pg(Pr(oi,t))}catch{}}}function z$e(){Xi();let e=B0(oi).filter(r=>r.endsWith(".json")),t=e.reduce((r,s)=>{try{return r+N0(Pr(oi,s)).size}catch{return r}},0),n=Array.from(vs.values()).reduce((r,s)=>r+s.hits,0);return{memEntries:vs.size,diskEntries:e.length,totalHits:n,sizeKB:Math.round(t/1024)}}function G$e(){eP=!0}function IU(){return eP?(eP=!1,!0):!1}async function MU(e,t){let n=F0.get(e);if(n)return n;let r=t().finally(()=>F0.delete(e));return F0.set(e,r),r}function V$e(){return F0.size}function W$e(){rP=!0}function K$e(){rP=!1}function L0(e){if(rP){Xi();try{if(N0(cl).size>J$e){let n=cl+"."+Date.now();O0(n,nP(cl)),O0(cl,"")}}catch{}try{I$e(cl,JSON.stringify(e)+`
2105
+ `,"utf-8")}catch{}}}function Y$e(e=50){if(Xi(),!tP(cl))return[];try{return nP(cl,"utf-8").trim().split(`
2106
+ `).slice(-e).map(n=>JSON.parse(n))}catch{return[]}}function Q$e(){sP=!0}function Z$e(){sP=!1}function X$e(e,t,n={}){if(!sP)return null;Xi();let r=`dump_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,s=Pr(j0,`${r}.txt`);try{let i=["=== METADATA ===",JSON.stringify(n,null,2),"","=== SYSTEM PROMPT ===",e,"","=== MESSAGES ===",...t.map((o,a)=>`--- [${a}] ${o.role} ---
2097
2107
  ${o.content}
2098
2108
  `)].join(`
2099
- `);return O0(s,i,"utf-8"),s}catch{return null}}function EU(){return Xi(),B0(j0).filter(e=>e.endsWith(".txt")).map(e=>{try{let t=Pr(j0,e),n=N0(t);return{id:e.replace(".txt",""),path:t,sizeKB:Math.round(n.size/1024),createdAt:n.mtime.toISOString()}}catch{return null}}).filter(Boolean)}function FU(e){let t=Ig.get(e);return t?t.state==="open"&&Date.now()-t.lastFailure>DU?(t.state="half_open",!1):t.state==="open":!1}function LU(e){let t=Ig.get(e);t&&(t.successes++,t.failures=0,t.state==="half_open"&&(t.state="closed"))}function OU(e){let t=Ig.get(e)||{failures:0,successes:0,lastFailure:0,state:"closed"};t.failures++,t.lastFailure=Date.now(),t.failures>=X$e&&(t.state="open"),Ig.set(e,t)}function eCe(){return Object.fromEntries(Ig.entries())}async function tCe(e,t){let{cacheKey:n,cacheTTLMs:r,retryConfig:s,endpoint:i}=t;if(FU(i))throw new Error(`Circuit breaker open for ${i}. Try again in ${Math.round(DU/1e3)}s.`);if(n&&!IU()){let c=RU(n);if(c)return L0({timestamp:new Date().toISOString(),provider:"cache",model:"",type:"cache_hit",cacheKey:n}),c}let o=Date.now(),a=async()=>{try{let c=await _U(e,s);LU(i);let l=Date.now()-o;return L0({timestamp:new Date().toISOString(),provider:i,model:"",type:"response",durationMs:l,inputTokens:c.usage?.inputTokens,outputTokens:c.usage?.outputTokens}),n&&PU(n,c,r),c}catch(c){throw OU(i),L0({timestamp:new Date().toISOString(),provider:i,model:"",type:"error",error:c.message,durationMs:Date.now()-o}),c}};return n?MU(n,a):a()}function nCe(){Xi();let e=Date.now()-1440*60*1e3;for(let n of B0(oi))try{let r=Pr(oi,n);N0(r).mtimeMs<e&&Pg(r)}catch{}let t=EU().sort((n,r)=>r.createdAt.localeCompare(n.createdAt));for(let n of t.slice(50))try{Pg(n.path)}catch{}}var q0,oi,TU,j0,cl,E$e,vs,L$e,O$e,Mg,eP,F0,rP,V$e,sP,Ig,X$e,DU,H0=w(()=>{"use strict";q0=Pr(I$e(),".aiaca","api"),oi=Pr(q0,"cache"),TU=Pr(q0,"logs"),j0=Pr(q0,"dumps"),cl=Pr(TU,"api.log");E$e={maxRetries:3,baseDelayMs:1e3,maxDelayMs:6e4,jitter:!0,retryableStatuses:[408,425,429,500,502,503,504,529],retryableErrors:[/ECONNRESET/i,/ETIMEDOUT/i,/ENETUNREACH/i,/overloaded/i,/timeout/i,/socket hang up/i]};vs=new Map,L$e=100,O$e=300*1e3,Mg=!1;eP=!1;F0=new Map;rP=!1,V$e=10*1024*1024;sP=!1;Ig=new Map,X$e=5,DU=6e4});import{render as qCe}from"ink";import{useState as mt,useCallback as uP,useEffect as lH}from"react";import{Box as tr,Text as dl,useApp as jCe,useStdout as BCe,useInput as uH}from"ink";import{useState as bH,useEffect as vH}from"react";import{Box as to,Text as ir}from"ink";import{jsx as hr,jsxs as $s}from"react/jsx-runtime";var SH=[" \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551"," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551"," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D"],eS=["#ff6b6b","#ee5a24","#f0932b","#6ab04c","#22a6b3","#7c3aed"];function wH({animated:e=!0,subtitle:t}){let[n,r]=bH(0);return vH(()=>{if(!e)return;let s=setInterval(()=>r(i=>(i+1)%eS.length),400);return()=>clearInterval(s)},[e]),$s(to,{flexDirection:"column",alignItems:"center",marginBottom:1,children:[SH.map((s,i)=>hr(ir,{color:eS[(i+n)%eS.length],children:s},i)),t&&hr(to,{marginTop:1,children:$s(ir,{color:"gray",italic:!0,children:[" ",t]})})]})}function pP({provider:e,model:t,cwd:n,gitBranch:r,version:s="1.0.0"}){return $s(to,{flexDirection:"column",children:[hr(wH,{subtitle:`AI Agentic Coding Assistant v${s}`}),$s(to,{borderStyle:"single",borderColor:"gray",paddingX:2,paddingY:0,flexDirection:"column",children:[$s(to,{gap:1,children:[hr(ir,{color:"gray",children:"Provider:"}),hr(ir,{color:"cyan",bold:!0,children:e}),$s(ir,{color:"gray",children:["(",t,")"]})]}),$s(to,{gap:1,children:[hr(ir,{color:"gray",children:" CWD:"}),hr(ir,{children:n})]}),r&&$s(to,{gap:1,children:[hr(ir,{color:"gray",children:" Git:"}),$s(ir,{color:"green",children:["\u2387 ",r]})]}),$s(to,{gap:1,marginTop:1,children:[hr(ir,{color:"gray",children:"Type your prompt or"}),hr(ir,{color:"yellow",children:"/help"}),hr(ir,{color:"gray",children:"for commands \u2022"}),hr(ir,{color:"yellow",children:"Ctrl+C"}),hr(ir,{color:"gray",children:"to exit"})]})]})]})}import HU,{useState as zU,useEffect as rCe}from"react";import{Box as Ss,Text as Ut,useStdin as sCe,useStdout as iCe}from"ink";tf();Mr();Xg();pS();cf();import{execSync as ia}from"child_process";import{existsSync as jU,writeFileSync as iP}from"fs";import{join as Eg}from"path";var iz={default:{name:"default",colors:{primary:"#7c3aed",secondary:"#06b6d4",success:"#22c55e",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6",muted:"#6b7280",text:"#f9fafb",border:"#374151",prompt:"#7c3aed",toolName:"#06b6d4",toolOutput:"#9ca3af",diffAdded:"#22c55e",diffRemoved:"#ef4444",agent:["#f59e0b","#06b6d4","#8b5cf6","#ec4899"]}},dark:{name:"dark",colors:{primary:"#a78bfa",secondary:"#67e8f9",success:"#4ade80",error:"#f87171",warning:"#fbbf24",info:"#60a5fa",muted:"#9ca3af",text:"#ffffff",border:"#4b5563",prompt:"#a78bfa",toolName:"#67e8f9",toolOutput:"#d1d5db",diffAdded:"#4ade80",diffRemoved:"#f87171",agent:["#fbbf24","#67e8f9","#c084fc","#f472b6"]}},light:{name:"light",colors:{primary:"#6d28d9",secondary:"#0891b2",success:"#16a34a",error:"#dc2626",warning:"#d97706",info:"#2563eb",muted:"#4b5563",text:"#111827",border:"#d1d5db",prompt:"#6d28d9",toolName:"#0891b2",toolOutput:"#6b7280",diffAdded:"#16a34a",diffRemoved:"#dc2626",agent:["#d97706","#0891b2","#7c3aed","#db2777"]}},ocean:{name:"ocean",colors:{primary:"#0ea5e9",secondary:"#14b8a6",success:"#10b981",error:"#f43f5e",warning:"#f59e0b",info:"#06b6d4",muted:"#64748b",text:"#f0f9ff",border:"#1e3a5f",prompt:"#0ea5e9",toolName:"#14b8a6",toolOutput:"#94a3b8",diffAdded:"#10b981",diffRemoved:"#f43f5e",agent:["#f59e0b","#14b8a6","#8b5cf6","#ec4899"]}}};function NP(){return Object.keys(iz)}Ls();mu();import{execSync as kwe}from"child_process";function Hq(e){try{let t=kwe("git worktree list --porcelain",{cwd:e,encoding:"utf-8"}),n=[],r={};for(let s of t.split(`
2100
- `))s.startsWith("worktree ")?r={path:s.slice(9)}:s.startsWith("HEAD ")?r.head=s.slice(5):s.startsWith("branch ")?r.branch=s.slice(7).replace("refs/heads/",""):s==="bare"?r.isBare=!0:s===""&&(r.path&&n.push({path:r.path,branch:r.branch||"detached",head:r.head||"",isBare:!!r.isBare,isMain:n.length===0}),r={});return n}catch{return[]}}tA();import{existsSync as gFe,mkdirSync as Gq,readdirSync as hFe,readFileSync as yFe,writeFileSync as xwe}from"fs";import{join as S1}from"path";import{homedir as $we}from"os";var zq=S1($we(),".aiaca","plugins"),w1=new Map;function Cwe(){return Gq(zq,{recursive:!0}),zq}function Vq(){return Array.from(w1.values())}function Jq(e,t){let n=S1(Cwe(),e);Gq(n,{recursive:!0});let r={name:e,version:"1.0.0",description:`Plugin: ${e}`};return xwe(S1(n,"manifest.json"),JSON.stringify(r,null,2),"utf-8"),`Plugin "${e}" installed at ${n}`}function Wq(e){return w1.get(e)?(w1.delete(e),!0):!1}import{execSync as Kq}from"child_process";var v0={enabled:!1,recording:!1,lastTranscript:""};function Awe(){try{return process.platform==="win32"?(Kq("where whisper",{encoding:"utf-8",timeout:2e3}),!0):(Kq("which whisper",{encoding:"utf-8",timeout:2e3}),!0)}catch{return!1}}function Yq(){return Awe()?(v0.enabled=!0,!0):!1}function Qq(){v0.enabled=!1,v0.recording=!1}function Zq(){return{...v0}}import{existsSync as $Fe,mkdirSync as CFe,readFileSync as AFe,writeFileSync as TFe}from"fs";import{join as Twe}from"path";import{homedir as _we}from"os";var IFe=Twe(_we(),".aiaca","recordings");function Xq(e,t="markdown"){return t==="json"?JSON.stringify(e,null,2):e.map(n=>{let r=n.role==="user"?"**You**":"**AIACA**",s=n.timestamp.slice(11,19);return`### ${r} (${s})
2109
+ `);return O0(s,i,"utf-8"),s}catch{return null}}function EU(){return Xi(),B0(j0).filter(e=>e.endsWith(".txt")).map(e=>{try{let t=Pr(j0,e),n=N0(t);return{id:e.replace(".txt",""),path:t,sizeKB:Math.round(n.size/1024),createdAt:n.mtime.toISOString()}}catch{return null}}).filter(Boolean)}function FU(e){let t=Ig.get(e);return t?t.state==="open"&&Date.now()-t.lastFailure>DU?(t.state="half_open",!1):t.state==="open":!1}function LU(e){let t=Ig.get(e);t&&(t.successes++,t.failures=0,t.state==="half_open"&&(t.state="closed"))}function OU(e){let t=Ig.get(e)||{failures:0,successes:0,lastFailure:0,state:"closed"};t.failures++,t.lastFailure=Date.now(),t.failures>=eCe&&(t.state="open"),Ig.set(e,t)}function tCe(){return Object.fromEntries(Ig.entries())}async function nCe(e,t){let{cacheKey:n,cacheTTLMs:r,retryConfig:s,endpoint:i}=t;if(FU(i))throw new Error(`Circuit breaker open for ${i}. Try again in ${Math.round(DU/1e3)}s.`);if(n&&!IU()){let c=RU(n);if(c)return L0({timestamp:new Date().toISOString(),provider:"cache",model:"",type:"cache_hit",cacheKey:n}),c}let o=Date.now(),a=async()=>{try{let c=await _U(e,s);LU(i);let l=Date.now()-o;return L0({timestamp:new Date().toISOString(),provider:i,model:"",type:"response",durationMs:l,inputTokens:c.usage?.inputTokens,outputTokens:c.usage?.outputTokens}),n&&PU(n,c,r),c}catch(c){throw OU(i),L0({timestamp:new Date().toISOString(),provider:i,model:"",type:"error",error:c.message,durationMs:Date.now()-o}),c}};return n?MU(n,a):a()}function rCe(){Xi();let e=Date.now()-1440*60*1e3;for(let n of B0(oi))try{let r=Pr(oi,n);N0(r).mtimeMs<e&&Pg(r)}catch{}let t=EU().sort((n,r)=>r.createdAt.localeCompare(n.createdAt));for(let n of t.slice(50))try{Pg(n.path)}catch{}}var q0,oi,TU,j0,cl,D$e,vs,O$e,j$e,Mg,eP,F0,rP,J$e,sP,Ig,eCe,DU,H0=w(()=>{"use strict";q0=Pr(M$e(),".aiaca","api"),oi=Pr(q0,"cache"),TU=Pr(q0,"logs"),j0=Pr(q0,"dumps"),cl=Pr(TU,"api.log");D$e={maxRetries:3,baseDelayMs:1e3,maxDelayMs:6e4,jitter:!0,retryableStatuses:[408,425,429,500,502,503,504,529],retryableErrors:[/ECONNRESET/i,/ETIMEDOUT/i,/ENETUNREACH/i,/overloaded/i,/timeout/i,/socket hang up/i]};vs=new Map,O$e=100,j$e=300*1e3,Mg=!1;eP=!1;F0=new Map;rP=!1,J$e=10*1024*1024;sP=!1;Ig=new Map,eCe=5,DU=6e4});import{render as UCe}from"ink";import{useState as mt,useCallback as uP,useEffect as lH}from"react";import{Box as tr,Text as dl,useApp as BCe,useStdout as NCe,useInput as uH}from"ink";import{useState as bH,useEffect as vH}from"react";import{Box as to,Text as ir}from"ink";import{jsx as hr,jsxs as $s}from"react/jsx-runtime";var SH=[" \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551"," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551"," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D"],eS=["#ff6b6b","#ee5a24","#f0932b","#6ab04c","#22a6b3","#7c3aed"];function wH({animated:e=!0,subtitle:t}){let[n,r]=bH(0);return vH(()=>{if(!e)return;let s=setInterval(()=>r(i=>(i+1)%eS.length),400);return()=>clearInterval(s)},[e]),$s(to,{flexDirection:"column",alignItems:"center",marginBottom:1,children:[SH.map((s,i)=>hr(ir,{color:eS[(i+n)%eS.length],children:s},i)),t&&hr(to,{marginTop:1,children:$s(ir,{color:"gray",italic:!0,children:[" ",t]})})]})}function pP({provider:e,model:t,cwd:n,gitBranch:r,version:s="1.0.0"}){return $s(to,{flexDirection:"column",children:[hr(wH,{subtitle:`AI Agentic Coding Assistant v${s}`}),$s(to,{borderStyle:"single",borderColor:"gray",paddingX:2,paddingY:0,flexDirection:"column",children:[$s(to,{gap:1,children:[hr(ir,{color:"gray",children:"Provider:"}),hr(ir,{color:"cyan",bold:!0,children:e}),$s(ir,{color:"gray",children:["(",t,")"]})]}),$s(to,{gap:1,children:[hr(ir,{color:"gray",children:" CWD:"}),hr(ir,{children:n})]}),r&&$s(to,{gap:1,children:[hr(ir,{color:"gray",children:" Git:"}),$s(ir,{color:"green",children:["\u2387 ",r]})]}),$s(to,{gap:1,marginTop:1,children:[hr(ir,{color:"gray",children:"Type your prompt or"}),hr(ir,{color:"yellow",children:"/help"}),hr(ir,{color:"gray",children:"for commands \u2022"}),hr(ir,{color:"yellow",children:"Ctrl+C"}),hr(ir,{color:"gray",children:"to exit"})]})]})]})}import HU,{useState as zU,useEffect as sCe}from"react";import{Box as Ss,Text as Ut,useStdin as iCe,useStdout as oCe}from"ink";tf();Mr();Xg();pS();cf();import{execSync as ia}from"child_process";import{existsSync as jU,writeFileSync as iP}from"fs";import{join as Eg}from"path";var iz={default:{name:"default",colors:{primary:"#7c3aed",secondary:"#06b6d4",success:"#22c55e",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6",muted:"#6b7280",text:"#f9fafb",border:"#374151",prompt:"#7c3aed",toolName:"#06b6d4",toolOutput:"#9ca3af",diffAdded:"#22c55e",diffRemoved:"#ef4444",agent:["#f59e0b","#06b6d4","#8b5cf6","#ec4899"]}},dark:{name:"dark",colors:{primary:"#a78bfa",secondary:"#67e8f9",success:"#4ade80",error:"#f87171",warning:"#fbbf24",info:"#60a5fa",muted:"#9ca3af",text:"#ffffff",border:"#4b5563",prompt:"#a78bfa",toolName:"#67e8f9",toolOutput:"#d1d5db",diffAdded:"#4ade80",diffRemoved:"#f87171",agent:["#fbbf24","#67e8f9","#c084fc","#f472b6"]}},light:{name:"light",colors:{primary:"#6d28d9",secondary:"#0891b2",success:"#16a34a",error:"#dc2626",warning:"#d97706",info:"#2563eb",muted:"#4b5563",text:"#111827",border:"#d1d5db",prompt:"#6d28d9",toolName:"#0891b2",toolOutput:"#6b7280",diffAdded:"#16a34a",diffRemoved:"#dc2626",agent:["#d97706","#0891b2","#7c3aed","#db2777"]}},ocean:{name:"ocean",colors:{primary:"#0ea5e9",secondary:"#14b8a6",success:"#10b981",error:"#f43f5e",warning:"#f59e0b",info:"#06b6d4",muted:"#64748b",text:"#f0f9ff",border:"#1e3a5f",prompt:"#0ea5e9",toolName:"#14b8a6",toolOutput:"#94a3b8",diffAdded:"#10b981",diffRemoved:"#f43f5e",agent:["#f59e0b","#14b8a6","#8b5cf6","#ec4899"]}}};function NP(){return Object.keys(iz)}Ls();mu();import{execSync as xwe}from"child_process";function Hq(e){try{let t=xwe("git worktree list --porcelain",{cwd:e,encoding:"utf-8"}),n=[],r={};for(let s of t.split(`
2110
+ `))s.startsWith("worktree ")?r={path:s.slice(9)}:s.startsWith("HEAD ")?r.head=s.slice(5):s.startsWith("branch ")?r.branch=s.slice(7).replace("refs/heads/",""):s==="bare"?r.isBare=!0:s===""&&(r.path&&n.push({path:r.path,branch:r.branch||"detached",head:r.head||"",isBare:!!r.isBare,isMain:n.length===0}),r={});return n}catch{return[]}}tA();import{existsSync as hFe,mkdirSync as Gq,readdirSync as yFe,readFileSync as bFe,writeFileSync as $we}from"fs";import{join as S1}from"path";import{homedir as Cwe}from"os";var zq=S1(Cwe(),".aiaca","plugins"),w1=new Map;function Awe(){return Gq(zq,{recursive:!0}),zq}function Vq(){return Array.from(w1.values())}function Jq(e,t){let n=S1(Awe(),e);Gq(n,{recursive:!0});let r={name:e,version:"1.0.0",description:`Plugin: ${e}`};return $we(S1(n,"manifest.json"),JSON.stringify(r,null,2),"utf-8"),`Plugin "${e}" installed at ${n}`}function Wq(e){return w1.get(e)?(w1.delete(e),!0):!1}import{execSync as Kq}from"child_process";var v0={enabled:!1,recording:!1,lastTranscript:""};function Twe(){try{return process.platform==="win32"?(Kq("where whisper",{encoding:"utf-8",timeout:2e3}),!0):(Kq("which whisper",{encoding:"utf-8",timeout:2e3}),!0)}catch{return!1}}function Yq(){return Twe()?(v0.enabled=!0,!0):!1}function Qq(){v0.enabled=!1,v0.recording=!1}function Zq(){return{...v0}}import{existsSync as CFe,mkdirSync as AFe,readFileSync as TFe,writeFileSync as _Fe}from"fs";import{join as _we}from"path";import{homedir as Rwe}from"os";var MFe=_we(Rwe(),".aiaca","recordings");function Xq(e,t="markdown"){return t==="json"?JSON.stringify(e,null,2):e.map(n=>{let r=n.role==="user"?"**You**":"**AIACA**",s=n.timestamp.slice(11,19);return`### ${r} (${s})
2101
2111
 
2102
2112
  ${n.content}
2103
2113
  `}).join(`
2104
2114
  ---
2105
2115
 
2106
- `)}function e5(e,t){let n=[],r=e.toLowerCase();for(let s=0;s<t.length;s++){let i=t[s].content.toLowerCase();if(i.includes(r)){let o=i.indexOf(r),a=Math.max(0,o-40),c=Math.min(i.length,o+e.length+40);n.push({index:s,preview:t[s].content.slice(a,c)})}}return n}KA();function t5(e){let t=`-- ${e.mode.toUpperCase()} --`,n=`Col ${e.cursor}`;return`${t} ${n}`}import{spawn as FFe}from"child_process";var Rwe=new Map;function n5(){return Array.from(Rwe.values())}Rp();var oP=[{name:"help",aliases:["h","?"],description:"Show available commands",handler:async()=>oP.map(e=>` /${e.name.padEnd(16)} ${e.description}`).join(`
2116
+ `)}function e5(e,t){let n=[],r=e.toLowerCase();for(let s=0;s<t.length;s++){let i=t[s].content.toLowerCase();if(i.includes(r)){let o=i.indexOf(r),a=Math.max(0,o-40),c=Math.min(i.length,o+e.length+40);n.push({index:s,preview:t[s].content.slice(a,c)})}}return n}KA();function t5(e){let t=`-- ${e.mode.toUpperCase()} --`,n=`Col ${e.cursor}`;return`${t} ${n}`}import{spawn as LFe}from"child_process";var Pwe=new Map;function n5(){return Array.from(Pwe.values())}Rp();var oP=[{name:"help",aliases:["h","?"],description:"Show available commands",handler:async()=>oP.map(e=>` /${e.name.padEnd(16)} ${e.description}`).join(`
2107
2117
  `)},{name:"clear",description:"Clear conversation history",handler:async(e,t)=>(t.clearHistory(),"History cleared.")},{name:"compact",description:"Compact conversation to save context",handler:async(e,t)=>{await t.compact()}},{name:"exit",aliases:["quit","q"],description:"Exit AIACA",handler:async(e,t)=>{try{let n=await Promise.resolve().then(()=>(Wu(),Ju));if(n.getConfig().enabled){let r=await n.purge("explicit_exit");r.success||console.error(`\u26A0\uFE0F Purge had warnings: ${r.warnings.join(", ")}`)}}catch{}t.exit()}},{name:"sessions",aliases:["session"],description:"List recent sessions",handler:async()=>{let e=Yg().slice(0,10);return e.length?e.map(t=>` ${t.id.slice(0,12)} | ${t.startedAt.slice(0,16)} | ${t.messageCount} msgs`).join(`
2108
2118
  `):"No sessions."}},{name:"login",description:"Set or update API credentials",handler:async()=>{let{runSetupWizard:e}=await Promise.resolve().then(()=>(hl(),rf));console.log(`
2109
2119
  Exiting AIACA to run the setup wizard...
@@ -2556,15 +2566,15 @@ ${f}`}},{name:"doctor",description:"Diagnose common issues",handler:async(e,t)=>
2556
2566
  `)}},{name:"feedback",description:"Send feedback",handler:async e=>e.trim()?`Feedback recorded: "${e.trim()}" (Thank you!)`:"Usage: /feedback <message>"},{name:"stats",description:"Show session statistics",handler:async(e,t)=>{let n=t.session.messages,r=n.filter(o=>o.role==="user").length,s=n.filter(o=>o.role==="assistant").length,i=Ub(n);return`Messages: ${n.length} (${r} user, ${s} assistant)
2557
2567
  Tokens: ~${i.toLocaleString()}
2558
2568
  Cost: ${ma(t.costTracker.totalCostUSD)}`}},{name:"summary",description:"Generate conversation summary",handler:async(e,t)=>t.session.messages.length<2?"Too few messages.":`Session: ${t.session.messages.length} messages over ${t.costTracker.getSummary().duration}
2559
- Topics: ${t.session.messages.filter(n=>n.role==="user").slice(0,3).map(n=>n.content.slice(0,50)).join("; ")}`}];function BU(){return oP}function NU(e){return oP.find(t=>t.name===e||t.aliases?.includes(e))}function qU(e){return e.startsWith("/")}function UU(e){let t=e.slice(1).trim(),n=t.indexOf(" ");return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1)}}import{jsx as Qt,jsxs as Kr}from"react/jsx-runtime";function aP({onSubmit:e,disabled:t=!1,prefix:n,placeholder:r}){let[s,i]=zU(""),[o,a]=zU(0),{stdin:c}=sCe(),{stdout:l}=iCe(),u=(l?.columns||80)-4,d=BU(),f=s.startsWith("/")&&!s.includes(" ")&&s.length>0,p=s.slice(1).toLowerCase(),[m,g]=HU.useState([]);HU.useEffect(()=>{if(!f||s.length===0){g([]);return}Promise.resolve().then(()=>(rg(),ng)).then(S=>{if(!S.getConfig().enabled)return;let x=S.complete({input:s,cursorPosition:s.length,projectPath:process.cwd()});g(x.slice(0,10))}).catch(()=>{})},[s,f]);let h=f?m.length>0?m.map(S=>({name:S.text.startsWith("/")?S.text.slice(1):S.text,description:S.description||"",aliases:[]})):d.filter(S=>S.name.startsWith(p)||S.aliases?.some(x=>x.startsWith(p))).slice(0,10):[];if(rCe(()=>{if(t||!c)return;let S=x=>{let A=x.toString();if(A==="\r"||A===`
2560
- `){if(f&&h.length>0&&p.length>0){let I=h[o];if(I&&s!==`/${I.name}`){i(`/${I.name} `),a(0);return}}s.trim()&&(e(s.trim()),i(""),a(0));return}if(A===" "){f&&h.length>0&&(i(`/${h[o].name} `),a(0));return}if(A==="\x1B[A"){a(I=>Math.max(0,I-1));return}if(A==="\x1B[B"){a(I=>Math.min(h.length-1,I+1));return}if(A==="\x7F"||A==="\b"){i(I=>I.slice(0,-1)),a(0);return}if(A===""&&process.exit(0),A===""){i(""),a(0);return}if(A==="\x1B"&&x.length===1||A.startsWith("\x1B[")&&A!=="\x1B[A"&&A!=="\x1B[B")return;let j=A.replace(/\r\n/g,`
2569
+ Topics: ${t.session.messages.filter(n=>n.role==="user").slice(0,3).map(n=>n.content.slice(0,50)).join("; ")}`}];function BU(){return oP}function NU(e){return oP.find(t=>t.name===e||t.aliases?.includes(e))}function qU(e){return e.startsWith("/")}function UU(e){let t=e.slice(1).trim(),n=t.indexOf(" ");return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1)}}import{jsx as Qt,jsxs as Kr}from"react/jsx-runtime";function aP({onSubmit:e,disabled:t=!1,prefix:n,placeholder:r}){let[s,i]=zU(""),[o,a]=zU(0),{stdin:c}=iCe(),{stdout:l}=oCe(),u=(l?.columns||80)-4,d=BU(),f=s.startsWith("/")&&!s.includes(" ")&&s.length>0,p=s.slice(1).toLowerCase(),[m,g]=HU.useState([]);HU.useEffect(()=>{if(!f||s.length===0){g([]);return}Promise.resolve().then(()=>(rg(),ng)).then(S=>{if(!S.getConfig().enabled)return;let x=S.complete({input:s,cursorPosition:s.length,projectPath:process.cwd()});g(x.slice(0,10))}).catch(()=>{})},[s,f]);let h=f?m.length>0?m.map(S=>({name:S.text.startsWith("/")?S.text.slice(1):S.text,description:S.description||"",aliases:[]})):d.filter(S=>S.name.startsWith(p)||S.aliases?.some(x=>x.startsWith(p))).slice(0,10):[];if(sCe(()=>{if(t||!c)return;let S=x=>{let A=x.toString();if(A==="\r"||A===`
2570
+ `){if(f&&h.length>0&&p.length>0){let M=h[o];if(M&&s!==`/${M.name}`){i(`/${M.name} `),a(0);return}}s.trim()&&(e(s.trim()),i(""),a(0));return}if(A===" "){f&&h.length>0&&(i(`/${h[o].name} `),a(0));return}if(A==="\x1B[A"){a(M=>Math.max(0,M-1));return}if(A==="\x1B[B"){a(M=>Math.min(h.length-1,M+1));return}if(A==="\x7F"||A==="\b"){i(M=>M.slice(0,-1)),a(0);return}if(A===""&&process.exit(0),A===""){i(""),a(0);return}if(A==="\x1B"&&x.length===1||A.startsWith("\x1B[")&&A!=="\x1B[A"&&A!=="\x1B[B")return;let D=A.replace(/\r\n/g,`
2561
2571
  `).replace(/\r/g,`
2562
- `).replace(/[^\x20-\x7E\n\u00A0-\uFFFF]/g,"");j&&(i(I=>I+j),a(0))};return c.on("data",S),()=>{c.off("data",S)}},[c,t,s,e,f,h,o,p]),t)return Qt(Ss,{children:Qt(Ut,{color:"gray",dimColor:!0,children:" waiting for response... (Esc to stop)"})});if(n)return Qt(Ss,{children:Qt(Ut,{color:"gray",children:n})});if(!s)return Kr(Ss,{children:[Qt(Ut,{color:"gray",children:"\u2502"}),Qt(Ut,{color:"gray",dimColor:!0,children:r||"ask a question or describe a task \u21B5"})]});let v=s.includes(`
2572
+ `).replace(/[^\x20-\x7E\n\u00A0-\uFFFF]/g,"");D&&(i(M=>M+D),a(0))};return c.on("data",S),()=>{c.off("data",S)}},[c,t,s,e,f,h,o,p]),t)return Qt(Ss,{children:Qt(Ut,{color:"gray",dimColor:!0,children:" waiting for response... (Esc to stop)"})});if(n)return Qt(Ss,{children:Qt(Ut,{color:"gray",children:n})});if(!s)return Kr(Ss,{children:[Qt(Ut,{color:"gray",children:"\u2502"}),Qt(Ut,{color:"gray",dimColor:!0,children:r||"ask a question or describe a task \u21B5"})]});let v=s.includes(`
2563
2573
  `),y=s.split(`
2564
- `),b=v&&(s.includes("{")||s.includes("import ")||s.includes("//")||s.includes("function "));if(v){let x=y.slice(0,12),A=y.length-12;return Kr(Ss,{flexDirection:"column",children:[Kr(Ss,{borderStyle:"round",borderColor:b?"cyan":"gray",flexDirection:"column",paddingX:1,children:[b&&Kr(Ut,{color:"cyan",dimColor:!0,children:[" pasted code (",y.length," lines)"]}),x.map((j,I)=>Kr(Ut,{color:b?"green":"white",wrap:"truncate",children:[b?`${String(I+1).padStart(3)} \u2502 `:"",j.slice(0,u)]},I)),A>0&&Kr(Ut,{color:"gray",dimColor:!0,children:[" ... +",A," more lines"]})]}),Kr(Ss,{children:[Qt(Ut,{color:"gray",children:"\u2502"}),Qt(Ut,{color:"yellow",children:" Enter"}),Qt(Ut,{color:"gray",children:" to send \u2022 "}),Qt(Ut,{color:"yellow",children:"Ctrl+U"}),Qt(Ut,{color:"gray",children:" to clear"})]})]})}if(f&&h.length>0)return Kr(Ss,{flexDirection:"column",children:[Kr(Ss,{children:[Qt(Ut,{color:"gray",children:"\u2502"}),Qt(Ut,{color:"yellow",children:s}),Qt(Ut,{inverse:!0,children:" "})]}),Kr(Ss,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,marginLeft:1,children:[h.map((S,x)=>Kr(Ss,{gap:1,children:[Qt(Ut,{color:x===o?"cyan":"yellow",bold:x===o,inverse:x===o,children:` /${S.name.padEnd(14)} `}),Qt(Ut,{color:"gray",children:S.description})]},S.name)),Qt(Ut,{color:"gray",dimColor:!0,children:" \u2191\u2193 navigate \u2022 Tab complete \u2022 Enter select"})]})]});let k=s.length>u?"..."+s.slice(-(u-3)):s;return Kr(Ss,{children:[Qt(Ut,{color:"gray",children:"\u2502"}),Qt(Ut,{children:k}),Qt(Ut,{inverse:!0,children:" "})]})}cf();import{Box as z0,Text as ai,useStdout as oCe}from"ink";import{Fragment as aCe,jsx as ci,jsxs as Dg}from"react/jsx-runtime";function G0({provider:e,model:t,mode:n,costTracker:r,messageCount:s,cwd:i}){let{stdout:o}=oCe(),a=o?.columns||80,c=r.getSummary(),l=Math.min(100,Math.round(c.totalTokens/2e5*100)),u=l>80?"red":l>50?"yellow":"green",d=i?i.length>28?"\u2026"+i.slice(-28):i:"",f=t.replace(/-\d{8}$/,"").replace(/-preview$/,""),p=c.totalCostUSD||0,m=c.totalTokens||0,g=m>=1e3?`${(m/1e3).toFixed(1)}k`:String(m);return Dg(z0,{marginTop:1,children:[Dg(z0,{gap:1,children:[ci(ai,{color:"cyan",bold:!0,children:e}),ci(ai,{color:"gray",dimColor:!0,children:f}),ci(ai,{color:"gray",children:"\u2022"}),ci(ai,{color:n==="plan"?"yellow":n==="bypass"?"red":"green",children:n}),ci(ai,{color:"gray",children:"\u2022"}),Dg(ai,{color:u,children:["\u2B24 ",l,"%"]}),Dg(ai,{color:"gray",dimColor:!0,children:["(",g," tok)"]}),p>0?Dg(aCe,{children:[ci(ai,{color:"gray",children:"\u2022"}),ci(ai,{color:"gray",dimColor:!0,children:ma(p)})]}):null]}),ci(z0,{flexGrow:1}),ci(z0,{children:ci(ai,{color:"gray",dimColor:!0,children:d})})]})}import{Box as Yd,Text as Fg}from"ink";import{jsx as oa,jsxs as cP}from"react/jsx-runtime";var cCe=[{title:"Session",commands:[["/clear","Clear history"],["/compact","Compact conversation"],["/export","Export as markdown"],["/sessions","List sessions"],["/resume","Resume session"]]},{title:"Model & Config",commands:[["/model","Switch provider/model"],["/permissions","Change permission mode"],["/config","View/set config"],["/theme","Change theme"]]},{title:"Development",commands:[["/diff","Show git diff"],["/status","Git status"],["/branch","Git branches"],["/commit","Create commit"],["/review","Code review"]]},{title:"Context",commands:[["/memory","Project memory"],["/context","Context usage"],["/files","Referenced files"],["/init","Create AIACA.md"]]},{title:"System",commands:[["/cost","Session cost"],["/tools","List tools"],["/doctor","Diagnose issues"],["/version","Show version"],["/exit","Exit AIACA"]]}];function GU({visible:e}){return e?cP(Yd,{flexDirection:"column",borderStyle:"double",borderColor:"magenta",paddingX:2,paddingY:1,children:[oa(Yd,{justifyContent:"center",marginBottom:1,children:oa(Fg,{bold:!0,color:"magenta",children:"AIACA Commands"})}),oa(Yd,{flexWrap:"wrap",gap:2,children:cCe.map(t=>cP(Yd,{flexDirection:"column",width:30,children:[oa(Fg,{bold:!0,color:"cyan",children:t.title}),t.commands.map(([n,r])=>cP(Yd,{gap:1,children:[oa(Fg,{color:"yellow",children:n.padEnd(14)}),oa(Fg,{color:"gray",children:r})]},n))]},t.title))}),oa(Yd,{marginTop:1,justifyContent:"center",children:oa(Fg,{color:"gray",italic:!0,children:"Press any key to close"})})]}):null}import{Box as aa,Text as ll}from"ink";import{Box as Xn,Text as ae}from"ink";import{jsx as O,jsxs as Yr}from"react/jsx-runtime";function JU({content:e}){let t=SCe(e);return O(Xn,{flexDirection:"column",children:t.map((n,r)=>O(lCe,{block:n},r))})}function lCe({block:e}){switch(e.type){case"code":return O(uCe,{lang:e.lang,content:e.content});case"heading":return O(mCe,{level:e.level,text:e.text});case"list":return O(gCe,{items:e.items});case"ordered":return O(hCe,{items:e.items});case"quote":return O(yCe,{lines:e.lines});case"table":return O(bCe,{header:e.header,rows:e.rows});case"hr":return O(Xn,{marginY:0,children:O(ae,{color:"gray",children:"\u2500".repeat(60)})});case"paragraph":return O(vCe,{text:e.text})}}function uCe({lang:e,content:t}){let n=t.split(`
2565
- `);return Yr(Xn,{flexDirection:"column",marginY:1,borderStyle:"round",borderColor:"gray",paddingX:1,children:[e?Yr(ae,{color:"gray",dimColor:!0,children:[" ",e]}):null,n.map((r,s)=>Yr(Xn,{children:[Yr(ae,{color:"gray",dimColor:!0,children:[String(s+1).padStart(3)," \u2502 "]}),O(ae,{children:pCe(r)})]},s))]})}var dCe=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","import","export","from","as","default","class","extends","implements","new","async","await","try","catch","finally","throw","typeof","instanceof","in","of","this","super","yield","static","public","private","protected","def","elif","lambda","and","or","not","pass","void","func","package","type","interface","struct","enum","match","fn","use","pub","impl","mut","with","global","nonlocal","raise","except","using"]),fCe=new Set(["true","false","null","undefined","None","True","False","NaN","Infinity","self"]),Lg=/(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|(`[^`]*`|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')|(\b\d+(?:\.\d+)?\b)|([A-Za-z_$][A-Za-z0-9_$]*)/g;function pCe(e){let t=[],n=0,r;Lg.lastIndex=0;let s=0;for(;(r=Lg.exec(e))!==null;){if(r.index>n&&t.push(O(ae,{children:e.slice(n,r.index)},s++)),r[1])t.push(O(ae,{color:"gray",dimColor:!0,children:r[1]},s++));else if(r[2])t.push(O(ae,{color:"greenBright",children:r[2]},s++));else if(r[3])t.push(O(ae,{color:"yellow",children:r[3]},s++));else if(r[4]){let i=r[4];dCe.has(i)?t.push(O(ae,{color:"magenta",children:i},s++)):fCe.has(i)?t.push(O(ae,{color:"yellow",children:i},s++)):t.push(O(ae,{children:i},s++))}n=Lg.lastIndex,r.index===Lg.lastIndex&&Lg.lastIndex++}return n<e.length&&t.push(O(ae,{children:e.slice(n)},s++)),t.length?t:[O(ae,{children:" "},0)]}function mCe({level:e,text:t}){let r=["magenta","cyan","blue"][Math.min(e-1,2)];return Yr(Xn,{marginTop:1,children:[O(ae,{bold:!0,color:r,children:e===1?"\u2588 ":e===2?"\u258C ":"\u258E "}),O(ae,{bold:!0,color:r,children:jg(t)})]})}function gCe({items:e}){return O(Xn,{flexDirection:"column",paddingLeft:2,children:e.map((t,n)=>Yr(Xn,{children:[O(ae,{color:"cyan",children:" \u2022 "}),O(ae,{children:jg(t)})]},n))})}function hCe({items:e}){return O(Xn,{flexDirection:"column",paddingLeft:2,children:e.map((t,n)=>Yr(Xn,{children:[Yr(ae,{color:"cyan",children:[String(n+1).padStart(3),". "]}),O(ae,{children:jg(t)})]},n))})}function yCe({lines:e}){return O(Xn,{flexDirection:"column",marginY:0,paddingLeft:1,children:e.map((t,n)=>Yr(Xn,{children:[O(ae,{color:"gray",children:"\u2502 "}),O(ae,{color:"gray",italic:!0,children:jg(t)})]},n))})}function bCe({header:e,rows:t}){let n=e.length,r=[];for(let i=0;i<n;i++){let o=e[i]?.length||0;for(let a of t)o=Math.max(o,(a[i]||"").length);r[i]=Math.min(Math.max(o,3),40)}let s=(i,o)=>i.length>o?i.slice(0,o-1)+"\u2026":i.padEnd(o);return Yr(Xn,{flexDirection:"column",marginY:1,children:[O(Xn,{children:e.map((i,o)=>Yr(ae,{bold:!0,color:"cyan",children:[s(i,r[o]),o<n-1?" ":""]},o))}),O(ae,{color:"gray",children:r.map(i=>"\u2500".repeat(i)).join(" ")}),t.map((i,o)=>O(Xn,{children:r.map((a,c)=>Yr(ae,{children:[s(i[c]||"",a),c<n-1?" ":""]},c))},o))]})}function vCe({text:e}){return O(Xn,{children:O(ae,{children:jg(e)})})}var Og=/(\*\*|__)(.+?)\1|(\*|_)(.+?)\3|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)/g;function jg(e){let t=[],n=0,r,s=0;for(Og.lastIndex=0;(r=Og.exec(e))!==null;)r.index>n&&t.push(O(ae,{children:e.slice(n,r.index)},s++)),r[2]!==void 0?t.push(O(ae,{bold:!0,children:r[2]},s++)):r[4]!==void 0?t.push(O(ae,{italic:!0,children:r[4]},s++)):r[5]!==void 0?t.push(O(ae,{color:"yellowBright",children:r[5]},s++)):r[6]!==void 0&&t.push(O(ae,{color:"blue",underline:!0,children:r[6]},s++)),n=Og.lastIndex,r.index===Og.lastIndex&&Og.lastIndex++;return n<e.length&&t.push(O(ae,{children:e.slice(n)},s++)),t.length?t:[O(ae,{children:e},0)]}function SCe(e){let t=[],n=e.split(`
2574
+ `),b=v&&(s.includes("{")||s.includes("import ")||s.includes("//")||s.includes("function "));if(v){let x=y.slice(0,12),A=y.length-12;return Kr(Ss,{flexDirection:"column",children:[Kr(Ss,{borderStyle:"round",borderColor:b?"cyan":"gray",flexDirection:"column",paddingX:1,children:[b&&Kr(Ut,{color:"cyan",dimColor:!0,children:[" pasted code (",y.length," lines)"]}),x.map((D,M)=>Kr(Ut,{color:b?"green":"white",wrap:"truncate",children:[b?`${String(M+1).padStart(3)} \u2502 `:"",D.slice(0,u)]},M)),A>0&&Kr(Ut,{color:"gray",dimColor:!0,children:[" ... +",A," more lines"]})]}),Kr(Ss,{children:[Qt(Ut,{color:"gray",children:"\u2502"}),Qt(Ut,{color:"yellow",children:" Enter"}),Qt(Ut,{color:"gray",children:" to send \u2022 "}),Qt(Ut,{color:"yellow",children:"Ctrl+U"}),Qt(Ut,{color:"gray",children:" to clear"})]})]})}if(f&&h.length>0)return Kr(Ss,{flexDirection:"column",children:[Kr(Ss,{children:[Qt(Ut,{color:"gray",children:"\u2502"}),Qt(Ut,{color:"yellow",children:s}),Qt(Ut,{inverse:!0,children:" "})]}),Kr(Ss,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,marginLeft:1,children:[h.map((S,x)=>Kr(Ss,{gap:1,children:[Qt(Ut,{color:x===o?"cyan":"yellow",bold:x===o,inverse:x===o,children:` /${S.name.padEnd(14)} `}),Qt(Ut,{color:"gray",children:S.description})]},S.name)),Qt(Ut,{color:"gray",dimColor:!0,children:" \u2191\u2193 navigate \u2022 Tab complete \u2022 Enter select"})]})]});let k=s.length>u?"..."+s.slice(-(u-3)):s;return Kr(Ss,{children:[Qt(Ut,{color:"gray",children:"\u2502"}),Qt(Ut,{children:k}),Qt(Ut,{inverse:!0,children:" "})]})}cf();import{Box as z0,Text as ai,useStdout as aCe}from"ink";import{Fragment as cCe,jsx as ci,jsxs as Dg}from"react/jsx-runtime";function G0({provider:e,model:t,mode:n,costTracker:r,messageCount:s,cwd:i}){let{stdout:o}=aCe(),a=o?.columns||80,c=r.getSummary(),l=Math.min(100,Math.round(c.totalTokens/2e5*100)),u=l>80?"red":l>50?"yellow":"green",d=i?i.length>28?"\u2026"+i.slice(-28):i:"",f=t.replace(/-\d{8}$/,"").replace(/-preview$/,""),p=c.totalCostUSD||0,m=c.totalTokens||0,g=m>=1e3?`${(m/1e3).toFixed(1)}k`:String(m);return Dg(z0,{marginTop:1,children:[Dg(z0,{gap:1,children:[ci(ai,{color:"cyan",bold:!0,children:e}),ci(ai,{color:"gray",dimColor:!0,children:f}),ci(ai,{color:"gray",children:"\u2022"}),ci(ai,{color:n==="plan"?"yellow":n==="bypass"?"red":"green",children:n}),ci(ai,{color:"gray",children:"\u2022"}),Dg(ai,{color:u,children:["\u2B24 ",l,"%"]}),Dg(ai,{color:"gray",dimColor:!0,children:["(",g," tok)"]}),p>0?Dg(cCe,{children:[ci(ai,{color:"gray",children:"\u2022"}),ci(ai,{color:"gray",dimColor:!0,children:ma(p)})]}):null]}),ci(z0,{flexGrow:1}),ci(z0,{children:ci(ai,{color:"gray",dimColor:!0,children:d})})]})}import{Box as Yd,Text as Fg}from"ink";import{jsx as oa,jsxs as cP}from"react/jsx-runtime";var lCe=[{title:"Session",commands:[["/clear","Clear history"],["/compact","Compact conversation"],["/export","Export as markdown"],["/sessions","List sessions"],["/resume","Resume session"]]},{title:"Model & Config",commands:[["/model","Switch provider/model"],["/permissions","Change permission mode"],["/config","View/set config"],["/theme","Change theme"]]},{title:"Development",commands:[["/diff","Show git diff"],["/status","Git status"],["/branch","Git branches"],["/commit","Create commit"],["/review","Code review"]]},{title:"Context",commands:[["/memory","Project memory"],["/context","Context usage"],["/files","Referenced files"],["/init","Create AIACA.md"]]},{title:"System",commands:[["/cost","Session cost"],["/tools","List tools"],["/doctor","Diagnose issues"],["/version","Show version"],["/exit","Exit AIACA"]]}];function GU({visible:e}){return e?cP(Yd,{flexDirection:"column",borderStyle:"double",borderColor:"magenta",paddingX:2,paddingY:1,children:[oa(Yd,{justifyContent:"center",marginBottom:1,children:oa(Fg,{bold:!0,color:"magenta",children:"AIACA Commands"})}),oa(Yd,{flexWrap:"wrap",gap:2,children:lCe.map(t=>cP(Yd,{flexDirection:"column",width:30,children:[oa(Fg,{bold:!0,color:"cyan",children:t.title}),t.commands.map(([n,r])=>cP(Yd,{gap:1,children:[oa(Fg,{color:"yellow",children:n.padEnd(14)}),oa(Fg,{color:"gray",children:r})]},n))]},t.title))}),oa(Yd,{marginTop:1,justifyContent:"center",children:oa(Fg,{color:"gray",italic:!0,children:"Press any key to close"})})]}):null}import{Box as aa,Text as ll}from"ink";import{Box as Xn,Text as ce}from"ink";import{jsx as j,jsxs as Yr}from"react/jsx-runtime";function JU({content:e}){let t=wCe(e);return j(Xn,{flexDirection:"column",children:t.map((n,r)=>j(uCe,{block:n},r))})}function uCe({block:e}){switch(e.type){case"code":return j(dCe,{lang:e.lang,content:e.content});case"heading":return j(gCe,{level:e.level,text:e.text});case"list":return j(hCe,{items:e.items});case"ordered":return j(yCe,{items:e.items});case"quote":return j(bCe,{lines:e.lines});case"table":return j(vCe,{header:e.header,rows:e.rows});case"hr":return j(Xn,{marginY:0,children:j(ce,{color:"gray",children:"\u2500".repeat(60)})});case"paragraph":return j(SCe,{text:e.text})}}function dCe({lang:e,content:t}){let n=t.split(`
2575
+ `);return Yr(Xn,{flexDirection:"column",marginY:1,borderStyle:"round",borderColor:"gray",paddingX:1,children:[e?Yr(ce,{color:"gray",dimColor:!0,children:[" ",e]}):null,n.map((r,s)=>Yr(Xn,{children:[Yr(ce,{color:"gray",dimColor:!0,children:[String(s+1).padStart(3)," \u2502 "]}),j(ce,{children:mCe(r)})]},s))]})}var fCe=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","import","export","from","as","default","class","extends","implements","new","async","await","try","catch","finally","throw","typeof","instanceof","in","of","this","super","yield","static","public","private","protected","def","elif","lambda","and","or","not","pass","void","func","package","type","interface","struct","enum","match","fn","use","pub","impl","mut","with","global","nonlocal","raise","except","using"]),pCe=new Set(["true","false","null","undefined","None","True","False","NaN","Infinity","self"]),Lg=/(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|(`[^`]*`|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')|(\b\d+(?:\.\d+)?\b)|([A-Za-z_$][A-Za-z0-9_$]*)/g;function mCe(e){let t=[],n=0,r;Lg.lastIndex=0;let s=0;for(;(r=Lg.exec(e))!==null;){if(r.index>n&&t.push(j(ce,{children:e.slice(n,r.index)},s++)),r[1])t.push(j(ce,{color:"gray",dimColor:!0,children:r[1]},s++));else if(r[2])t.push(j(ce,{color:"greenBright",children:r[2]},s++));else if(r[3])t.push(j(ce,{color:"yellow",children:r[3]},s++));else if(r[4]){let i=r[4];fCe.has(i)?t.push(j(ce,{color:"magenta",children:i},s++)):pCe.has(i)?t.push(j(ce,{color:"yellow",children:i},s++)):t.push(j(ce,{children:i},s++))}n=Lg.lastIndex,r.index===Lg.lastIndex&&Lg.lastIndex++}return n<e.length&&t.push(j(ce,{children:e.slice(n)},s++)),t.length?t:[j(ce,{children:" "},0)]}function gCe({level:e,text:t}){let r=["magenta","cyan","blue"][Math.min(e-1,2)];return Yr(Xn,{marginTop:1,children:[j(ce,{bold:!0,color:r,children:e===1?"\u2588 ":e===2?"\u258C ":"\u258E "}),j(ce,{bold:!0,color:r,children:jg(t)})]})}function hCe({items:e}){return j(Xn,{flexDirection:"column",paddingLeft:2,children:e.map((t,n)=>Yr(Xn,{children:[j(ce,{color:"cyan",children:" \u2022 "}),j(ce,{children:jg(t)})]},n))})}function yCe({items:e}){return j(Xn,{flexDirection:"column",paddingLeft:2,children:e.map((t,n)=>Yr(Xn,{children:[Yr(ce,{color:"cyan",children:[String(n+1).padStart(3),". "]}),j(ce,{children:jg(t)})]},n))})}function bCe({lines:e}){return j(Xn,{flexDirection:"column",marginY:0,paddingLeft:1,children:e.map((t,n)=>Yr(Xn,{children:[j(ce,{color:"gray",children:"\u2502 "}),j(ce,{color:"gray",italic:!0,children:jg(t)})]},n))})}function vCe({header:e,rows:t}){let n=e.length,r=[];for(let i=0;i<n;i++){let o=e[i]?.length||0;for(let a of t)o=Math.max(o,(a[i]||"").length);r[i]=Math.min(Math.max(o,3),40)}let s=(i,o)=>i.length>o?i.slice(0,o-1)+"\u2026":i.padEnd(o);return Yr(Xn,{flexDirection:"column",marginY:1,children:[j(Xn,{children:e.map((i,o)=>Yr(ce,{bold:!0,color:"cyan",children:[s(i,r[o]),o<n-1?" ":""]},o))}),j(ce,{color:"gray",children:r.map(i=>"\u2500".repeat(i)).join(" ")}),t.map((i,o)=>j(Xn,{children:r.map((a,c)=>Yr(ce,{children:[s(i[c]||"",a),c<n-1?" ":""]},c))},o))]})}function SCe({text:e}){return j(Xn,{children:j(ce,{children:jg(e)})})}var Og=/(\*\*|__)(.+?)\1|(\*|_)(.+?)\3|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)/g;function jg(e){let t=[],n=0,r,s=0;for(Og.lastIndex=0;(r=Og.exec(e))!==null;)r.index>n&&t.push(j(ce,{children:e.slice(n,r.index)},s++)),r[2]!==void 0?t.push(j(ce,{bold:!0,children:r[2]},s++)):r[4]!==void 0?t.push(j(ce,{italic:!0,children:r[4]},s++)):r[5]!==void 0?t.push(j(ce,{color:"yellowBright",children:r[5]},s++)):r[6]!==void 0&&t.push(j(ce,{color:"blue",underline:!0,children:r[6]},s++)),n=Og.lastIndex,r.index===Og.lastIndex&&Og.lastIndex++;return n<e.length&&t.push(j(ce,{children:e.slice(n)},s++)),t.length?t:[j(ce,{children:e},0)]}function wCe(e){let t=[],n=e.split(`
2566
2576
  `),r=0;for(;r<n.length;){let s=n[r];if(s.startsWith("```")){let a=s.slice(3).trim(),c=[];for(r++;r<n.length&&!n[r].startsWith("```");)c.push(n[r]),r++;t.push({type:"code",lang:a,content:c.join(`
2567
2577
  `)}),r++;continue}let i=s.match(/^(#{1,6})\s+(.+)/);if(i){t.push({type:"heading",level:i[1].length,text:i[2]}),r++;continue}if(s.includes("|")&&r+1<n.length&&/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(n[r+1])&&n[r+1].includes("-")){let a=VU(s);r+=2;let c=[];for(;r<n.length&&n[r].includes("|")&&n[r].trim();)c.push(VU(n[r])),r++;t.push({type:"table",header:a,rows:c});continue}if(/^---+$/.test(s.trim())){t.push({type:"hr"}),r++;continue}if(/^\s*>\s?/.test(s)){let a=[];for(;r<n.length&&/^\s*>\s?/.test(n[r]);)a.push(n[r].replace(/^\s*>\s?/,"")),r++;t.push({type:"quote",lines:a});continue}if(/^\s*\d+\.\s+/.test(s)){let a=[];for(;r<n.length&&/^\s*\d+\.\s+/.test(n[r]);)a.push(n[r].replace(/^\s*\d+\.\s+/,"")),r++;t.push({type:"ordered",items:a});continue}if(/^\s*[-*]\s/.test(s)){let a=[];for(;r<n.length&&/^\s*[-*]\s/.test(n[r]);)a.push(n[r].replace(/^\s*[-*]\s+/,"")),r++;t.push({type:"list",items:a});continue}if(!s.trim()){r++;continue}let o=[];for(;r<n.length&&n[r].trim()&&!n[r].startsWith("#")&&!n[r].startsWith("```")&&!/^\s*[-*]\s/.test(n[r])&&!/^\s*\d+\.\s+/.test(n[r])&&!/^\s*>\s?/.test(n[r]);)o.push(n[r]),r++;o.length&&t.push({type:"paragraph",text:o.join(`
2568
- `)})}return t}function VU(e){return e.trim().replace(/^\||\|$/g,"").split("|").map(t=>t.trim())}import{jsx as Qr,jsxs as Qd}from"react/jsx-runtime";function V0({message:e,elapsed:t}){return e.role==="user"?Qr(wCe,{content:e.content}):Qr(kCe,{content:e.content,toolCalls:e.toolCalls,usage:e.usage,elapsed:t})}function wCe({content:e}){return Qr(aa,{flexDirection:"column",marginBottom:1,children:Qr(aa,{borderStyle:"single",borderColor:"cyan",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:1,children:Qr(ll,{color:"white",children:e})})})}function kCe({content:e,toolCalls:t,usage:n,elapsed:r}){return Qd(aa,{flexDirection:"column",marginBottom:1,children:[Qd(aa,{borderStyle:"single",borderColor:"magenta",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:1,flexDirection:"column",children:[t&&t.length>0&&Qr(aa,{flexDirection:"column",marginBottom:0,children:t.map(s=>Qd(aa,{gap:1,children:[Qr(ll,{color:"yellow",children:"\u26A1"}),Qr(ll,{color:"cyan",bold:!0,children:s.name}),Qr(ll,{color:"gray",children:xCe(s)})]},s.id))}),e?Qr(JU,{content:e}):null]}),n&&Qd(aa,{paddingLeft:2,marginTop:0,children:[Qd(ll,{color:"gray",dimColor:!0,children:["\u25B8 Tokens: ",(n.inputTokens+n.outputTokens).toLocaleString()]}),r!==void 0&&Qd(ll,{color:"gray",dimColor:!0,children:[" \u2022 Time: ",$Ce(r)]})]})]})}function xCe(e){let t=e.input;return e.name==="bash"||e.name==="powershell"?`$ ${t.command}`:e.name==="file_read"?`${t.path}`:e.name==="file_write"||e.name==="file_edit"?`${t.path}`:e.name==="grep"?`"${t.pattern}"`:e.name==="glob"?`${t.pattern}`:JSON.stringify(t).slice(0,50)}function $Ce(e){let t=Math.floor(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function WU({text:e,level:t}){return Qr(aa,{paddingLeft:2,marginBottom:1,children:Qr(ll,{color:t==="error"?"red":t==="warning"?"yellow":"gray",italic:!0,children:e})})}import{useState as ACe,useEffect as TCe}from"react";import{Box as Zd,Text as Zr}from"ink";import{Box as KU,Text as J0}from"ink";import{jsx as YU,jsxs as W0}from"react/jsx-runtime";function QU({diff:e,maxLines:t=12}){let n=CCe(e);if(n.length===0)return null;let r=n.slice(0,t),s=n.length-r.length,i=n.filter(a=>a.kind==="add").length,o=n.filter(a=>a.kind==="del").length;return W0(KU,{flexDirection:"column",paddingLeft:2,children:[(i>0||o>0)&&W0(KU,{gap:1,children:[W0(J0,{color:"greenBright",children:["+",i]}),W0(J0,{color:"redBright",children:["-",o]})]}),r.map((a,c)=>YU(J0,{color:a.kind==="add"?"greenBright":a.kind==="del"?"redBright":"gray",dimColor:a.kind==="ctx",wrap:"truncate-end",children:(a.kind==="add"?"+ ":a.kind==="del"?"- ":" ")+a.text},c)),s>0&&YU(J0,{color:"gray",dimColor:!0,children:` \u2026 +${s} more lines`})]})}function CCe(e){let t=[];for(let n of e.split(`
2569
- `))n.startsWith("+ ")?t.push({kind:"add",text:n.slice(2)}):n.startsWith("- ")?t.push({kind:"del",text:n.slice(2)}):n.startsWith(" ")&&t.push({kind:"ctx",text:n.slice(2)});return t}import{jsx as Ir,jsxs as ul}from"react/jsx-runtime";var ZU=["Pondering","Engineering","Crafting","Reasoning","Orchestrating","Assembling","Architecting","Composing","Strategizing","Forging"],XU=["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"],eH=["\u2726 \u25B0\u25B1\u25B1\u25B1","\u2727 \u25B0\u25B0\u25B1\u25B1","\u2726 \u25B1\u25B0\u25B0\u25B1","\u2727 \u25B1\u25B1\u25B0\u25B0","\u2726 \u25B1\u25B1\u25B1\u25B0","\u2727 \u25B1\u25B1\u25B0\u25B0","\u2726 \u25B1\u25B0\u25B0\u25B1","\u2727 \u25B0\u25B0\u25B1\u25B1"];function tH({tools:e,thinking:t,streamText:n,startTime:r}){let[s,i]=ACe(0);TCe(()=>{let p=setInterval(()=>i(m=>m+1),120);return()=>clearInterval(p)},[]);let o=((Date.now()-r)/1e3).toFixed(0),a=XU[s%XU.length],c=eH[s%eH.length],l=ZU[Math.floor(s/12)%ZU.length],u=".".repeat(s%3+1),d=e.some(p=>p.status==="running"),f=t&&!n;return ul(Zd,{flexDirection:"column",marginTop:1,children:[e.map((p,m)=>Ir(_Ce,{tool:p,spinner:a},`act-${m}`)),n?ul(Zd,{marginTop:e.length?1:0,paddingLeft:1,children:[Ir(Zr,{color:"magenta",children:"\u23FA "}),Ir(Zr,{children:n})]}):f&&!d?ul(Zd,{marginTop:e.length?1:0,gap:1,children:[Ir(Zr,{color:"cyanBright",children:c}),ul(Zr,{color:"cyanBright",bold:!0,children:[l,u]}),ul(Zr,{color:"gray",dimColor:!0,children:["(",o,"s \xB7 esc to redirect)"]})]}):null]})}function _Ce({tool:e,spinner:t}){let n=e.status==="running"?Ir(Zr,{color:"yellowBright",children:t}):e.status==="done"?Ir(Zr,{color:"greenBright",children:"\u23FA"}):Ir(Zr,{color:"redBright",children:"\u23FA"}),r=RCe(e.name),s=PCe(e.name,e.input),i=e.status==="running"?"yellowBright":e.status==="done"?"white":"redBright";return ul(Zd,{flexDirection:"column",children:[ul(Zd,{gap:1,children:[n,Ir(Zr,{color:i,bold:!0,children:r}),s?Ir(Zr,{color:"gray",children:s}):null,e.durationMs!==void 0&&e.status!=="running"&&Ir(Zr,{color:"gray",dimColor:!0,children:ICe(e.durationMs)})]}),e.status==="done"&&e.output&&ECe(e.name)&&DCe(e.output)?Ir(QU,{diff:e.output,maxLines:12}):e.status!=="running"&&e.output?Ir(Zd,{paddingLeft:2,children:Ir(Zr,{color:"gray",dimColor:!0,wrap:"truncate-end",children:"\u23BF "+MCe(e.output)})}):null]})}function RCe(e){return{file_read:"Read",file_write:"Write",file_edit:"Edit",notebook_edit:"Edit Notebook",bash:"Bash",powershell:"Shell",grep:"Search",glob:"Find",code_search:"Code Search",code_index:"Index",code_references:"References",find_callers:"Callers",impact_analysis:"Impact",nl_search:"Search",web_fetch:"Fetch",web_search:"Web Search",search_past_work:"Recall",analyze_code:"Analyze",detect_smells:"Lint",generate_tests:"Gen Tests",find_untested:"Coverage",infer_types:"Types",doc_create:"Create Doc",spawn_specialist:"Specialist",spawn_pipeline:"Pipeline",agent:"Sub-agent",todo_write:"Plan",enter_plan_mode:"Plan Mode",exit_plan_mode:"Exit Plan",task_create:"Task",task_get:"Task",task_list:"Tasks",task_update:"Task",task_output:"Task Out",task_stop:"Stop Task",skill:"Skill",skill_search:"Find Skill",ask_user:"Ask",diff_preview:"Diff",explain:"Explain",image_read:"Image",clipboard_image:"Clipboard",cron_create:"Schedule",cron_list:"Schedules",cron_delete:"Unschedule"}[e]||e}function PCe(e,t){switch(e){case"bash":case"powershell":return`$ ${String(t.command||"").slice(0,70)}`;case"file_read":return ca(t.path);case"file_write":return ca(t.path);case"file_edit":return ca(t.path);case"notebook_edit":return ca(t.path);case"grep":return`"${t.pattern}"${t.path?` in ${ca(t.path)}`:""}`;case"glob":return String(t.pattern||"");case"code_search":case"nl_search":return`"${String(t.query||t.q||"").slice(0,60)}"`;case"web_fetch":return String(t.url||"");case"web_search":return`"${t.query}"`;case"spawn_specialist":return`${t.specialist} \u2014 ${String(t.task||"").slice(0,50)}`;case"doc_create":return ca(t.path||t.output);case"todo_write":return Array.isArray(t.todos)?`${t.todos.length} steps`:"";case"generate_tests":return ca(t.path);case"analyze_code":case"detect_smells":return ca(t.path);case"ask_user":return String(t.question||"").slice(0,70);default:{let n=JSON.stringify(t);return n.length>2?n.slice(0,50):""}}}function ca(e){let t=String(e||"");if(!t)return"";let n=t.replace(/\\/g,"/").split("/");return n.length>3?"\u2026/"+n.slice(-2).join("/"):t}function ICe(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}function MCe(e){let t=e.split(`
2570
- `).map(s=>s.trim()).filter(Boolean),n=t[0]||"",r=t.length>1?` (+${t.length-1} more)`:"";return n.slice(0,90)+r}function ECe(e){return e==="file_edit"||e==="file_write"}function DCe(e){return/^[+\-] /m.test(e)}vy();import{useState as nH,useEffect as rH}from"react";import{Box as la,Text as ws}from"ink";import{jsx as ks,jsxs as eo}from"react/jsx-runtime";var sH=["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"];function iH({active:e}){let[t,n]=nH(()=>qs()),[r,s]=nH(0);if(rH(()=>{let d=kx(),f=p=>n(p);return d.on("change",f),()=>{d.off("change",f)}},[]),rH(()=>{if(!e)return;let d=setInterval(()=>s(f=>f+1),120);return()=>clearInterval(d)},[e]),t.length===0)return null;let i=t.filter(d=>d.status==="completed").length,o=t.length,a=o>0?Math.round(i/o*100):0,c=16,l=Math.round(i/o*c),u=sH[r%sH.length];return eo(la,{flexDirection:"column",borderStyle:"round",borderColor:i===o?"green":"cyan",paddingX:1,marginX:1,marginY:1,children:[eo(la,{justifyContent:"space-between",children:[eo(la,{gap:1,children:[ks(ws,{color:"cyanBright",bold:!0,children:"\u{1F4CB} Plan"}),eo(ws,{color:"gray",children:[i,"/",o]})]}),eo(la,{gap:1,children:[ks(ws,{color:"green",children:"\u2588".repeat(l)}),ks(ws,{color:"gray",children:"\u2591".repeat(c-l)}),eo(ws,{color:"gray",dimColor:!0,children:[a,"%"]})]})]}),ks(la,{flexDirection:"column",marginTop:0,children:t.map((d,f)=>ks(FCe,{todo:d,spinner:u},f))})]})}function FCe({todo:e,spinner:t}){return e.status==="completed"?eo(la,{gap:1,children:[ks(ws,{color:"green",children:"\u2714"}),ks(ws,{color:"gray",strikethrough:!0,dimColor:!0,children:e.text})]}):e.status==="in_progress"?eo(la,{gap:1,children:[ks(ws,{color:"yellowBright",children:t}),ks(ws,{color:"white",bold:!0,children:e.text})]}):eo(la,{gap:1,children:[ks(ws,{color:"gray",dimColor:!0,children:"\u25CB"}),ks(ws,{color:"gray",children:e.text})]})}import{Box as K0,Text as Bg}from"ink";import{jsx as Ng,jsxs as Y0}from"react/jsx-runtime";function oH({changes:e}){if(!e||e.length===0)return null;let t=e.filter(r=>r.action==="created").length,n=e.filter(r=>r.action==="edited"||r.action==="wrote").length;return Y0(K0,{flexDirection:"column",borderStyle:"round",borderColor:"green",paddingX:1,marginX:1,marginY:1,children:[Y0(K0,{gap:1,children:[Ng(Bg,{color:"greenBright",bold:!0,children:"\u{1F4D2} Change Ledger"}),Y0(Bg,{color:"gray",children:[e.length," file",e.length>1?"s":"",t?` \xB7 ${t} new`:"",n?` \xB7 ${n} edited`:""]})]}),Ng(K0,{flexDirection:"column",children:e.map((r,s)=>Y0(K0,{gap:1,children:[Ng(Bg,{color:r.action==="created"?"greenBright":"yellowBright",children:r.action==="created"?"\uFF0B":"\u270E"}),Ng(Bg,{color:"gray",dimColor:!0,children:r.action}),Ng(Bg,{color:"white",children:LCe(r.path)})]},s))})]})}function LCe(e){let t=String(e||"").replace(/\\/g,"/"),n=t.split("/");return n.length>4?"\u2026/"+n.slice(-3).join("/"):t}import{useState as aH}from"react";import{Box as qg,Text as er,useInput as OCe}from"ink";import{jsx as Xr,jsxs as ua}from"react/jsx-runtime";var lP=[{name:"gemini-2.5-flash-lite",provider:"gemini",description:"Fastest, cheapest Gemini model \u2014 ideal for simple tasks",cost:"$0.05/$0.20"},{name:"gemini-2.5-flash",provider:"gemini",description:"Balanced speed and quality",cost:"$0.15/$0.60"},{name:"gemini-2.5-pro",provider:"gemini",description:"Most capable Gemini model \u2014 complex reasoning",cost:"$1.25/$10"},{name:"gemini-3.5-flash",provider:"gemini",description:"Latest Gemini 3.5 generation flash",cost:"$0.15/$0.60"},{name:"gemini-3.1-pro-preview",provider:"gemini",description:"Preview of Gemini 3.1 Pro",cost:"$1.25/$10"},{name:"gemini-3.1-flash-lite",provider:"gemini",description:"Lightweight Gemini 3.1",cost:"$0.05/$0.20"},{name:"gemini-3-flash-preview",provider:"gemini",description:"Gemini 3 flash preview",cost:"$0.10/$0.40"},{name:"gemma-4-31b-it",provider:"gemini",description:"Gemma 4 31B instruction-tuned (open model)",cost:"$0.10/$0.30"},{name:"gemma-4-26b-a4b-it",provider:"gemini",description:"Gemma 4 26B variant",cost:"$0.08/$0.25"},{name:"claude-opus-4-8",provider:"claude",description:"Claude Opus 4.8 \u2014 most capable, agentic coding",cost:"$5/$25"},{name:"claude-sonnet-4-6",provider:"claude",description:"Claude Sonnet 4.6 \u2014 best speed + intelligence",cost:"$3/$15"},{name:"claude-haiku-4-5",provider:"claude",description:"Claude Haiku 4.5 \u2014 fastest, near-frontier",cost:"$1/$5"},{name:"claude-opus-4-7",provider:"claude",description:"Claude Opus 4.7",cost:"$5/$25"},{name:"claude-opus-4-6",provider:"claude",description:"Claude Opus 4.6",cost:"$5/$25"},{name:"claude-sonnet-4-5",provider:"claude",description:"Claude Sonnet 4.5",cost:"$3/$15"},{name:"claude-opus-4-1-20250805",provider:"claude",description:"Claude Opus 4.1",cost:"$15/$75"},{name:"claude-sonnet-4-20250514",provider:"claude",description:"Claude Sonnet 4",cost:"$3/$15"},{name:"claude-3-7-sonnet-20250219",provider:"claude",description:"Claude 3.7 Sonnet (hybrid reasoning)",cost:"$3/$15"},{name:"claude-3-5-sonnet-20241022",provider:"claude",description:"Claude 3.5 Sonnet",cost:"$3/$15"},{name:"claude-3-5-haiku-20241022",provider:"claude",description:"Claude 3.5 Haiku \u2014 fast and cheap",cost:"$0.80/$4"},{name:"claude-3-opus-20240229",provider:"claude",description:"Claude 3 Opus",cost:"$15/$75"}];function cH({currentModel:e,onSelect:t,onCancel:n}){let[r,s]=aH(""),[i,o]=aH(()=>Math.max(0,lP.findIndex(l=>l.name===e))),a=r?lP.filter(l=>l.name.toLowerCase().includes(r.toLowerCase())||l.description.toLowerCase().includes(r.toLowerCase())):lP,c=Math.min(i,a.length-1);return OCe((l,u)=>{if(u.escape){n();return}if(u.return){a[c]&&t(a[c]);return}if(u.upArrow){o(d=>Math.max(0,Math.min(a.length-1,d)-1));return}if(u.downArrow){o(d=>Math.min(a.length-1,d+1));return}if(u.backspace||u.delete){s(d=>d.slice(0,-1)),o(0);return}l&&!u.ctrl&&!u.meta&&(s(d=>d+l),o(0))}),ua(qg,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,marginX:1,children:[ua(qg,{gap:1,children:[Xr(er,{color:"cyan",bold:!0,children:"/model"}),Xr(er,{color:"gray",children:"Select model:"}),ua(er,{color:"white",inverse:!0,children:[" ",r||" "]}),!r&&Xr(er,{color:"gray",dimColor:!0,children:" type to search"})]}),ua(qg,{flexDirection:"column",marginTop:1,children:[a.length===0?ua(er,{color:"yellow",dimColor:!0,children:[' No models match "',r,'"']}):a.slice(0,12).map((l,u)=>{let d=u===c,f=l.name===e;return ua(qg,{gap:1,children:[Xr(er,{color:d?"cyan":"gray",children:d?"\u25B8":" "}),Xr(er,{color:d?"cyan":l.provider==="gemini"?"magenta":"yellow",bold:d,children:l.name.padEnd(28)}),Xr(er,{color:d?"white":"gray",dimColor:!d,children:l.description}),f&&Xr(er,{color:"green",children:" \u2713"})]},l.name)}),a.length>12&&ua(er,{color:"gray",dimColor:!0,children:[" (+",a.length-12," more \u2014 keep typing to filter)"]})]}),ua(qg,{marginTop:1,gap:2,children:[Xr(er,{color:"gray",dimColor:!0,children:"ESC to cancel"}),Xr(er,{color:"gray",children:"\u2022"}),Xr(er,{color:"gray",dimColor:!0,children:"\u2191\u2193 to navigate"}),Xr(er,{color:"gray",children:"\u2022"}),Xr(er,{color:"gray",dimColor:!0,children:"\u21B5 to select"})]})]})}Mr();Zi();Iy();tf();Ey();cf();XT();Xg();x$();import{jsx as xe,jsxs as da}from"react/jsx-runtime";function dH(){let{exit:e}=jCe(),{stdout:t}=BCe(),n=Ts(),r=process.cwd(),s=no(r),[i,o]=mt(n.provider),[a,c]=mt(of(n,n.provider)),[l,u]=mt(()=>Wd(n.provider,As(n,n.provider),of(n,n.provider))),[d,f]=mt(n.permissions.mode),[p,m]=mt([]),[g,h]=mt(""),[v,y]=mt(!1),[b,k]=mt([]),[S,x]=mt(0),[A,j]=mt(null),[I,ye]=mt(!1),[Ne,mn]=mt(!0),[nn,De]=mt(null),[Et,gn]=mt(null),[T,ce]=mt(null),[se,C]=mt(!1),[M,$e]=mt(!1),[ot,nr]=mt([]),[rr,J]=mt(null),[be]=mt(()=>Ry(n.permissions.mode,n.permissions.rules)),[Ge]=mt(()=>My(n.hooks)),[hn]=mt(()=>nh()),[yn]=mt(()=>{let P=ef(r,i,a);return global.__currentSession=P,P});lH(()=>{HF(P=>gn(P))},[]),lH(()=>{As(n,i)||j(`No API key for ${i}. Run /login to set credentials.`),Promise.resolve().then(()=>(vy(),gF)).then(K=>K.initTodoStore(r)).catch(()=>{}),Promise.resolve().then(()=>(Cc(),$c)).then(K=>{if(K.getConfig().enabled&&!K.getAgentIdentity("root-agent"))try{K.createAgentIdentity({agentId:"root-agent"})}catch{}}).catch(()=>{});let rn=null;return Promise.resolve().then(()=>(M0(),I0)).then(K=>{K.startAutoDreamScheduler(l,1800*1e3),rn=K.stopAutoDreamScheduler}).catch(()=>{}),Promise.resolve().then(()=>(B1(),j1)).then(K=>{K.registerPresence();let sn=K.loadTeamConfig();sn.enabled&&sn.mode!=="disabled"&&sn.mode!=="manual"&&(K.startAutoSync(sn.intervalMs,sn.mode),sn.enableFileWatcher&&K.startFileWatcher())}).catch(()=>{}),Promise.resolve().then(()=>(Br(),jr)).then(K=>{let sn=process.cwd();K.isIndexed(sn)&&K.loadProject(sn)}).catch(()=>{}),Promise.resolve().then(()=>(Mf(),If)).then(K=>{K.initFileDiff(process.cwd())}).catch(()=>{}),Promise.resolve().then(()=>(Lp(),Fp)).then(async K=>{try{let{listSessions:sn,loadSession:fa}=await Promise.resolve().then(()=>(tf(),bP)),Hg=sn().slice(0,30);for(let zg of Hg){if(K.isSessionIndexed(zg.id))continue;let pa=fa(zg.id);pa?.messages&&pa.messages.length>2&&await K.indexSession({sessionId:pa.id,projectPath:pa.cwd||process.cwd(),messages:pa.messages})}}catch{}}).catch(()=>{}),Promise.resolve().then(()=>(C0(),$0)).then(async K=>{try{let{briefing:sn,diff:fa}=await K.diffSinceLastSession(process.cwd(),yn.id,{format:"plain",detail:"brief"});fa&&fa.significance!=="none"&&(j(`\u{1F4CB} ${sn}`),yn.resumeBriefing=K.formatBriefing(fa,{format:"markdown",detail:"detailed"}))}catch{}}).catch(()=>{}),()=>{rn&&rn()}},[]),uH((P,rn)=>{rn.escape&&v&&nn&&(nn.abort(),y(!1),h(""),k([]),gn(null),$e(!0),j("\u{1F500} Interrupted. Redirect AIACA below \u2014 or press Enter on an empty line to just stop."))});let li=uP(P=>{Et&&(Et.resolve(P),zF(),gn(null))},[Et]),Ce=uP(P=>{let rn=As(n,P),K=of(n,P);o(P),c(K),u(Wd(P,rn,K))},[n]),bn=uP(async P=>{if(M){if($e(!1),!P.trim()){j("\u23F9 Stopped.");return}P=`[Redirect \u2014 I interrupted the previous work. New focus:] ${P}`}if(!P.trim())return;mn(!1),j(null);let rn=await Promise.resolve().then(()=>(Na(),Ba)),K=rn.detectReturn(p);if(K&&K.durationMs&&K.durationMs>6e4){let ne=rn.summarizeHeuristic(K);(ne.totalEvents>0||(K.durationMs||0)>300*1e3)&&j(`\u{1F44B} Welcome back! ${ne.briefSummary}`)}rn.recordActivity();try{let ne=await Promise.resolve().then(()=>(rg(),ng));if(ne.getConfig().enableLearning){let Ht=P.startsWith("/");ne.recordUsage(P,Ht?"command":"prior_query",{projectPath:process.cwd()})}}catch{}if(Promise.resolve().then(()=>(M0(),I0)).then(ne=>ne.recordActivity()).catch(()=>{}),qU(P)){let{name:ne,args:Ht}=UU(P);if(ne==="help"){ye(!0);return}if((ne==="model"||ne==="m")&&!Ht.trim()){C(!0);return}let Gg=NU(ne);if(!Gg){j(`Unknown command: /${ne}`);return}let Vg={session:yn,config:n,costTracker:hn,permissions:be,setProvider:Ce,setModel:Dt=>{c(Dt),u(Wd(i,As(n,i),Dt))},setPermissionMode:Dt=>{f(Dt),be.mode=Dt},clearHistory:()=>{m([]),j("History cleared.")},compact:async()=>{if(p.length<4){j("Too few messages.");return}let Dt=await zy(p,l);Dt.summary&&(m(Gy(p,Dt.summary)),j(`Compacted (~${Dt.tokensSaved} tokens saved)`))},exit:()=>{ml(yn),e()}},xs=await Gg.handler(Ht,Vg);if(xs)if(xs.startsWith("__RESUME__")){let Dt=JSON.parse(xs.slice(10));m(Dt),j(`Resumed (${Dt.length} messages)`)}else j(xs);return}y(!0),h(""),k([]),nr([]),J(null),x(Date.now());let sn=new AbortController;De(sn),ce(P);let fa={role:"user",content:P,timestamp:new Date().toISOString()},Hg=[...p,fa],zg=ne=>{ne.type==="text"&&ne.text&&h(Ht=>Ht+ne.text)},pa=ne=>{k(Ht=>[...Ht,{name:ne.name,input:ne.input,status:"running"}])},pH=(ne,Ht,Gg)=>{let Vg=Ht.startsWith("Error")||Ht.startsWith("\u{1F6AB}");if(k(xs=>xs.map(Dt=>Dt.name===ne.name&&Dt.status==="running"?{...Dt,status:Vg?"error":"done",output:Ht,durationMs:Gg}:Dt)),!Vg){let xs=ne.input?.path,Dt=ne.name==="file_write"?Ht.includes("created")?"created":"wrote":ne.name==="file_edit"||ne.name==="notebook_edit"?"edited":ne.name==="doc_create"?"created":null;Dt&&xs&&nr(Z0=>Z0.some(fP=>fP.path===xs&&fP.action===Dt)?Z0:[...Z0,{path:xs,action:Dt}])}};try{let ne=await _v(Hg,{provider:l,cwd:r,config:n,session:yn,permissions:be,hooks:Ge,costTracker:hn,abortSignal:sn.signal,onStream:zg,onToolStart:pa,onToolEnd:pH,onError:Ht=>{Ht.recoverable||j(Ht.message)}});sn.signal.aborted||(m(ne),yn.messages=ne,ml(yn),nr(Ht=>(Ht.length&&J(Ht),Ht)))}catch(ne){ne.code!=="ABORTED"&&j(`Error: ${ne.message}`),sn.signal.aborted||m(Hg)}y(!1),h(""),k([]),De(null),ce(null)},[p,l,i,n,yn,be,Ge,hn,r,Ce,e,M]),Ug=Math.max(4,(t?.rows||30)-10),dP=new Set,Q0=p.filter((P,rn)=>{if(P.role==="user"&&P.content.startsWith("<tool_result")||P.role==="user"&&/^Tool result:|^\[Tool result/.test(P.content)||P.role==="user"&&P.content.includes("<intent_reminder")||P.role==="user"&&P.content.startsWith("[System:")||P.role==="assistant"&&!P.content.trim()||P.role==="assistant"&&P.content.startsWith("[Calling:"))return!1;if(P.role==="user"){let K=`user:${P.content.slice(0,200)}`;if(dP.has(K))return!1;dP.add(K)}return!0}).slice(-Ug);return I?da(tr,{flexDirection:"column",children:[xe(GU,{visible:!0}),xe(aP,{onSubmit:()=>ye(!1),prefix:"press enter to close"})]}):se?da(tr,{flexDirection:"column",children:[xe(tr,{flexDirection:"column",paddingX:1,children:Q0.map((P,rn)=>xe(V0,{message:P},`${P.timestamp}-${rn}`))}),xe(cH,{currentModel:a,onSelect:P=>{Ce(P.provider),setTimeout(()=>{c(P.name),u(Wd(P.provider,As(n,P.provider),P.name)),j(`Switched to ${P.provider} (${P.name})`),C(!1)},0)},onCancel:()=>C(!1)}),xe(G0,{provider:i,model:a,mode:d,costTracker:hn,messageCount:p.length,cwd:r})]}):Et?da(tr,{flexDirection:"column",children:[xe(tr,{flexDirection:"column",paddingX:1,children:Q0.map((P,rn)=>xe(V0,{message:P},`${P.timestamp}-${rn}`))}),xe(NCe,{pending:Et,onDecision:li}),xe(G0,{provider:i,model:a,mode:d,costTracker:hn,messageCount:p.length,cwd:r})]}):da(tr,{flexDirection:"column",children:[Ne&&p.length===0&&xe(pP,{provider:i,model:a,cwd:r,gitBranch:s.isRepo?s.branch:void 0}),xe(iH,{active:v}),da(tr,{flexDirection:"column",paddingX:1,flexGrow:1,children:[Q0.map((P,rn)=>xe(V0,{message:P},`${P.timestamp}-${rn}`)),T&&xe(tr,{flexDirection:"column",marginBottom:1,children:xe(tr,{borderStyle:"single",borderColor:"cyan",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:1,children:xe(dl,{color:"white",children:T})})}),b.length>0||v&&!g||g?xe(tH,{tools:b.map(P=>({name:P.name,input:P.input,status:P.status,output:P.output,durationMs:P.durationMs})),thinking:v,streamText:g,startTime:S}):null,A&&xe(WU,{text:A,level:"info"}),!v&&rr&&xe(oH,{changes:rr}),M&&da(tr,{borderStyle:"round",borderColor:"magenta",paddingX:1,marginX:1,marginTop:1,children:[xe(dl,{color:"magentaBright",bold:!0,children:"\u{1F500} Redirect AIACA"}),xe(dl,{color:"gray",children:" \u2014 tell it what to focus on instead (Enter on empty line to stop)"})]})]}),xe(tr,{paddingX:1,children:xe(aP,{onSubmit:bn,disabled:v,placeholder:M?"Steer AIACA in a new direction\u2026":void 0})}),xe(G0,{provider:i,model:a,mode:d,costTracker:hn,messageCount:p.length,cwd:r})]})}function NCe({pending:e,onDecision:t}){let[n,r]=mt(0),s=[{label:"Allow",key:"y",value:"allow",color:"green"},{label:"Deny",key:"n",value:"deny",color:"red"},{label:"Always allow",key:"a",value:"always",color:"cyan"}];return uH((i,o)=>{o.leftArrow&&r(a=>Math.max(0,a-1)),o.rightArrow&&r(a=>Math.min(2,a+1)),o.return&&t(s[n].value),i==="y"&&t("allow"),i==="n"&&t("deny"),i==="a"&&t("always")}),da(tr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,marginX:1,marginY:1,children:[da(tr,{gap:1,children:[xe(dl,{color:"yellow",bold:!0,children:"\u26A0 Permission"}),xe(dl,{color:"cyan",bold:!0,children:e.toolName})]}),xe(tr,{paddingLeft:2,children:xe(dl,{children:e.description})}),xe(tr,{marginTop:1,gap:2,children:s.map((i,o)=>xe(dl,{color:o===n?i.color:"gray",bold:o===n,inverse:o===n,children:` ${i.label} (${i.key}) `},i.key))})]})}hl();import{jsx as zCe}from"react/jsx-runtime";process.setMaxListeners(50);var UCe=process.stderr.write.bind(process.stderr);process.stderr.write=((e,...t)=>{let n=typeof e=="string"?e:e?.toString?.()||"";return n.includes("non-text parts")||n.includes("API key should be set when using the Gemini API")?!0:UCe(e,...t)});process.on("exit",()=>{try{let e=global.__currentSession;e?.id&&(C0(),sr($0)).captureSnapshot(process.cwd(),e.id,`Session ended with ${e.messages?.length||0} messages`).catch(()=>{})}catch{}try{let e=global.__currentSession;e?.id&&(fs(),sr(ds)).teardownSession(e.id,"process_exit"),(fs(),sr(ds)).destroyAllSessions("process_exit")}catch{}});var fH=e=>{try{(fs(),sr(ds)).destroyAllSessions(e)}catch{}};process.on("SIGINT",()=>fH("SIGINT"));process.on("SIGTERM",()=>fH("SIGTERM"));async function HCe(){aS()||await cS(),qCe(zCe(dH,{}))}HCe().catch(e=>{console.error("AIACA startup error:",e),process.exit(1)});
2578
+ `)})}return t}function VU(e){return e.trim().replace(/^\||\|$/g,"").split("|").map(t=>t.trim())}import{jsx as Qr,jsxs as Qd}from"react/jsx-runtime";function V0({message:e,elapsed:t}){return e.role==="user"?Qr(kCe,{content:e.content}):Qr(xCe,{content:e.content,toolCalls:e.toolCalls,usage:e.usage,elapsed:t})}function kCe({content:e}){return Qr(aa,{flexDirection:"column",marginBottom:1,children:Qr(aa,{borderStyle:"single",borderColor:"cyan",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:1,children:Qr(ll,{color:"white",children:e})})})}function xCe({content:e,toolCalls:t,usage:n,elapsed:r}){return Qd(aa,{flexDirection:"column",marginBottom:1,children:[Qd(aa,{borderStyle:"single",borderColor:"magenta",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:1,flexDirection:"column",children:[t&&t.length>0&&Qr(aa,{flexDirection:"column",marginBottom:0,children:t.map(s=>Qd(aa,{gap:1,children:[Qr(ll,{color:"yellow",children:"\u26A1"}),Qr(ll,{color:"cyan",bold:!0,children:s.name}),Qr(ll,{color:"gray",children:$Ce(s)})]},s.id))}),e?Qr(JU,{content:e}):null]}),n&&Qd(aa,{paddingLeft:2,marginTop:0,children:[Qd(ll,{color:"gray",dimColor:!0,children:["\u25B8 Tokens: ",(n.inputTokens+n.outputTokens).toLocaleString()]}),r!==void 0&&Qd(ll,{color:"gray",dimColor:!0,children:[" \u2022 Time: ",CCe(r)]})]})]})}function $Ce(e){let t=e.input;return e.name==="bash"||e.name==="powershell"?`$ ${t.command}`:e.name==="file_read"?`${t.path}`:e.name==="file_write"||e.name==="file_edit"?`${t.path}`:e.name==="grep"?`"${t.pattern}"`:e.name==="glob"?`${t.pattern}`:JSON.stringify(t).slice(0,50)}function CCe(e){let t=Math.floor(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function WU({text:e,level:t}){return Qr(aa,{paddingLeft:2,marginBottom:1,children:Qr(ll,{color:t==="error"?"red":t==="warning"?"yellow":"gray",italic:!0,children:e})})}import{useState as TCe,useEffect as _Ce}from"react";import{Box as Zd,Text as Zr}from"ink";import{Box as KU,Text as J0}from"ink";import{jsx as YU,jsxs as W0}from"react/jsx-runtime";function QU({diff:e,maxLines:t=12}){let n=ACe(e);if(n.length===0)return null;let r=n.slice(0,t),s=n.length-r.length,i=n.filter(a=>a.kind==="add").length,o=n.filter(a=>a.kind==="del").length;return W0(KU,{flexDirection:"column",paddingLeft:2,children:[(i>0||o>0)&&W0(KU,{gap:1,children:[W0(J0,{color:"greenBright",children:["+",i]}),W0(J0,{color:"redBright",children:["-",o]})]}),r.map((a,c)=>YU(J0,{color:a.kind==="add"?"greenBright":a.kind==="del"?"redBright":"gray",dimColor:a.kind==="ctx",wrap:"truncate-end",children:(a.kind==="add"?"+ ":a.kind==="del"?"- ":" ")+a.text},c)),s>0&&YU(J0,{color:"gray",dimColor:!0,children:` \u2026 +${s} more lines`})]})}function ACe(e){let t=[];for(let n of e.split(`
2579
+ `))n.startsWith("+ ")?t.push({kind:"add",text:n.slice(2)}):n.startsWith("- ")?t.push({kind:"del",text:n.slice(2)}):n.startsWith(" ")&&t.push({kind:"ctx",text:n.slice(2)});return t}import{jsx as Ir,jsxs as ul}from"react/jsx-runtime";var ZU=["Pondering","Engineering","Crafting","Reasoning","Orchestrating","Assembling","Architecting","Composing","Strategizing","Forging"],XU=["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"],eH=["\u2726 \u25B0\u25B1\u25B1\u25B1","\u2727 \u25B0\u25B0\u25B1\u25B1","\u2726 \u25B1\u25B0\u25B0\u25B1","\u2727 \u25B1\u25B1\u25B0\u25B0","\u2726 \u25B1\u25B1\u25B1\u25B0","\u2727 \u25B1\u25B1\u25B0\u25B0","\u2726 \u25B1\u25B0\u25B0\u25B1","\u2727 \u25B0\u25B0\u25B1\u25B1"];function tH({tools:e,thinking:t,streamText:n,startTime:r}){let[s,i]=TCe(0);_Ce(()=>{let p=setInterval(()=>i(m=>m+1),120);return()=>clearInterval(p)},[]);let o=((Date.now()-r)/1e3).toFixed(0),a=XU[s%XU.length],c=eH[s%eH.length],l=ZU[Math.floor(s/12)%ZU.length],u=".".repeat(s%3+1),d=e.some(p=>p.status==="running"),f=t&&!n;return ul(Zd,{flexDirection:"column",marginTop:1,children:[e.map((p,m)=>Ir(RCe,{tool:p,spinner:a},`act-${m}`)),n?ul(Zd,{marginTop:e.length?1:0,paddingLeft:1,children:[Ir(Zr,{color:"magenta",children:"\u23FA "}),Ir(Zr,{children:n})]}):f&&!d?ul(Zd,{marginTop:e.length?1:0,gap:1,children:[Ir(Zr,{color:"cyanBright",children:c}),ul(Zr,{color:"cyanBright",bold:!0,children:[l,u]}),ul(Zr,{color:"gray",dimColor:!0,children:["(",o,"s \xB7 esc to redirect)"]})]}):null]})}function RCe({tool:e,spinner:t}){let n=e.status==="running"?Ir(Zr,{color:"yellowBright",children:t}):e.status==="done"?Ir(Zr,{color:"greenBright",children:"\u23FA"}):Ir(Zr,{color:"redBright",children:"\u23FA"}),r=PCe(e.name),s=ICe(e.name,e.input),i=e.status==="running"?"yellowBright":e.status==="done"?"white":"redBright";return ul(Zd,{flexDirection:"column",children:[ul(Zd,{gap:1,children:[n,Ir(Zr,{color:i,bold:!0,children:r}),s?Ir(Zr,{color:"gray",children:s}):null,e.durationMs!==void 0&&e.status!=="running"&&Ir(Zr,{color:"gray",dimColor:!0,children:MCe(e.durationMs)})]}),e.status==="done"&&e.output&&DCe(e.name)&&FCe(e.output)?Ir(QU,{diff:e.output,maxLines:12}):e.status!=="running"&&e.output?Ir(Zd,{paddingLeft:2,children:Ir(Zr,{color:"gray",dimColor:!0,wrap:"truncate-end",children:"\u23BF "+ECe(e.output)})}):null]})}function PCe(e){return{file_read:"Read",file_write:"Write",file_edit:"Edit",notebook_edit:"Edit Notebook",bash:"Bash",powershell:"Shell",grep:"Search",glob:"Find",code_search:"Code Search",code_index:"Index",code_references:"References",find_callers:"Callers",impact_analysis:"Impact",nl_search:"Search",web_fetch:"Fetch",web_search:"Web Search",search_past_work:"Recall",analyze_code:"Analyze",detect_smells:"Lint",generate_tests:"Gen Tests",find_untested:"Coverage",infer_types:"Types",doc_create:"Create Doc",spawn_specialist:"Specialist",spawn_pipeline:"Pipeline",agent:"Sub-agent",todo_write:"Plan",enter_plan_mode:"Plan Mode",exit_plan_mode:"Exit Plan",task_create:"Task",task_get:"Task",task_list:"Tasks",task_update:"Task",task_output:"Task Out",task_stop:"Stop Task",skill:"Skill",skill_search:"Find Skill",ask_user:"Ask",diff_preview:"Diff",explain:"Explain",image_read:"Image",clipboard_image:"Clipboard",cron_create:"Schedule",cron_list:"Schedules",cron_delete:"Unschedule"}[e]||e}function ICe(e,t){switch(e){case"bash":case"powershell":return`$ ${String(t.command||"").slice(0,70)}`;case"file_read":return ca(t.path);case"file_write":return ca(t.path);case"file_edit":return ca(t.path);case"notebook_edit":return ca(t.path);case"grep":return`"${t.pattern}"${t.path?` in ${ca(t.path)}`:""}`;case"glob":return String(t.pattern||"");case"code_search":case"nl_search":return`"${String(t.query||t.q||"").slice(0,60)}"`;case"web_fetch":return String(t.url||"");case"web_search":return`"${t.query}"`;case"spawn_specialist":return`${t.specialist} \u2014 ${String(t.task||"").slice(0,50)}`;case"doc_create":return ca(t.path||t.output);case"todo_write":return Array.isArray(t.todos)?`${t.todos.length} steps`:"";case"generate_tests":return ca(t.path);case"analyze_code":case"detect_smells":return ca(t.path);case"ask_user":return String(t.question||"").slice(0,70);default:{let n=JSON.stringify(t);return n.length>2?n.slice(0,50):""}}}function ca(e){let t=String(e||"");if(!t)return"";let n=t.replace(/\\/g,"/").split("/");return n.length>3?"\u2026/"+n.slice(-2).join("/"):t}function MCe(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}function ECe(e){let t=e.split(`
2580
+ `).map(s=>s.trim()).filter(Boolean),n=t[0]||"",r=t.length>1?` (+${t.length-1} more)`:"";return n.slice(0,90)+r}function DCe(e){return e==="file_edit"||e==="file_write"}function FCe(e){return/^[+\-] /m.test(e)}vy();import{useState as nH,useEffect as rH}from"react";import{Box as la,Text as ws}from"ink";import{jsx as ks,jsxs as eo}from"react/jsx-runtime";var sH=["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"];function iH({active:e}){let[t,n]=nH(()=>qs()),[r,s]=nH(0);if(rH(()=>{let d=kx(),f=p=>n(p);return d.on("change",f),()=>{d.off("change",f)}},[]),rH(()=>{if(!e)return;let d=setInterval(()=>s(f=>f+1),120);return()=>clearInterval(d)},[e]),t.length===0)return null;let i=t.filter(d=>d.status==="completed").length,o=t.length,a=o>0?Math.round(i/o*100):0,c=16,l=Math.round(i/o*c),u=sH[r%sH.length];return eo(la,{flexDirection:"column",borderStyle:"round",borderColor:i===o?"green":"cyan",paddingX:1,marginX:1,marginY:1,children:[eo(la,{justifyContent:"space-between",children:[eo(la,{gap:1,children:[ks(ws,{color:"cyanBright",bold:!0,children:"\u{1F4CB} Plan"}),eo(ws,{color:"gray",children:[i,"/",o]})]}),eo(la,{gap:1,children:[ks(ws,{color:"green",children:"\u2588".repeat(l)}),ks(ws,{color:"gray",children:"\u2591".repeat(c-l)}),eo(ws,{color:"gray",dimColor:!0,children:[a,"%"]})]})]}),ks(la,{flexDirection:"column",marginTop:0,children:t.map((d,f)=>ks(LCe,{todo:d,spinner:u},f))})]})}function LCe({todo:e,spinner:t}){return e.status==="completed"?eo(la,{gap:1,children:[ks(ws,{color:"green",children:"\u2714"}),ks(ws,{color:"gray",strikethrough:!0,dimColor:!0,children:e.text})]}):e.status==="in_progress"?eo(la,{gap:1,children:[ks(ws,{color:"yellowBright",children:t}),ks(ws,{color:"white",bold:!0,children:e.text})]}):eo(la,{gap:1,children:[ks(ws,{color:"gray",dimColor:!0,children:"\u25CB"}),ks(ws,{color:"gray",children:e.text})]})}import{Box as K0,Text as Bg}from"ink";import{jsx as Ng,jsxs as Y0}from"react/jsx-runtime";function oH({changes:e}){if(!e||e.length===0)return null;let t=e.filter(r=>r.action==="created").length,n=e.filter(r=>r.action==="edited"||r.action==="wrote").length;return Y0(K0,{flexDirection:"column",borderStyle:"round",borderColor:"green",paddingX:1,marginX:1,marginY:1,children:[Y0(K0,{gap:1,children:[Ng(Bg,{color:"greenBright",bold:!0,children:"\u{1F4D2} Change Ledger"}),Y0(Bg,{color:"gray",children:[e.length," file",e.length>1?"s":"",t?` \xB7 ${t} new`:"",n?` \xB7 ${n} edited`:""]})]}),Ng(K0,{flexDirection:"column",children:e.map((r,s)=>Y0(K0,{gap:1,children:[Ng(Bg,{color:r.action==="created"?"greenBright":"yellowBright",children:r.action==="created"?"\uFF0B":"\u270E"}),Ng(Bg,{color:"gray",dimColor:!0,children:r.action}),Ng(Bg,{color:"white",children:OCe(r.path)})]},s))})]})}function OCe(e){let t=String(e||"").replace(/\\/g,"/"),n=t.split("/");return n.length>4?"\u2026/"+n.slice(-3).join("/"):t}import{useState as aH}from"react";import{Box as qg,Text as er,useInput as jCe}from"ink";import{jsx as Xr,jsxs as ua}from"react/jsx-runtime";var lP=[{name:"gemini-2.5-flash-lite",provider:"gemini",description:"Fastest, cheapest Gemini model \u2014 ideal for simple tasks",cost:"$0.05/$0.20"},{name:"gemini-2.5-flash",provider:"gemini",description:"Balanced speed and quality",cost:"$0.15/$0.60"},{name:"gemini-2.5-pro",provider:"gemini",description:"Most capable Gemini model \u2014 complex reasoning",cost:"$1.25/$10"},{name:"gemini-3.5-flash",provider:"gemini",description:"Latest Gemini 3.5 generation flash",cost:"$0.15/$0.60"},{name:"gemini-3.1-pro-preview",provider:"gemini",description:"Preview of Gemini 3.1 Pro",cost:"$1.25/$10"},{name:"gemini-3.1-flash-lite",provider:"gemini",description:"Lightweight Gemini 3.1",cost:"$0.05/$0.20"},{name:"gemini-3-flash-preview",provider:"gemini",description:"Gemini 3 flash preview",cost:"$0.10/$0.40"},{name:"gemma-4-31b-it",provider:"gemini",description:"Gemma 4 31B instruction-tuned (open model)",cost:"$0.10/$0.30"},{name:"gemma-4-26b-a4b-it",provider:"gemini",description:"Gemma 4 26B variant",cost:"$0.08/$0.25"},{name:"claude-opus-4-8",provider:"claude",description:"Claude Opus 4.8 \u2014 most capable, agentic coding",cost:"$5/$25"},{name:"claude-sonnet-4-6",provider:"claude",description:"Claude Sonnet 4.6 \u2014 best speed + intelligence",cost:"$3/$15"},{name:"claude-haiku-4-5",provider:"claude",description:"Claude Haiku 4.5 \u2014 fastest, near-frontier",cost:"$1/$5"},{name:"claude-opus-4-7",provider:"claude",description:"Claude Opus 4.7",cost:"$5/$25"},{name:"claude-opus-4-6",provider:"claude",description:"Claude Opus 4.6",cost:"$5/$25"},{name:"claude-sonnet-4-5",provider:"claude",description:"Claude Sonnet 4.5",cost:"$3/$15"},{name:"claude-opus-4-1-20250805",provider:"claude",description:"Claude Opus 4.1",cost:"$15/$75"},{name:"claude-sonnet-4-20250514",provider:"claude",description:"Claude Sonnet 4",cost:"$3/$15"},{name:"claude-3-7-sonnet-20250219",provider:"claude",description:"Claude 3.7 Sonnet (hybrid reasoning)",cost:"$3/$15"},{name:"claude-3-5-sonnet-20241022",provider:"claude",description:"Claude 3.5 Sonnet",cost:"$3/$15"},{name:"claude-3-5-haiku-20241022",provider:"claude",description:"Claude 3.5 Haiku \u2014 fast and cheap",cost:"$0.80/$4"},{name:"claude-3-opus-20240229",provider:"claude",description:"Claude 3 Opus",cost:"$15/$75"}];function cH({currentModel:e,onSelect:t,onCancel:n}){let[r,s]=aH(""),[i,o]=aH(()=>Math.max(0,lP.findIndex(l=>l.name===e))),a=r?lP.filter(l=>l.name.toLowerCase().includes(r.toLowerCase())||l.description.toLowerCase().includes(r.toLowerCase())):lP,c=Math.min(i,a.length-1);return jCe((l,u)=>{if(u.escape){n();return}if(u.return){a[c]&&t(a[c]);return}if(u.upArrow){o(d=>Math.max(0,Math.min(a.length-1,d)-1));return}if(u.downArrow){o(d=>Math.min(a.length-1,d+1));return}if(u.backspace||u.delete){s(d=>d.slice(0,-1)),o(0);return}l&&!u.ctrl&&!u.meta&&(s(d=>d+l),o(0))}),ua(qg,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,marginX:1,children:[ua(qg,{gap:1,children:[Xr(er,{color:"cyan",bold:!0,children:"/model"}),Xr(er,{color:"gray",children:"Select model:"}),ua(er,{color:"white",inverse:!0,children:[" ",r||" "]}),!r&&Xr(er,{color:"gray",dimColor:!0,children:" type to search"})]}),ua(qg,{flexDirection:"column",marginTop:1,children:[a.length===0?ua(er,{color:"yellow",dimColor:!0,children:[' No models match "',r,'"']}):a.slice(0,12).map((l,u)=>{let d=u===c,f=l.name===e;return ua(qg,{gap:1,children:[Xr(er,{color:d?"cyan":"gray",children:d?"\u25B8":" "}),Xr(er,{color:d?"cyan":l.provider==="gemini"?"magenta":"yellow",bold:d,children:l.name.padEnd(28)}),Xr(er,{color:d?"white":"gray",dimColor:!d,children:l.description}),f&&Xr(er,{color:"green",children:" \u2713"})]},l.name)}),a.length>12&&ua(er,{color:"gray",dimColor:!0,children:[" (+",a.length-12," more \u2014 keep typing to filter)"]})]}),ua(qg,{marginTop:1,gap:2,children:[Xr(er,{color:"gray",dimColor:!0,children:"ESC to cancel"}),Xr(er,{color:"gray",children:"\u2022"}),Xr(er,{color:"gray",dimColor:!0,children:"\u2191\u2193 to navigate"}),Xr(er,{color:"gray",children:"\u2022"}),Xr(er,{color:"gray",dimColor:!0,children:"\u21B5 to select"})]})]})}Mr();Zi();Iy();tf();Ey();cf();XT();Xg();x$();import{jsx as xe,jsxs as da}from"react/jsx-runtime";function dH(){let{exit:e}=BCe(),{stdout:t}=NCe(),n=Ts(),r=process.cwd(),s=no(r),[i,o]=mt(n.provider),[a,c]=mt(of(n,n.provider)),[l,u]=mt(()=>Wd(n.provider,As(n,n.provider),of(n,n.provider))),[d,f]=mt(n.permissions.mode),[p,m]=mt([]),[g,h]=mt(""),[v,y]=mt(!1),[b,k]=mt([]),[S,x]=mt(0),[A,D]=mt(null),[M,ee]=mt(!1),[Ne,mn]=mt(!0),[nn,De]=mt(null),[Et,gn]=mt(null),[T,le]=mt(null),[ie,C]=mt(!1),[I,$e]=mt(!1),[ot,nr]=mt([]),[rr,J]=mt(null),[be]=mt(()=>Ry(n.permissions.mode,n.permissions.rules)),[Ge]=mt(()=>My(n.hooks)),[hn]=mt(()=>nh()),[yn]=mt(()=>{let P=ef(r,i,a);return global.__currentSession=P,P});lH(()=>{HF(P=>gn(P))},[]),lH(()=>{As(n,i)||D(`No API key for ${i}. Run /login to set credentials.`),Promise.resolve().then(()=>(vy(),gF)).then(K=>K.initTodoStore(r)).catch(()=>{}),Promise.resolve().then(()=>(Cc(),$c)).then(K=>{if(K.getConfig().enabled&&!K.getAgentIdentity("root-agent"))try{K.createAgentIdentity({agentId:"root-agent"})}catch{}}).catch(()=>{});let rn=null;return Promise.resolve().then(()=>(M0(),I0)).then(K=>{K.startAutoDreamScheduler(l,1800*1e3),rn=K.stopAutoDreamScheduler}).catch(()=>{}),Promise.resolve().then(()=>(B1(),j1)).then(K=>{K.registerPresence();let sn=K.loadTeamConfig();sn.enabled&&sn.mode!=="disabled"&&sn.mode!=="manual"&&(K.startAutoSync(sn.intervalMs,sn.mode),sn.enableFileWatcher&&K.startFileWatcher())}).catch(()=>{}),Promise.resolve().then(()=>(Br(),jr)).then(K=>{let sn=process.cwd();K.isIndexed(sn)&&K.loadProject(sn)}).catch(()=>{}),Promise.resolve().then(()=>(Mf(),If)).then(K=>{K.initFileDiff(process.cwd())}).catch(()=>{}),Promise.resolve().then(()=>(Lp(),Fp)).then(async K=>{try{let{listSessions:sn,loadSession:fa}=await Promise.resolve().then(()=>(tf(),bP)),Hg=sn().slice(0,30);for(let zg of Hg){if(K.isSessionIndexed(zg.id))continue;let pa=fa(zg.id);pa?.messages&&pa.messages.length>2&&await K.indexSession({sessionId:pa.id,projectPath:pa.cwd||process.cwd(),messages:pa.messages})}}catch{}}).catch(()=>{}),Promise.resolve().then(()=>(C0(),$0)).then(async K=>{try{let{briefing:sn,diff:fa}=await K.diffSinceLastSession(process.cwd(),yn.id,{format:"plain",detail:"brief"});fa&&fa.significance!=="none"&&(D(`\u{1F4CB} ${sn}`),yn.resumeBriefing=K.formatBriefing(fa,{format:"markdown",detail:"detailed"}))}catch{}}).catch(()=>{}),()=>{rn&&rn()}},[]),uH((P,rn)=>{rn.escape&&v&&nn&&(nn.abort(),y(!1),h(""),k([]),gn(null),$e(!0),D("\u{1F500} Interrupted. Redirect AIACA below \u2014 or press Enter on an empty line to just stop."))});let li=uP(P=>{Et&&(Et.resolve(P),zF(),gn(null))},[Et]),Ce=uP(P=>{let rn=As(n,P),K=of(n,P);o(P),c(K),u(Wd(P,rn,K))},[n]),bn=uP(async P=>{if(I){if($e(!1),!P.trim()){D("\u23F9 Stopped.");return}P=`[Redirect \u2014 I interrupted the previous work. New focus:] ${P}`}if(!P.trim())return;mn(!1),D(null);let rn=await Promise.resolve().then(()=>(Na(),Ba)),K=rn.detectReturn(p);if(K&&K.durationMs&&K.durationMs>6e4){let re=rn.summarizeHeuristic(K);(re.totalEvents>0||(K.durationMs||0)>300*1e3)&&D(`\u{1F44B} Welcome back! ${re.briefSummary}`)}rn.recordActivity();try{let re=await Promise.resolve().then(()=>(rg(),ng));if(re.getConfig().enableLearning){let Ht=P.startsWith("/");re.recordUsage(P,Ht?"command":"prior_query",{projectPath:process.cwd()})}}catch{}if(Promise.resolve().then(()=>(M0(),I0)).then(re=>re.recordActivity()).catch(()=>{}),qU(P)){let{name:re,args:Ht}=UU(P);if(re==="help"){ee(!0);return}if((re==="model"||re==="m")&&!Ht.trim()){C(!0);return}let Gg=NU(re);if(!Gg){D(`Unknown command: /${re}`);return}let Vg={session:yn,config:n,costTracker:hn,permissions:be,setProvider:Ce,setModel:Dt=>{c(Dt),u(Wd(i,As(n,i),Dt))},setPermissionMode:Dt=>{f(Dt),be.mode=Dt},clearHistory:()=>{m([]),D("History cleared.")},compact:async()=>{if(p.length<4){D("Too few messages.");return}let Dt=await zy(p,l);Dt.summary&&(m(Gy(p,Dt.summary)),D(`Compacted (~${Dt.tokensSaved} tokens saved)`))},exit:()=>{ml(yn),e()}},xs=await Gg.handler(Ht,Vg);if(xs)if(xs.startsWith("__RESUME__")){let Dt=JSON.parse(xs.slice(10));m(Dt),D(`Resumed (${Dt.length} messages)`)}else D(xs);return}y(!0),h(""),k([]),nr([]),J(null),x(Date.now());let sn=new AbortController;De(sn),le(P);let fa={role:"user",content:P,timestamp:new Date().toISOString()},Hg=[...p,fa],zg=re=>{re.type==="text"&&re.text&&h(Ht=>Ht+re.text)},pa=re=>{k(Ht=>[...Ht,{name:re.name,input:re.input,status:"running"}])},pH=(re,Ht,Gg)=>{let Vg=Ht.startsWith("Error")||Ht.startsWith("\u{1F6AB}");if(k(xs=>xs.map(Dt=>Dt.name===re.name&&Dt.status==="running"?{...Dt,status:Vg?"error":"done",output:Ht,durationMs:Gg}:Dt)),!Vg){let xs=re.input?.path,Dt=re.name==="file_write"?Ht.includes("created")?"created":"wrote":re.name==="file_edit"||re.name==="notebook_edit"?"edited":re.name==="doc_create"?"created":null;Dt&&xs&&nr(Z0=>Z0.some(fP=>fP.path===xs&&fP.action===Dt)?Z0:[...Z0,{path:xs,action:Dt}])}};try{let re=await _v(Hg,{provider:l,cwd:r,config:n,session:yn,permissions:be,hooks:Ge,costTracker:hn,abortSignal:sn.signal,onStream:zg,onToolStart:pa,onToolEnd:pH,onError:Ht=>{Ht.recoverable||D(Ht.message)}});sn.signal.aborted||(m(re),yn.messages=re,ml(yn),nr(Ht=>(Ht.length&&J(Ht),Ht)))}catch(re){re.code!=="ABORTED"&&D(`Error: ${re.message}`),sn.signal.aborted||m(Hg)}y(!1),h(""),k([]),De(null),le(null)},[p,l,i,n,yn,be,Ge,hn,r,Ce,e,I]),Ug=Math.max(4,(t?.rows||30)-10),dP=new Set,Q0=p.filter((P,rn)=>{if(P.role==="user"&&P.content.startsWith("<tool_result")||P.role==="user"&&/^Tool result:|^\[Tool result/.test(P.content)||P.role==="user"&&P.content.includes("<intent_reminder")||P.role==="user"&&P.content.startsWith("[System:")||P.role==="assistant"&&!P.content.trim()||P.role==="assistant"&&P.content.startsWith("[Calling:"))return!1;if(P.role==="user"){let K=`user:${P.content.slice(0,200)}`;if(dP.has(K))return!1;dP.add(K)}return!0}).slice(-Ug);return M?da(tr,{flexDirection:"column",children:[xe(GU,{visible:!0}),xe(aP,{onSubmit:()=>ee(!1),prefix:"press enter to close"})]}):ie?da(tr,{flexDirection:"column",children:[xe(tr,{flexDirection:"column",paddingX:1,children:Q0.map((P,rn)=>xe(V0,{message:P},`${P.timestamp}-${rn}`))}),xe(cH,{currentModel:a,onSelect:P=>{Ce(P.provider),setTimeout(()=>{c(P.name),u(Wd(P.provider,As(n,P.provider),P.name)),D(`Switched to ${P.provider} (${P.name})`),C(!1)},0)},onCancel:()=>C(!1)}),xe(G0,{provider:i,model:a,mode:d,costTracker:hn,messageCount:p.length,cwd:r})]}):Et?da(tr,{flexDirection:"column",children:[xe(tr,{flexDirection:"column",paddingX:1,children:Q0.map((P,rn)=>xe(V0,{message:P},`${P.timestamp}-${rn}`))}),xe(qCe,{pending:Et,onDecision:li}),xe(G0,{provider:i,model:a,mode:d,costTracker:hn,messageCount:p.length,cwd:r})]}):da(tr,{flexDirection:"column",children:[Ne&&p.length===0&&xe(pP,{provider:i,model:a,cwd:r,gitBranch:s.isRepo?s.branch:void 0}),xe(iH,{active:v}),da(tr,{flexDirection:"column",paddingX:1,flexGrow:1,children:[Q0.map((P,rn)=>xe(V0,{message:P},`${P.timestamp}-${rn}`)),T&&xe(tr,{flexDirection:"column",marginBottom:1,children:xe(tr,{borderStyle:"single",borderColor:"cyan",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:1,children:xe(dl,{color:"white",children:T})})}),b.length>0||v&&!g||g?xe(tH,{tools:b.map(P=>({name:P.name,input:P.input,status:P.status,output:P.output,durationMs:P.durationMs})),thinking:v,streamText:g,startTime:S}):null,A&&xe(WU,{text:A,level:"info"}),!v&&rr&&xe(oH,{changes:rr}),I&&da(tr,{borderStyle:"round",borderColor:"magenta",paddingX:1,marginX:1,marginTop:1,children:[xe(dl,{color:"magentaBright",bold:!0,children:"\u{1F500} Redirect AIACA"}),xe(dl,{color:"gray",children:" \u2014 tell it what to focus on instead (Enter on empty line to stop)"})]})]}),xe(tr,{paddingX:1,children:xe(aP,{onSubmit:bn,disabled:v,placeholder:I?"Steer AIACA in a new direction\u2026":void 0})}),xe(G0,{provider:i,model:a,mode:d,costTracker:hn,messageCount:p.length,cwd:r})]})}function qCe({pending:e,onDecision:t}){let[n,r]=mt(0),s=[{label:"Allow",key:"y",value:"allow",color:"green"},{label:"Deny",key:"n",value:"deny",color:"red"},{label:"Always allow",key:"a",value:"always",color:"cyan"}];return uH((i,o)=>{o.leftArrow&&r(a=>Math.max(0,a-1)),o.rightArrow&&r(a=>Math.min(2,a+1)),o.return&&t(s[n].value),i==="y"&&t("allow"),i==="n"&&t("deny"),i==="a"&&t("always")}),da(tr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,marginX:1,marginY:1,children:[da(tr,{gap:1,children:[xe(dl,{color:"yellow",bold:!0,children:"\u26A0 Permission"}),xe(dl,{color:"cyan",bold:!0,children:e.toolName})]}),xe(tr,{paddingLeft:2,children:xe(dl,{children:e.description})}),xe(tr,{marginTop:1,gap:2,children:s.map((i,o)=>xe(dl,{color:o===n?i.color:"gray",bold:o===n,inverse:o===n,children:` ${i.label} (${i.key}) `},i.key))})]})}hl();import{jsx as GCe}from"react/jsx-runtime";process.setMaxListeners(50);var HCe=process.stderr.write.bind(process.stderr);process.stderr.write=((e,...t)=>{let n=typeof e=="string"?e:e?.toString?.()||"";return n.includes("non-text parts")||n.includes("API key should be set when using the Gemini API")?!0:HCe(e,...t)});process.on("exit",()=>{try{let e=global.__currentSession;e?.id&&(C0(),sr($0)).captureSnapshot(process.cwd(),e.id,`Session ended with ${e.messages?.length||0} messages`).catch(()=>{})}catch{}try{let e=global.__currentSession;e?.id&&(fs(),sr(ds)).teardownSession(e.id,"process_exit"),(fs(),sr(ds)).destroyAllSessions("process_exit")}catch{}});var fH=e=>{try{(fs(),sr(ds)).destroyAllSessions(e)}catch{}};process.on("SIGINT",()=>fH("SIGINT"));process.on("SIGTERM",()=>fH("SIGTERM"));async function zCe(){aS()||await cS(),UCe(GCe(dH,{}))}zCe().catch(e=>{console.error("AIACA startup error:",e),process.exit(1)});