agentix-cli 0.52.1 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/{App-X6FGYBLX.js → App-R62ZQVSF.js} +2 -2
  2. package/dist/{ChatApp-XMUOXQ2M.js → ChatApp-AS567EFE.js} +2 -2
  3. package/dist/{agent-KKVMU3VB.js → agent-H4NB4BUA.js} +2 -2
  4. package/dist/{board-dashboard-KETIFTBD.js → board-dashboard-E3MUVNVQ.js} +446 -144
  5. package/dist/board-dashboard-E3MUVNVQ.js.map +1 -0
  6. package/dist/{chunk-3IUU4YFI.js → chunk-47EEUZBK.js} +5 -5
  7. package/dist/{chunk-3IUU4YFI.js.map → chunk-47EEUZBK.js.map} +1 -1
  8. package/dist/{chunk-B5UA3X6E.js → chunk-6OOK7Y4S.js} +2 -2
  9. package/dist/{chunk-E57WKMRR.js → chunk-7DPKPBRJ.js} +2 -2
  10. package/dist/{chunk-AKAM4BNC.js → chunk-7OWXFLAM.js} +13 -13
  11. package/dist/{chunk-AWRRBNWQ.js → chunk-C5JXPMTW.js} +2 -2
  12. package/dist/{chunk-H7R3F2CO.js → chunk-CCMM5TP4.js} +2 -2
  13. package/dist/{chunk-WCNKTV6G.js → chunk-D4HAR3L3.js} +14 -14
  14. package/dist/chunk-D4HAR3L3.js.map +1 -0
  15. package/dist/{chunk-7BQQWI4T.js → chunk-FS4WBYY3.js} +2 -2
  16. package/dist/chunk-FSZXY53Z.js +7 -0
  17. package/dist/chunk-FSZXY53Z.js.map +1 -0
  18. package/dist/{chunk-64UYAWAK.js → chunk-IDYP7G7Z.js} +6 -6
  19. package/dist/chunk-IDYP7G7Z.js.map +1 -0
  20. package/dist/{chunk-7NF45XCM.js → chunk-KB7YIM3W.js} +2 -2
  21. package/dist/{chunk-XOUIZBAQ.js → chunk-KFG6WWFS.js} +2 -2
  22. package/dist/{chunk-YPPTPBBV.js → chunk-KJWBQZT7.js} +2 -2
  23. package/dist/{chunk-MHBUAU2B.js → chunk-NF52Q3TV.js} +2 -2
  24. package/dist/{chunk-YS3Z2Z64.js → chunk-OMTRHHZJ.js} +13 -13
  25. package/dist/chunk-OMTRHHZJ.js.map +1 -0
  26. package/dist/{chunk-QDPLR3SB.js → chunk-OV35MJKS.js} +2 -2
  27. package/dist/{chunk-QZ4M2KAC.js → chunk-PGJL5V6Y.js} +2 -2
  28. package/dist/{chunk-76NNONUJ.js → chunk-QU6ZUKAD.js} +2 -2
  29. package/dist/chunk-SABOPOYX.js +1111 -0
  30. package/dist/chunk-SABOPOYX.js.map +1 -0
  31. package/dist/{chunk-NKSCUCVZ.js → chunk-TH5KNJLA.js} +2 -2
  32. package/dist/{chunk-7M7VJMGP.js → chunk-VD4TMPJI.js} +2 -2
  33. package/dist/cli.js +1 -1
  34. package/dist/client-XTQDYMOX.js +2 -0
  35. package/dist/{config-FGCJVXYX.js → config-3SW4V44Z.js} +2 -2
  36. package/dist/config-mutator-H32FXUYJ.js +2 -0
  37. package/dist/doctor-J6RCHFVE.js +2 -0
  38. package/dist/index.d.ts +42 -0
  39. package/dist/index.js +1 -1
  40. package/dist/program-SQTOPCQW.js +2 -0
  41. package/dist/{promote-NBFF7ZIW.js → promote-DJFMTLRC.js} +2 -2
  42. package/dist/query-UAZUMU4N.js +2 -0
  43. package/dist/{registry-5ZP3ZNSH.js → registry-4OUBA2TY.js} +2 -2
  44. package/dist/{request-planner-ZEXFARZE.js → request-planner-2H7HCUCZ.js} +2 -2
  45. package/dist/{review-candidates-F2HNH2TZ.js → review-candidates-U7R64OCS.js} +2 -2
  46. package/dist/{routing-XSRZ7V23.js → routing-LVQH6WOJ.js} +2 -2
  47. package/dist/schedule-tool-2BONJVCJ.js +2 -0
  48. package/dist/scheduler-7CEXDECA.js +2 -0
  49. package/dist/{seat-IPDLEUI5.js → seat-2KGFNCIW.js} +2 -2
  50. package/dist/{select-BYOX63CR.js → select-XGK27RPP.js} +2 -2
  51. package/dist/set-enabled-7YGN2FAZ.js +2 -0
  52. package/dist/set-enabled-7YGN2FAZ.js.map +1 -0
  53. package/dist/{tool-WW4YCMSP.js → tool-HKDIZ6I4.js} +2 -2
  54. package/dist/wiki-6YT7B5HU.js +2 -0
  55. package/package.json +1 -1
  56. package/dist/board-dashboard-KETIFTBD.js.map +0 -1
  57. package/dist/chunk-64UYAWAK.js.map +0 -1
  58. package/dist/chunk-6BXKZY76.js +0 -7
  59. package/dist/chunk-6BXKZY76.js.map +0 -1
  60. package/dist/chunk-7PK32QT5.js +0 -1107
  61. package/dist/chunk-7PK32QT5.js.map +0 -1
  62. package/dist/chunk-WCNKTV6G.js.map +0 -1
  63. package/dist/chunk-YS3Z2Z64.js.map +0 -1
  64. package/dist/client-AVQSLPIZ.js +0 -2
  65. package/dist/config-mutator-5JSG3CHW.js +0 -2
  66. package/dist/doctor-VITHTLEC.js +0 -2
  67. package/dist/program-MNFDOQGQ.js +0 -2
  68. package/dist/query-XCXR57IV.js +0 -2
  69. package/dist/schedule-tool-AKCVLCWK.js +0 -2
  70. package/dist/scheduler-BEGZJWJU.js +0 -2
  71. package/dist/wiki-IVJJQUKB.js +0 -2
  72. /package/dist/{App-X6FGYBLX.js.map → App-R62ZQVSF.js.map} +0 -0
  73. /package/dist/{ChatApp-XMUOXQ2M.js.map → ChatApp-AS567EFE.js.map} +0 -0
  74. /package/dist/{agent-KKVMU3VB.js.map → agent-H4NB4BUA.js.map} +0 -0
  75. /package/dist/{chunk-B5UA3X6E.js.map → chunk-6OOK7Y4S.js.map} +0 -0
  76. /package/dist/{chunk-E57WKMRR.js.map → chunk-7DPKPBRJ.js.map} +0 -0
  77. /package/dist/{chunk-AKAM4BNC.js.map → chunk-7OWXFLAM.js.map} +0 -0
  78. /package/dist/{chunk-AWRRBNWQ.js.map → chunk-C5JXPMTW.js.map} +0 -0
  79. /package/dist/{chunk-H7R3F2CO.js.map → chunk-CCMM5TP4.js.map} +0 -0
  80. /package/dist/{chunk-7BQQWI4T.js.map → chunk-FS4WBYY3.js.map} +0 -0
  81. /package/dist/{chunk-7NF45XCM.js.map → chunk-KB7YIM3W.js.map} +0 -0
  82. /package/dist/{chunk-XOUIZBAQ.js.map → chunk-KFG6WWFS.js.map} +0 -0
  83. /package/dist/{chunk-YPPTPBBV.js.map → chunk-KJWBQZT7.js.map} +0 -0
  84. /package/dist/{chunk-MHBUAU2B.js.map → chunk-NF52Q3TV.js.map} +0 -0
  85. /package/dist/{chunk-QDPLR3SB.js.map → chunk-OV35MJKS.js.map} +0 -0
  86. /package/dist/{chunk-QZ4M2KAC.js.map → chunk-PGJL5V6Y.js.map} +0 -0
  87. /package/dist/{chunk-76NNONUJ.js.map → chunk-QU6ZUKAD.js.map} +0 -0
  88. /package/dist/{chunk-NKSCUCVZ.js.map → chunk-TH5KNJLA.js.map} +0 -0
  89. /package/dist/{chunk-7M7VJMGP.js.map → chunk-VD4TMPJI.js.map} +0 -0
  90. /package/dist/{client-AVQSLPIZ.js.map → client-XTQDYMOX.js.map} +0 -0
  91. /package/dist/{config-FGCJVXYX.js.map → config-3SW4V44Z.js.map} +0 -0
  92. /package/dist/{config-mutator-5JSG3CHW.js.map → config-mutator-H32FXUYJ.js.map} +0 -0
  93. /package/dist/{doctor-VITHTLEC.js.map → doctor-J6RCHFVE.js.map} +0 -0
  94. /package/dist/{program-MNFDOQGQ.js.map → program-SQTOPCQW.js.map} +0 -0
  95. /package/dist/{promote-NBFF7ZIW.js.map → promote-DJFMTLRC.js.map} +0 -0
  96. /package/dist/{query-XCXR57IV.js.map → query-UAZUMU4N.js.map} +0 -0
  97. /package/dist/{registry-5ZP3ZNSH.js.map → registry-4OUBA2TY.js.map} +0 -0
  98. /package/dist/{request-planner-ZEXFARZE.js.map → request-planner-2H7HCUCZ.js.map} +0 -0
  99. /package/dist/{review-candidates-F2HNH2TZ.js.map → review-candidates-U7R64OCS.js.map} +0 -0
  100. /package/dist/{routing-XSRZ7V23.js.map → routing-LVQH6WOJ.js.map} +0 -0
  101. /package/dist/{schedule-tool-AKCVLCWK.js.map → schedule-tool-2BONJVCJ.js.map} +0 -0
  102. /package/dist/{scheduler-BEGZJWJU.js.map → scheduler-7CEXDECA.js.map} +0 -0
  103. /package/dist/{seat-IPDLEUI5.js.map → seat-2KGFNCIW.js.map} +0 -0
  104. /package/dist/{select-BYOX63CR.js.map → select-XGK27RPP.js.map} +0 -0
  105. /package/dist/{tool-WW4YCMSP.js.map → tool-HKDIZ6I4.js.map} +0 -0
  106. /package/dist/{wiki-IVJJQUKB.js.map → wiki-6YT7B5HU.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ import{g as j,h as x,o as O,p as I}from"./chunk-S7CVSKOX.js";import{m as S,p as L}from"./chunk-47EEUZBK.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as E,constants as T,existsSync as y,readFileSync as b,readdirSync as $,statSync as B}from"fs";import{join as P,resolve as m}from"path";import{homedir as M}from"os";import{createRequire as X}from"module";import{execFile as _}from"child_process";var q=(n,t)=>new Promise(e=>{try{_(n,t,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),R="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function N(n={}){if((n.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let t=n.helper===void 0?I():n.helper;if(!t)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(n.run??q)(t,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:t,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:t,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:R}:i.alertStyle==="none"?{state:"hidden",path:t,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:R}:{state:"ready",path:t,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:t,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(n={}){let t=[];await G(t),V(t);let e=K(t);return e&&U(t,e),e&&Q(t,e),e&&Y(t,e),e&&ee(t,e),e&&ne(t,e),e&&await F(t,e),e&&Z(t,e),n.running!==!1&&e&&await te(t,e),{checks:t,summary:W(t)}}var we=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async n=>{let{checks:t,summary:e}=await J({running:n.running!==!1});n.json?process.stdout.write(JSON.stringify({checks:t,summary:e},null,2)+`
2
+ `):ie(t),process.exit(e.errors>0?1:0)});async function F(n,t,e=N){if(!O(t.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&n.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function Z(n,t,e=process.platform,i=s=>{try{return E(s,T.X_OK),!0}catch{return!1}}){let s=t.reminders;if(!s?.enabled)return;if(e!=="darwin"){n.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let r=s.command||"remindctl",a=r.includes("/")?i(r)?r:null:x(r,process.env.PATH||"",i);n.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${r} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function G(n){let t=Number(process.versions.node.split(".")[0]);n.push({severity:t==22?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:t==22?void 0:"AgentX requires Node 22.x.",fix:t==22?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return h(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
3
+ `)[0]}catch{return null}},i=e("npm");n.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else n.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let l;try{l=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else n.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else n.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{X(import.meta.url)("better-sqlite3"),n.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){n.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function V(n){if(process.platform!=="darwin")return;let t=P(M(),"Library/LaunchAgents"),e=[];try{e=$(t).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return E(s,T.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(P(t,s),"utf-8")),a=x("ffmpeg",r,i);n.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${r}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function K(n){let t=m(process.cwd(),"agentx.json");if(!y(t))return n.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${t}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(t,"utf-8"))}catch(a){return n.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(t),n.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){n.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function U(n,t){let e=new Set;if(C(t,e),e.size===0){n.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=m(process.cwd(),".env"),s={};if(y(i))for(let l of b(i,"utf-8").split(/\r?\n/)){let u=l.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);u&&(s[u[1]]=u[2])}let r=[],a=[];for(let l of e){let u=process.env[l]??s[l];u===void 0?r.push(l):(!u.trim()||/^["']?\s*["']?$/.test(u))&&a.push(l)}r.length===0&&a.length===0?n.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&n.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),a.length>0&&n.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(n,t){if(typeof n=="string")for(let e of n.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))t.add(e[1]);else if(Array.isArray(n))for(let e of n)C(e,t);else if(n&&typeof n=="object")for(let e of Object.values(n))C(e,t)}function Q(n,t){let e=[];for(let[i,s]of Object.entries(t.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{B(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?n.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):n.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
4
+ `),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function Y(n,t){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(t.agents||{})){if(!r.workspace)continue;let a=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let l of["settings.json","settings.local.json"]){let u=m(a,".claude",l);if(!y(u))continue;let w;try{w=JSON.parse(b(u,"utf-8"))}catch(d){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${d.message}`});continue}let k=w.env||{};for(let[d,p]of Object.entries(k)){if(typeof p!="string")continue;let g=p.match(e);g&&i.push({severity:"fail",agent:s,msg:`${l} env.${d} contains unexpanded ${[...new Set(g)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let o=k.PATH;if(typeof o=="string"){let d=o.split(":").filter(Boolean);d.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){n.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(t.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)n.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function ee(n,t){let e=t.webhooks??[],i=[],s=m(process.cwd(),t.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let o of $(s))o.endsWith(".json")&&!o.startsWith("_")&&!o.endsWith(".disabled.json")&&r.add(o.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let o of e){if(!o.enabled||!a.has(o.source))continue;!(o.triggers&&Object.keys(o.triggers).length>0)&&!o.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${o.id}" (${o.source} -> ${o.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let o of e)if(!(!o.enabled||!o.triggers)){for(let[c,d]of Object.entries(o.triggers))r.size>0&&!r.has(d)&&i.push({severity:"fail",title:`webhook "${o.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${t.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});o.defaultWorkflow&&r.size>0&&!r.has(o.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${o.id}".defaultWorkflow -> "${o.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let o of $(s))if(!(!o.endsWith(".json")||o.startsWith("_")||o.endsWith(".disabled.json")))try{let c=JSON.parse(b(m(s,o),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${c.id??o}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((t.mesh?.peers??[]).map(o=>o.name));for(let o of e)!o.enabled||!o.node||l.has(o.node)||i.push({severity:"fail",title:`webhook "${o.id}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let o of e){if(!o.enabled)continue;let c=`${o.source}:${o.agentId}`,d=u.get(c);d?i.push({severity:"warn",title:`webhook entries "${d}" and "${o.id}" both enabled for ${o.source} -> ${o.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(c,o.id)}let w=new Set(Object.keys(t.agents??{}));for(let o of t.channels?.gitlab?.agentMappings??[])if(o?.agentId){if(o.node){l.has(o.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${o.agentId}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(o.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${o.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[o,c]of Object.entries(t.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||i.push({severity:"fail",title:`telegram account "${o}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${o}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let k=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[o,c]of Object.entries(t.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let g of d){let A=`${g.kind}::${g.label}`;p.has(A)&&i.push({severity:"warn",title:`agents.${o}.integrations: duplicate (${g.kind}, ${g.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(A),k.has(g.kind)||i.push({severity:"warn",title:`agents.${o}.integrations: unknown kind "${g.kind}" on integration "${g.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let H=g.credentials||{};for(let[D,v]of Object.entries(H))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${o}.integrations[${g.kind}/${g.label}].${D} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){n.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(t.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)n.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}async function te(n,t){let e=t.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};t.dashboard?.token&&(i.Authorization=`Bearer ${t.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(r),!a.ok){n.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();n.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e})}catch{n.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function ne(n,t){let e=Object.entries(t.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
5
+ `)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else n.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){n.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=m(r.workspace,".codegraph","codegraph.db");y(a)?n.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):n.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function W(n){return{errors:n.filter(t=>t.severity==="fail").length,warnings:n.filter(t=>t.severity==="warn").length,ok:n.filter(t=>t.severity==="ok").length}}function ie(n){console.log(),console.log(f.bold(" agentx doctor")),console.log();let t=new Map;for(let i of n)t.has(i.group)||t.set(i.group,[]),t.get(i.group).push(i);for(let[i,s]of t){console.log(f.bold(" "+i));for(let r of s){let a=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
6
+ `))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=W(n);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{N as a,J as b,we as c,F as d,Z as e};
7
+ //# sourceMappingURL=chunk-FSZXY53Z.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/doctor.ts","../src/notify/helper-status.ts"],"sourcesContent":["import { Command } from \"commander\"\nimport chalk from \"chalk\"\nimport { execFileSync } from \"child_process\"\nimport { accessSync, constants, existsSync, readFileSync, readdirSync, statSync } from \"fs\"\nimport { join, resolve } from \"path\"\nimport { homedir } from \"os\"\nimport { createRequire } from \"module\"\nimport { loadDaemonConfig } from \"@/daemon/config\"\nimport { findOnPath, plistPathEnv } from \"@/desktop/install\"\nimport { localSettings } from \"@/notify/local\"\nimport { helperStatus } from \"@/notify/helper-status\"\n\n// --- agentx doctor ---\n//\n// Pre-flight health check. Catches the common \"why isn't it working\" reasons\n// before the operator hits them at runtime:\n// - wrong Node version\n// - invalid / missing agentx.json\n// - agents with claude-code tier but no claude CLI installed\n// - ${FOO} references in agentx.json that have no matching env var\n// - agent workspace dirs that don't exist\n// - daemon reachable? (when --check-running, default true)\n//\n// Exit code: 0 if clean, 1 if any error, 0 if only warnings (so CI won't block\n// on advisory checks).\n\nexport type Severity = \"ok\" | \"warn\" | \"fail\"\n\nexport interface Check {\n severity: Severity\n group: string\n title: string\n detail?: string\n fix?: string\n}\n\n/** Run every preflight check and return the result as data. Exposed so\n * the dashboard's /admin/doctor route can render the same checks the\n * `agentx doctor` CLI prints — without spawning a child process. */\nexport async function runDoctorChecks(\n opts: { running?: boolean } = {},\n): Promise<{ checks: Check[]; summary: { errors: number; warnings: number; ok: number } }> {\n const checks: Check[] = []\n await runEnvChecks(checks)\n runDesktopChecks(checks)\n const cfg = runConfigChecks(checks)\n if (cfg) runReferenceChecks(checks, cfg)\n if (cfg) runWorkspaceChecks(checks, cfg)\n if (cfg) runWorkspaceSettingsChecks(checks, cfg)\n if (cfg) runRoutingChecks(checks, cfg)\n if (cfg) runCodegraphChecks(checks, cfg)\n if (cfg) await runNotificationChecks(checks, cfg)\n if (cfg) runReminderChecks(checks, cfg)\n if (opts.running !== false && cfg) await runRuntimeChecks(checks, cfg)\n return { checks, summary: summarize(checks) }\n}\n\nexport const doctor = new Command()\n .name(\"doctor\")\n .description(\"pre-flight health check: Node, config, credentials, daemon\")\n .option(\"--no-running\", \"skip the live daemon probe\")\n .option(\"--json\", \"emit machine-readable JSON (stable shape for CI)\")\n .action(async (opts) => {\n const { checks, summary } = await runDoctorChecks({ running: opts.running !== false })\n if (opts.json) {\n process.stdout.write(JSON.stringify({ checks, summary }, null, 2) + \"\\n\")\n } else {\n printHumanReport(checks)\n }\n process.exit(summary.errors > 0 ? 1 : 0)\n })\n\n// ---------------------------------------------------------------------------\n// Checks\n// ---------------------------------------------------------------------------\n\n/** On a Mac with banners on: can AgentX Helper post them with its icon? */\nexport async function runNotificationChecks(checks: Check[], cfg: any, status = helperStatus): Promise<void> {\n if (!localSettings(cfg.notifications?.local).banner) return\n const helper = await status()\n if (helper.state === \"unsupported\") return\n checks.push({\n severity: helper.state === \"ready\" ? \"ok\" : \"warn\",\n group: \"Notifications\",\n title: helper.message,\n detail: helper.path,\n fix: helper.fix,\n })\n}\n\n/** reminders.enabled: macOS only, and the daemon needs remindctl. */\nexport function runReminderChecks(\n checks: Check[],\n cfg: any,\n platform: NodeJS.Platform = process.platform,\n isExecutable: (file: string) => boolean = (file) => { try { accessSync(file, constants.X_OK); return true } catch { return false } },\n): void {\n const r = cfg.reminders\n if (!r?.enabled) return\n if (platform !== \"darwin\") {\n checks.push({\n severity: \"warn\",\n group: \"Reminders\",\n title: \"Reminders hand-back unavailable on this machine\",\n detail: \"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.\",\n fix: \"Set reminders.enabled to false here, or enable it on the Mac node instead.\",\n })\n return\n }\n const command = r.command || \"remindctl\"\n const found = command.includes(\"/\") ? (isExecutable(command) ? command : null) : findOnPath(command, process.env.PATH || \"\", isExecutable)\n checks.push(found\n ? { severity: \"ok\", group: \"Reminders\", title: `Watching ${(r.lists || []).join(\", \")} for due reminders`, detail: found }\n : {\n severity: \"fail\",\n group: \"Reminders\",\n title: `${command} not found`,\n detail: \"The daemon reads Apple Reminders through remindctl.\",\n fix: \"brew install steipete/tap/remindctl, or set reminders.command to its full path.\",\n })\n}\n\nasync function runEnvChecks(checks: Check[]): Promise<void> {\n const nodeMajor = Number(process.versions.node.split(\".\")[0])\n checks.push({\n severity: nodeMajor == 22 ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: `Node.js ${process.versions.node}`,\n detail: nodeMajor == 22 ? undefined : \"AgentX requires Node 22.x.\",\n fix: nodeMajor == 22 ? undefined : \"Install Node 22 (nvm install 22 && nvm use 22)\",\n })\n\n const which = (bin: string): string | null => {\n try { return execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [bin], { encoding: \"utf-8\" }).trim().split(\"\\n\")[0] }\n catch { return null }\n }\n const npmPath = which(\"npm\")\n checks.push({\n severity: npmPath ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: npmPath ? \"npm on PATH\" : \"npm not found\",\n detail: npmPath || undefined,\n })\n\n // Claude CLI is only required if the config references claude-code agents;\n // we report it advisory here and promote to fail in the config step below.\n const claudePath = which(\"claude\")\n if (claudePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"claude\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `claude CLI ${ver || \"installed\"}`, detail: claudePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"claude CLI not on PATH\",\n detail: \"Only required for agents on the claude-code tier.\",\n fix: \"See https://docs.anthropic.com/en/docs/claude-code\",\n })\n }\n\n const codexPath = which(\"codex\")\n if (codexPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codex\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `codex CLI ${ver || \"installed\"}`, detail: codexPath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"codex CLI not on PATH\",\n detail: \"Only required for agents on the codex-cli tier.\",\n fix: \"Install with `npm i -g @openai/codex`.\",\n })\n }\n\n const openCodePath = which(\"opencode\")\n if (openCodePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"opencode\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `opencode CLI ${ver || \"installed\"}`, detail: openCodePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"opencode CLI not on PATH\",\n detail: \"Only required for agents on the opencode tier.\",\n fix: \"Install from https://opencode.ai/docs/.\",\n })\n }\n\n try {\n createRequire(import.meta.url)(\"better-sqlite3\")\n checks.push({\n severity: \"ok\",\n group: \"Environment\",\n title: `better-sqlite3 loads for Node ${process.version}`,\n detail: `NODE_MODULE_VERSION ${process.versions.modules}`,\n })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Environment\",\n title: \"better-sqlite3 native binding does not load\",\n detail: e?.message ?? String(e),\n fix: `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`,\n })\n }\n}\n\n/** The desktop app's login item runs with only the PATH its plist sets, so\n * check that local Whisper's ffmpeg is reachable there, not in this shell. */\nfunction runDesktopChecks(checks: Check[]): void {\n if (process.platform !== \"darwin\") return\n // Older installs used another label; apps/mac-voice/install.sh keeps it.\n const agents = join(homedir(), \"Library/LaunchAgents\")\n let names: string[] = []\n try { names = readdirSync(agents).filter(n => /agentx\\.voice.*\\.plist$/.test(n)) } catch { return }\n const isExecutable = (file: string) => { try { accessSync(file, constants.X_OK); return true } catch { return false } }\n for (const name of names) {\n const path = plistPathEnv(readFileSync(join(agents, name), \"utf-8\"))\n const ffmpeg = findOnPath(\"ffmpeg\", path, isExecutable)\n checks.push(ffmpeg\n ? { severity: \"ok\", group: \"Desktop\", title: \"ffmpeg reachable by the desktop app\", detail: `${ffmpeg} (${name})` }\n : {\n severity: \"warn\",\n group: \"Desktop\",\n title: \"ffmpeg not reachable by the desktop app\",\n detail: `Local Whisper transcription fails without it. ${name} sets PATH to ${path}.`,\n fix: \"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install.\",\n })\n }\n}\n\nfunction runConfigChecks(checks: Check[]): any {\n const cfgPath = resolve(process.cwd(), \"agentx.json\")\n if (!existsSync(cfgPath)) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json not found\",\n detail: `Looked in ${cfgPath}`,\n fix: \"Run `agentx setup` to create one via the web wizard.\",\n })\n return null\n }\n let cfg: any\n try { cfg = JSON.parse(readFileSync(cfgPath, \"utf-8\")) }\n catch (e: any) {\n checks.push({ severity: \"fail\", group: \"Config\", title: \"agentx.json is not valid JSON\", detail: e.message })\n return null\n }\n try {\n // Full schema validation — catches missing required fields.\n loadDaemonConfig(cfgPath)\n checks.push({ severity: \"ok\", group: \"Config\", title: `agentx.json valid (${Object.keys(cfg.agents || {}).length} agents, ${Object.keys(cfg.crons || {}).length} schedules)` })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json failed schema validation\",\n detail: e.message,\n fix: \"Open /admin → Advanced tab to edit and re-save.\",\n })\n }\n const claudeCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"claude-code\")\n if (claudeCodeAgents.length > 0) {\n const hasClaude = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"claude\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasClaude) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${claudeCodeAgents.length} agent(s) use claude-code tier but claude CLI is missing`,\n detail: claudeCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk.\",\n })\n }\n }\n const codexCliAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"codex-cli\")\n if (codexCliAgents.length > 0) {\n const hasCodex = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codex\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasCodex) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${codexCliAgents.length} agent(s) use codex-cli tier but codex CLI is missing`,\n detail: codexCliAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code.\",\n })\n }\n }\n const openCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"opencode\")\n if (openCodeAgents.length > 0) {\n const hasOpenCode = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"opencode\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasOpenCode) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${openCodeAgents.length} agent(s) use opencode tier but OpenCode CLI is missing`,\n detail: openCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier.\",\n })\n }\n }\n return cfg\n}\n\nfunction runReferenceChecks(checks: Check[], cfg: any): void {\n // Parse ${VAR} references out of the config (recursively) and verify each\n // one has a matching value in .env or process.env.\n const refs = new Set<string>()\n collectEnvRefs(cfg, refs)\n if (refs.size === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: \"No ${VAR} references in agentx.json\" })\n return\n }\n const envFile = resolve(process.cwd(), \".env\")\n const envFromFile: Record<string, string> = {}\n if (existsSync(envFile)) {\n for (const line of readFileSync(envFile, \"utf-8\").split(/\\r?\\n/)) {\n const m = line.match(/^\\s*([A-Z_][A-Z0-9_]*)\\s*=\\s*(.*)$/i)\n if (m) envFromFile[m[1]] = m[2]\n }\n }\n const missing: string[] = []\n const empty: string[] = []\n for (const name of refs) {\n const raw = process.env[name] ?? envFromFile[name]\n if (raw === undefined) missing.push(name)\n else if (!raw.trim() || /^[\"']?\\s*[\"']?$/.test(raw)) empty.push(name)\n }\n if (missing.length === 0 && empty.length === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: `${refs.size} env reference(s) resolved` })\n } else {\n if (missing.length > 0) {\n checks.push({\n severity: \"fail\",\n group: \"Secrets\",\n title: `${missing.length} env var(s) referenced in agentx.json but missing`,\n detail: missing.join(\", \"),\n fix: `Add to .env — e.g. ${missing[0]}=<value>`,\n })\n }\n if (empty.length > 0) {\n checks.push({\n severity: \"warn\",\n group: \"Secrets\",\n title: `${empty.length} env var(s) set but empty`,\n detail: empty.join(\", \"),\n })\n }\n }\n}\n\nfunction collectEnvRefs(node: unknown, into: Set<string>): void {\n if (typeof node === \"string\") {\n for (const m of node.matchAll(/\\$\\{([A-Z_][A-Z0-9_]*)\\}/g)) into.add(m[1])\n } else if (Array.isArray(node)) {\n for (const item of node) collectEnvRefs(item, into)\n } else if (node && typeof node === \"object\") {\n for (const v of Object.values(node)) collectEnvRefs(v, into)\n }\n}\n\nfunction runWorkspaceChecks(checks: Check[], cfg: any): void {\n const missing: string[] = []\n for (const [id, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const abs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n try {\n const st = statSync(abs)\n if (!st.isDirectory()) missing.push(`${id}: ${abs} (exists but not a directory)`)\n } catch { missing.push(`${id}: ${abs}`) }\n }\n if (missing.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspaces\", title: \"All agent workspace folders exist\" })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Workspaces\",\n title: `${missing.length} agent workspace(s) missing`,\n detail: missing.join(\"\\n \"),\n fix: \"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them.\",\n })\n }\n}\n\n// Audit each agent's .claude/settings.json for known traps:\n// - unexpanded ${VAR} literals in env values (Claude Code does NOT expand them)\n// - env.PATH missing /usr/bin or /bin (basic utils unreachable)\n// - JSON syntax errors\n// - permissions.allow: [] explicitly empty alongside non-empty deny\n// Each finding is FAIL severity for the ${VAR} / PATH cases (these break the\n// agent's Bash tool entirely), WARN for the lockdown case.\nfunction runWorkspaceSettingsChecks(checks: Check[], cfg: any): void {\n const VAR_RE = /\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}/g\n const findings: Array<{ severity: Severity; agent: string; msg: string }> = []\n\n for (const [agentId, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const wsAbs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n for (const fname of [\"settings.json\", \"settings.local.json\"]) {\n const p = resolve(wsAbs, \".claude\", fname)\n if (!existsSync(p)) continue\n let data: any\n try {\n data = JSON.parse(readFileSync(p, \"utf-8\"))\n } catch (e: any) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname}: JSON parse error — ${e.message}` })\n continue\n }\n const env = (data.env || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(env)) {\n if (typeof v !== \"string\") continue\n const unexpanded = v.match(VAR_RE)\n if (unexpanded) {\n findings.push({\n severity: \"fail\",\n agent: agentId,\n msg: `${fname} env.${k} contains unexpanded ${[...new Set(unexpanded)].join(\",\")} — Claude Code does NOT expand \\${VAR} in settings.json (use a fully-literal value)`,\n })\n }\n }\n const pathVal = env.PATH\n if (typeof pathVal === \"string\") {\n const parts = pathVal.split(\":\").filter(Boolean)\n if (!parts.includes(\"/usr/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /usr/bin — cat/head/sh/which will fail` })\n }\n if (!parts.includes(\"/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /bin — ls/cp/mv will fail` })\n }\n }\n const perms = data.permissions\n if (perms && typeof perms === \"object\" && \"allow\" in perms) {\n const allow = perms.allow\n const deny = perms.deny\n if (Array.isArray(allow) && allow.length === 0 && Array.isArray(deny) && deny.length > 0) {\n findings.push({\n severity: \"warn\",\n agent: agentId,\n msg: `${fname} permissions.allow is explicitly [] with ${deny.length} deny rules — agent may be locked out (omit the key to use defaults instead)`,\n })\n }\n }\n }\n }\n\n if (findings.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspace settings\", title: `All ${Object.keys(cfg.agents || {}).length} agent .claude/settings.json files clean` })\n return\n }\n for (const f of findings) {\n checks.push({\n severity: f.severity,\n group: \"Workspace settings\",\n title: `${f.agent}: ${f.msg}`,\n fix: f.severity === \"fail\" ? \"Edit .claude/settings.json — replace ${VAR} with the literal value or omit the key to inherit.\" : \"Either remove the empty allow list or populate it.\",\n })\n }\n}\n\n// Surface routing / dispatch fragilities the recurring-patches plan\n// cataloged: webhook entries that route many event-types to a single\n// handler (github, gitlab), trigger maps pointing at workflow ids that\n// don't exist, mesh `node` fields naming peers that aren't configured,\n// gitlab agentMappings referencing unknown agents, and the very common\n// \"I edited agentx.json but didn't reload\" pitfall.\nfunction runRoutingChecks(checks: Check[], cfg: any): void {\n const webhooks = (cfg.webhooks ?? []) as Array<{\n id: string\n source: string\n agentId: string\n enabled: boolean\n node?: string\n secretEnv?: string\n triggers?: Record<string, string>\n defaultWorkflow?: string\n }>\n const findings: Array<{ severity: Severity; title: string; fix?: string }> = []\n\n // Build the set of known workflow ids. Workflows live as JSON files under\n // `workflows.dir` (default .agentx/workflows/). The id is the filename\n // sans extension; we don't need to parse the contents for this check.\n const workflowDir = resolve(process.cwd(), cfg.workflows?.dir || \".agentx/workflows\")\n const knownWorkflows = new Set<string>()\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (f.endsWith(\".json\") && !f.startsWith(\"_\") && !f.endsWith(\".disabled.json\")) {\n knownWorkflows.add(f.replace(/\\.json$/, \"\"))\n }\n }\n }\n } catch { /* directory not yet populated; checks below tolerate empty set */ }\n\n // 1. Multi-event-type sources (github, gitlab) without a triggers map.\n // Without it, every inbound event hits the same agent and the\n // duplicate-firing class of bug returns. Surface as REVIEW (warn) —\n // operators may genuinely want a single-handler setup, but they\n // should opt in by setting `defaultWorkflow` explicitly.\n const multiEventSources = new Set([\"github\", \"gitlab\"])\n for (const w of webhooks) {\n if (!w.enabled) continue\n if (!multiEventSources.has(w.source)) continue\n const hasTriggers = w.triggers && Object.keys(w.triggers).length > 0\n if (!hasTriggers && !w.defaultWorkflow) {\n findings.push({\n severity: \"warn\",\n title: `webhook \"${w.id}\" (${w.source} -> ${w.agentId}) has no triggers map; every event-type collapses to the bound agent`,\n fix: `Add a triggers map: { \"issues.opened\": \"wf-id\", \"pull_request.synchronize\": \"wf-id\" } — or set defaultWorkflow.`,\n })\n }\n }\n\n // 2. Trigger map references workflow ids that don't exist on disk.\n // Hard-fails the dispatch at runtime (and silently — dispatcher just\n // logs \"workflow not found\" and bails). Surface here as FAIL.\n for (const w of webhooks) {\n if (!w.enabled || !w.triggers) continue\n for (const [eventType, workflowId] of Object.entries(w.triggers)) {\n if (knownWorkflows.size > 0 && !knownWorkflows.has(workflowId)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".triggers[\"${eventType}\"] -> \"${workflowId}\" — no such workflow under ${cfg.workflows?.dir || \".agentx/workflows\"}`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n if (w.defaultWorkflow && knownWorkflows.size > 0 && !knownWorkflows.has(w.defaultWorkflow)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".defaultWorkflow -> \"${w.defaultWorkflow}\" — no such workflow`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n\n // 2b. Incoherent workflow lifecycle: status=active says \"reviewed, ship\n // it\" while state=quarantined means the runtime refuses to dispatch\n // it (conflict detector parked it). The two axes are independent\n // (state is the only dispatch gate — see workflowSchema), so this\n // combo silently looks live while never firing.\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (!f.endsWith(\".json\") || f.startsWith(\"_\") || f.endsWith(\".disabled.json\")) continue\n try {\n const wf = JSON.parse(readFileSync(resolve(workflowDir, f), \"utf-8\"))\n if (wf?.status === \"active\" && wf?.state === \"quarantined\") {\n findings.push({\n severity: \"warn\",\n title: `workflow \"${wf.id ?? f}\" is status=active but state=quarantined — it looks live but will never dispatch`,\n fix: `Resolve the conflict the detector flagged, then set state back to \"active\" (or set status to \"review\" while parked).`,\n })\n }\n } catch { /* unparseable file is caught by workflow validate */ }\n }\n }\n } catch { /* directory races are non-fatal for doctor */ }\n\n // 3. Mesh-routed webhooks naming peers that don't exist.\n const peers = new Set<string>(((cfg.mesh?.peers ?? []) as Array<{ name: string }>).map(p => p.name))\n for (const w of webhooks) {\n if (!w.enabled || !w.node) continue\n if (!peers.has(w.node)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\" routes to mesh peer \"${w.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or remove the node field on the webhook.`,\n })\n }\n }\n\n // 4. Two enabled webhook entries collide on (source, agentId): the\n // Phase 3 dispatcher takes the first match, the second is silently\n // ignored — operators rarely realize.\n const seen = new Map<string, string>()\n for (const w of webhooks) {\n if (!w.enabled) continue\n const key = `${w.source}:${w.agentId}`\n const prior = seen.get(key)\n if (prior) {\n findings.push({\n severity: \"warn\",\n title: `webhook entries \"${prior}\" and \"${w.id}\" both enabled for ${w.source} -> ${w.agentId}; only the first is dispatched`,\n fix: `Disable one entry, or merge their triggers maps into a single entry.`,\n })\n } else {\n seen.set(key, w.id)\n }\n }\n\n // 5. GitLab agentMappings referencing agent ids that aren't in agents.\n // A mapping with `node:` set is a cross-mesh route — the agent lives\n // on a remote peer, not locally — so missing-from-agents is correct\n // and not a finding. We still warn when `node` names a peer that\n // isn't configured (caught by check #3 above for webhooks; same\n // invariant should hold for agentMappings).\n const agentIds = new Set(Object.keys(cfg.agents ?? {}))\n for (const m of (cfg.channels?.gitlab?.agentMappings ?? [])) {\n if (!m?.agentId) continue\n if (m.node) {\n // Cross-mesh route — verify the named peer exists.\n if (!peers.has(m.node)) {\n findings.push({\n severity: \"fail\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" routes to mesh peer \"${m.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or drop the node field on the mapping.`,\n })\n }\n continue\n }\n if (!agentIds.has(m.agentId)) {\n findings.push({\n severity: \"warn\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" — no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,\n fix: `Add the agent to agents.*, set node:\"<peer>\" if the agent lives remotely, or remove the mapping.`,\n })\n }\n }\n\n // 6. Telegram accounts without an agentBinding silently drop every DM.\n for (const [acctId, acct] of Object.entries((cfg.channels?.telegram?.accounts ?? {}) as Record<string, { agentBinding?: string }>)) {\n if (!acct.agentBinding) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\" has no agentBinding; every DM to this bot will drop`,\n fix: `Set agentBinding to a valid agent id.`,\n })\n } else if (!agentIds.has(acct.agentBinding)) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\".agentBinding -> \"${acct.agentBinding}\" — no such agent in agents.*`,\n fix: `Fix the agentBinding or define the agent in agents.*.`,\n })\n }\n }\n\n // 7. Per-agent integrations: missing env vars + unknown kinds + duplicates.\n // The new agents[].integrations[] block declares third-party credentials\n // (telegram-bot, hubspot, gitlab-user, gmail, ...). Doctor scans for:\n // - duplicate (kind, label) on the same agent (config integrity)\n // - tokenEnv refs that don't exist in process.env (latent failure)\n // - kinds outside the canonical INTEGRATION_KINDS set (typos)\n // Failures are warnings, not blocking — credentials may be set on the\n // daemon process and absent from the doctor's local shell.\n const KNOWN_KINDS = new Set([\n \"telegram-bot\", \"whatsapp\", \"slack-bot\", \"discord-bot\",\n \"gitlab-user\", \"github-user\",\n \"gmail\", \"hotmail\", \"smtp\",\n \"hubspot\", \"salesforce\", \"pipedrive\", \"odoo\",\n \"trello\", \"linear\", \"asana\", \"jira\", \"notion\",\n \"stripe\", \"sentry\", \"vercel\", \"twilio\", \"custom\",\n ])\n for (const [agentId, a] of Object.entries((cfg.agents ?? {}) as Record<string, any>)) {\n const list = (a.integrations as any[] | undefined) ?? []\n if (!list.length) continue\n const seen = new Set<string>()\n for (const i of list) {\n const key = `${i.kind}::${i.label}`\n if (seen.has(key)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: duplicate (${i.kind}, ${i.label})`,\n fix: `Remove the duplicate or rename one. (kind, label) must be unique per agent.`,\n })\n }\n seen.add(key)\n if (!KNOWN_KINDS.has(i.kind)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: unknown kind \"${i.kind}\" on integration \"${i.label}\"`,\n fix: `Use a canonical kind from INTEGRATION_KINDS, or \"custom\" for ad-hoc services.`,\n })\n }\n const creds = (i.credentials || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(creds)) {\n if (typeof v === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(v) && !process.env[v]) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations[${i.kind}/${i.label}].${k} -> $${v} but env var is unset (in this shell)`,\n fix: `Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`,\n })\n }\n }\n }\n }\n\n // (Removed: the \"agentx.json newer than daemon pid\" check produced\n // false positives because the pid file is only rewritten on start,\n // not on hot-reload. The signal-to-noise was too low. A future check\n // can query /reload's `lastReload` timestamp via the daemon API\n // instead of using filesystem mtimes.)\n\n if (findings.length === 0) {\n checks.push({\n severity: \"ok\",\n group: \"Routing\",\n title: `${webhooks.length} webhook(s), ${Object.keys(cfg.channels?.telegram?.accounts ?? {}).length} telegram account(s) — all routing references resolve`,\n })\n return\n }\n for (const f of findings) {\n checks.push({ severity: f.severity, group: \"Routing\", title: f.title, fix: f.fix })\n }\n}\n\nasync function runRuntimeChecks(checks: Check[], cfg: any): Promise<void> {\n const url = cfg.dashboard?.daemonUrl?.replace(/\\/+$/, \"\") || \"http://127.0.0.1:18800\"\n const headers: Record<string, string> = {}\n if (cfg.dashboard?.token) headers[\"Authorization\"] = `Bearer ${cfg.dashboard.token}`\n try {\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), 2000)\n const r = await fetch(url + \"/health\", { headers, signal: ac.signal })\n clearTimeout(timer)\n if (!r.ok) {\n checks.push({ severity: \"warn\", group: \"Runtime\", title: `Daemon responded ${r.status}`, detail: url })\n return\n }\n const body: any = await r.json()\n checks.push({\n severity: \"ok\",\n group: \"Runtime\",\n title: `Daemon healthy — ${body.agents?.length ?? 0} agents live, uptime ${Math.round((body.uptime ?? 0) / 60)}m`,\n detail: url,\n })\n } catch {\n checks.push({\n severity: \"warn\",\n group: \"Runtime\",\n title: \"Daemon not reachable (not running?)\",\n detail: url,\n fix: \"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`.\",\n })\n }\n}\n\nfunction runCodegraphChecks(checks: Check[], cfg: any): void {\n const optedIn = Object.entries(cfg.agents || {})\n .filter(([, a]: [string, any]) =>\n a?.codegraph === true && (a.tier === \"claude-code\" || a.tier === \"codex-cli\"),\n ) as Array<[string, any]>\n\n if (optedIn.length === 0) return // No agent uses codegraph — skip silently.\n\n // Binary on PATH.\n let cgPath: string | null = null\n try {\n cgPath = execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codegraph\"], { encoding: \"utf-8\" })\n .trim().split(\"\\n\")[0] || null\n } catch { cgPath = null }\n\n if (cgPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codegraph\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `codegraph CLI ${ver || \"installed\"}`,\n detail: cgPath,\n })\n } else {\n checks.push({\n severity: \"fail\",\n group: \"CodeGraph\",\n title: \"codegraph CLI not on PATH\",\n detail: `${optedIn.length} agent(s) have codegraph:true but the binary isn't available.`,\n fix: \"Install with `npm i -g @colbymchenry/codegraph`.\",\n })\n }\n\n // Per-workspace index presence.\n for (const [agentId, def] of optedIn) {\n if (!def.workspace || !existsSync(def.workspace)) {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: workspace missing`,\n detail: `Workspace path ${def.workspace} does not exist — codegraph will skip this agent.`,\n })\n continue\n }\n const dbPath = resolve(def.workspace, \".codegraph\", \"codegraph.db\")\n if (existsSync(dbPath)) {\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `${agentId}: index present`,\n detail: dbPath,\n })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: index not built yet`,\n detail: \".codegraph/ missing — daemon will background-index this workspace on next boot.\",\n fix: `Run \\`codegraph init --index ${def.workspace}\\` to build it now.`,\n })\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Output\n// ---------------------------------------------------------------------------\n\nfunction summarize(checks: Check[]): { errors: number; warnings: number; ok: number } {\n return {\n errors: checks.filter((c) => c.severity === \"fail\").length,\n warnings: checks.filter((c) => c.severity === \"warn\").length,\n ok: checks.filter((c) => c.severity === \"ok\").length,\n }\n}\n\nfunction printHumanReport(checks: Check[]): void {\n console.log()\n console.log(chalk.bold(\" agentx doctor\"))\n console.log()\n\n const groups = new Map<string, Check[]>()\n for (const c of checks) {\n if (!groups.has(c.group)) groups.set(c.group, [])\n groups.get(c.group)!.push(c)\n }\n for (const [group, items] of groups) {\n console.log(chalk.bold(\" \" + group))\n for (const c of items) {\n const marker = c.severity === \"ok\" ? chalk.green(\"✓\")\n : c.severity === \"warn\" ? chalk.yellow(\"!\")\n : chalk.red(\"✗\")\n console.log(` ${marker} ${c.title}`)\n if (c.detail) console.log(chalk.dim(\" \" + c.detail.replace(/\\n/g, \"\\n \")))\n if (c.fix) console.log(chalk.dim(\" → \" + c.fix))\n }\n console.log()\n }\n\n const s = summarize(checks)\n if (s.errors > 0) {\n console.log(chalk.red.bold(` ${s.errors} error${s.errors === 1 ? \"\" : \"s\"}`) +\n (s.warnings ? chalk.yellow(`, ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}`) : \"\") +\n `. Fix the error${s.errors === 1 ? \"\" : \"s\"} and rerun.`)\n } else if (s.warnings > 0) {\n console.log(chalk.yellow.bold(` ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}.`) + chalk.dim(\" Review but not blocking.\"))\n } else {\n console.log(chalk.green.bold(` All checks passed (${s.ok}).`))\n }\n console.log()\n}\n","import { execFile } from \"child_process\"\nimport { findHelper } from \"./local\"\n\n// Why a banner shows the Script Editor icon instead of the AgentX logo,\n// in words a person can act on. `agentx notify` falls back to osascript\n// silently — it must never fail to notify — so this is where the reason\n// surfaces: `agentx notifications show` and `agentx doctor` print it.\n//\n// Reading the status never posts a banner and never shows the macOS\n// \"allow notifications\" prompt.\n\nexport type HelperState = \"ready\" | \"unsupported\" | \"missing\" | \"outdated\" | \"not-asked\" | \"not-allowed\" | \"hidden\"\n\nexport interface HelperStatus {\n state: HelperState\n /** One plain sentence on what the person will see. */\n message: string\n /** What to do about it; absent when nothing needs doing. */\n fix?: string\n /** The helper binary that was checked, when there is one. */\n path?: string\n}\n\n/** Runs a command and resolves its stdout, or null when it failed. */\ntype Capture = (file: string, args: string[]) => Promise<string | null>\n\nconst capture: Capture = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: 5_000 }, (err, stdout) => done(err ? null : String(stdout)))\n } catch {\n done(null)\n }\n })\n\nconst SETTINGS = \"Open System Settings › Notifications › AgentX Helper, turn on Allow notifications and choose Banners.\"\n\nexport async function helperStatus(\n deps: { platform?: NodeJS.Platform; helper?: string | null; run?: Capture } = {},\n): Promise<HelperStatus> {\n if ((deps.platform ?? process.platform) !== \"darwin\") {\n return { state: \"unsupported\", message: \"Desktop banners are only shown on a Mac.\" }\n }\n const path = deps.helper === undefined ? findHelper() : deps.helper\n if (!path) {\n return {\n state: \"missing\",\n message: \"AgentX Helper is not installed, so banners come from Script Editor and show its icon.\",\n fix: \"Run agentx desktop install, then run agentx notify \\\"Hello\\\" --title \\\"Test\\\" and click Allow.\",\n }\n }\n const out = await (deps.run ?? capture)(path, [\"notify-status\"])\n let status: { authorization?: string; alertStyle?: string } | null = null\n try { status = out ? JSON.parse(out) : null } catch { status = null }\n if (!status) {\n return {\n state: \"outdated\",\n path,\n message: \"AgentX Helper is too old to report whether it may notify.\",\n fix: \"Run agentx desktop install to update it.\",\n }\n }\n if (status.authorization === \"notDetermined\") {\n return {\n state: \"not-asked\",\n path,\n message: \"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.\",\n fix: \"Run agentx notify \\\"Hello\\\" --title \\\"Test\\\" and click Allow when macOS asks.\",\n }\n }\n if (status.authorization === \"denied\") {\n return { state: \"not-allowed\", path, message: \"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.\", fix: SETTINGS }\n }\n if (status.alertStyle === \"none\") {\n return { state: \"hidden\", path, message: \"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.\", fix: SETTINGS }\n }\n return { state: \"ready\", path, message: \"AgentX Helper posts banners with the AgentX icon.\" }\n}\n"],"mappings":"4GAOAA,IAPA,OAAS,WAAAC,MAAe,YACxB,OAAOC,MAAW,QAClB,OAAS,gBAAAC,MAAoB,gBAC7B,OAAS,cAAAC,EAAY,aAAAC,EAAW,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,YAAAC,MAAgB,KACvF,OAAS,QAAAC,EAAM,WAAAC,MAAe,OAC9B,OAAS,WAAAC,MAAe,KACxB,OAAS,iBAAAC,MAAqB,SCN9B,OAAS,YAAAC,MAAgB,gBA0BzB,IAAMC,EAAmB,CAACC,EAAMC,IAC9B,IAAI,QAASC,GAAS,CACpB,GAAI,CACFC,EAASH,EAAMC,EAAM,CAAE,QAAS,GAAM,EAAG,CAACG,EAAKC,IAAWH,EAAKE,EAAM,KAAO,OAAOC,CAAM,CAAC,CAAC,CAC7F,MAAE,CACAH,EAAK,IAAI,CACX,CACF,CAAC,EAEGI,EAAW,kHAEjB,eAAsBC,EACpBC,EAA8E,CAAC,EACxD,CACvB,IAAKA,EAAK,UAAY,QAAQ,YAAc,SAC1C,MAAO,CAAE,MAAO,cAAe,QAAS,0CAA2C,EAErF,IAAMC,EAAOD,EAAK,SAAW,OAAYE,EAAW,EAAIF,EAAK,OAC7D,GAAI,CAACC,EACH,MAAO,CACL,MAAO,UACP,QAAS,wFACT,IAAK,4FACP,EAEF,IAAME,EAAM,MAAOH,EAAK,KAAOT,GAASU,EAAM,CAAC,eAAe,CAAC,EAC3DG,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AAM,CAAC,EAEhE,QAAQ,IAAI,CACd","names":["init_config","Command","chalk","execFileSync","accessSync","constants","existsSync","readFileSync","readdirSync","statSync","join","resolve","homedir","createRequire","execFile","capture","file","args","done","execFile","err","stdout","SETTINGS","helperStatus","deps","path","findHelper","out","status","runDoctorChecks","opts","checks","runEnvChecks","runDesktopChecks","cfg","runConfigChecks","runReferenceChecks","runWorkspaceChecks","runWorkspaceSettingsChecks","runRoutingChecks","runCodegraphChecks","runNotificationChecks","runReminderChecks","runRuntimeChecks","summarize","doctor","Command","summary","printHumanReport","status","helperStatus","localSettings","helper","platform","isExecutable","file","accessSync","constants","r","command","found","findOnPath","nodeMajor","which","bin","execFileSync","npmPath","claudePath","ver","codexPath","openCodePath","createRequire","e","agents","join","homedir","names","readdirSync","n","name","path","plistPathEnv","readFileSync","ffmpeg","cfgPath","resolve","existsSync","loadDaemonConfig","claudeCodeAgents","id","codexCliAgents","openCodeAgents","refs","collectEnvRefs","envFile","envFromFile","line","m","missing","empty","raw","node","into","item","v","a","abs","statSync","VAR_RE","findings","agentId","wsAbs","fname","p","data","env","k","unexpanded","pathVal","parts","perms","allow","deny","f","webhooks","workflowDir","knownWorkflows","multiEventSources","w","eventType","workflowId","wf","peers","seen","key","prior","agentIds","acctId","acct","KNOWN_KINDS","list","i","creds","url","headers","ac","timer","body","optedIn","cgPath","def","dbPath","c","chalk","groups","group","items","marker","s"]}
@@ -1,4 +1,4 @@
1
- import{a as jn,b as Un,h as Yn,n as Vn}from"./chunk-AWRRBNWQ.js";import{a as Tt}from"./chunk-N6EWZGIX.js";import{a as Hn}from"./chunk-WP6KLXTP.js";import{b as Bn}from"./chunk-DP7RTNDM.js";import{b as Kn,c as Gn,d as Jn,e as Qn,h as zn}from"./chunk-XOUIZBAQ.js";import{a as kt,b as Wn}from"./chunk-J3SOEFRE.js";import{a as It,b as qn}from"./chunk-SIU6STB2.js";import{a as Xn}from"./chunk-W4YR2RO2.js";import{a as $n}from"./chunk-7NF45XCM.js";import{a as Mn,b as Pn,c as Rn,d as _n,f as En}from"./chunk-DWADWDMU.js";import{a as Dn,b as On}from"./chunk-WKTFP3SK.js";import{a as Fn}from"./chunk-7M7VJMGP.js";import{b as Nn,c as Ln}from"./chunk-YPPTPBBV.js";import{a as Ye,c as Re}from"./chunk-2GIDVZ4H.js";import{q as vn,t as Cn,v as be,w as An}from"./chunk-MHBUAU2B.js";import{a as Pe,b as Xe,f as xt}from"./chunk-72SZI2UW.js";import{a as ye,b as bt}from"./chunk-FCPTN6NF.js";import{c as xn,d as Tn}from"./chunk-QOYAX2FT.js";import{e as ge}from"./chunk-DSYKYZMT.js";import{d as kn,e as re,f as In,g as Sn,h as wt}from"./chunk-3IUU4YFI.js";An();xt();var Zn="session-continuity",es={continues:Pe("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Pe("Does the new request refer to something stated earlier in the conversation?")};function ts(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:St(s.message,1200),previousRequest:s.previousMessage?St(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>St(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function ns(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function St(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as eo,execFile as to}from"node:child_process";import{createHash as no,randomBytes as so}from"node:crypto";import{createInterface as ro}from"node:readline";import{promisify as oo}from"node:util";var io=oo(to),oe=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},vt=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=io("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new oe("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=no("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([u],[l])=>u.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new oe("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let g=[...this.entries].find(([,h])=>!h.busy);if(!g)throw new oe("Warm server capacity reached",!0);this.close(g[1]),this.entries.delete(g[0])}let u={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:so(32).toString("hex")},l=eo("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:u,stdio:["pipe","pipe","pipe"]});o={child:l,env:u,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let d=o;l.stderr.resume(),l.on("exit",()=>this.close(d)),l.on("error",()=>this.close(d));try{await new Promise((g,h)=>{let w=ro({input:l.stdout}),x=()=>I(new oe("OpenCode server failed before dispatch",!0)),b=()=>I(new Error("task cancelled by operator")),S=setTimeout(x,15e3),I=E=>{clearTimeout(S),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",b),w.close(),l.stdout.resume(),E?h(E):g()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",b,{once:!0}),w.on("line",E=>{try{let A=new URL(JSON.parse(E).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;d.url=A.origin,I()}catch{}}),e.signal?.aborted&&b()})}catch(g){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),g}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(u=!1)=>{c||(c=!0,a.busy=!1,u||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},ss=new vt;import{execa as st}from"execa";import{spawn as ao}from"node:child_process";import{createHash as co}from"node:crypto";import{createInterface as uo}from"node:readline";var ie=class extends Error{},lo=s=>ao("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Ct=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),uo({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
1
+ import{a as jn,b as Un,h as Yn,n as Vn}from"./chunk-C5JXPMTW.js";import{a as Tt}from"./chunk-N6EWZGIX.js";import{a as Hn}from"./chunk-WP6KLXTP.js";import{b as Bn}from"./chunk-DP7RTNDM.js";import{b as Kn,c as Gn,d as Jn,e as Qn,h as zn}from"./chunk-KFG6WWFS.js";import{a as kt,b as Wn}from"./chunk-J3SOEFRE.js";import{a as It,b as qn}from"./chunk-SIU6STB2.js";import{a as Xn}from"./chunk-W4YR2RO2.js";import{a as $n}from"./chunk-KB7YIM3W.js";import{a as Mn,b as Pn,c as Rn,d as _n,f as En}from"./chunk-DWADWDMU.js";import{a as Dn,b as On}from"./chunk-WKTFP3SK.js";import{a as Fn}from"./chunk-VD4TMPJI.js";import{b as Nn,c as Ln}from"./chunk-KJWBQZT7.js";import{a as Ye,c as Re}from"./chunk-2GIDVZ4H.js";import{q as vn,t as Cn,v as be,w as An}from"./chunk-NF52Q3TV.js";import{a as Pe,b as Xe,f as xt}from"./chunk-72SZI2UW.js";import{a as ye,b as bt}from"./chunk-FCPTN6NF.js";import{c as xn,d as Tn}from"./chunk-QOYAX2FT.js";import{e as ge}from"./chunk-DSYKYZMT.js";import{d as kn,e as re,f as In,g as Sn,h as wt}from"./chunk-47EEUZBK.js";An();xt();var Zn="session-continuity",es={continues:Pe("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Pe("Does the new request refer to something stated earlier in the conversation?")};function ts(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:St(s.message,1200),previousRequest:s.previousMessage?St(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>St(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function ns(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function St(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as eo,execFile as to}from"node:child_process";import{createHash as no,randomBytes as so}from"node:crypto";import{createInterface as ro}from"node:readline";import{promisify as oo}from"node:util";var io=oo(to),oe=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},vt=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=io("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new oe("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=no("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([u],[l])=>u.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new oe("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let g=[...this.entries].find(([,h])=>!h.busy);if(!g)throw new oe("Warm server capacity reached",!0);this.close(g[1]),this.entries.delete(g[0])}let u={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:so(32).toString("hex")},l=eo("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:u,stdio:["pipe","pipe","pipe"]});o={child:l,env:u,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let d=o;l.stderr.resume(),l.on("exit",()=>this.close(d)),l.on("error",()=>this.close(d));try{await new Promise((g,h)=>{let w=ro({input:l.stdout}),x=()=>I(new oe("OpenCode server failed before dispatch",!0)),b=()=>I(new Error("task cancelled by operator")),S=setTimeout(x,15e3),I=E=>{clearTimeout(S),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",b),w.close(),l.stdout.resume(),E?h(E):g()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",b,{once:!0}),w.on("line",E=>{try{let A=new URL(JSON.parse(E).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;d.url=A.origin,I()}catch{}}),e.signal?.aborted&&b()})}catch(g){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),g}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(u=!1)=>{c||(c=!0,a.busy=!1,u||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},ss=new vt;import{execa as st}from"execa";import{spawn as ao}from"node:child_process";import{createHash as co}from"node:crypto";import{createInterface as uo}from"node:readline";var ie=class extends Error{},lo=s=>ao("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Ct=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),uo({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
2
2
  `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},At=class{constructor(e=lo,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=co("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[S])=>b.localeCompare(S))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ie("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let b=[...this.entries].find(([,S])=>!S.connection.busy);if(!b)throw new ie("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:n,connection:new Ct(e,this.launchProcess)}}catch{throw new ie("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",u,l,d,g=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let w=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),x=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(x),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((E,A)=>{i.failTurn=A,i.notify=(v,_)=>{if(_?.threadId!==l)return;let N=_.item,P={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:v.replace("/","."),...N?{item:{...N,type:P[N.type]||N.type}}:{}}),v==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(u=N.text),v==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=_.delta,e.onDelta?.(_.delta,c)),v==="thread/tokenUsage/updated"){let L=_.tokenUsage.last,O=L.cachedInputTokens||0;d={inputTokens:(d?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-O),outputTokens:(d?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(d?.cacheReadTokens||0)+O,cacheCreateTokens:(d?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}v==="turn/completed"&&(_.turn.status==="completed"?E():A(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:u??c,codexSessionId:l,billedModel:e.model,usage:d,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new ie(b.message);return{content:c,codexSessionId:l,usage:d,error:b.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(w),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},rs=new At;import{execFile as vo}from"child_process";import{StringDecoder as De}from"string_decoder";import{mkdtempSync as bs,readFileSync as ws,rmSync as xs}from"fs";import{join as tt}from"path";import{tmpdir as Ts}from"os";function Ve(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let u=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${u?` Resets ${u[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Ze(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var os=null;function et(){return os}function Ta(s){os=s}function _e(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var we=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},is=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=_e(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new we(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new we(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=_e(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=_e(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=_e(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=_e(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",u=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${u})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${u})`)}}}}}};import{spawn as go}from"child_process";import{existsSync as po,readFileSync as mo}from"fs";import{resolve as ho}from"path";function fo(s){let e=ho(s,"CLAUDE.md");if(!po(e))return null;try{let t=mo(e,"utf8");return En(t)}catch{return null}}var yo=20*60*1e3,bo=5e3,Ee=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},as=class{constructor(e={}){this.opts=e}spawn(e,t){return new $t(e,t,this.opts)}},$t=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=go(r,o,{cwd:t.workspace,env:Re({...process.env},t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:fo(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let u of c)u(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
3
3
  `);let a=e.deadlineMs??yo,c=o+a,u=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Ee(a));try{for(;;){let l=c-Date.now();if(l<=0)throw u();let d=await this.nextEvent(l);if(d===null&&!this.exited)throw u();if(d===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:d.type,raw:d},d.type==="result"){this.onResultEvent(d);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},bo);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
4
  `))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};wt();import{resolve as cs,join as ds}from"path";bt();var wo=4e3;function us(s){try{let e=ds(cs(s.root),".agentx","db.sqlite"),t=Tt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=ye(),r=s.input.command?s.input.command.slice(0,wo):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -27,7 +27,7 @@ ${s}`}function Co(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
27
27
  `,d)}};A.stdout?.on("data",y=>{P+=O.write(y);let k=P.split(`
28
28
  `);P=k.pop()||"";for(let M of k)F(M)}),A.stderr?.on("data",y=>{L+=H.write(y)});let p=await A;if(i&&i.removeEventListener("abort",N),P+=O.end(),P.trim()&&F(P),L+=H.end(),v)return{content:"",error:_||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(p.exitCode!==0||w){let y=p,k;return y.timedOut?k=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:w?k=w:y.code==="ENOENT"||/ENOENT|spawn opencode/i.test((y.shortMessage||"")+" "+L)?k=hs():k=L.trim()||`OpenCode exited with code ${y.exitCode??"unknown"}`,{content:"",...G(k),duration:Date.now()-c,usage:g,opencodeSessionId:h}}return b=!1,{content:d.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||s.model,opencodeSessionId:h}}catch(I){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let E=/ENOENT|spawn opencode/i.test(I?.message||"")?hs():I?.message;return{content:d,...G(E||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:h}}finally{S?.(),x?.release(b)}}async function Lo(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ce(s,e,n),c="",u=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of u)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...G(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Fo(s,e,t,n,r,o,i,a,c){let u=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),d=new AbortController,g=!1,h=()=>{let b=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{d.abort(new Error(b))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let w=setTimeout(()=>{g=!0;try{d.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);w.unref?.();let x=()=>({content:"",...G(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-u});try{let b=s.provider||"claude-code",S=n?`${n}
29
29
 
30
- ${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),A=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,v=_n(s),_=Object.keys(v).length>0,N={task:S,cwd:s.workspace,provider:b,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:d.signal,mcpServers:_?v:void 0};if(r){let{generateStream:F}=await import("./agent-KKVMU3VB.js"),p="",y,k,M,T;for await(let R of F(N)){if(c)try{c(R)}catch{}if(R.type==="text_delta")p+=R.text,r(R.text,p);else if(R.type==="thinking_delta")R.text&&i&&i(R.text);else if(R.type==="generate_result"){if(R.result.content&&R.result.content!==p){let q=R.result.content.slice(p.length);q?(p=R.result.content,r(q,p)):p=R.result.content}y=R.result.tokensUsed,R.result.inputTokens!=null&&(k=R.result.inputTokens),R.result.outputTokens!=null&&(M=R.result.outputTokens)}else if(R.type==="done"){if(R.result.content&&R.result.content!==p){let q=R.result.content.slice(p.length);q?(p=R.result.content,r(q,p)):p=R.result.content}R.result.tokensUsed!=null&&(y=R.result.tokensUsed)}else R.type==="error"&&(T=R.error)}return T&&!p?g?x():T==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...G(`Orchestrator error: ${T}`),duration:Date.now()-u}:((k===void 0||M===void 0)&&y&&(k=Math.round(y*.7),M=y-k),{content:p||"Done.",tokensUsed:y,usage:k!==void 0||M!==void 0?{inputTokens:k||0,outputTokens:M||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u})}let{generate:P}=await import("./agent-KKVMU3VB.js"),L=await P(N),O=L.inputTokens,H=L.outputTokens;if((O===void 0||H===void 0)&&L.tokensUsed){let F=L.tokensUsed;O=Math.round(F*.7),H=F-O}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:O!==void 0||H!==void 0?{inputTokens:O||0,outputTokens:H||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u}}catch(b){return g?x():b?.message==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...G(`Orchestrator error: ${b.message}`),duration:Date.now()-u}}finally{clearTimeout(w),a&&a.removeEventListener("abort",h)}}async function Ho(s,e,t,n,r,o,i){let a=et();if(!a)return null;let c=Date.now(),u=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",d={agentId:e.agentId,channel:u,chatId:l};if(e.freshSession)try{await a.kill(d,"freshSession=true")}catch{}let g,h=!1;try{let p=a.list().length;g=a.acquire(d,{agentId:e.agentId,channel:u,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),h=a.list().length>p}catch(p){return p instanceof we,null}h&&Dt(e.agentId,s,e.model,n,"persistent");let w=ce(s,e,t),x="",b,S,I,E,A,v,_,N="",P="",L=p=>{if(!i||!p)return;let y;if(P&&p.startsWith(P)?y=p.slice(P.length):y=N&&!N.endsWith(`
30
+ ${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),A=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,v=_n(s),_=Object.keys(v).length>0,N={task:S,cwd:s.workspace,provider:b,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:d.signal,mcpServers:_?v:void 0};if(r){let{generateStream:F}=await import("./agent-H4NB4BUA.js"),p="",y,k,M,T;for await(let R of F(N)){if(c)try{c(R)}catch{}if(R.type==="text_delta")p+=R.text,r(R.text,p);else if(R.type==="thinking_delta")R.text&&i&&i(R.text);else if(R.type==="generate_result"){if(R.result.content&&R.result.content!==p){let q=R.result.content.slice(p.length);q?(p=R.result.content,r(q,p)):p=R.result.content}y=R.result.tokensUsed,R.result.inputTokens!=null&&(k=R.result.inputTokens),R.result.outputTokens!=null&&(M=R.result.outputTokens)}else if(R.type==="done"){if(R.result.content&&R.result.content!==p){let q=R.result.content.slice(p.length);q?(p=R.result.content,r(q,p)):p=R.result.content}R.result.tokensUsed!=null&&(y=R.result.tokensUsed)}else R.type==="error"&&(T=R.error)}return T&&!p?g?x():T==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...G(`Orchestrator error: ${T}`),duration:Date.now()-u}:((k===void 0||M===void 0)&&y&&(k=Math.round(y*.7),M=y-k),{content:p||"Done.",tokensUsed:y,usage:k!==void 0||M!==void 0?{inputTokens:k||0,outputTokens:M||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u})}let{generate:P}=await import("./agent-H4NB4BUA.js"),L=await P(N),O=L.inputTokens,H=L.outputTokens;if((O===void 0||H===void 0)&&L.tokensUsed){let F=L.tokensUsed;O=Math.round(F*.7),H=F-O}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:O!==void 0||H!==void 0?{inputTokens:O||0,outputTokens:H||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u}}catch(b){return g?x():b?.message==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...G(`Orchestrator error: ${b.message}`),duration:Date.now()-u}}finally{clearTimeout(w),a&&a.removeEventListener("abort",h)}}async function Ho(s,e,t,n,r,o,i){let a=et();if(!a)return null;let c=Date.now(),u=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",d={agentId:e.agentId,channel:u,chatId:l};if(e.freshSession)try{await a.kill(d,"freshSession=true")}catch{}let g,h=!1;try{let p=a.list().length;g=a.acquire(d,{agentId:e.agentId,channel:u,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),h=a.list().length>p}catch(p){return p instanceof we,null}h&&Dt(e.agentId,s,e.model,n,"persistent");let w=ce(s,e,t),x="",b,S,I,E,A,v,_,N="",P="",L=p=>{if(!i||!p)return;let y;if(P&&p.startsWith(P)?y=p.slice(P.length):y=N&&!N.endsWith(`
31
31
  `)?`
32
32
 
33
33
  ${p}`:p,P=p,!!y){N+=y;try{i(y,N)}catch{}}},O=!1,H=()=>{O=!0,a.kill(d,"operator-cancel").catch(()=>{})};o&&(o.aborted?H():o.addEventListener("abort",H,{once:!0}));let F=!1;try{let p=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let y of g.runTurn({message:w,taskId:e.taskId??"unknown",deadlineMs:p})){if(F=!0,r)try{r(y.raw)}catch{}if(y.type==="assistant"){let k=y.raw.message?.content??[];for(let T of k)T.type==="text"&&typeof T.text=="string"?(x=T.text,L(T.text)):T.type==="tool_use"&&(P="");let M=y.raw.message?.usage;if(M){let T=(M.input_tokens||0)+(M.cache_read_input_tokens||0)+(M.cache_creation_input_tokens||0);T>0&&(E=T)}}if(y.type==="result"){let k=y.raw;if(k.is_error){let M=G(typeof k.result=="string"?k.result:"claude error");b=M.error,S=M.errorKind}else typeof k.result=="string"&&k.result.length>0&&(x=k.result,N||L(k.result));typeof k.session_id=="string"&&(_=k.session_id),k.usage&&(I={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(A=k.num_turns),typeof k.message?.model=="string"?v=k.message.model:typeof k.model=="string"&&(v=k.model)}}}catch(p){if(O)b="task cancelled by operator",S="cancelled";else if(F)if(p instanceof Ee){let y=G(`Claude Code timed out after ${Math.round(p.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);b=y.error,S=y.errorKind}else{let y=G(`persistent claude process error: ${p?.message||String(p)}`);b=y.error,S=y.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${p?.message||p}); falling back to spawn-per-task`),a.release(d,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",H),null}finally{o&&o.removeEventListener("abort",H)}return O&&!b&&(b="task cancelled by operator",S="cancelled"),{content:O?"":x,error:b,errorKind:S,duration:Date.now()-c,usage:I,contextTokens:E,numTurns:A,billedModel:v,claudeSessionId:_}}function Ps(s){return re(s.autonomy)?s.taskId?gs(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function jo(s,e,t,n,r,o,i){let a=e.autonomy,c=ps(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let u=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:u,message:`${Sn(a)}
@@ -127,9 +127,9 @@ Agent: ${t.slice(0,1e3)}`}],{model:li,maxTokens:512})).content.trim().match(/\[[
127
127
  `}return r}if(n==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Ue(i,800)}
128
128
  `}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
129
129
  `:""}}var _r=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Bn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;classifier;graphStore;handoverStore=new jn;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new ot(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Fn(void 0,void 0,"unified"),this.memoryStore=new Un,this.patternStore=new ct,this.rateLimiter=new it,this.tokenTracker=new ve,this.messageQueue=new at,Zs({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Nn({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Ln({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let u=c.toLowerCase();n.includes(u)&&u.length>o&&(r=i,o=u.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,c=[];try{let g=this.sessions.getSession(e.agentId,n,r);i=Os(g.messages,e.message??""),c=Ns(g.messages,e.message??"",this.config.session.continuityStateTurns),g.updatedAt&&(a=Math.round((Date.now()-Date.parse(g.updatedAt))/6e4))}catch{}let u={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await be(Zn,ts(u),es,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!ns(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),ee().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-453FXKHQ.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let u=o.split(/[:@.]/).filter(Boolean).slice(0,4);this.memoryStore.addMemory(e,{agentId:e,category:"fact",content:`[Rotation memo \xB7 ${i}] ${c.memo}`,keywords:["rotation-memo",r,...u],source:{channel:r,chatId:o,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}}),this.sessions.setRotationMemo(e,r,o,c.memo,i),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let n=[];for(let[r,o]of this.agents)r!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
130
- `)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(a){i={content:"",error:a?.message??String(a)}}if(e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Kn().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,r){let o=re(e.autonomy),i=o?null:Xs().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(i){let m=await i;if(m.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${m.sessionId}`),{content:m.text,viaAttachedSession:m.sessionId};this.log(`[${e.agentId}] attached session did not take it (${m.reason}) \u2014 spawning`)}let a=this.agents.get(e.agentId);if(!a){if(o)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let m=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(C=>C.id===e.agentId));if(m){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${m.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(m.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:m.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${m.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",u=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||o){let m=Date.now(),f=25*6e4,C=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-m>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(D=>setTimeout(D,C))}}else{let m=a.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,c,u,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:u,originalContext:e.context});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let C=this.messageQueue.pendingCount(e.agentId,c,u);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${C}) behind=${a.runningTasks.map(D=>D.id).join(",")||"-"} chat=${c}:${u} at=${new Date().toISOString()}`),{content:"",error:`__queued__:${f}:${C}`}}}let l=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(m,f)=>{this.log(`[${e.agentId}] ${m} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(!l.ok)return this.log(`[${e.agentId}] ${l.reason}`),{content:"",error:l.reason};a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let d={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(d),e.runningTaskId=d.id,e.onStart)try{e.onStart(d.id)}catch{}let g=new AbortController;this.taskAborts.set(d.id,{agentId:e.agentId,channel:d.channel,chatId:typeof d.chatId=="string"?d.chatId:"",originalMessage:e.message||"",controller:g});let h={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(d.id,h);let w=m=>{if(m){h.buffer+=m,h.buffer.length>$r&&(h.buffer=h.buffer.slice(h.buffer.length-$r));for(let f of h.subscribers)try{f(m)}catch{}}},x=ye();e.taskId=x;let b=new Map,S;if(t){let m=ca();S=f=>{let C=m(f);if(C&&w(C),Rr(x,e.agentId,f),Pr(b,f),r)try{r(f)}catch{}}}else S=m=>{if(Rr(x,e.agentId,m),Pr(b,m),r)try{r(m)}catch{}};let I=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,E=I?setTimeout(()=>g.abort(new Error(`timed out after ${Math.round(I/1e3)}s`)),I):void 0;E?.unref?.();let A=(a.def.preSpawnTimeoutSec??sa)*1e3,v=setTimeout(()=>{g.abort(new Error(`timed out before spawn after ${Math.round(A/1e3)}s in step "${d.step??"start"}"`))},A);v.unref?.();let _=()=>{v&&clearTimeout(v),v=void 0},N=()=>`task=${d.id} chat=${c}:${u} at=${new Date().toISOString()}`,P;g.signal.addEventListener("abort",()=>{let m=gt(g.signal).message;/^timed out/.test(m)&&(P=d.step??"start"),this.log(`[${e.agentId}] task ${d.id} aborted in step "${d.step??"start"}" \u2014 ${m} ${N()}`)},{once:!0});let L=m=>{d.step=m,this.log(`[${e.agentId}] step ${m} ${N()}`)},O=(m,f,C=0)=>g.signal.aborted?Promise.reject(gt(g.signal)):(L(m),(m==="agent"||m==="workflow-auto-run")&&_(),Cr(f(),g.signal,C)),H=!1,F=m=>{if(H)return;H=!0,this.runReleases.delete(d.id),E&&clearTimeout(E),_(),a.activeTasks--;let f=a.runningTasks.findIndex(C=>C.id===d.id);f!==-1&&a.runningTasks.splice(f,1),this.taskAborts.delete(d.id),h.done=!0,h.endedAt=new Date;for(let C of h.subscribers)try{C(`
130
+ `)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(a){i={content:"",error:a?.message??String(a)}}if(e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Kn().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,r){let o=re(e.autonomy),i=o?null:Xs().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(i){let m=await i;if(m.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${m.sessionId}`),{content:m.text,viaAttachedSession:m.sessionId};this.log(`[${e.agentId}] attached session did not take it (${m.reason}) \u2014 spawning`)}let a=this.agents.get(e.agentId);if(!a){if(o)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let m=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(C=>C.id===e.agentId));if(m){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${m.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(m.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:m.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${m.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",u=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||c==="reminder"||o){let m=Date.now(),f=25*6e4,C=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-m>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(D=>setTimeout(D,C))}}else{let m=a.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,c,u,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:u,originalContext:e.context});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let C=this.messageQueue.pendingCount(e.agentId,c,u);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${C}) behind=${a.runningTasks.map(D=>D.id).join(",")||"-"} chat=${c}:${u} at=${new Date().toISOString()}`),{content:"",error:`__queued__:${f}:${C}`}}}let l=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(m,f)=>{this.log(`[${e.agentId}] ${m} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(!l.ok)return this.log(`[${e.agentId}] ${l.reason}`),{content:"",error:l.reason};a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let d={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(d),e.runningTaskId=d.id,e.onStart)try{e.onStart(d.id)}catch{}let g=new AbortController;this.taskAborts.set(d.id,{agentId:e.agentId,channel:d.channel,chatId:typeof d.chatId=="string"?d.chatId:"",originalMessage:e.message||"",controller:g});let h={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(d.id,h);let w=m=>{if(m){h.buffer+=m,h.buffer.length>$r&&(h.buffer=h.buffer.slice(h.buffer.length-$r));for(let f of h.subscribers)try{f(m)}catch{}}},x=ye();e.taskId=x;let b=new Map,S;if(t){let m=ca();S=f=>{let C=m(f);if(C&&w(C),Rr(x,e.agentId,f),Pr(b,f),r)try{r(f)}catch{}}}else S=m=>{if(Rr(x,e.agentId,m),Pr(b,m),r)try{r(m)}catch{}};let I=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,E=I?setTimeout(()=>g.abort(new Error(`timed out after ${Math.round(I/1e3)}s`)),I):void 0;E?.unref?.();let A=(a.def.preSpawnTimeoutSec??sa)*1e3,v=setTimeout(()=>{g.abort(new Error(`timed out before spawn after ${Math.round(A/1e3)}s in step "${d.step??"start"}"`))},A);v.unref?.();let _=()=>{v&&clearTimeout(v),v=void 0},N=()=>`task=${d.id} chat=${c}:${u} at=${new Date().toISOString()}`,P;g.signal.addEventListener("abort",()=>{let m=gt(g.signal).message;/^timed out/.test(m)&&(P=d.step??"start"),this.log(`[${e.agentId}] task ${d.id} aborted in step "${d.step??"start"}" \u2014 ${m} ${N()}`)},{once:!0});let L=m=>{d.step=m,this.log(`[${e.agentId}] step ${m} ${N()}`)},O=(m,f,C=0)=>g.signal.aborted?Promise.reject(gt(g.signal)):(L(m),(m==="agent"||m==="workflow-auto-run")&&_(),Cr(f(),g.signal,C)),H=!1,F=m=>{if(H)return;H=!0,this.runReleases.delete(d.id),E&&clearTimeout(E),_(),a.activeTasks--;let f=a.runningTasks.findIndex(C=>C.id===d.id);f!==-1&&a.runningTasks.splice(f,1),this.taskAborts.delete(d.id),h.done=!0,h.endedAt=new Date;for(let C of h.subscribers)try{C(`
131
131
  [task finished]
132
- `)}catch{}h.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(d.id),ta).unref?.();try{let C=h.endedAt,D={id:d.id,agentId:e.agentId,channel:d.channel,chatId:d.chatId,sender:d.sender,message:e.message||"",startedAt:d.startedAt.toISOString(),endedAt:C.toISOString(),durationMs:C.getTime()-d.startedAt.getTime(),ok:!m?.error,error:m?.error,...P?{status:"timeout",step:P}:{},responseText:m?.content||"",transcript:h.buffer};this.persistTaskRecord(D);let W=(D.responseText||D.error||"").trim();if(W){let Q=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:C,ok:D.ok})}}catch(C){this.log(`[${e.agentId}] task history persist failed: ${C?.message}`)}this.messageQueue.markDone(e.agentId,c,u).then(C=>{if(C.length!==0){this.log(`[${e.agentId}] flushing ${C.length} queued message(s) after task=${d.id} chat=${c}:${u} at=${new Date().toISOString()}`);for(let D of C){let W=D.originalContext||{channel:D.channel,sender:D.sender,chatId:D.chatId};this.execute({message:D.text,agentId:e.agentId,context:W}).then(Q=>this.postQueuedResponseToChannel(e.agentId,W,Q)).catch(Q=>{this.log(`[${e.agentId}] queued message failed: ${Q.message}`)})}}}).catch(C=>{this.log(`[${e.agentId}] queue flush failed: ${C.message}`)})};this.runReleases.set(d.id,F),this.messageQueue.markRunning(e.agentId,c,u),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${N()}`);let p=e.context?.channel||"api",{evaluateRequest:y,selectRequestContext:k}=await import("./request-planner-ZEXFARZE.js"),M=await O("request-gate",()=>y(e.message,e.agentId,p));M.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let T=e.context?.chatId||e.context?.group||e.context?.sender||"default",R=e.context?.sender||"User",q=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,p,T),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${p}:${T}`),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:T,reason:"stale",at:new Date().toISOString()})),e.freshSession||await O("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,p,T,e.seedHistory));let Dr=[...this.sessions.getSession(e.agentId,p,T).messages].reverse().find(m=>m.role==="agent")?.content;vr({agent:e.agentId,channel:p,chatId:T,message:e.message,previousReply:Dr,taskId:x}),this.sessions.addUserMessage(e.agentId,p,T,R,e.message);let Zt=Date.now();ee().emit("task:started",{agentId:e.agentId,channel:p,chatId:T,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(Zt).toISOString(),taskId:x,resumeOrigin:Ks(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let Y,en=this.classifier;if(en&&p!=="a2a"&&!q)try{Y=await O("classify",()=>en.classify({text:e.message,channel:p,sender:e.context?.sender,agentId:e.agentId}))||void 0}catch(m){this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`)}let Ae=this.config.workflows?.matching,fe;if(this.config.workflows?.enabled&&Ae?.enabled&&!o)try{let m=new Yn({baseDir:B(process.cwd(),this.config.workflows.dir)}),f=Vn({agentId:e.agentId,channel:p,message:e.message,intentPath:Y?.path},m.list());f&&f.confidence>=Ae.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Ae.mode} reasons=${f.reasons.join(",")||"n/a"}`),Ae.mode==="auto"&&f.confidence>=Ae.autoRunThreshold&&(this.workflowAutoRunner?fe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(m){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${m?.message||m}`)}let Or=this.wikiHub.getAgentWiki(e.agentId),tn=this.memoryStore.findRelevant(e.message,e.agentId,q?3:8),nn=this.memoryStore.buildContext(tn),sn=this.memoryStore.contextFacts(tn),Nr=this.patternStore.findRelevant(e.message,e.agentId,5),Lr=this.patternStore.buildContext(Nr),rn="";if(!q)try{let{loadLocalSkills:m,getAutoInjectSkills:f}=await import("./loader-EVHZ2R73.js"),C=await O("skills",()=>m(a.def.workspace));rn=f(C,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,p,T):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,p,T):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,p,T):void 0;if(j&&this.sessions.isSessionStale(e.agentId,p,T)&&(this.log(`[${e.agentId}] session stale for ${p}:${T}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,p,T,"stale"),this.sessions.clearClaudeSessionId(e.agentId,p,T),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:T,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,p,T)){let m=this.sessions.getLastTurnContextTokens(e.agentId,p,T);this.log(`[${e.agentId}] tier-2 rotation for ${p}:${T} (last turn context: ${m} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,p,T,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,p,T),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:T,reason:"tier-2",lastTurnInputTokens:m,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,p,T)){let m=this.sessions.getTurnCount(e.agentId,p,T);this.log(`[${e.agentId}] max-turns rotation for ${p}:${T} (${m} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,p,T,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,p,T),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:T,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let m=j;await O("rotate",()=>this.maybeRotateForContinuity(e,a,p,T,m))&&(j=void 0)}try{let m=await O("compact",()=>this.sessions.compactIfNeeded(e.agentId,p,T,this.memoryStore));if(m.compacted){let f=m.qualityScore??"?",C=m.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${p}:${T} (quality: ${f}%, ${C} entities lost)`),m.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${m.lostEntities.slice(0,5).join(", ")}`),m.drift){let D=m.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${D.overallScore} (lexicon=${D.lexiconDecay}, tools=${D.toolShift}, semantic=${D.semanticDrift})`),D.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${D.lostWords.slice(0,5).join(", ")}`)}}}catch(m){this.log(`[${e.agentId}] compaction failed (non-fatal): ${m.message}`)}let Fr=process.env.AGENTX_CONTEXT_SURGERY==="1",Hr=q?{maxMessages:8,maxChars:2400}:Fr&&Ar(p,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,jr=!j&&!q?ia(Or,e.agentId):void 0,Be=j?void 0:this.sessions.buildHistoryContext(e.agentId,p,T,Hr),Ur=j?void 0:this.sessions.getRotationMemo(e.agentId,p,T)??void 0,on,an=[];if(this.config.procedures?.injection?.enabled&&!j&&!q)try{let m=new He({baseDir:B(process.cwd(),this.config.procedures.dir)}),f=Gt(e.message,m.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){on=Jt(f),an=f.map(C=>({id:C.procedure.meta.id,title:C.procedure.meta.title}));for(let C of f)this.log(`[${e.agentId}] procedure match ${C.procedure.meta.id} score=${C.score.toFixed(2)} (${C.reasons.join(",")})`)}}catch(m){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${m?.message||m}`)}if(ge&&ge.cat)try{let f=this.sessions.getSession(e.agentId,p,T).messages,C=f[0],D=f[f.length-1],W=Be===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${Be.length}c/${Be.split(`
132
+ `)}catch{}h.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(d.id),ta).unref?.();try{let C=h.endedAt,D={id:d.id,agentId:e.agentId,channel:d.channel,chatId:d.chatId,sender:d.sender,message:e.message||"",startedAt:d.startedAt.toISOString(),endedAt:C.toISOString(),durationMs:C.getTime()-d.startedAt.getTime(),ok:!m?.error,error:m?.error,...P?{status:"timeout",step:P}:{},responseText:m?.content||"",transcript:h.buffer};this.persistTaskRecord(D);let W=(D.responseText||D.error||"").trim();if(W){let Q=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:C,ok:D.ok})}}catch(C){this.log(`[${e.agentId}] task history persist failed: ${C?.message}`)}this.messageQueue.markDone(e.agentId,c,u).then(C=>{if(C.length!==0){this.log(`[${e.agentId}] flushing ${C.length} queued message(s) after task=${d.id} chat=${c}:${u} at=${new Date().toISOString()}`);for(let D of C){let W=D.originalContext||{channel:D.channel,sender:D.sender,chatId:D.chatId};this.execute({message:D.text,agentId:e.agentId,context:W}).then(Q=>this.postQueuedResponseToChannel(e.agentId,W,Q)).catch(Q=>{this.log(`[${e.agentId}] queued message failed: ${Q.message}`)})}}}).catch(C=>{this.log(`[${e.agentId}] queue flush failed: ${C.message}`)})};this.runReleases.set(d.id,F),this.messageQueue.markRunning(e.agentId,c,u),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${N()}`);let p=e.context?.channel||"api",{evaluateRequest:y,selectRequestContext:k}=await import("./request-planner-2H7HCUCZ.js"),M=await O("request-gate",()=>y(e.message,e.agentId,p));M.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let T=e.context?.chatId||e.context?.group||e.context?.sender||"default",R=e.context?.sender||"User",q=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,p,T),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${p}:${T}`),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:T,reason:"stale",at:new Date().toISOString()})),e.freshSession||await O("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,p,T,e.seedHistory));let Dr=[...this.sessions.getSession(e.agentId,p,T).messages].reverse().find(m=>m.role==="agent")?.content;vr({agent:e.agentId,channel:p,chatId:T,message:e.message,previousReply:Dr,taskId:x}),this.sessions.addUserMessage(e.agentId,p,T,R,e.message);let Zt=Date.now();ee().emit("task:started",{agentId:e.agentId,channel:p,chatId:T,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(Zt).toISOString(),taskId:x,resumeOrigin:Ks(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let Y,en=this.classifier;if(en&&p!=="a2a"&&!q)try{Y=await O("classify",()=>en.classify({text:e.message,channel:p,sender:e.context?.sender,agentId:e.agentId}))||void 0}catch(m){this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`)}let Ae=this.config.workflows?.matching,fe;if(this.config.workflows?.enabled&&Ae?.enabled&&!o)try{let m=new Yn({baseDir:B(process.cwd(),this.config.workflows.dir)}),f=Vn({agentId:e.agentId,channel:p,message:e.message,intentPath:Y?.path},m.list());f&&f.confidence>=Ae.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Ae.mode} reasons=${f.reasons.join(",")||"n/a"}`),Ae.mode==="auto"&&f.confidence>=Ae.autoRunThreshold&&(this.workflowAutoRunner?fe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(m){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${m?.message||m}`)}let Or=this.wikiHub.getAgentWiki(e.agentId),tn=this.memoryStore.findRelevant(e.message,e.agentId,q?3:8),nn=this.memoryStore.buildContext(tn),sn=this.memoryStore.contextFacts(tn),Nr=this.patternStore.findRelevant(e.message,e.agentId,5),Lr=this.patternStore.buildContext(Nr),rn="";if(!q)try{let{loadLocalSkills:m,getAutoInjectSkills:f}=await import("./loader-EVHZ2R73.js"),C=await O("skills",()=>m(a.def.workspace));rn=f(C,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,p,T):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,p,T):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,p,T):void 0;if(j&&this.sessions.isSessionStale(e.agentId,p,T)&&(this.log(`[${e.agentId}] session stale for ${p}:${T}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,p,T,"stale"),this.sessions.clearClaudeSessionId(e.agentId,p,T),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:T,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,p,T)){let m=this.sessions.getLastTurnContextTokens(e.agentId,p,T);this.log(`[${e.agentId}] tier-2 rotation for ${p}:${T} (last turn context: ${m} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,p,T,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,p,T),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:T,reason:"tier-2",lastTurnInputTokens:m,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,p,T)){let m=this.sessions.getTurnCount(e.agentId,p,T);this.log(`[${e.agentId}] max-turns rotation for ${p}:${T} (${m} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,p,T,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,p,T),ee().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:T,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let m=j;await O("rotate",()=>this.maybeRotateForContinuity(e,a,p,T,m))&&(j=void 0)}try{let m=await O("compact",()=>this.sessions.compactIfNeeded(e.agentId,p,T,this.memoryStore));if(m.compacted){let f=m.qualityScore??"?",C=m.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${p}:${T} (quality: ${f}%, ${C} entities lost)`),m.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${m.lostEntities.slice(0,5).join(", ")}`),m.drift){let D=m.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${D.overallScore} (lexicon=${D.lexiconDecay}, tools=${D.toolShift}, semantic=${D.semanticDrift})`),D.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${D.lostWords.slice(0,5).join(", ")}`)}}}catch(m){this.log(`[${e.agentId}] compaction failed (non-fatal): ${m.message}`)}let Fr=process.env.AGENTX_CONTEXT_SURGERY==="1",Hr=q?{maxMessages:8,maxChars:2400}:Fr&&Ar(p,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,jr=!j&&!q?ia(Or,e.agentId):void 0,Be=j?void 0:this.sessions.buildHistoryContext(e.agentId,p,T,Hr),Ur=j?void 0:this.sessions.getRotationMemo(e.agentId,p,T)??void 0,on,an=[];if(this.config.procedures?.injection?.enabled&&!j&&!q)try{let m=new He({baseDir:B(process.cwd(),this.config.procedures.dir)}),f=Gt(e.message,m.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){on=Jt(f),an=f.map(C=>({id:C.procedure.meta.id,title:C.procedure.meta.title}));for(let C of f)this.log(`[${e.agentId}] procedure match ${C.procedure.meta.id} score=${C.score.toFixed(2)} (${C.reasons.join(",")})`)}}catch(m){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${m?.message||m}`)}if(ge&&ge.cat)try{let f=this.sessions.getSession(e.agentId,p,T).messages,C=f[0],D=f[f.length-1],W=Be===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${Be.length}c/${Be.split(`
133
133
  `).length}L`,Q=`[${e.agentId}] ${p}:${T} ${W} | session.messages=${f.length}`+(f.length>0?` first=${C.timestamp.slice(11,19)}(${C.role}:${(C.content||"").slice(0,40).replace(/\n/g," ")}) last=${D.timestamp.slice(11,19)}(${D.role}:${(D.content||"").slice(0,40).replace(/\n/g," ")})`:"");ge.cat("context",Q)}catch(m){ge.cat("context",`[${e.agentId}] context-diag error: ${m?.message??m}`)}let cn;if(a.def.contextReferences&&!j)try{let m=a.def.workspace,f=this.referencesCache.get(m);if(!f){let[D,W]=await O("references",()=>Promise.all([kt(a.def.workspace),It(a.def.workspace)]));if(D.byId.size===0&&W.recipes.length===0){let[Q,le]=await O("references",()=>Promise.all([kt(process.cwd()),It(process.cwd())]));f={refs:Q,recipes:le}}else f={refs:D,recipes:W};this.referencesCache.set(m,f)}let C=qn({agentId:e.agentId,intentTags:Y?.path,message:e.message},f.recipes,f.refs);C.cards.length>0&&(cn=Wn(C.cards,500*4)),C.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${C.unresolvedIds.join(", ")}`)}catch(m){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${m?.message||m}`)}let dn=this.sessions.getCrossSessionSummary(e.agentId,p,T,e.message),un,We=Ds(e.message);if(We)try{let m=this.sessions.recallTurns({agentId:e.agentId,channel:p,chatId:T,lookbackDays:We.lookbackDays,limit:12});if(m.turns.length>0){let f=[`[Long-memory recall \u2014 last ${We.lookbackDays}d on this chat (cue-triggered)]`],C=[...m.turns].sort((D,W)=>D.ts.localeCompare(W.ts));for(let D of C){let W=D.ts.slice(11,16)+" "+D.day,Q=D.role==="user"?D.senderName||"User":D.senderName||"Agent";f.push(`${W} ${Q}: ${D.content}`)}m.hasMore&&f.push(`[\u2026${m.totalScanned-m.turns.length}+ older turns available \u2014 call /recall with before=${m.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),un=f.join(`
134
134
  `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${We.lookbackDays}d, turns=${m.turns.length}, scanned=${m.totalScanned}`)}}catch(m){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${m.message}`)}let Br=q?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",ln,gn,pn=!1;if(Br==="planner"&&!M.active&&p!=="voice"&&p!=="desktop"){try{let{planContext:m}=await import("./context-planner-LJT5IKH6.js"),f=await O("plan-context",()=>m({agentId:e.agentId,channel:p,chatId:T,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(pn=!0,ln=f.sessionHistory,nn=f.memoryContext,sn=f.memoryFacts,dn=f.crossChatContext,gn=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(m){this.log(`[${e.agentId}] planner failed (non-fatal): ${m.message} \u2014 falling back to layered (keeping --resume for continuity)`)}pn&&j&&(this.sessions.clearClaudeSessionId(e.agentId,p,T),j=void 0)}let pt=`${e.agentId}:${p}:${T}`,Ke=Rn(e.message);Ke&&(Ke==="default"?(this.activeSouls.delete(pt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(pt,Ke),this.log(`[${e.agentId}] Soul switched to: ${Ke}`)));let Wr=this.activeSouls.get(pt),Kr=Mn(a.def.workspace,Wr),qr=Pn(Kr),Gr=this.agentMemory.indexMarkdown(e.agentId),Jr=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
135
135
  Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",Qr=a.def.richMessages!==!1&&(p==="telegram"||p==="whatsapp")?["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text."].join(`
@@ -143,8 +143,8 @@ ${$}`),f+=$.length}catch{}}}let zr=mt.length>0?mt.join(`
143
143
 
144
144
  `):"",ht=[a.def.systemPrompt||"",Jr,Qr,mn,zr,qr||"",Gr||""].filter(m=>m.trim().length>0).join(`
145
145
 
146
- `)||void 0,hn={channel:p,chatId:T,channelScope:e.context?.group?"group":p==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,p),systemPrompt:a.def.systemPrompt,sender:R,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:q||Ar(p,a.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:q?void 0:Lr||void 0,procedureContext:on,references:cn,skillInjection:rn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ln??Be,memoryContext:nn||void 0,crossChatContext:dn||void 0,longMemoryRecall:un||void 0,wikiContext:jr,handoverNote:this.buildHandoverNote(e.agentId,p,T),rotationMemo:Ur,intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},Ge=M.active&&M.preprocess?await O("select-context",()=>k(hn)):{input:hn,excluded:[]};Ge.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ge.excluded.join(", ")}`);let Je=Ws(Ge.input,q?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Xr=Hn(Je,{memory:sn,procedures:an,wikiContext:Ge.input.wikiContext}),ft=(Je?.length??0)+(ht?.length??0)+(e.message?.length??0),Qe={history:Je?.length??0,sysPrompt:ht?.length??0,message:e.message?.length??0},fn=or(e.agentId,p,T);ir(fn,ft,Qe);let yn=ar(fn);yn&&this.log(`[${e.agentId}] ${yn}`),ft>16e3&&this.log(`[${e.agentId}] large context for ${p}:${T}: ${ft} bytes (history=${Qe.history}, sysPrompt=${Qe.sysPrompt}, message=${Qe.message})`);let yt,bn=$n(a.def.tier,this.config.decisions.routing);if(!e.model&&bn&&(!M.active||M.preprocess))try{let{routeTaskModel:m}=await import("./routing-XSRZ7V23.js"),f=await O("route-model",()=>m({message:e.message,agent:e.agentId,channel:p,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,p,T),cheapModel:bn}));f.downgraded&&(yt=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let Yr={...e,systemPromptAppend:ht,...yt?{model:yt}:{}},ue,wn=kr({agent:e.agentId,request:e.message,taskId:x,budgetMinutes:a.def.maxExecutionMinutes??20}),Vr=S;S=m=>{wn.observe(m),Vr?.(m)};try{let m=this.workflowAutoRunner;if(fe&&m){let U=fe;try{let J=await O("workflow-auto-run",()=>m({workflowId:U.workflowId,agentId:e.agentId,channel:p,chatId:T,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:p,chatId:T,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:U.workflowId,matchConfidence:U.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${fe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),ue={content:"",duration:0,metadata:{handledByWorkflow:fe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:fe.confidence}},ue}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(a.def.tier==="claude-code"){L("dispatch-gate");let U=a.def.persistentProcess?et():null,J=U!=null&&U.hasLive({agentId:e.agentId,channel:p,chatId:T}),se=!!j||J,Z=[Ys(se),sr(se)].find(Me=>Me&&Me.abort);if(Z){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Z.reason}`);let Me={content:"",error:Z.message,duration:0};if(!t){h.buffer=`[error] ${Z.message}`;for(let Zr of h.subscribers)try{Zr(h.buffer)}catch{}}return ue=Me,Me}tr();let $e=rr();$e&&this.log(`[${e.agentId}] ${$e}`)}let f=a.def.tier==="claude-code",C=f?t:(U,J)=>{U&&w(U),t&&t(U,J)},D=!1,W=f?n:U=>{U&&(D?w(U):(w(`\u{1F4AD} ${U}`),D=!0)),n&&n(U)},Q=()=>{D&&(w(`
146
+ `)||void 0,hn={channel:p,chatId:T,channelScope:e.context?.group?"group":p==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,p),systemPrompt:a.def.systemPrompt,sender:R,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:q||Ar(p,a.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:q?void 0:Lr||void 0,procedureContext:on,references:cn,skillInjection:rn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ln??Be,memoryContext:nn||void 0,crossChatContext:dn||void 0,longMemoryRecall:un||void 0,wikiContext:jr,handoverNote:this.buildHandoverNote(e.agentId,p,T),rotationMemo:Ur,intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},Ge=M.active&&M.preprocess?await O("select-context",()=>k(hn)):{input:hn,excluded:[]};Ge.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ge.excluded.join(", ")}`);let Je=Ws(Ge.input,q?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Xr=Hn(Je,{memory:sn,procedures:an,wikiContext:Ge.input.wikiContext}),ft=(Je?.length??0)+(ht?.length??0)+(e.message?.length??0),Qe={history:Je?.length??0,sysPrompt:ht?.length??0,message:e.message?.length??0},fn=or(e.agentId,p,T);ir(fn,ft,Qe);let yn=ar(fn);yn&&this.log(`[${e.agentId}] ${yn}`),ft>16e3&&this.log(`[${e.agentId}] large context for ${p}:${T}: ${ft} bytes (history=${Qe.history}, sysPrompt=${Qe.sysPrompt}, message=${Qe.message})`);let yt,bn=$n(a.def.tier,this.config.decisions.routing);if(!e.model&&bn&&(!M.active||M.preprocess))try{let{routeTaskModel:m}=await import("./routing-LVQH6WOJ.js"),f=await O("route-model",()=>m({message:e.message,agent:e.agentId,channel:p,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,p,T),cheapModel:bn}));f.downgraded&&(yt=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let Yr={...e,systemPromptAppend:ht,...yt?{model:yt}:{}},ue,wn=kr({agent:e.agentId,request:e.message,taskId:x,budgetMinutes:a.def.maxExecutionMinutes??20}),Vr=S;S=m=>{wn.observe(m),Vr?.(m)};try{let m=this.workflowAutoRunner;if(fe&&m){let U=fe;try{let J=await O("workflow-auto-run",()=>m({workflowId:U.workflowId,agentId:e.agentId,channel:p,chatId:T,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:p,chatId:T,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:U.workflowId,matchConfidence:U.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${fe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),ue={content:"",duration:0,metadata:{handledByWorkflow:fe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:fe.confidence}},ue}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(a.def.tier==="claude-code"){L("dispatch-gate");let U=a.def.persistentProcess?et():null,J=U!=null&&U.hasLive({agentId:e.agentId,channel:p,chatId:T}),se=!!j||J,Z=[Ys(se),sr(se)].find(Me=>Me&&Me.abort);if(Z){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Z.reason}`);let Me={content:"",error:Z.message,duration:0};if(!t){h.buffer=`[error] ${Z.message}`;for(let Zr of h.subscribers)try{Zr(h.buffer)}catch{}}return ue=Me,Me}tr();let $e=rr();$e&&this.log(`[${e.agentId}] ${$e}`)}let f=a.def.tier==="claude-code",C=f?t:(U,J)=>{U&&w(U),t&&t(U,J)},D=!1,W=f?n:U=>{U&&(D?w(U):(w(`\u{1F4AD} ${U}`),D=!0)),n&&n(U)},Q=()=>{D&&(w(`
147
147
  `),D=!1)},le=f?C:C?(U,J)=>{Q(),C(U,J)}:void 0,$=await O("agent",()=>Rs(a.def,Yr,this.providers,le,Je,j,S,g.signal,W),na);if(!$.error){let U=aa(a.def.toolUseRequired,b);if(U){let J=Array.from(b.entries()).map(([se,ze])=>`${se}=${ze}`).join(", ")||"none";$.error=`tool_required_not_called: ${U} (invoked: ${J})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${U}, observed ${J}`)}}ue=$;let ne=$.usage?Us($.usage):void 0;if(ee().emit("task:completed",{taskId:x,agentId:e.agentId,channel:p,chatId:T,durationMs:Date.now()-Zt,error:$.error||void 0,inputTokens:ne?.inputTokens,outputTokens:ne?.outputTokens,cacheReadTokens:ne?.cacheReadTokens,cacheCreateTokens:ne?.cacheCreateTokens,tier2InputTokens:ne?.tier2InputTokens,tier2OutputTokens:ne?.tier2OutputTokens,tier2CacheReadTokens:ne?.tier2CacheReadTokens,tier2CacheCreateTokens:ne?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:M.arm,numTurns:$.numTurns,injectedContext:Xr,finalResponse:$.content||void 0,billedModel:$.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let U=$.error?`[error] ${$.error}`:$.content;h.buffer=U;for(let J of h.subscribers)try{J(U)}catch{}}if($.error)a.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,p,T,$.content),Sr({agent:e.agentId,channel:p,chatId:T,request:e.message,reply:$.content,taskId:x}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,p,T,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,p,T,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,p,T,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,p,T,$.usage,$.contextTokens),$.usage){let Z=$.contextTokens,$e=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(Z??$e)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${p}:${T}: context=${Z??"n/a"} tokens (cumulative turn total=${$e}) \u2014 next turn will rotate`)}if(Dn({channel:p,content:`User: ${e.message}`,responseLength:$.content.length}).capture){try{let Z=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:Z,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:p,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
148
148
 
149
149
  Agent: ${$.content}`,meta:oa(Y,e.context)})}catch{}On(e.agentId,e.message,$.content,{channel:p,chatId:T,sender:R},this.memoryStore).catch(()=>{}),Qs(e.agentId,e.message,$.content,{channel:p,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=$.billedModel||e.model||a.def.model,se=e.context?.channel,ze=se&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${se}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,J,se,ze),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${N()}`)}return $}catch(m){a.errors++,this.log(`[${e.agentId}] unexpected error: ${m.message}`);let f=Ve(m.message);return ue={content:"",error:Ze(f),errorKind:f.kind},ue}finally{wn.stop(),F(ue)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=B(process.cwd(),Ce,this.safe(e.agentId),t);V(n)||Vi(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);ea(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=B(process.cwd(),Ce,this.safe(e));if(!V(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),u=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let d of[u,c]){let g=B(a,d);if(V(g))try{for(let h of te(g)){if(!h.endsWith(".json"))continue;let w=h.split("-")[0],x=parseInt(w,10);if(!Number.isFinite(x)||x<i||x>n)continue;let b=Math.floor((n-x)/36e5),S=t-1-b;S>=0&&S<t&&o[S]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Ce);if(!V(e))return 0;let t=0;for(let n of te(e)){let r=B(e,n),o;try{o=te(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=B(r,i),c;try{c=te(a).filter(u=>u.endsWith(".json")).sort().reverse()}catch{continue}for(let u of c)try{let l=JSON.parse(je(B(a,u),"utf-8")),d=(l.responseText||l.error||"").trim();if(!d)continue;let g=d.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:g,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=ra){let t=B(process.cwd(),Ce);if(!V(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of te(t)){let i=B(t,o),a;try{a=te(i)}catch{continue}for(let c of a){let u=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(u)||u>=n))try{Zi(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Ce,this.safe(e));if(!V(n))return[];let r=te(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=B(n,i),c;try{c=te(a).filter(u=>u.endsWith(".json"))}catch{continue}c.sort().reverse();for(let u of c){if(o.length>=t)break;try{let l=JSON.parse(je(B(a,u),"utf-8")),{transcript:d,responseText:g,...h}=l;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Ce,this.safe(e));if(!V(n))return null;let r=this.safe(t),o=te(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=B(n,i,`${r}.json`);if(V(a))try{return JSON.parse(je(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=Xn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.error?.startsWith("__queued__"))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:u}=o,l=o.controller.signal.aborted,d=!1;l&&u&&(d=this.sessions.removeLastUserMessageIfMatches(i,a,c,u)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let g=this.messageQueue.pendingCount(i,a,c),h=!1;if(r.replace){let w=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(w))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${w}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${g}${d?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:d,pending:g}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(u=>{let l=!1,d=g=>{l||(l=!0,u(g))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:g=>d({ok:!0,agentId:e,channel:a,chatId:c,taskId:g,queued:!1})}).then(g=>{g.error?.startsWith("__queued__")?d({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):g.error?d({ok:!1,status:500,error:g.error||"run did not start"}):d({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>d({ok:!1,status:500,error:g?.message??String(g)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};export{ss as a,rs as b,Ta as c,is as d,fo as e,as as f,us as g,Ea as h,La as i,Fa as j,Ro as k,$s as l,No as m,Lo as n,Fo as o,Rs as p,ot as q,it as r,pc as s,jt as t,ee as u,zs as v,hi as w,Xs as x,He as y,Hi as z,ji as A,Ui as B,Bi as C,Wi as D,Gt as E,Xd as F,Yd as G,oa as H,ia as I,Vt as J,Mr as K,Pr as L,aa as M,Rr as N,_r as O};
150
- //# sourceMappingURL=chunk-64UYAWAK.js.map
150
+ //# sourceMappingURL=chunk-IDYP7G7Z.js.map