agentix-cli 0.61.0 → 0.63.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 (109) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/SettingsWindow.swift +48 -26
  2. package/dist/{App-LQXWKBVY.js → App-B6WGWI3A.js} +2 -2
  3. package/dist/{ChatApp-75TL4LKW.js → ChatApp-BHRANF7Z.js} +2 -2
  4. package/dist/{agent-DH4FMMMY.js → agent-D2BHFDUA.js} +2 -2
  5. package/dist/{board-dashboard-C6AZHDHU.js → board-dashboard-SMCZBJKO.js} +489 -213
  6. package/dist/board-dashboard-SMCZBJKO.js.map +1 -0
  7. package/dist/{chunk-3XVTFNYM.js → chunk-2ZKDZ4FM.js} +2 -2
  8. package/dist/{chunk-WOPFHKBF.js → chunk-33YJIUYL.js} +2 -2
  9. package/dist/{chunk-E2PWCU2N.js → chunk-5QP56S4O.js} +2 -2
  10. package/dist/chunk-5UYXEO3I.js +131 -0
  11. package/dist/chunk-5UYXEO3I.js.map +1 -0
  12. package/dist/{chunk-DTEQNXK3.js → chunk-5WMHW4A6.js} +2 -2
  13. package/dist/{chunk-BCXKRD5L.js → chunk-7LETLAIH.js} +153 -152
  14. package/dist/chunk-7LETLAIH.js.map +1 -0
  15. package/dist/{chunk-2VQIPJH5.js → chunk-AZBOYKQA.js} +2 -2
  16. package/dist/{chunk-JORXRF4E.js → chunk-BHE5TJSN.js} +2 -2
  17. package/dist/chunk-BYJ3A55Y.js +13 -0
  18. package/dist/chunk-BYJ3A55Y.js.map +1 -0
  19. package/dist/{chunk-CRSXKQLZ.js → chunk-EA7H3EUX.js} +2 -2
  20. package/dist/{chunk-27P5NLTC.js → chunk-I2SD4XZ6.js} +2 -2
  21. package/dist/{chunk-JO3PSLWL.js → chunk-JZMKKDT3.js} +5 -5
  22. package/dist/{chunk-WBGC7MWX.js → chunk-LQ5J6COO.js} +2 -2
  23. package/dist/{chunk-N5KD3TVN.js → chunk-N42YWYIR.js} +7 -7
  24. package/dist/{chunk-N5KD3TVN.js.map → chunk-N42YWYIR.js.map} +1 -1
  25. package/dist/{chunk-S7TCVIET.js → chunk-OVF37EXJ.js} +9 -9
  26. package/dist/{chunk-S7TCVIET.js.map → chunk-OVF37EXJ.js.map} +1 -1
  27. package/dist/{chunk-YQCOX4R3.js → chunk-P4GOKVK2.js} +2 -2
  28. package/dist/{chunk-WIBMNQKJ.js → chunk-PMGPGMBZ.js} +2 -2
  29. package/dist/{chunk-NBGNPKAF.js → chunk-PTB2TPOC.js} +2 -2
  30. package/dist/{chunk-B3DCYBP4.js → chunk-TX3ZOO22.js} +2 -2
  31. package/dist/{chunk-E2BJVHBR.js → chunk-WGWNVLVW.js} +2 -2
  32. package/dist/{chunk-LXUG2X26.js → chunk-XT3E5MLX.js} +2 -2
  33. package/dist/{chunk-Y76THZUQ.js → chunk-ZGWW6FZF.js} +205 -206
  34. package/dist/chunk-ZGWW6FZF.js.map +1 -0
  35. package/dist/cli.js +1 -1
  36. package/dist/client-YIBETZDJ.js +2 -0
  37. package/dist/{config-3XC7EYB7.js → config-EXNBBAZG.js} +2 -2
  38. package/dist/config-mutator-MFNZNWCZ.js +2 -0
  39. package/dist/doctor-IITNYJU5.js +2 -0
  40. package/dist/index.d.ts +10 -1
  41. package/dist/index.js +2 -2
  42. package/dist/index.js.map +1 -1
  43. package/dist/program-NPPLJAQ7.js +2 -0
  44. package/dist/{promote-UR2GSHKC.js → promote-KPEOVZ5V.js} +2 -2
  45. package/dist/query-WRWFAW5G.js +2 -0
  46. package/dist/{registry-PGALUW5L.js → registry-MRMQBYE4.js} +2 -2
  47. package/dist/{request-planner-NHE3IRJN.js → request-planner-PLBDCYKI.js} +2 -2
  48. package/dist/{review-candidates-6GKRSRBQ.js → review-candidates-LEO2N65G.js} +2 -2
  49. package/dist/{routing-AQKHAU3Z.js → routing-POORZC7A.js} +2 -2
  50. package/dist/schedule-tool-ZI4XBEN6.js +2 -0
  51. package/dist/scheduler-VPPKD4FY.js +2 -0
  52. package/dist/{seat-6FMW2QI4.js → seat-PBFG5R7D.js} +2 -2
  53. package/dist/{select-5VONJMLH.js → select-WORPEXHN.js} +2 -2
  54. package/dist/{set-enabled-YHD3IJJZ.js → set-enabled-HGQWVDUD.js} +2 -2
  55. package/dist/{tool-MXJGLJZ5.js → tool-T2BIWDXP.js} +2 -2
  56. package/dist/wiki-KTDNYDOD.js +2 -0
  57. package/package.json +2 -1
  58. package/dist/board-dashboard-C6AZHDHU.js.map +0 -1
  59. package/dist/chunk-BCXKRD5L.js.map +0 -1
  60. package/dist/chunk-RVEMQCWW.js +0 -130
  61. package/dist/chunk-RVEMQCWW.js.map +0 -1
  62. package/dist/chunk-S7CVSKOX.js +0 -13
  63. package/dist/chunk-S7CVSKOX.js.map +0 -1
  64. package/dist/chunk-Y76THZUQ.js.map +0 -1
  65. package/dist/client-QVZIZFV4.js +0 -2
  66. package/dist/config-mutator-HKU63FJM.js +0 -2
  67. package/dist/doctor-YFA4ZSRH.js +0 -2
  68. package/dist/program-L6VAFALE.js +0 -2
  69. package/dist/query-XUP3BMVS.js +0 -2
  70. package/dist/schedule-tool-6NMCLTIH.js +0 -2
  71. package/dist/scheduler-RAYGNDWT.js +0 -2
  72. package/dist/wiki-ZQLEYY24.js +0 -2
  73. /package/dist/{App-LQXWKBVY.js.map → App-B6WGWI3A.js.map} +0 -0
  74. /package/dist/{ChatApp-75TL4LKW.js.map → ChatApp-BHRANF7Z.js.map} +0 -0
  75. /package/dist/{agent-DH4FMMMY.js.map → agent-D2BHFDUA.js.map} +0 -0
  76. /package/dist/{chunk-3XVTFNYM.js.map → chunk-2ZKDZ4FM.js.map} +0 -0
  77. /package/dist/{chunk-WOPFHKBF.js.map → chunk-33YJIUYL.js.map} +0 -0
  78. /package/dist/{chunk-E2PWCU2N.js.map → chunk-5QP56S4O.js.map} +0 -0
  79. /package/dist/{chunk-DTEQNXK3.js.map → chunk-5WMHW4A6.js.map} +0 -0
  80. /package/dist/{chunk-2VQIPJH5.js.map → chunk-AZBOYKQA.js.map} +0 -0
  81. /package/dist/{chunk-JORXRF4E.js.map → chunk-BHE5TJSN.js.map} +0 -0
  82. /package/dist/{chunk-CRSXKQLZ.js.map → chunk-EA7H3EUX.js.map} +0 -0
  83. /package/dist/{chunk-27P5NLTC.js.map → chunk-I2SD4XZ6.js.map} +0 -0
  84. /package/dist/{chunk-JO3PSLWL.js.map → chunk-JZMKKDT3.js.map} +0 -0
  85. /package/dist/{chunk-WBGC7MWX.js.map → chunk-LQ5J6COO.js.map} +0 -0
  86. /package/dist/{chunk-YQCOX4R3.js.map → chunk-P4GOKVK2.js.map} +0 -0
  87. /package/dist/{chunk-WIBMNQKJ.js.map → chunk-PMGPGMBZ.js.map} +0 -0
  88. /package/dist/{chunk-NBGNPKAF.js.map → chunk-PTB2TPOC.js.map} +0 -0
  89. /package/dist/{chunk-B3DCYBP4.js.map → chunk-TX3ZOO22.js.map} +0 -0
  90. /package/dist/{chunk-E2BJVHBR.js.map → chunk-WGWNVLVW.js.map} +0 -0
  91. /package/dist/{chunk-LXUG2X26.js.map → chunk-XT3E5MLX.js.map} +0 -0
  92. /package/dist/{client-QVZIZFV4.js.map → client-YIBETZDJ.js.map} +0 -0
  93. /package/dist/{config-3XC7EYB7.js.map → config-EXNBBAZG.js.map} +0 -0
  94. /package/dist/{config-mutator-HKU63FJM.js.map → config-mutator-MFNZNWCZ.js.map} +0 -0
  95. /package/dist/{doctor-YFA4ZSRH.js.map → doctor-IITNYJU5.js.map} +0 -0
  96. /package/dist/{program-L6VAFALE.js.map → program-NPPLJAQ7.js.map} +0 -0
  97. /package/dist/{promote-UR2GSHKC.js.map → promote-KPEOVZ5V.js.map} +0 -0
  98. /package/dist/{query-XUP3BMVS.js.map → query-WRWFAW5G.js.map} +0 -0
  99. /package/dist/{registry-PGALUW5L.js.map → registry-MRMQBYE4.js.map} +0 -0
  100. /package/dist/{request-planner-NHE3IRJN.js.map → request-planner-PLBDCYKI.js.map} +0 -0
  101. /package/dist/{review-candidates-6GKRSRBQ.js.map → review-candidates-LEO2N65G.js.map} +0 -0
  102. /package/dist/{routing-AQKHAU3Z.js.map → routing-POORZC7A.js.map} +0 -0
  103. /package/dist/{schedule-tool-6NMCLTIH.js.map → schedule-tool-ZI4XBEN6.js.map} +0 -0
  104. /package/dist/{scheduler-RAYGNDWT.js.map → scheduler-VPPKD4FY.js.map} +0 -0
  105. /package/dist/{seat-6FMW2QI4.js.map → seat-PBFG5R7D.js.map} +0 -0
  106. /package/dist/{select-5VONJMLH.js.map → select-WORPEXHN.js.map} +0 -0
  107. /package/dist/{set-enabled-YHD3IJJZ.js.map → set-enabled-HGQWVDUD.js.map} +0 -0
  108. /package/dist/{tool-MXJGLJZ5.js.map → tool-T2BIWDXP.js.map} +0 -0
  109. /package/dist/{wiki-ZQLEYY24.js.map → wiki-KTDNYDOD.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{e as o}from"./chunk-E2BJVHBR.js";import{resolve as a}from"path";import{existsSync as h,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),i="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=i,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let i=a(this.agentsDir,t,this.mode),r=new o(i,this.log);return this.agentStores.set(e,r),r}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let i of e)t.add(i.agentId);if(h(this.agentsDir))for(let i of c(this.agentsDir))!i.startsWith("_")&&!i.startsWith(".")&&t.add(i);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),i=this.getAgentEntries(t),r=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let d of s.sources)r.add(d);return i.filter(s=>!r.has(s.id))}summary(){return this.listAgents().map(e=>{let i=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:i.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
2
- //# sourceMappingURL=chunk-2VQIPJH5.js.map
1
+ import{e as o}from"./chunk-WGWNVLVW.js";import{resolve as a}from"path";import{existsSync as h,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),i="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=i,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let i=a(this.agentsDir,t,this.mode),r=new o(i,this.log);return this.agentStores.set(e,r),r}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let i of e)t.add(i.agentId);if(h(this.agentsDir))for(let i of c(this.agentsDir))!i.startsWith("_")&&!i.startsWith(".")&&t.add(i);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),i=this.getAgentEntries(t),r=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let d of s.sources)r.add(d);return i.filter(s=>!r.has(s.id))}summary(){return this.listAgents().map(e=>{let i=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:i.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
2
+ //# sourceMappingURL=chunk-AZBOYKQA.js.map
@@ -1,4 +1,4 @@
1
- import{b as S,c as O}from"./chunk-CRSXKQLZ.js";import{a as I,b as X}from"./chunk-FCPTN6NF.js";import{a as F,b as oe}from"./chunk-7I7IEX4S.js";import{d as M}from"./chunk-QIJLFPWE.js";import{execFile as Oe}from"child_process";import{writeFileSync as ee,mkdirSync as A,existsSync as b,readFileSync as Le}from"fs";import{resolve as _}from"path";var ce=["off","shadow","authoritative"],ae={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},de="INTENT_LEDGER_MODE";function B(n,e=process.env){let t=P(e[ae[n]]);if(t)return t;let i=P(e[de]);return i||"off"}function P(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return ce.includes(e)?e:null}X();import ue from"better-sqlite3";import{existsSync as Xe,mkdirSync as le}from"fs";import{dirname as ge,resolve as me}from"path";var T=class{db;path;constructor(e={}){this.path=me(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),le(ge(this.path),{recursive:!0}),this.db=new ue(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),fe(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let i=this.findEventBySourceId(e.source,e.sourceEventId);if(i)return i}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
1
+ import{b as S,c as O}from"./chunk-EA7H3EUX.js";import{a as I,b as X}from"./chunk-FCPTN6NF.js";import{a as F,b as oe}from"./chunk-7I7IEX4S.js";import{d as M}from"./chunk-QIJLFPWE.js";import{execFile as Oe}from"child_process";import{writeFileSync as ee,mkdirSync as A,existsSync as b,readFileSync as Le}from"fs";import{resolve as _}from"path";var ce=["off","shadow","authoritative"],ae={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},de="INTENT_LEDGER_MODE";function B(n,e=process.env){let t=P(e[ae[n]]);if(t)return t;let i=P(e[de]);return i||"off"}function P(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return ce.includes(e)?e:null}X();import ue from"better-sqlite3";import{existsSync as Xe,mkdirSync as le}from"fs";import{dirname as ge,resolve as me}from"path";var T=class{db;path;constructor(e={}){this.path=me(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),le(ge(this.path),{recursive:!0}),this.db=new ue(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),fe(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let i=this.findEventBySourceId(e.source,e.sourceEventId);if(i)return i}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
2
2
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let i=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
3
3
  FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return i?U(i):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
4
4
  FROM intent_events WHERE id = ?`).get(e);return t?U(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
@@ -120,4 +120,4 @@ ${r.prompt}`,r.maxOutputTokens),agentId:r.agent,autonomy:r.autonomy,timeoutMinut
120
120
  `);return t.length<=e?t.join(`
121
121
  `):t.slice(-e).join(`
122
122
  `)}function ke(n,e,t){return new Promise((i,r)=>{Oe("/bin/sh",["-c",n],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(s,c,o)=>{if(s&&s.killed){r(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}i({stdout:String(c??""),stderr:String(o??""),code:s?typeof s.code=="number"?s.code:1:0})})})}export{T as a,G as b,nt as c,be as d,it as e,rt as f,$ as g,Q as h,B as i,Ye as j,H as k,K as l,ct as m,$e as n,ne as o,ie as p,re as q,we as r,C as s};
123
- //# sourceMappingURL=chunk-JORXRF4E.js.map
123
+ //# sourceMappingURL=chunk-BHE5TJSN.js.map
@@ -0,0 +1,13 @@
1
+ import{existsSync as w,readFileSync as A}from"node:fs";import{dirname as g,join as a}from"node:path";import{fileURLToPath as L}from"node:url";var p="tn.acme.agentx.voice",H="AgentX Desktop.app",d="AgentX Helper.app";function I(n,t,r){return n!=="darwin"||t!=="arm64"||Number(r.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function M(n,t){if(t&&!Object.hasOwn(n,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let r=t||Object.keys(n)[0];if(!r)throw new Error("No agents configured. Run agentx setup first.");return r}function c(n){return`'${n.replace(/'/g,"'\\''")}'`}var y="/usr/bin:/bin:/usr/sbin:/sbin";function C(n,t){return t||[...new Set([...n?[g(n)]:[],...y.split(":")])].join(":")}function u(n){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return n.replace(/&(amp|lt|gt|quot|apos);/g,(r,e)=>t[e])}function j(n){let t=n.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?u(t[1]):y}var X=n=>/agentx\.voice.*\.plist$/.test(n);function U(n,t){let r=null,e=[];for(let{file:i,plist:l}of[...t].sort((s,o)=>s.file<o.file?-1:1)){let s=l.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],o=l.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!o||!u(o).endsWith("/Contents/MacOS/AgentXVoice")||(r?e.push({file:i,label:u(s)}):r={file:i,label:u(s)})}return{keep:r??{file:a(n,`${p}.plist`),label:p},remove:e}}function G(n,t,r){for(let e of t.split(":"))if(e&&r(a(e,n)))return a(e,n);return null}function F(n){let t=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),r={PATH:n.path,...n.agent?{AGENTX_VOICE_AGENT:n.agent}:{},AGENTX_DAEMON_URL:n.url,AGENTX_MAC_HELPER:n.helper,AGENTX_PASTE_COMMAND:`cd ${c(n.cwd)} && ${c(n.node)} ${c(n.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0"><dict>
4
+ <key>Label</key><string>${t(n.label??p)}</string>
5
+ <key>ProgramArguments</key><array><string>${t(n.executable)}</string></array>
6
+ <key>WorkingDirectory</key><string>${t(n.cwd)}</string>
7
+ <key>EnvironmentVariables</key><dict>${Object.entries(r).map(([e,i])=>`<key>${e}</key><string>${t(i)}</string>`).join("")}</dict>
8
+ <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
9
+ <key>ProcessType</key><string>Interactive</string>
10
+ <key>StandardErrorPath</key><string>${t(n.log)}</string>
11
+ </dict></plist>
12
+ `}function B(n){return n?["--icon",n]:[]}function S(n){return a(n,"Applications",d,"Contents/MacOS/agentx-mac-helper")}function k(n=g(L(import.meta.url))){for(let t=n;;t=g(t)){try{if(JSON.parse(A(a(t,"package.json"),"utf8")).name==="agentix-cli")return t}catch{}if(g(t)===t)return null}}function x(n,t,r){if(r)return r;let e=S(t);return w(e)||!n?e:a(n,"apps/mac-helper/build",d,"Contents/MacOS/agentx-mac-helper")}import{execFile as E}from"child_process";import{existsSync as m}from"fs";import{homedir as b}from"os";import{isAbsolute as v}from"path";var N={banner:!0,sound:!0,soundName:"Glass",volume:.4},T=5e3,$=(n,t)=>new Promise(r=>{try{E(n,t,{timeout:T},e=>r(!e))}catch{r(!1)}});function Y(n){return{...N,...n??{}}}function P(n){if(!/^[\w -]+$/.test(n))return null;let t=`/System/Library/Sounds/${n}.aiff`;return m(t)?t:null}function _(){let n=x(k(),b(),process.env.AGENTX_MAC_HELPER);return m(n)?n:null}function z(n,t={}){let r=t.run??$,e=t.platform??process.platform,i=async(l,s)=>{let o=t.helper===void 0?_():t.helper;o&&await r(o,["notify","--title",l,"--message",s])||await r("/usr/bin/osascript",["-e","on run argv","-e","display notification (item 2 of argv) with title (item 1 of argv)","-e","end run",l,s])};return async(l,s)=>{if(e!=="darwin")return;let o=[];n.banner&&o.push(i(l,s));let f=n.sound?P(n.soundName):null;if(f){let h=Math.min(1,Math.max(0,n.volume));o.push(r("/usr/bin/afplay",["-v",String(h),f]))}await Promise.all(o)}}function Z(n,t,r=process.platform){let e={...n??{}};if("banner"in t&&(e.banner=!!t.banner),"sound"in t&&(e.sound=!!t.sound),"soundName"in t){let i=String(t.soundName).trim();if(!(r==="darwin"?P(i)!==null:/^[\w -]+$/.test(i)))throw new Error(`no system sound named "${i}" in /System/Library/Sounds`);e.soundName=i}if("icon"in t){let i=String(t.icon??"").trim().replace(/^~(?=\/)/,b());if(!i)delete e.icon;else{if(!v(i)||!/\.(png|jpe?g|icns)$/i.test(i))throw new Error("icon must be the full path to a .png, .jpg or .icns file");if(r==="darwin"&&!m(i))throw new Error(`no icon file at ${i}`);e.icon=i}}if("volume"in t){let i=Number(t.volume);if(!Number.isFinite(i)||i<0||i>1)throw new Error("volume must be between 0 and 1");e.volume=i}return e}export{H as a,d as b,I as c,M as d,C as e,j as f,X as g,U as h,G as i,F as j,B as k,S as l,k as m,x as n,N as o,Y as p,_ as q,z as r,Z as s};
13
+ //# sourceMappingURL=chunk-BYJ3A55Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/desktop/install.ts","../src/notify/local.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nexport const DESKTOP_LABEL = 'tn.acme.agentx.voice'\nexport const DESKTOP_APP = 'AgentX Desktop.app'\nexport const HELPER_APP = 'AgentX Helper.app'\nexport function desktopPlatformError(platform: string, arch: string, release: string): string | null {\n if (platform !== 'darwin' || arch !== 'arm64' || Number(release.split('.')[0]) < 23)\n return 'AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.'\n return null\n}\nexport function selectDesktopAgent(agents: Record<string, unknown>, requested?: string): string {\n if (requested && !Object.hasOwn(agents, requested)) throw new Error(`Unknown agent: ${requested}. Run agentx agent list.`)\n const id = requested || Object.keys(agents)[0]\n if (!id) throw new Error('No agents configured. Run agentx setup first.')\n return id\n}\nexport function shellQuote(value: string): string { return `'${value.replace(/'/g, \"'\\\\''\")}'` }\n/** launchd's default PATH, which is all a login item gets unless the plist sets one. */\nexport const LAUNCHD_PATH = '/usr/bin:/bin:/usr/sbin:/sbin'\n/** PATH for the login item: AGENTX_VOICE_PATH when set, else the folder of\n * the ffmpeg found at install time (mlx_whisper needs it) ahead of launchd's default. */\nexport function desktopPath(ffmpeg: string | null, override?: string): string {\n if (override) return override\n return [...new Set([...(ffmpeg ? [dirname(ffmpeg)] : []), ...LAUNCHD_PATH.split(':')])].join(':')\n}\nfunction unxml(s: string): string {\n const ents: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" }\n return s.replace(/&(amp|lt|gt|quot|apos);/g, (_, e) => ents[e])\n}\n/** The PATH a login item plist sets, or launchd's default when it sets none. */\nexport function plistPathEnv(plist: string): string {\n const m = plist.match(/<key>PATH<\\/key>\\s*<string>([^<]*)<\\/string>/)\n return m ? unxml(m[1]) : LAUNCHD_PATH\n}\n/** Login item files the voice app may have been installed under. */\nexport const isVoiceLoginItemFile = (name: string) => /agentx\\.voice.*\\.plist$/.test(name)\nexport type LoginItem = { file: string; label: string }\n/** One login item per Mac. The label was renamed once and\n * apps/mac-voice/install.sh writes its own, so adopt the first existing\n * `*agentx.voice*` item that runs the voice app (any bundle name) and\n * retire the others; with none, use DESKTOP_LABEL. Plists are XML text. */\nexport function adoptLoginItem(dir: string, items: { file: string; plist: string }[]): { keep: LoginItem; remove: LoginItem[] } {\n let keep: LoginItem | null = null\n const remove: LoginItem[] = []\n for (const { file, plist } of [...items].sort((a, b) => (a.file < b.file ? -1 : 1))) {\n const label = plist.match(/<key>Label<\\/key>\\s*<string>([^<]*)<\\/string>/)?.[1]\n const program = plist.match(/<key>ProgramArguments<\\/key>\\s*<array>\\s*<string>([^<]*)<\\/string>/)?.[1]\n if (!label || !program || !unxml(program).endsWith('/Contents/MacOS/AgentXVoice')) continue\n if (keep) remove.push({ file, label: unxml(label) })\n else keep = { file, label: unxml(label) }\n }\n return { keep: keep ?? { file: join(dir, `${DESKTOP_LABEL}.plist`), label: DESKTOP_LABEL }, remove }\n}\n/** The file that a process with this PATH would run, or null. */\nexport function findOnPath(bin: string, path: string, isExecutable: (file: string) => boolean): string | null {\n for (const dir of path.split(':')) if (dir && isExecutable(join(dir, bin))) return join(dir, bin)\n return null\n}\n/** Without `agent` the app talks to the agent picked in its menu-bar\n * icon; with it, that agent is pinned and the menu cannot switch. */\nexport function desktopPlist(opts: { label?: string; executable: string; cwd: string; agent?: string; url: string; helper: string; cli: string; node: string; log: string; path: string }): string {\n const xml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&apos;')\n const env = {\n PATH: opts.path,\n ...(opts.agent ? { AGENTX_VOICE_AGENT: opts.agent } : {}),\n AGENTX_DAEMON_URL: opts.url,\n AGENTX_MAC_HELPER: opts.helper,\n AGENTX_PASTE_COMMAND: `cd ${shellQuote(opts.cwd)} && ${shellQuote(opts.node)} ${shellQuote(opts.cli)} paste`,\n }\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>${xml(opts.label ?? DESKTOP_LABEL)}</string>\n<key>ProgramArguments</key><array><string>${xml(opts.executable)}</string></array>\n<key>WorkingDirectory</key><string>${xml(opts.cwd)}</string>\n<key>EnvironmentVariables</key><dict>${Object.entries(env).map(([k,v]) => `<key>${k}</key><string>${xml(v)}</string>`).join('')}</dict>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>\n<key>ProcessType</key><string>Interactive</string>\n<key>StandardErrorPath</key><string>${xml(opts.log)}</string>\n</dict></plist>\\n`\n}\n/** build.sh arguments for the helper: the banner icon from\n * notifications.local.icon, or none for the bundled AgentX logo. */\nexport function helperBuildArgs(icon?: string): string[] {\n return icon ? ['--icon', icon] : []\n}\nexport function installedHelper(home: string): string {\n return join(home, 'Applications', HELPER_APP, 'Contents/MacOS/agentx-mac-helper')\n}\n/** The AgentX package folder, found by walking up from this file (dist/\n * when installed, src/ in a checkout) — never from the caller's cwd, so\n * `agentx notify` finds a repo-built helper from any folder. */\nexport function packageRoot(from = dirname(fileURLToPath(import.meta.url))): string | null {\n for (let dir = from; ; dir = dirname(dir)) {\n try {\n if (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name === 'agentix-cli') return dir\n } catch { /* no package.json here — keep walking up */ }\n if (dirname(dir) === dir) return null\n }\n}\n/** The helper to run: an explicit path, else the one `agentx desktop\n * install` put in ~/Applications, else one built in the package. */\nexport function resolveHelper(root: string | null, home: string, override?: string): string {\n if (override) return override\n const installed = installedHelper(home)\n if (existsSync(installed) || !root) return installed\n return join(root, 'apps/mac-helper/build', HELPER_APP, 'Contents/MacOS/agentx-mac-helper')\n}\n","import { execFile } from \"child_process\"\nimport { existsSync } from \"fs\"\nimport { homedir } from \"os\"\nimport { isAbsolute } from \"path\"\nimport { packageRoot, resolveHelper } from \"@/desktop/install\"\n\n// What happens on THIS machine when a notification is delivered: a banner\n// on screen and a short sound. The push goes to the phone; these are for\n// the person sitting at the Mac that raised the event.\n//\n// Both are awaited rather than fired and forgotten. A caller that exits\n// straight after notifying — a `launchctl submit` job that removes itself,\n// a cron one-liner — used to take the sound down with it before it\n// played. Waiting costs about a second and makes the step reliable.\n//\n// The banner is posted by the AgentX Helper app when it is installed, so\n// it carries the helper's icon (the AgentX logo by default). Without the\n// helper, or before macOS has allowed it to notify, osascript posts it,\n// and macOS shows it as coming from Script Editor.\n//\n// Never fatal: a notification whose banner failed still arrived, and no\n// caller should have to handle an audio error to say a build finished.\n\nexport interface LocalSettings {\n /** Show a desktop banner (macOS only; other platforms skip it). */\n banner: boolean\n /** Play a sound (macOS only). */\n sound: boolean\n /** A macOS system sound, by name: /System/Library/Sounds/<name>.aiff. */\n soundName: string\n /** 0 (silent) … 1 (full). */\n volume: number\n /** Image for the helper's app icon, which macOS puts on its banners.\n * Unset: the AgentX logo. Applied when `agentx desktop install` builds\n * the helper, since macOS reads the icon from the app, not the banner. */\n icon?: string\n}\n\n/** Glass is the gentlest system sound that is still audible over a\n * keyboard — Basso and Sosumi are alerts, Funk and Frog are jokes, and\n * Ping is the one every other app already uses. */\nexport const DEFAULT_LOCAL: LocalSettings = { banner: true, sound: true, soundName: \"Glass\", volume: 0.4 }\n\n/** Shows the banner and plays the sound for one delivered notification. */\nexport type LocalAlert = (title: string, message: string) => Promise<void>\n\n/** Runs a command; resolves true when it exited 0. */\ntype Run = (file: string, args: string[]) => Promise<boolean>\n\n/** Neither step may hold a caller hostage: afplay on a long custom sound,\n * or osascript stuck on a permission prompt, is cut off here. */\nconst STEP_TIMEOUT_MS = 5_000\n\nconst run: Run = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: STEP_TIMEOUT_MS }, (err) => done(!err))\n } catch {\n done(false) // no osascript / afplay on this machine — not worth reporting\n }\n })\n\n/** Fill gaps in a partial `notifications.local` block with the defaults. */\nexport function localSettings(cfg: Partial<LocalSettings> | undefined): LocalSettings {\n return { ...DEFAULT_LOCAL, ...(cfg ?? {}) }\n}\n\n/** The system sound file for a name, or null when there is none. Names\n * only — a path in the config must not reach afplay. */\nexport function soundPath(name: string): string | null {\n if (!/^[\\w -]+$/.test(name)) return null\n const path = `/System/Library/Sounds/${name}.aiff`\n return existsSync(path) ? path : null\n}\n\n/** The AgentX Helper binary when one is built or installed, else null.\n * AGENTX_MAC_HELPER points at a helper somewhere else. */\nexport function findHelper(): string | null {\n const path = resolveHelper(packageRoot(), homedir(), process.env.AGENTX_MAC_HELPER)\n return existsSync(path) ? path : null\n}\n\nexport function localAlert(\n settings: LocalSettings,\n deps: { run?: Run; platform?: NodeJS.Platform; helper?: string | null } = {},\n): LocalAlert {\n const exec = deps.run ?? run\n const platform = deps.platform ?? process.platform\n const banner = async (title: string, message: string): Promise<void> => {\n const helper = deps.helper === undefined ? findHelper() : deps.helper\n // A non-zero exit is usually \"not allowed to notify yet\" — the first\n // banner asks — so this one goes through osascript instead.\n if (helper && await exec(helper, [\"notify\", \"--title\", title, \"--message\", message])) return\n // Title and message travel as argv, never spliced into the script,\n // so a quote in either cannot turn into AppleScript.\n await exec(\"/usr/bin/osascript\", [\n \"-e\", \"on run argv\",\n \"-e\", \"display notification (item 2 of argv) with title (item 1 of argv)\",\n \"-e\", \"end run\",\n title, message,\n ])\n }\n return async (title, message) => {\n if (platform !== \"darwin\") return\n const steps: Promise<unknown>[] = []\n if (settings.banner) steps.push(banner(title, message))\n const path = settings.sound ? soundPath(settings.soundName) : null\n if (path) {\n const volume = Math.min(1, Math.max(0, settings.volume))\n steps.push(exec(\"/usr/bin/afplay\", [\"-v\", String(volume), path]))\n }\n await Promise.all(steps)\n }\n}\n\n/**\n * Apply a change to a stored `notifications.local` block, the one rule\n * both the CLI and the dashboard write through. Returns the new block;\n * throws on a value that would not load. Only a Mac has sounds to check a\n * name against — elsewhere the setting is inert, so it need only be\n * well-formed.\n */\nexport function patchLocal(\n current: Partial<LocalSettings> | undefined,\n patch: Record<string, unknown>,\n platform: NodeJS.Platform = process.platform,\n): Partial<LocalSettings> {\n const next = { ...(current ?? {}) }\n if (\"banner\" in patch) next.banner = Boolean(patch.banner)\n if (\"sound\" in patch) next.sound = Boolean(patch.sound)\n if (\"soundName\" in patch) {\n const name = String(patch.soundName).trim()\n const ok = platform === \"darwin\" ? soundPath(name) !== null : /^[\\w -]+$/.test(name)\n if (!ok) throw new Error(`no system sound named \"${name}\" in /System/Library/Sounds`)\n next.soundName = name\n }\n if (\"icon\" in patch) {\n const icon = String(patch.icon ?? \"\").trim().replace(/^~(?=\\/)/, homedir())\n if (!icon) delete next.icon\n else {\n if (!isAbsolute(icon) || !/\\.(png|jpe?g|icns)$/i.test(icon)) throw new Error(\"icon must be the full path to a .png, .jpg or .icns file\")\n if (platform === \"darwin\" && !existsSync(icon)) throw new Error(`no icon file at ${icon}`)\n next.icon = icon\n }\n }\n if (\"volume\" in patch) {\n const v = Number(patch.volume)\n if (!Number.isFinite(v) || v < 0 || v > 1) throw new Error(\"volume must be between 0 and 1\")\n next.volume = v\n }\n return next\n}\n"],"mappings":"AAAA,OAAS,cAAAA,EAAY,gBAAAC,MAAoB,UACzC,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAS,iBAAAC,MAAqB,WAEvB,IAAMC,EAAgB,uBAChBC,EAAc,qBACdC,EAAa,oBACnB,SAASC,EAAqBC,EAAkBC,EAAcC,EAAgC,CACnG,OAAIF,IAAa,UAAYC,IAAS,SAAW,OAAOC,EAAQ,MAAM,GAAG,EAAE,CAAC,CAAC,EAAI,GACxE,yEACF,IACT,CACO,SAASC,EAAmBC,EAAiCC,EAA4B,CAC9F,GAAIA,GAAa,CAAC,OAAO,OAAOD,EAAQC,CAAS,EAAG,MAAM,IAAI,MAAM,kBAAkBA,2BAAmC,EACzH,IAAMC,EAAKD,GAAa,OAAO,KAAKD,CAAM,EAAE,CAAC,EAC7C,GAAI,CAACE,EAAI,MAAM,IAAI,MAAM,+CAA+C,EACxE,OAAOA,CACT,CACO,SAASC,EAAWC,EAAuB,CAAE,MAAO,IAAIA,EAAM,QAAQ,KAAM,OAAO,IAAK,CAExF,IAAMC,EAAe,gCAGrB,SAASC,EAAYC,EAAuBC,EAA2B,CAC5E,OAAIA,GACG,CAAC,GAAG,IAAI,IAAI,CAAC,GAAID,EAAS,CAAClB,EAAQkB,CAAM,CAAC,EAAI,CAAC,EAAI,GAAGF,EAAa,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,GAAG,CAClG,CACA,SAASI,EAAMC,EAAmB,CAChC,IAAMC,EAA+B,CAAE,IAAK,IAAK,GAAI,IAAK,GAAI,IAAK,KAAM,IAAK,KAAM,GAAI,EACxF,OAAOD,EAAE,QAAQ,2BAA4B,CAACE,EAAG,IAAMD,EAAK,CAAC,CAAC,CAChE,CAEO,SAASE,EAAaC,EAAuB,CAClD,IAAMC,EAAID,EAAM,MAAM,8CAA8C,EACpE,OAAOC,EAAIN,EAAMM,EAAE,CAAC,CAAC,EAAIV,CAC3B,CAEO,IAAMW,EAAwBC,GAAiB,0BAA0B,KAAKA,CAAI,EAMlF,SAASC,EAAeC,EAAaC,EAAoF,CAC9H,IAAIC,EAAyB,KACvBC,EAAsB,CAAC,EAC7B,OAAW,CAAE,KAAAC,EAAM,MAAAT,CAAM,GAAK,CAAC,GAAGM,CAAK,EAAE,KAAK,CAACI,EAAGC,IAAOD,EAAE,KAAOC,EAAE,KAAO,GAAK,CAAE,EAAG,CACnF,IAAMC,EAAQZ,EAAM,MAAM,+CAA+C,IAAI,CAAC,EACxEa,EAAUb,EAAM,MAAM,oEAAoE,IAAI,CAAC,EACjG,CAACY,GAAS,CAACC,GAAW,CAAClB,EAAMkB,CAAO,EAAE,SAAS,6BAA6B,IAC5EN,EAAMC,EAAO,KAAK,CAAE,KAAAC,EAAM,MAAOd,EAAMiB,CAAK,CAAE,CAAC,EAC9CL,EAAO,CAAE,KAAAE,EAAM,MAAOd,EAAMiB,CAAK,CAAE,GAE1C,MAAO,CAAE,KAAML,GAAQ,CAAE,KAAM/B,EAAK6B,EAAK,GAAG3B,SAAqB,EAAG,MAAOA,CAAc,EAAG,OAAA8B,CAAO,CACrG,CAEO,SAASM,EAAWC,EAAaC,EAAcC,EAAwD,CAC5G,QAAWZ,KAAOW,EAAK,MAAM,GAAG,EAAG,GAAIX,GAAOY,EAAazC,EAAK6B,EAAKU,CAAG,CAAC,EAAG,OAAOvC,EAAK6B,EAAKU,CAAG,EAChG,OAAO,IACT,CAGO,SAASG,EAAaC,EAAsK,CACjM,IAAMC,EAAOxB,GAAcA,EAAE,QAAQ,KAAM,OAAO,EAAE,QAAQ,KAAM,MAAM,EAAE,QAAQ,KAAM,MAAM,EAAE,QAAQ,KAAM,QAAQ,EAAE,QAAQ,KAAM,QAAQ,EACxIyB,EAAM,CACV,KAAMF,EAAK,KACX,GAAIA,EAAK,MAAQ,CAAE,mBAAoBA,EAAK,KAAM,EAAI,CAAC,EACvD,kBAAmBA,EAAK,IACxB,kBAAmBA,EAAK,OACxB,qBAAsB,MAAM9B,EAAW8B,EAAK,GAAG,QAAQ9B,EAAW8B,EAAK,IAAI,KAAK9B,EAAW8B,EAAK,GAAG,SACrG,EACA,MAAO;AAAA;AAAA;AAAA,0BAGiBC,EAAID,EAAK,OAASzC,CAAa;AAAA,4CACb0C,EAAID,EAAK,UAAU;AAAA,qCAC1BC,EAAID,EAAK,GAAG;AAAA,uCACV,OAAO,QAAQE,CAAG,EAAE,IAAI,CAAC,CAACC,EAAEC,CAAC,IAAM,QAAQD,kBAAkBF,EAAIG,CAAC,YAAY,EAAE,KAAK,EAAE;AAAA;AAAA;AAAA,sCAGxFH,EAAID,EAAK,GAAG;AAAA;AAAA,CAElD,CAGO,SAASK,EAAgBC,EAAyB,CACvD,OAAOA,EAAO,CAAC,SAAUA,CAAI,EAAI,CAAC,CACpC,CACO,SAASC,EAAgBC,EAAsB,CACpD,OAAOnD,EAAKmD,EAAM,eAAgB/C,EAAY,kCAAkC,CAClF,CAIO,SAASgD,EAAYC,EAAOtD,EAAQE,EAAc,YAAY,GAAG,CAAC,EAAkB,CACzF,QAAS4B,EAAMwB,GAAQxB,EAAM9B,EAAQ8B,CAAG,EAAG,CACzC,GAAI,CACF,GAAI,KAAK,MAAM/B,EAAaE,EAAK6B,EAAK,cAAc,EAAG,MAAM,CAAC,EAAE,OAAS,cAAe,OAAOA,CACjG,MAAE,CAAqD,CACvD,GAAI9B,EAAQ8B,CAAG,IAAMA,EAAK,OAAO,KAErC,CAGO,SAASyB,EAAcC,EAAqBJ,EAAcjC,EAA2B,CAC1F,GAAIA,EAAU,OAAOA,EACrB,IAAMsC,EAAYN,EAAgBC,CAAI,EACtC,OAAItD,EAAW2D,CAAS,GAAK,CAACD,EAAaC,EACpCxD,EAAKuD,EAAM,wBAAyBnD,EAAY,kCAAkC,CAC3F,CC7GA,OAAS,YAAAqD,MAAgB,gBACzB,OAAS,cAAAC,MAAkB,KAC3B,OAAS,WAAAC,MAAe,KACxB,OAAS,cAAAC,MAAkB,OAsCpB,IAAMC,EAA+B,CAAE,OAAQ,GAAM,MAAO,GAAM,UAAW,QAAS,OAAQ,EAAI,EAUnGC,EAAkB,IAElBC,EAAW,CAACC,EAAMC,IACtB,IAAI,QAASC,GAAS,CACpB,GAAI,CACFC,EAASH,EAAMC,EAAM,CAAE,QAASH,CAAgB,EAAIM,GAAQF,EAAK,CAACE,CAAG,CAAC,CACxE,MAAE,CACAF,EAAK,EAAK,CACZ,CACF,CAAC,EAGI,SAASG,EAAcC,EAAwD,CACpF,MAAO,CAAE,GAAGT,EAAe,GAAIS,GAAO,CAAC,CAAG,CAC5C,CAIO,SAASC,EAAUC,EAA6B,CACrD,GAAI,CAAC,YAAY,KAAKA,CAAI,EAAG,OAAO,KACpC,IAAMC,EAAO,0BAA0BD,SACvC,OAAOE,EAAWD,CAAI,EAAIA,EAAO,IACnC,CAIO,SAASE,GAA4B,CAC1C,IAAMF,EAAOG,EAAcC,EAAY,EAAGC,EAAQ,EAAG,QAAQ,IAAI,iBAAiB,EAClF,OAAOJ,EAAWD,CAAI,EAAIA,EAAO,IACnC,CAEO,SAASM,EACdC,EACAC,EAA0E,CAAC,EAC/D,CACZ,IAAMC,EAAOD,EAAK,KAAOlB,EACnBoB,EAAWF,EAAK,UAAY,QAAQ,SACpCG,EAAS,MAAOC,EAAeC,IAAmC,CACtE,IAAMC,EAASN,EAAK,SAAW,OAAYN,EAAW,EAAIM,EAAK,OAG3DM,GAAU,MAAML,EAAKK,EAAQ,CAAC,SAAU,UAAWF,EAAO,YAAaC,CAAO,CAAC,GAGnF,MAAMJ,EAAK,qBAAsB,CAC/B,KAAM,cACN,KAAM,oEACN,KAAM,UACNG,EAAOC,CACT,CAAC,CACH,EACA,MAAO,OAAOD,EAAOC,IAAY,CAC/B,GAAIH,IAAa,SAAU,OAC3B,IAAMK,EAA4B,CAAC,EAC/BR,EAAS,QAAQQ,EAAM,KAAKJ,EAAOC,EAAOC,CAAO,CAAC,EACtD,IAAMb,EAAOO,EAAS,MAAQT,EAAUS,EAAS,SAAS,EAAI,KAC9D,GAAIP,EAAM,CACR,IAAMgB,EAAS,KAAK,IAAI,EAAG,KAAK,IAAI,EAAGT,EAAS,MAAM,CAAC,EACvDQ,EAAM,KAAKN,EAAK,kBAAmB,CAAC,KAAM,OAAOO,CAAM,EAAGhB,CAAI,CAAC,CAAC,EAElE,MAAM,QAAQ,IAAIe,CAAK,CACzB,CACF,CASO,SAASE,EACdC,EACAC,EACAT,EAA4B,QAAQ,SACZ,CACxB,IAAMU,EAAO,CAAE,GAAIF,GAAW,CAAC,CAAG,EAGlC,GAFI,WAAYC,IAAOC,EAAK,OAAS,EAAQD,EAAM,QAC/C,UAAWA,IAAOC,EAAK,MAAQ,EAAQD,EAAM,OAC7C,cAAeA,EAAO,CACxB,IAAMpB,EAAO,OAAOoB,EAAM,SAAS,EAAE,KAAK,EAE1C,GAAI,EADOT,IAAa,SAAWZ,EAAUC,CAAI,IAAM,KAAO,YAAY,KAAKA,CAAI,GAC1E,MAAM,IAAI,MAAM,0BAA0BA,8BAAiC,EACpFqB,EAAK,UAAYrB,EAEnB,GAAI,SAAUoB,EAAO,CACnB,IAAME,EAAO,OAAOF,EAAM,MAAQ,EAAE,EAAE,KAAK,EAAE,QAAQ,WAAYd,EAAQ,CAAC,EAC1E,GAAI,CAACgB,EAAM,OAAOD,EAAK,SAClB,CACH,GAAI,CAACE,EAAWD,CAAI,GAAK,CAAC,uBAAuB,KAAKA,CAAI,EAAG,MAAM,IAAI,MAAM,0DAA0D,EACvI,GAAIX,IAAa,UAAY,CAACT,EAAWoB,CAAI,EAAG,MAAM,IAAI,MAAM,mBAAmBA,GAAM,EACzFD,EAAK,KAAOC,GAGhB,GAAI,WAAYF,EAAO,CACrB,IAAMI,EAAI,OAAOJ,EAAM,MAAM,EAC7B,GAAI,CAAC,OAAO,SAASI,CAAC,GAAKA,EAAI,GAAKA,EAAI,EAAG,MAAM,IAAI,MAAM,gCAAgC,EAC3FH,EAAK,OAASG,EAEhB,OAAOH,CACT","names":["existsSync","readFileSync","dirname","join","fileURLToPath","DESKTOP_LABEL","DESKTOP_APP","HELPER_APP","desktopPlatformError","platform","arch","release","selectDesktopAgent","agents","requested","id","shellQuote","value","LAUNCHD_PATH","desktopPath","ffmpeg","override","unxml","s","ents","_","plistPathEnv","plist","m","isVoiceLoginItemFile","name","adoptLoginItem","dir","items","keep","remove","file","a","b","label","program","findOnPath","bin","path","isExecutable","desktopPlist","opts","xml","env","k","v","helperBuildArgs","icon","installedHelper","home","packageRoot","from","resolveHelper","root","installed","execFile","existsSync","homedir","isAbsolute","DEFAULT_LOCAL","STEP_TIMEOUT_MS","run","file","args","done","execFile","err","localSettings","cfg","soundPath","name","path","existsSync","findHelper","resolveHelper","packageRoot","homedir","localAlert","settings","deps","exec","platform","banner","title","message","helper","steps","volume","patchLocal","current","patch","next","icon","isAbsolute","v"]}
@@ -1,5 +1,5 @@
1
- import{u as m,v as $,z as x}from"./chunk-S7TCVIET.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
1
+ import{u as m,v as $,z as x}from"./chunk-OVF37EXJ.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
4
4
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{w as a,J as b,N as c,j as d,A as e};
5
- //# sourceMappingURL=chunk-CRSXKQLZ.js.map
5
+ //# sourceMappingURL=chunk-EA7H3EUX.js.map
@@ -1,2 +1,2 @@
1
- import{q as p}from"./chunk-JORXRF4E.js";import{b as i,c as u,d as l,e as c}from"./chunk-CRSXKQLZ.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
2
- //# sourceMappingURL=chunk-27P5NLTC.js.map
1
+ import{q as p}from"./chunk-BHE5TJSN.js";import{b as i,c as u,d as l,e as c}from"./chunk-EA7H3EUX.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
2
+ //# sourceMappingURL=chunk-I2SD4XZ6.js.map
@@ -1,4 +1,4 @@
1
- import{a as Wn,b as Kn,h as ss,n as rs}from"./chunk-WIBMNQKJ.js";import{a as Bn}from"./chunk-WP6KLXTP.js";import{a as kt}from"./chunk-N6EWZGIX.js";import{b as qn}from"./chunk-DP7RTNDM.js";import{b as Jn,c as vt,d as Qn,e as Xn,h as Yn}from"./chunk-JORXRF4E.js";import{a as It,b as Gn}from"./chunk-J3SOEFRE.js";import{a as St,b as zn}from"./chunk-SIU6STB2.js";import{e as Vn,i as Zn,j as es,k as ts}from"./chunk-X5C5W3E4.js";import{a as ns}from"./chunk-W4YR2RO2.js";import{a as Pn}from"./chunk-WBGC7MWX.js";import{a as _n,b as En,c as Dn,d as On,f as Nn}from"./chunk-DWADWDMU.js";import{a as Ln,b as Fn}from"./chunk-NO2HOK4B.js";import{a as Un}from"./chunk-2VQIPJH5.js";import{b as Hn,c as jn}from"./chunk-E2BJVHBR.js";import{a as Ve,c as _e}from"./chunk-2GIDVZ4H.js";import{q as $n,t as Mn,v as we,w as Rn}from"./chunk-NBGNPKAF.js";import{a as Pe,b as Ye,f as Tt}from"./chunk-72SZI2UW.js";import{a as be,b as wt}from"./chunk-FCPTN6NF.js";import{c as kn,d as In}from"./chunk-QOYAX2FT.js";import{e as pe}from"./chunk-DSYKYZMT.js";import{d as Sn,e as oe,f as vn,g as Cn,h as xt,s as An,z as uo}from"./chunk-S7TCVIET.js";Rn();Tt();var os="session-continuity",is={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 as(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Ct(s.message,1200),previousRequest:s.previousMessage?Ct(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Ct(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function cs(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 Ct(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as lo,execFile as go}from"node:child_process";import{createHash as po,randomBytes as ho}from"node:crypto";import{createInterface as mo}from"node:readline";import{promisify as fo}from"node:util";var yo=fo(go),ie=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},At=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=yo("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 ie("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=po("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([d],[l])=>d.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new ie("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 p=[...this.entries].find(([,y])=>!y.busy);if(!p)throw new ie("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:ho(32).toString("hex")},l=lo("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:d,stdio:["pipe","pipe","pipe"]});o={child:l,env:d,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let u=o;l.stderr.resume(),l.on("exit",()=>this.close(u)),l.on("error",()=>this.close(u));try{await new Promise((p,y)=>{let b=mo({input:l.stdout}),x=()=>k(new ie("OpenCode server failed before dispatch",!0)),w=()=>k(new Error("task cancelled by operator")),I=setTimeout(x,15e3),k=_=>{clearTimeout(I),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",w),b.close(),l.stdout.resume(),_?y(_):p()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",w,{once:!0}),b.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;u.url=A.origin,k()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}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:(d=!1)=>{c||(c=!0,a.busy=!1,d||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()))}}}},ds=new At;import{execa as rt}from"execa";import{spawn as bo}from"node:child_process";import{createHash as wo}from"node:crypto";import{createInterface as xo}from"node:readline";var ae=class extends Error{},To=s=>bo("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),$t=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(),xo({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 Wn,b as Kn,h as ss,n as rs}from"./chunk-PMGPGMBZ.js";import{a as Bn}from"./chunk-WP6KLXTP.js";import{a as kt}from"./chunk-N6EWZGIX.js";import{b as qn}from"./chunk-DP7RTNDM.js";import{b as Jn,c as vt,d as Qn,e as Xn,h as Yn}from"./chunk-BHE5TJSN.js";import{a as It,b as Gn}from"./chunk-J3SOEFRE.js";import{a as St,b as zn}from"./chunk-SIU6STB2.js";import{e as Vn,i as Zn,j as es,k as ts}from"./chunk-X5C5W3E4.js";import{a as ns}from"./chunk-W4YR2RO2.js";import{a as Pn}from"./chunk-LQ5J6COO.js";import{a as _n,b as En,c as Dn,d as On,f as Nn}from"./chunk-DWADWDMU.js";import{a as Ln,b as Fn}from"./chunk-NO2HOK4B.js";import{a as Un}from"./chunk-AZBOYKQA.js";import{b as Hn,c as jn}from"./chunk-WGWNVLVW.js";import{a as Ve,c as _e}from"./chunk-2GIDVZ4H.js";import{q as $n,t as Mn,v as we,w as Rn}from"./chunk-PTB2TPOC.js";import{a as Pe,b as Ye,f as Tt}from"./chunk-72SZI2UW.js";import{a as be,b as wt}from"./chunk-FCPTN6NF.js";import{c as kn,d as In}from"./chunk-QOYAX2FT.js";import{e as pe}from"./chunk-DSYKYZMT.js";import{d as Sn,e as oe,f as vn,g as Cn,h as xt,s as An,z as uo}from"./chunk-OVF37EXJ.js";Rn();Tt();var os="session-continuity",is={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 as(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Ct(s.message,1200),previousRequest:s.previousMessage?Ct(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Ct(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function cs(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 Ct(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as lo,execFile as go}from"node:child_process";import{createHash as po,randomBytes as ho}from"node:crypto";import{createInterface as mo}from"node:readline";import{promisify as fo}from"node:util";var yo=fo(go),ie=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},At=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=yo("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 ie("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=po("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([d],[l])=>d.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new ie("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 p=[...this.entries].find(([,y])=>!y.busy);if(!p)throw new ie("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:ho(32).toString("hex")},l=lo("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:d,stdio:["pipe","pipe","pipe"]});o={child:l,env:d,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let u=o;l.stderr.resume(),l.on("exit",()=>this.close(u)),l.on("error",()=>this.close(u));try{await new Promise((p,y)=>{let b=mo({input:l.stdout}),x=()=>k(new ie("OpenCode server failed before dispatch",!0)),w=()=>k(new Error("task cancelled by operator")),I=setTimeout(x,15e3),k=_=>{clearTimeout(I),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",w),b.close(),l.stdout.resume(),_?y(_):p()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",w,{once:!0}),b.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;u.url=A.origin,k()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}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:(d=!1)=>{c||(c=!0,a.busy=!1,d||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()))}}}},ds=new At;import{execa as rt}from"execa";import{spawn as bo}from"node:child_process";import{createHash as wo}from"node:crypto";import{createInterface as xo}from"node:readline";var ae=class extends Error{},To=s=>bo("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),$t=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(),xo({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()}},Mt=class{constructor(e=To,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=wo("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[I])=>w.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ae("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 w=[...this.entries].find(([,I])=>!I.connection.busy);if(!w)throw new ae("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:n,connection:new $t(e,this.launchProcess)}}catch{throw new ae("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="",d,l,u,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=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 w={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",{...w,...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 k=new Promise((_,A)=>{i.failTurn=A,i.notify=(v,R)=>{if(R?.threadId!==l)return;let N=R.item,M={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...R,type:v.replace("/","."),...N?{item:{...N,type:M[N.type]||N.type}}:{}}),v==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),v==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=R.delta,e.onDelta?.(R.delta,c)),v==="thread/tokenUsage/updated"){let O=R.tokenUsage.last,F=O.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(O.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(O.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(O.cacheWriteInputTokens||0)}}v==="turn/completed"&&(R.turn.status==="completed"?_():A(new Error(R.turn.error?.message||`Codex turn ${R.turn.status}`)))}});return k.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await k,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new ae(w.message);return{content:c,codexSessionId:l,usage:u,error:w.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(b),e.signal?.removeEventListener("abort",y),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())}}},us=new Mt;import{execFile as Oo}from"child_process";import{StringDecoder as Oe}from"string_decoder";import{mkdtempSync as Ss,readFileSync as vs,rmSync as Cs}from"fs";import{join as nt}from"path";import{tmpdir as As}from"os";function Ze(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 d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[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 et(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var ls=null;function tt(){return ls}function Ya(s){ls=s}function Ee(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var xe=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},gs=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=Ee(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 xe(`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 xe(`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=Ee(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=Ee(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Ee(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=Ee(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",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as ko}from"child_process";import{existsSync as Io,readFileSync as So}from"fs";import{resolve as vo}from"path";function Co(s){let e=vo(s,"CLAUDE.md");if(!Io(e))return null;try{let t=So(e,"utf8");return Nn(t)}catch{return null}}var Ao=20*60*1e3,$o=5e3,De=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},ps=class{constructor(e={}){this.opts=e}spawn(e,t){return new Rt(e,t,this.opts)}},Rt=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=ko(r,o,{cwd:t.workspace,env:_e({...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:Co(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 d of c)d(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??Ao,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new De(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);if(u===null&&!this.exited)throw d();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);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)},$o);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"}}};xt();import{resolve as hs,join as ms}from"path";wt();var Mo=4e3;function fs(s){try{let e=ms(hs(s.root),".agentx","db.sqlite"),t=kt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=be(),r=s.input.command?s.input.command.slice(0,Mo):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -27,7 +27,7 @@ ${s}`}function No(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
27
27
  `,u)}};A.stdout?.on("data",g=>{M+=F.write(g);let T=M.split(`
28
28
  `);M=T.pop()||"";for(let E of T)H(E)}),A.stderr?.on("data",g=>{O+=D.write(g)});let C=await A;if(i&&i.removeEventListener("abort",N),M+=F.end(),M.trim()&&H(M),O+=D.end(),v)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:y};if(C.exitCode!==0||b){let g=C,T;return g.timedOut?T=`OpenCode timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:b?T=b:g.code==="ENOENT"||/ENOENT|spawn opencode/i.test((g.shortMessage||"")+" "+O)?T=Ts():T=O.trim()||`OpenCode exited with code ${g.exitCode??"unknown"}`,{content:"",...q(T),duration:Date.now()-c,usage:p,opencodeSessionId:y}}return w=!1,{content:u.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||s.model,opencodeSessionId:y}}catch(k){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(k?.message||"")?Ts():k?.message;return{content:u,...q(_||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:y}}finally{I?.(),x?.release(w)}}async function Jo(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=de(s,e,n),c="",d=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of d)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function zo(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,y=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(w))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{once:!0}));let b=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);b.unref?.();let x=()=>({content:"",...q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let w=s.provider||"claude-code",I=n?`${n}
29
29
 
30
- ${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=On(s),R=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:R?v:void 0};if(r){let{generateStream:H}=await import("./agent-DH4FMMMY.js"),C="",g,T,E,L;for await(let m of H(N)){if(c)try{c(m)}catch{}if(m.type==="text_delta")C+=m.text,r(m.text,C);else if(m.type==="thinking_delta")m.text&&i&&i(m.text);else if(m.type==="generate_result"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}g=m.result.tokensUsed,m.result.inputTokens!=null&&(T=m.result.inputTokens),m.result.outputTokens!=null&&(E=m.result.outputTokens)}else if(m.type==="done"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}m.result.tokensUsed!=null&&(g=m.result.tokensUsed)}else m.type==="error"&&(L=m.error)}return L&&!C?p?x():L==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${L}`),duration:Date.now()-d}:((T===void 0||E===void 0)&&g&&(T=Math.round(g*.7),E=g-T),{content:C||"Done.",tokensUsed:g,usage:T!==void 0||E!==void 0?{inputTokens:T||0,outputTokens:E||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:M}=await import("./agent-DH4FMMMY.js"),O=await M(N),F=O.inputTokens,D=O.outputTokens;if((F===void 0||D===void 0)&&O.tokensUsed){let H=O.tokensUsed;F=Math.round(H*.7),D=H-F}return{content:O.content||"Done.",tokensUsed:O.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(w){return p?x():w?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${w.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",y)}}async function Qo(s,e,t,n,r,o,i){let a=tt();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let C=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>C}catch(C){return C instanceof xe,null}y&&Nt(e.agentId,s,e.model,n,"persistent");let b=de(s,e,t),x="",w,I,k,_,A,v,R,N="",M="",O=C=>{if(!i||!C)return;let g;if(M&&C.startsWith(M)?g=C.slice(M.length):g=N&&!N.endsWith(`
30
+ ${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=On(s),R=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:R?v:void 0};if(r){let{generateStream:H}=await import("./agent-D2BHFDUA.js"),C="",g,T,E,L;for await(let m of H(N)){if(c)try{c(m)}catch{}if(m.type==="text_delta")C+=m.text,r(m.text,C);else if(m.type==="thinking_delta")m.text&&i&&i(m.text);else if(m.type==="generate_result"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}g=m.result.tokensUsed,m.result.inputTokens!=null&&(T=m.result.inputTokens),m.result.outputTokens!=null&&(E=m.result.outputTokens)}else if(m.type==="done"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}m.result.tokensUsed!=null&&(g=m.result.tokensUsed)}else m.type==="error"&&(L=m.error)}return L&&!C?p?x():L==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${L}`),duration:Date.now()-d}:((T===void 0||E===void 0)&&g&&(T=Math.round(g*.7),E=g-T),{content:C||"Done.",tokensUsed:g,usage:T!==void 0||E!==void 0?{inputTokens:T||0,outputTokens:E||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:M}=await import("./agent-D2BHFDUA.js"),O=await M(N),F=O.inputTokens,D=O.outputTokens;if((F===void 0||D===void 0)&&O.tokensUsed){let H=O.tokensUsed;F=Math.round(H*.7),D=H-F}return{content:O.content||"Done.",tokensUsed:O.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(w){return p?x():w?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...q(`Orchestrator error: ${w.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",y)}}async function Qo(s,e,t,n,r,o,i){let a=tt();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let C=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>C}catch(C){return C instanceof xe,null}y&&Nt(e.agentId,s,e.model,n,"persistent");let b=de(s,e,t),x="",w,I,k,_,A,v,R,N="",M="",O=C=>{if(!i||!C)return;let g;if(M&&C.startsWith(M)?g=C.slice(M.length):g=N&&!N.endsWith(`
31
31
  `)?`
32
32
 
33
33
  ${C}`:C,M=C,!!g){N+=g;try{i(g,N)}catch{}}},F=!1,D=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?D():o.addEventListener("abort",D,{once:!0}));let H=!1;try{let C=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let g of p.runTurn({message:b,taskId:e.taskId??"unknown",deadlineMs:C})){if(H=!0,r)try{r(g.raw)}catch{}if(g.type==="assistant"){let T=g.raw.message?.content??[];for(let L of T)L.type==="text"&&typeof L.text=="string"?(x=L.text,O(L.text)):L.type==="tool_use"&&(M="");let E=g.raw.message?.usage;if(E){let L=(E.input_tokens||0)+(E.cache_read_input_tokens||0)+(E.cache_creation_input_tokens||0);L>0&&(_=L)}}if(g.type==="result"){let T=g.raw;if(T.is_error){let E=q(typeof T.result=="string"?T.result:"claude error");w=E.error,I=E.errorKind}else typeof T.result=="string"&&T.result.length>0&&(x=T.result,N||O(T.result));typeof T.session_id=="string"&&(R=T.session_id),T.usage&&(k={inputTokens:T.usage.input_tokens||0,outputTokens:T.usage.output_tokens||0,cacheReadTokens:T.usage.cache_read_input_tokens||0,cacheCreateTokens:T.usage.cache_creation_input_tokens||0}),typeof T.num_turns=="number"&&(A=T.num_turns),typeof T.message?.model=="string"?v=T.message.model:typeof T.model=="string"&&(v=T.model)}}}catch(C){if(F)w="task cancelled by operator",I="cancelled";else if(H)if(C instanceof De){let g=q(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);w=g.error,I=g.errorKind}else{let g=q(`persistent claude process error: ${C?.message||String(C)}`);w=g.error,I=g.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${C?.message||C}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",D),null}finally{o&&o.removeEventListener("abort",D)}return F&&!w&&(w="task cancelled by operator",I="cancelled"),{content:F?"":x,error:w,errorKind:I,duration:Date.now()-c,usage:k,contextTokens:_,numTurns:A,billedModel:v,claudeSessionId:R}}function Ns(s){return oe(s.autonomy)?s.taskId?bs(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function Xo(s,e,t,n,r,o,i){let a=e.autonomy,c=ws(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let d=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:d,message:`${Cn(a)}
@@ -130,7 +130,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:Ti,maxTokens:512})).content.trim().match(/\[[
130
130
  `:""}}var Ur=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new qn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new Wn;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 it(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Un(void 0,void 0,"unified"),this.memoryStore=new Kn,this.patternStore=new dt,this.rateLimiter=new at,this.tokenTracker=new Ce,this.messageQueue=new ct,cr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Hn({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new jn({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 d=c.toLowerCase();n.includes(d)&&d.length>o&&(r=i,o=d.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 p=this.sessions.getSession(e.agentId,n,r);i=Us(p.messages,e.message??""),c=Bs(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let d={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 we(os,as(d),is,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!cs(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 d=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,...d],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(`
131
131
  `)[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";Jn().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=oe(e.autonomy),i=o?null:or().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 h=await i;if(h.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${h.sessionId}`),{content:h.text,viaAttachedSession:h.sessionId};this.log(`[${e.agentId}] attached session did not take it (${h.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 h=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(S=>S.id===e.agentId));if(h){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${h.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(h.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:h.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${h.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",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",l;if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||c==="app"||c==="reminder"||c==="events"||o){let h=Date.now(),f=25*6e4,S=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(P=>setTimeout(P,S))}}else if(c==="voice"){let h=Date.now(),f=25*6e4,S=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(S);){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(P=>setTimeout(P,500))}l=S,this.voiceClaims.add(S)}else{let h=a.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,c,d,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:d,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 S=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${S}) behind=${a.runningTasks.map(P=>P.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:`__queued__:${f}:${S}`}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(h,f)=>{this.log(`[${e.agentId}] ${h} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(l&&this.voiceClaims.delete(l),!u.ok)return this.log(`[${e.agentId}] ${u.reason}`),{content:"",error:u.reason};a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let p={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(p),e.runningTaskId=p.id,e.onStart)try{e.onStart(p.id)}catch{}let y=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:y});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,b);let x=h=>{if(h){b.buffer+=h,b.buffer.length>Lr&&(b.buffer=b.buffer.slice(b.buffer.length-Lr));for(let f of b.subscribers)try{f(h)}catch{}}},w=be();e.taskId=w;let I=new Map,k;if(t){let h=Fa();k=f=>{let S=h(f);if(S&&x(S),jr(w,e.agentId,f),Hr(I,f),r)try{r(f)}catch{}}}else k=h=>{if(jr(w,e.agentId,h),Hr(I,h),r)try{r(h)}catch{}};let _=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,A=_?setTimeout(()=>y.abort(new Error(`timed out after ${Math.round(_/1e3)}s`)),_):void 0;A?.unref?.();let v=(a.def.preSpawnTimeoutSec??_a)*1e3,R=setTimeout(()=>{y.abort(new Error(`timed out before spawn after ${Math.round(v/1e3)}s in step "${p.step??"start"}"`))},v);R.unref?.();let N=()=>{R&&clearTimeout(R),R=void 0},M=()=>`task=${p.id} chat=${c}:${d} at=${new Date().toISOString()}`,O;y.signal.addEventListener("abort",()=>{let h=pt(y.signal).message;/^timed out/.test(h)&&(O=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${h} ${M()}`)},{once:!0});let F=h=>{p.step=h,this.log(`[${e.agentId}] step ${h} ${M()}`)},D=(h,f,S=0)=>y.signal.aborted?Promise.reject(pt(y.signal)):(F(h),(h==="agent"||h==="workflow-auto-run")&&N(),Or(f(),y.signal,S)),H=!1,C=h=>{if(H)return;H=!0,this.runReleases.delete(p.id),A&&clearTimeout(A),N(),a.activeTasks--;let f=a.runningTasks.findIndex(S=>S.id===p.id);f!==-1&&a.runningTasks.splice(f,1),this.taskAborts.delete(p.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
132
132
  [task finished]
133
- `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),Ra).unref?.();try{let S=b.endedAt,P={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-p.startedAt.getTime(),ok:!h?.error,error:h?.error,...O?{status:"timeout",step:O}:{},responseText:h?.content||"",transcript:b.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let J=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:J,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(S=>{if(S.length!==0){this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${p.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of S){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W}).then(J=>this.postQueuedResponseToChannel(e.agentId,W,J)).catch(J=>{this.log(`[${e.agentId}] queued message failed: ${J.message}`)})}}}).catch(S=>{this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(p.id,C),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${M()}`);let g=e.context?.channel||"api",{evaluateRequest:T,selectRequestContext:E}=await import("./request-planner-NHE3IRJN.js"),L=await D("request-gate",()=>T(e.message,e.agentId,g));L.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let m=e.context?.chatId||e.context?.group||e.context?.sender||"default",X=e.context?.sender||"User",Z=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,g,m),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${g}:${m}`),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"stale",at:new Date().toISOString()})),e.freshSession||await D("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,g,m,e.seedHistory));let Wr=[...this.sessions.getSession(e.agentId,g,m).messages].reverse().find(h=>h.role==="agent")?.content;Dr({agent:e.agentId,channel:g,chatId:m,message:e.message,previousReply:Wr,taskId:w}),this.sessions.addUserMessage(e.agentId,g,m,X,e.message);let tn=Date.now();ee().emit("task:started",{agentId:e.agentId,channel:g,chatId:m,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(tn).toISOString(),taskId:w,resumeOrigin:Xs(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let Y,nn=this.classifier;if(nn&&g!=="a2a"&&!Z)try{Y=await D("classify",()=>nn.classify({text:e.message,channel:g,sender:e.context?.sender,agentId:e.agentId}))||void 0}catch(h){this.log(`[classifier] classify failed for ${e.agentId}: ${h?.message||h}`)}let $e=this.config.workflows?.matching,ye;if(this.config.workflows?.enabled&&$e?.enabled&&!o)try{let h=new ss({baseDir:B(process.cwd(),this.config.workflows.dir)}),f=rs({agentId:e.agentId,channel:g,message:e.message,intentPath:Y?.path},h.list());f&&f.confidence>=$e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${$e.mode} reasons=${f.reasons.join(",")||"n/a"}`),$e.mode==="auto"&&f.confidence>=$e.autoRunThreshold&&(this.workflowAutoRunner?ye={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(h){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${h?.message||h}`)}let Kr=this.wikiHub.getAgentWiki(e.agentId),sn=this.memoryStore.findRelevant(e.message,e.agentId,Z?3:8),rn=this.memoryStore.buildContext(sn),on=this.memoryStore.contextFacts(sn),qr=this.patternStore.findRelevant(e.message,e.agentId,5),Gr=this.patternStore.buildContext(qr),an="";if(!Z)try{let{loadLocalSkills:h,getAutoInjectSkills:f}=await import("./loader-EVHZ2R73.js"),S=await D("skills",()=>h(a.def.workspace));an=f(S,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,g,m):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,g,m):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,g,m):void 0;if(j&&this.sessions.isSessionStale(e.agentId,g,m)&&(this.log(`[${e.agentId}] session stale for ${g}:${m}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"stale"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,g,m)){let h=this.sessions.getLastTurnContextTokens(e.agentId,g,m);this.log(`[${e.agentId}] tier-2 rotation for ${g}:${m} (last turn context: ${h} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"tier-2",lastTurnInputTokens:h,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,g,m)){let h=this.sessions.getTurnCount(e.agentId,g,m);this.log(`[${e.agentId}] max-turns rotation for ${g}:${m} (${h} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let h=j;await D("rotate",()=>this.maybeRotateForContinuity(e,a,g,m,h))&&(j=void 0)}try{let h=await D("compact",()=>this.sessions.compactIfNeeded(e.agentId,g,m,this.memoryStore));if(h.compacted){let f=h.qualityScore??"?",S=h.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${g}:${m} (quality: ${f}%, ${S} entities lost)`),h.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${h.lostEntities.slice(0,5).join(", ")}`),h.drift){let P=h.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(h){this.log(`[${e.agentId}] compaction failed (non-fatal): ${h.message}`)}let Jr=process.env.AGENTX_CONTEXT_SURGERY==="1",zr=Z?{maxMessages:8,maxChars:2400}:Jr&&Nr(g,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Qr=!j&&!Z?Na(Kr,e.agentId):void 0,We=j?void 0:this.sessions.buildHistoryContext(e.agentId,g,m,zr),Xr=j?void 0:this.sessions.getRotationMemo(e.agentId,g,m)??void 0,cn,dn=[];if(this.config.procedures?.injection?.enabled&&!j&&!Z)try{let h=new je({baseDir:B(process.cwd(),this.config.procedures.dir)}),f=zt(e.message,h.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){cn=Qt(f),dn=f.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of f)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(h){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${h?.message||h}`)}if(pe&&pe.cat)try{let f=this.sessions.getSession(e.agentId,g,m).messages,S=f[0],P=f[f.length-1],W=We===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${We.length}c/${We.split(`
133
+ `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),Ra).unref?.();try{let S=b.endedAt,P={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-p.startedAt.getTime(),ok:!h?.error,error:h?.error,...O?{status:"timeout",step:O}:{},responseText:h?.content||"",transcript:b.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let J=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:J,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(S=>{if(S.length!==0){this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${p.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of S){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W}).then(J=>this.postQueuedResponseToChannel(e.agentId,W,J)).catch(J=>{this.log(`[${e.agentId}] queued message failed: ${J.message}`)})}}}).catch(S=>{this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(p.id,C),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${M()}`);let g=e.context?.channel||"api",{evaluateRequest:T,selectRequestContext:E}=await import("./request-planner-PLBDCYKI.js"),L=await D("request-gate",()=>T(e.message,e.agentId,g));L.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let m=e.context?.chatId||e.context?.group||e.context?.sender||"default",X=e.context?.sender||"User",Z=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,g,m),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${g}:${m}`),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"stale",at:new Date().toISOString()})),e.freshSession||await D("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,g,m,e.seedHistory));let Wr=[...this.sessions.getSession(e.agentId,g,m).messages].reverse().find(h=>h.role==="agent")?.content;Dr({agent:e.agentId,channel:g,chatId:m,message:e.message,previousReply:Wr,taskId:w}),this.sessions.addUserMessage(e.agentId,g,m,X,e.message);let tn=Date.now();ee().emit("task:started",{agentId:e.agentId,channel:g,chatId:m,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(tn).toISOString(),taskId:w,resumeOrigin:Xs(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let Y,nn=this.classifier;if(nn&&g!=="a2a"&&!Z)try{Y=await D("classify",()=>nn.classify({text:e.message,channel:g,sender:e.context?.sender,agentId:e.agentId}))||void 0}catch(h){this.log(`[classifier] classify failed for ${e.agentId}: ${h?.message||h}`)}let $e=this.config.workflows?.matching,ye;if(this.config.workflows?.enabled&&$e?.enabled&&!o)try{let h=new ss({baseDir:B(process.cwd(),this.config.workflows.dir)}),f=rs({agentId:e.agentId,channel:g,message:e.message,intentPath:Y?.path},h.list());f&&f.confidence>=$e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${$e.mode} reasons=${f.reasons.join(",")||"n/a"}`),$e.mode==="auto"&&f.confidence>=$e.autoRunThreshold&&(this.workflowAutoRunner?ye={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(h){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${h?.message||h}`)}let Kr=this.wikiHub.getAgentWiki(e.agentId),sn=this.memoryStore.findRelevant(e.message,e.agentId,Z?3:8),rn=this.memoryStore.buildContext(sn),on=this.memoryStore.contextFacts(sn),qr=this.patternStore.findRelevant(e.message,e.agentId,5),Gr=this.patternStore.buildContext(qr),an="";if(!Z)try{let{loadLocalSkills:h,getAutoInjectSkills:f}=await import("./loader-EVHZ2R73.js"),S=await D("skills",()=>h(a.def.workspace));an=f(S,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,g,m):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,g,m):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,g,m):void 0;if(j&&this.sessions.isSessionStale(e.agentId,g,m)&&(this.log(`[${e.agentId}] session stale for ${g}:${m}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"stale"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,g,m)){let h=this.sessions.getLastTurnContextTokens(e.agentId,g,m);this.log(`[${e.agentId}] tier-2 rotation for ${g}:${m} (last turn context: ${h} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"tier-2",lastTurnInputTokens:h,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,g,m)){let h=this.sessions.getTurnCount(e.agentId,g,m);this.log(`[${e.agentId}] max-turns rotation for ${g}:${m} (${h} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,m,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,g,m),ee().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:m,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let h=j;await D("rotate",()=>this.maybeRotateForContinuity(e,a,g,m,h))&&(j=void 0)}try{let h=await D("compact",()=>this.sessions.compactIfNeeded(e.agentId,g,m,this.memoryStore));if(h.compacted){let f=h.qualityScore??"?",S=h.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${g}:${m} (quality: ${f}%, ${S} entities lost)`),h.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${h.lostEntities.slice(0,5).join(", ")}`),h.drift){let P=h.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(h){this.log(`[${e.agentId}] compaction failed (non-fatal): ${h.message}`)}let Jr=process.env.AGENTX_CONTEXT_SURGERY==="1",zr=Z?{maxMessages:8,maxChars:2400}:Jr&&Nr(g,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Qr=!j&&!Z?Na(Kr,e.agentId):void 0,We=j?void 0:this.sessions.buildHistoryContext(e.agentId,g,m,zr),Xr=j?void 0:this.sessions.getRotationMemo(e.agentId,g,m)??void 0,cn,dn=[];if(this.config.procedures?.injection?.enabled&&!j&&!Z)try{let h=new je({baseDir:B(process.cwd(),this.config.procedures.dir)}),f=zt(e.message,h.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){cn=Qt(f),dn=f.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of f)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(h){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${h?.message||h}`)}if(pe&&pe.cat)try{let f=this.sessions.getSession(e.agentId,g,m).messages,S=f[0],P=f[f.length-1],W=We===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${We.length}c/${We.split(`
134
134
  `).length}L`,J=`[${e.agentId}] ${g}:${m} ${W} | session.messages=${f.length}`+(f.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${P.timestamp.slice(11,19)}(${P.role}:${(P.content||"").slice(0,40).replace(/\n/g," ")})`:"");pe.cat("context",J)}catch(h){pe.cat("context",`[${e.agentId}] context-diag error: ${h?.message??h}`)}let un;if(a.def.contextReferences&&!j)try{let h=a.def.workspace,f=this.referencesCache.get(h);if(!f){let[P,W]=await D("references",()=>Promise.all([It(a.def.workspace),St(a.def.workspace)]));if(P.byId.size===0&&W.recipes.length===0){let[J,ge]=await D("references",()=>Promise.all([It(process.cwd()),St(process.cwd())]));f={refs:J,recipes:ge}}else f={refs:P,recipes:W};this.referencesCache.set(h,f)}let S=zn({agentId:e.agentId,intentTags:Y?.path,message:e.message},f.recipes,f.refs);S.cards.length>0&&(un=Gn(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(h){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${h?.message||h}`)}let ln=this.sessions.getCrossSessionSummary(e.agentId,g,m,e.message),gn,Ke=js(e.message);if(Ke)try{let h=this.sessions.recallTurns({agentId:e.agentId,channel:g,chatId:m,lookbackDays:Ke.lookbackDays,limit:12});if(h.turns.length>0){let f=[`[Long-memory recall \u2014 last ${Ke.lookbackDays}d on this chat (cue-triggered)]`],S=[...h.turns].sort((P,W)=>P.ts.localeCompare(W.ts));for(let P of S){let W=P.ts.slice(11,16)+" "+P.day,J=P.role==="user"?P.senderName||"User":P.senderName||"Agent";f.push(`${W} ${J}: ${P.content}`)}h.hasMore&&f.push(`[\u2026${h.totalScanned-h.turns.length}+ older turns available \u2014 call /recall with before=${h.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),gn=f.join(`
135
135
  `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ke.lookbackDays}d, turns=${h.turns.length}, scanned=${h.totalScanned}`)}}catch(h){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${h.message}`)}let Yr=Z?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",pn,hn,mn=!1;if(Yr==="planner"&&!L.active&&g!=="voice"&&g!=="desktop"){try{let{planContext:h}=await import("./context-planner-LJT5IKH6.js"),f=await D("plan-context",()=>h({agentId:e.agentId,channel:g,chatId:m,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(mn=!0,pn=f.sessionHistory,rn=f.memoryContext,on=f.memoryFacts,ln=f.crossChatContext,hn=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(h){this.log(`[${e.agentId}] planner failed (non-fatal): ${h.message} \u2014 falling back to layered (keeping --resume for continuity)`)}mn&&j&&(this.sessions.clearClaudeSessionId(e.agentId,g,m),j=void 0)}let ht=`${e.agentId}:${g}:${m}`,qe=Dn(e.message);qe&&(qe==="default"?(this.activeSouls.delete(ht),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(ht,qe),this.log(`[${e.agentId}] Soul switched to: ${qe}`)));let Vr=this.activeSouls.get(ht),Zr=_n(a.def.workspace,Vr),eo=En(Zr),to=this.agentMemory.indexMarkdown(e.agentId),no=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
136
136
  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.`:"",so=a.def.richMessages!==!1&&(g==="telegram"||g==="whatsapp"||g==="app")?["[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(`
@@ -144,8 +144,8 @@ ${$}`),f+=$.length}catch{}}}let ro=mt.length>0?mt.join(`
144
144
 
145
145
  `):"",ft=[a.def.systemPrompt||"",no,so,fn,ro,eo||"",to||""].filter(h=>h.trim().length>0).join(`
146
146
 
147
- `)||void 0,yn={channel:g,chatId:m,channelScope:e.context?.group?"group":g==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,g),systemPrompt:a.def.systemPrompt,sender:X,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:Z||Nr(g,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:Z?void 0:Gr||void 0,procedureContext:cn,references:un,skillInjection:an||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:pn??We,memoryContext:rn||void 0,crossChatContext:ln||void 0,longMemoryRecall:gn||void 0,wikiContext:Qr,handoverNote:this.buildHandoverNote(e.agentId,g,m),rotationMemo:Xr,eventDigest:j?void 0:Oa(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),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},Je=L.active&&L.preprocess?await D("select-context",()=>E(yn)):{input:yn,excluded:[]};Je.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Je.excluded.join(", ")}`);let ze=Qs(Je.input,Z?{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),oo=Bn(ze,{memory:on,procedures:dn,wikiContext:Je.input.wikiContext}),yt=(ze?.length??0)+(ft?.length??0)+(e.message?.length??0),Qe={history:ze?.length??0,sysPrompt:ft?.length??0,message:e.message?.length??0},bn=hr(e.agentId,g,m);mr(bn,yt,Qe);let wn=fr(bn);wn&&this.log(`[${e.agentId}] ${wn}`),yt>16e3&&this.log(`[${e.agentId}] large context for ${g}:${m}: ${yt} bytes (history=${Qe.history}, sysPrompt=${Qe.sysPrompt}, message=${Qe.message})`);let bt,xn=Pn(a.def.tier,this.config.decisions.routing);if(!e.model&&xn&&(!L.active||L.preprocess))try{let{routeTaskModel:h}=await import("./routing-AQKHAU3Z.js"),f=await D("route-model",()=>h({message:e.message,agent:e.agentId,channel:g,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,g,m),cheapModel:xn}));f.downgraded&&(bt=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let io={...e,systemPromptAppend:ft,...bt?{model:bt}:{}},le,Tn=Pr({agent:e.agentId,request:e.message,taskId:w,budgetMinutes:a.def.maxExecutionMinutes??20}),ao=k;k=h=>{Tn.observe(h),ao?.(h)};try{let h=this.workflowAutoRunner;if(ye&&h){let U=ye;try{let G=await D("workflow-auto-run",()=>h({workflowId:U.workflowId,agentId:e.agentId,channel:g,chatId:m,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:g,chatId:m,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 ${ye.workflowId} run=${G.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),le={content:"",duration:0,metadata:{handledByWorkflow:ye.workflowId,workflowRunId:G.runId,workflowMatchConfidence:ye.confidence}},le}catch(G){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${G?.message||G}`)}}if(a.def.tier==="claude-code"){F("dispatch-gate");let U=a.def.persistentProcess?tt():null,G=U!=null&&U.hasLive({agentId:e.agentId,channel:g,chatId:m}),re=!!j||G,te=[ir(re),gr(re)].find(Re=>Re&&Re.abort);if(te){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${te.reason}`);let Re={content:"",error:te.message,duration:0};if(!t){b.buffer=`[error] ${te.message}`;for(let co of b.subscribers)try{co(b.buffer)}catch{}}return le=Re,Re}ur();let Me=pr();Me&&this.log(`[${e.agentId}] ${Me}`)}let f=a.def.tier==="claude-code",S=f?t:(U,G)=>{U&&x(U),t&&t(U,G)},P=!1,W=f?n:U=>{U&&(P?x(U):(x(`\u{1F4AD} ${U}`),P=!0)),n&&n(U)},J=()=>{P&&(x(`
147
+ `)||void 0,yn={channel:g,chatId:m,channelScope:e.context?.group?"group":g==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,g),systemPrompt:a.def.systemPrompt,sender:X,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:Z||Nr(g,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:Z?void 0:Gr||void 0,procedureContext:cn,references:un,skillInjection:an||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:pn??We,memoryContext:rn||void 0,crossChatContext:ln||void 0,longMemoryRecall:gn||void 0,wikiContext:Qr,handoverNote:this.buildHandoverNote(e.agentId,g,m),rotationMemo:Xr,eventDigest:j?void 0:Oa(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),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},Je=L.active&&L.preprocess?await D("select-context",()=>E(yn)):{input:yn,excluded:[]};Je.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Je.excluded.join(", ")}`);let ze=Qs(Je.input,Z?{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),oo=Bn(ze,{memory:on,procedures:dn,wikiContext:Je.input.wikiContext}),yt=(ze?.length??0)+(ft?.length??0)+(e.message?.length??0),Qe={history:ze?.length??0,sysPrompt:ft?.length??0,message:e.message?.length??0},bn=hr(e.agentId,g,m);mr(bn,yt,Qe);let wn=fr(bn);wn&&this.log(`[${e.agentId}] ${wn}`),yt>16e3&&this.log(`[${e.agentId}] large context for ${g}:${m}: ${yt} bytes (history=${Qe.history}, sysPrompt=${Qe.sysPrompt}, message=${Qe.message})`);let bt,xn=Pn(a.def.tier,this.config.decisions.routing);if(!e.model&&xn&&(!L.active||L.preprocess))try{let{routeTaskModel:h}=await import("./routing-POORZC7A.js"),f=await D("route-model",()=>h({message:e.message,agent:e.agentId,channel:g,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,g,m),cheapModel:xn}));f.downgraded&&(bt=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let io={...e,systemPromptAppend:ft,...bt?{model:bt}:{}},le,Tn=Pr({agent:e.agentId,request:e.message,taskId:w,budgetMinutes:a.def.maxExecutionMinutes??20}),ao=k;k=h=>{Tn.observe(h),ao?.(h)};try{let h=this.workflowAutoRunner;if(ye&&h){let U=ye;try{let G=await D("workflow-auto-run",()=>h({workflowId:U.workflowId,agentId:e.agentId,channel:g,chatId:m,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:g,chatId:m,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 ${ye.workflowId} run=${G.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),le={content:"",duration:0,metadata:{handledByWorkflow:ye.workflowId,workflowRunId:G.runId,workflowMatchConfidence:ye.confidence}},le}catch(G){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${G?.message||G}`)}}if(a.def.tier==="claude-code"){F("dispatch-gate");let U=a.def.persistentProcess?tt():null,G=U!=null&&U.hasLive({agentId:e.agentId,channel:g,chatId:m}),re=!!j||G,te=[ir(re),gr(re)].find(Re=>Re&&Re.abort);if(te){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${te.reason}`);let Re={content:"",error:te.message,duration:0};if(!t){b.buffer=`[error] ${te.message}`;for(let co of b.subscribers)try{co(b.buffer)}catch{}}return le=Re,Re}ur();let Me=pr();Me&&this.log(`[${e.agentId}] ${Me}`)}let f=a.def.tier==="claude-code",S=f?t:(U,G)=>{U&&x(U),t&&t(U,G)},P=!1,W=f?n:U=>{U&&(P?x(U):(x(`\u{1F4AD} ${U}`),P=!0)),n&&n(U)},J=()=>{P&&(x(`
148
148
  `),P=!1)},ge=f?S:S?(U,G)=>{J(),S(U,G)}:void 0,$=await D("agent",()=>Ls(a.def,io,this.providers,ge,ze,j,k,y.signal,W),Pa);if(!$.error){let U=La(a.def.toolUseRequired,I);if(U){let G=Array.from(I.entries()).map(([re,Xe])=>`${re}=${Xe}`).join(", ")||"none";$.error=`tool_required_not_called: ${U} (invoked: ${G})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${U}, observed ${G}`)}}le=$;let se=$.usage?Js($.usage):void 0;if(ee().emit("task:completed",{taskId:w,agentId:e.agentId,channel:g,chatId:m,durationMs:Date.now()-tn,error:$.error||void 0,inputTokens:se?.inputTokens,outputTokens:se?.outputTokens,cacheReadTokens:se?.cacheReadTokens,cacheCreateTokens:se?.cacheCreateTokens,tier2InputTokens:se?.tier2InputTokens,tier2OutputTokens:se?.tier2OutputTokens,tier2CacheReadTokens:se?.tier2CacheReadTokens,tier2CacheCreateTokens:se?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:L.arm,numTurns:$.numTurns,injectedContext:oo,finalResponse:$.content||void 0,billedModel:$.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let U=$.error?`[error] ${$.error}`:$.content;b.buffer=U;for(let G of b.subscribers)try{G(U)}catch{}}if($.error)a.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,g,m,$.content),Er({agent:e.agentId,channel:g,chatId:m,request:e.message,reply:$.content,taskId:w}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,g,m,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,g,m,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,g,m,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,g,m,$.usage,$.contextTokens),$.usage){let te=$.contextTokens,Me=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(te??Me)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${g}:${m}: context=${te??"n/a"} tokens (cumulative turn total=${Me}) \u2014 next turn will rotate`)}if(Ln({channel:g,content:`User: ${e.message}`,responseLength:$.content.length}).capture){try{let te=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:te,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:g,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
149
149
 
150
150
  Agent: ${$.content}`,meta:Da(Y,e.context)})}catch{}Fn(e.agentId,e.message,$.content,{channel:g,chatId:m,sender:X},this.memoryStore).catch(()=>{}),er(e.agentId,e.message,$.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let G=$.billedModel||e.model||a.def.model,re=e.context?.channel,Xe=re&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${re}:${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,G,re,Xe),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${M()}`)}return $}catch(h){a.errors++,this.log(`[${e.agentId}] unexpected error: ${h.message}`);let f=Ze(h.message);return le={content:"",error:et(f),errorKind:f.kind},le}finally{Tn.stop(),C(le)}}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(),Ae,this.safe(e.agentId),t);V(n)||Aa(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);Ma(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(),Ae,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),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[d,c]){let p=B(a,u);if(V(p))try{for(let y of ne(p)){if(!y.endsWith(".json"))continue;let b=y.split("-")[0],x=parseInt(b,10);if(!Number.isFinite(x)||x<i||x>n)continue;let w=Math.floor((n-x)/36e5),I=t-1-w;I>=0&&I<t&&o[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Ae);if(!V(e))return 0;let t=0;for(let n of ne(e)){let r=B(e,n),o;try{o=ne(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=ne(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(Ue(B(a,d),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let p=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:p,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Ea){let t=B(process.cwd(),Ae);if(!V(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ne(t)){let i=B(t,o),a;try{a=ne(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{$a(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return[];let r=ne(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=ne(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let l=JSON.parse(Ue(B(a,d),"utf-8")),{transcript:u,responseText:p,...y}=l;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return null;let r=this.safe(t),o=ne(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(Ue(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=ns();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}}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,l=o.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),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 p=this.messageQueue.pendingCount(i,a,c),y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:y,edited:u,pending:p}}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(d=>{let l=!1,u=p=>{l||(l=!0,d(p))};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:p=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{p.error?.startsWith("__queued__")?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>u({ok:!1,status:500,error:p?.message??String(p)}))})}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{ds as a,us as b,Ya as c,gs as d,Co as e,ps as f,fs as g,dc as h,pc as i,hc as j,Uo as k,Ds as l,Go as m,Jo as n,zo as o,Ls as p,it as q,at as r,Wc as s,Bt as t,ee as u,tr as v,Ci as w,Ri as x,rr as y,id as z,or as A,je as B,ha as C,ma as D,fa as E,ya as F,ba as G,zt as H,Nu as I,Lu as J,Da as K,Oa as L,Na as M,en as N,Fr as O,Hr as P,La as Q,jr as R,Ur as S};
151
- //# sourceMappingURL=chunk-JO3PSLWL.js.map
151
+ //# sourceMappingURL=chunk-JZMKKDT3.js.map
@@ -1,2 +1,2 @@
1
- import{v as l,w}from"./chunk-NBGNPKAF.js";import{a as i,f as p}from"./chunk-72SZI2UW.js";w();p();var d="task-tier";function u(e){return{task:f(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:i("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function f(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2,m=60*60*1e3;function F(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function M(e){let n=(o,r=null)=>({downgraded:!1,needsFlagship:r,reason:o});if(e.channel==="voice"||e.channel==="desktop"||e.channel==="opencode")return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let o=e.sessionIdleMs??0,r=e.cacheTtlMs??m;if(o<r)return n(`follow-up on a warm cache (idle ${Math.round(o/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"}})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let s=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${s<(e.threshold??h)?"downgrade":"keep"} (${s.toFixed(2)})`,s);let a=e.threshold??h;return s>=a?n(`needs the flagship (${s.toFixed(2)})`,s):{model:e.cheapModel,downgraded:!0,needsFlagship:s,reason:`mechanical task (${s.toFixed(2)} below ${a}) \u2192 ${e.cheapModel}`}}export{F as a,M as b};
2
- //# sourceMappingURL=chunk-WBGC7MWX.js.map
1
+ import{v as l,w}from"./chunk-PTB2TPOC.js";import{a as i,f as p}from"./chunk-72SZI2UW.js";w();p();var d="task-tier";function u(e){return{task:f(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:i("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function f(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2,m=60*60*1e3;function F(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function M(e){let n=(o,r=null)=>({downgraded:!1,needsFlagship:r,reason:o});if(e.channel==="voice"||e.channel==="desktop"||e.channel==="opencode")return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let o=e.sessionIdleMs??0,r=e.cacheTtlMs??m;if(o<r)return n(`follow-up on a warm cache (idle ${Math.round(o/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"}})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let s=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${s<(e.threshold??h)?"downgrade":"keep"} (${s.toFixed(2)})`,s);let a=e.threshold??h;return s>=a?n(`needs the flagship (${s.toFixed(2)})`,s):{model:e.cheapModel,downgraded:!0,needsFlagship:s,reason:`mechanical task (${s.toFixed(2)} below ${a}) \u2192 ${e.cheapModel}`}}export{F as a,M as b};
2
+ //# sourceMappingURL=chunk-LQ5J6COO.js.map
@@ -1,7 +1,7 @@
1
- import{g as j,h as x,o as O,p as I}from"./chunk-S7CVSKOX.js";import{w as S,z as L}from"./chunk-S7TCVIET.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-N5KD3TVN.js.map
1
+ import{f as j,i as x,p as O,q as I}from"./chunk-BYJ3A55Y.js";import{w as S,z as _}from"./chunk-OVF37EXJ.js";_();import{Command as q}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 z}from"fs";import{join as P,resolve as m}from"path";import{homedir as X}from"os";import{createRequire as B}from"module";import{execFile as L}from"child_process";var M=(t,n)=>new Promise(e=>{try{L(t,n,{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(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)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(t.run??M)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,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:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:R}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:R}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function F(t={}){let n=[];await Z(n),U(n);let e=V(n);return e&&K(n,e),e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&ie(n,e),e&&await J(n,e),e&&G(n,e),t.running!==!1&&e&&await ne(n,e),{checks:n,summary:H(n)}}var ve=new q().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 t=>{let{checks:n,summary:e}=await F({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
2
+ `):oe(n),process.exit(e.errors>0?1:0)});async function J(t,n,e=N){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function G(t,n,e=process.platform,i=s=>{try{return E(s,T.X_OK),!0}catch{return!1}}){let s=n.reminders;if(!s?.enabled)return;if(e!=="darwin"){t.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);t.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 Z(t){let n=Number(process.versions.node.split(".")[0]);t.push({severity:n==22?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n==22?void 0:"AgentX requires Node 22.x.",fix:n==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");t.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{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else t.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{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else t.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{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.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{B(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.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 U(t){if(process.platform!=="darwin")return;let n=P(X(),"Library/LaunchAgents"),e=[];try{e=$(n).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(n,s),"utf-8")),a=x("ffmpeg",r,i);t.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 V(t){let n=m(process.cwd(),"agentx.json");if(!y(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.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}})()||t.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}})()||t.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}})()||t.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 K(t,n){let e=new Set;if(C(n,e),e.size===0){t.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?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&t.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&&t.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)C(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))C(e,n)}function Q(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{z(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.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(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(n.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){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)t.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(t,n){let e=n.webhooks??[],i=[],s=m(process.cwd(),n.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 ${n.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((n.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(n.agents??{}));for(let o of n.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(n.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(n.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 W=g.credentials||{};for(let[D,v]of Object.entries(W))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){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)t.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}function te(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function ne(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.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){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.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});let u=te(l.voice);u&&t.push(u)}catch{t.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 ie(t,n){let e=Object.entries(n.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{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else t.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)){t.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)?t.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):t.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 H(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function oe(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,s]of n){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=H(t);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,F as b,ve as c,J as d,G as e,te as f};
7
+ //# sourceMappingURL=chunk-N42YWYIR.js.map