agentix-cli 0.165.1 → 0.166.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 (149) hide show
  1. package/README.md +1 -1
  2. package/dist/{App-NV2JJMHN.js → App-UOZT7MWS.js} +2 -2
  3. package/dist/{ChatApp-CIGDPS3A.js → ChatApp-N7REHHH3.js} +2 -2
  4. package/dist/{absorb-eval-VPAASHZG.js → absorb-eval-MT3ZDYBM.js} +2 -2
  5. package/dist/{agent-UFMIPTQZ.js → agent-SUAQ7EBM.js} +2 -2
  6. package/dist/{board-dashboard-NUEVGTM7.js → board-dashboard-4C77NLY5.js} +399 -305
  7. package/dist/board-dashboard-4C77NLY5.js.map +1 -0
  8. package/dist/{chunk-GJ4SQRAE.js → chunk-33KKV3YU.js} +2 -2
  9. package/dist/{chunk-A3GDFLFB.js → chunk-64POGFQZ.js} +2 -2
  10. package/dist/{chunk-V7R5AJVN.js → chunk-7FH2FEFA.js} +2 -2
  11. package/dist/{chunk-NCEYJFF5.js → chunk-7O43PB6O.js} +2 -2
  12. package/dist/{chunk-PSTEWKR3.js → chunk-7UIK4S6T.js} +2 -2
  13. package/dist/{chunk-EXJGRK2N.js → chunk-A2D3PNDA.js} +2 -2
  14. package/dist/{chunk-ILHTAVZZ.js → chunk-AE3U4GR6.js} +85 -85
  15. package/dist/chunk-AE3U4GR6.js.map +1 -0
  16. package/dist/{chunk-4SJ2VFVI.js → chunk-AFLZHY5Y.js} +2 -2
  17. package/dist/{chunk-CDPQQAK6.js → chunk-APPTSTL5.js} +2 -2
  18. package/dist/chunk-B6GVATMI.js +92 -0
  19. package/dist/chunk-B6GVATMI.js.map +1 -0
  20. package/dist/{chunk-KVSHZKAL.js → chunk-B7QHC7N4.js} +2 -2
  21. package/dist/chunk-BE64IJWM.js +11 -0
  22. package/dist/chunk-BE64IJWM.js.map +1 -0
  23. package/dist/{chunk-T5IGXFSW.js → chunk-BQXKTQCX.js} +2 -2
  24. package/dist/{chunk-AYK2MO3B.js → chunk-CTN4KYE6.js} +2 -2
  25. package/dist/{chunk-CRUNUMVO.js → chunk-G3T73GGF.js} +2 -2
  26. package/dist/{chunk-BC7VOHNH.js → chunk-IJZNM5PS.js} +2 -2
  27. package/dist/{chunk-S6ZZKRDB.js → chunk-JMZNI257.js} +2 -2
  28. package/dist/{chunk-CGE5EAWC.js → chunk-L7RPH3T7.js} +2 -2
  29. package/dist/{chunk-DAWJHJKD.js → chunk-LM3K7U6H.js} +2 -2
  30. package/dist/{chunk-ON7Y3JSP.js → chunk-LQTTLXZY.js} +3 -3
  31. package/dist/{chunk-Y6JSB5II.js → chunk-NHWYEIET.js} +2 -2
  32. package/dist/{chunk-QT63Q6C5.js → chunk-QGKNDGH5.js} +2 -2
  33. package/dist/{chunk-FK2TJZNJ.js → chunk-QLJ3OMPL.js} +2 -2
  34. package/dist/{chunk-73SESASJ.js → chunk-SXKC2LH7.js} +2 -2
  35. package/dist/{chunk-VL74KOR7.js → chunk-VJVXEVZ7.js} +18 -9
  36. package/dist/{chunk-VL74KOR7.js.map → chunk-VJVXEVZ7.js.map} +1 -1
  37. package/dist/{chunk-KTJ6234K.js → chunk-XJYGMCAV.js} +241 -241
  38. package/dist/chunk-XJYGMCAV.js.map +1 -0
  39. package/dist/{chunk-YUGYKMY6.js → chunk-XML72AUF.js} +2 -2
  40. package/dist/chunk-XQ2EFLQW.js +41 -0
  41. package/dist/chunk-XQ2EFLQW.js.map +1 -0
  42. package/dist/{chunk-6Y53LLIX.js → chunk-YKHK47G5.js} +2 -2
  43. package/dist/{chunk-RUB4HZEG.js → chunk-YQ25AGX6.js} +2 -2
  44. package/dist/cli.js +1 -1
  45. package/dist/{client-D3CYQPUD.js → client-6ZHYSQU6.js} +2 -2
  46. package/dist/{config-OTO56OCX.js → config-WCEFYQL4.js} +2 -2
  47. package/dist/{config-mutate-5KKGQHC6.js → config-mutate-LW366SKL.js} +2 -2
  48. package/dist/config-mutator-NRHZ2XH3.js +2 -0
  49. package/dist/{contributions-SMSYSHPU.js → contributions-MUCJKT73.js} +2 -2
  50. package/dist/{doctor-5PFLKGNU.js → doctor-2N2MX5YP.js} +2 -2
  51. package/dist/{failure-candidates-HNENLQJC.js → failure-candidates-WGSFI7GR.js} +2 -2
  52. package/dist/{follow-up-tool-ME4DV7HT.js → follow-up-tool-W64LMQQN.js} +2 -2
  53. package/dist/{hub-WGUNZ2D5.js → hub-4ODFNGHL.js} +2 -2
  54. package/dist/index.d.ts +85 -38
  55. package/dist/index.js +1 -1
  56. package/dist/{program-GBPLSXFF.js → program-6YMRDLHO.js} +24 -24
  57. package/dist/{promote-TQ3OZ7EC.js → promote-OUSVJZ64.js} +2 -2
  58. package/dist/{query-M4VWXBHF.js → query-QVK5EN3P.js} +2 -2
  59. package/dist/{query-settings-Y4PWFLYK.js → query-settings-2TNLXEL5.js} +2 -2
  60. package/dist/{registry-GLNCV3KP.js → registry-BYIWNEFL.js} +2 -2
  61. package/dist/{request-planner-FE3C2QFQ.js → request-planner-7HEHLPA3.js} +2 -2
  62. package/dist/{review-candidates-R7QKVGMQ.js → review-candidates-NJNMSOCX.js} +2 -2
  63. package/dist/{routing-6J4OHUJS.js → routing-HCSXNUOY.js} +2 -2
  64. package/dist/schedule-tool-LJYBLCLV.js +2 -0
  65. package/dist/{scheduler-XDLJAWGC.js → scheduler-74MXJLQS.js} +2 -2
  66. package/dist/{seat-35AZG54F.js → seat-CAYDECW2.js} +2 -2
  67. package/dist/{select-6PC26YUI.js → select-QUVE6RN2.js} +2 -2
  68. package/dist/{set-enabled-UJOLDPZV.js → set-enabled-BWJN4IVG.js} +2 -2
  69. package/dist/token-tracker-XTHSSPLB.js +2 -0
  70. package/dist/tool-FZ4UXMON.js +8 -0
  71. package/dist/tool-FZ4UXMON.js.map +1 -0
  72. package/dist/{tool-QLIJQQ7W.js → tool-UC7OZWIB.js} +2 -2
  73. package/dist/traces-O4TIZ4SM.js +2 -0
  74. package/dist/{wiki-W7L5EJTZ.js → wiki-KNSPJT2O.js} +2 -2
  75. package/dist/wiki-enrich-RVRTAQQF.js +2 -0
  76. package/dist/{workflow-pilot-25NMZYUO.js → workflow-pilot-MKG6CJ6V.js} +2 -2
  77. package/package.json +1 -1
  78. package/dist/board-dashboard-NUEVGTM7.js.map +0 -1
  79. package/dist/chunk-AXDNFXYU.js +0 -41
  80. package/dist/chunk-AXDNFXYU.js.map +0 -1
  81. package/dist/chunk-ILHTAVZZ.js.map +0 -1
  82. package/dist/chunk-IVTO54EM.js +0 -90
  83. package/dist/chunk-IVTO54EM.js.map +0 -1
  84. package/dist/chunk-KTJ6234K.js.map +0 -1
  85. package/dist/chunk-XIRM45DH.js +0 -11
  86. package/dist/chunk-XIRM45DH.js.map +0 -1
  87. package/dist/config-mutator-XBUGJZER.js +0 -2
  88. package/dist/schedule-tool-FE3TWOGS.js +0 -2
  89. package/dist/token-tracker-B2UFOH46.js +0 -2
  90. package/dist/tool-LAMDUPTX.js +0 -6
  91. package/dist/tool-LAMDUPTX.js.map +0 -1
  92. package/dist/traces-G4HRLRA3.js +0 -2
  93. package/dist/wiki-enrich-3ZCL5TEC.js +0 -2
  94. /package/dist/{App-NV2JJMHN.js.map → App-UOZT7MWS.js.map} +0 -0
  95. /package/dist/{ChatApp-CIGDPS3A.js.map → ChatApp-N7REHHH3.js.map} +0 -0
  96. /package/dist/{absorb-eval-VPAASHZG.js.map → absorb-eval-MT3ZDYBM.js.map} +0 -0
  97. /package/dist/{agent-UFMIPTQZ.js.map → agent-SUAQ7EBM.js.map} +0 -0
  98. /package/dist/{chunk-GJ4SQRAE.js.map → chunk-33KKV3YU.js.map} +0 -0
  99. /package/dist/{chunk-A3GDFLFB.js.map → chunk-64POGFQZ.js.map} +0 -0
  100. /package/dist/{chunk-V7R5AJVN.js.map → chunk-7FH2FEFA.js.map} +0 -0
  101. /package/dist/{chunk-NCEYJFF5.js.map → chunk-7O43PB6O.js.map} +0 -0
  102. /package/dist/{chunk-PSTEWKR3.js.map → chunk-7UIK4S6T.js.map} +0 -0
  103. /package/dist/{chunk-EXJGRK2N.js.map → chunk-A2D3PNDA.js.map} +0 -0
  104. /package/dist/{chunk-4SJ2VFVI.js.map → chunk-AFLZHY5Y.js.map} +0 -0
  105. /package/dist/{chunk-CDPQQAK6.js.map → chunk-APPTSTL5.js.map} +0 -0
  106. /package/dist/{chunk-KVSHZKAL.js.map → chunk-B7QHC7N4.js.map} +0 -0
  107. /package/dist/{chunk-T5IGXFSW.js.map → chunk-BQXKTQCX.js.map} +0 -0
  108. /package/dist/{chunk-AYK2MO3B.js.map → chunk-CTN4KYE6.js.map} +0 -0
  109. /package/dist/{chunk-CRUNUMVO.js.map → chunk-G3T73GGF.js.map} +0 -0
  110. /package/dist/{chunk-BC7VOHNH.js.map → chunk-IJZNM5PS.js.map} +0 -0
  111. /package/dist/{chunk-S6ZZKRDB.js.map → chunk-JMZNI257.js.map} +0 -0
  112. /package/dist/{chunk-CGE5EAWC.js.map → chunk-L7RPH3T7.js.map} +0 -0
  113. /package/dist/{chunk-DAWJHJKD.js.map → chunk-LM3K7U6H.js.map} +0 -0
  114. /package/dist/{chunk-ON7Y3JSP.js.map → chunk-LQTTLXZY.js.map} +0 -0
  115. /package/dist/{chunk-Y6JSB5II.js.map → chunk-NHWYEIET.js.map} +0 -0
  116. /package/dist/{chunk-QT63Q6C5.js.map → chunk-QGKNDGH5.js.map} +0 -0
  117. /package/dist/{chunk-FK2TJZNJ.js.map → chunk-QLJ3OMPL.js.map} +0 -0
  118. /package/dist/{chunk-73SESASJ.js.map → chunk-SXKC2LH7.js.map} +0 -0
  119. /package/dist/{chunk-YUGYKMY6.js.map → chunk-XML72AUF.js.map} +0 -0
  120. /package/dist/{chunk-6Y53LLIX.js.map → chunk-YKHK47G5.js.map} +0 -0
  121. /package/dist/{chunk-RUB4HZEG.js.map → chunk-YQ25AGX6.js.map} +0 -0
  122. /package/dist/{client-D3CYQPUD.js.map → client-6ZHYSQU6.js.map} +0 -0
  123. /package/dist/{config-OTO56OCX.js.map → config-WCEFYQL4.js.map} +0 -0
  124. /package/dist/{config-mutate-5KKGQHC6.js.map → config-mutate-LW366SKL.js.map} +0 -0
  125. /package/dist/{config-mutator-XBUGJZER.js.map → config-mutator-NRHZ2XH3.js.map} +0 -0
  126. /package/dist/{contributions-SMSYSHPU.js.map → contributions-MUCJKT73.js.map} +0 -0
  127. /package/dist/{doctor-5PFLKGNU.js.map → doctor-2N2MX5YP.js.map} +0 -0
  128. /package/dist/{failure-candidates-HNENLQJC.js.map → failure-candidates-WGSFI7GR.js.map} +0 -0
  129. /package/dist/{follow-up-tool-ME4DV7HT.js.map → follow-up-tool-W64LMQQN.js.map} +0 -0
  130. /package/dist/{hub-WGUNZ2D5.js.map → hub-4ODFNGHL.js.map} +0 -0
  131. /package/dist/{program-GBPLSXFF.js.map → program-6YMRDLHO.js.map} +0 -0
  132. /package/dist/{promote-TQ3OZ7EC.js.map → promote-OUSVJZ64.js.map} +0 -0
  133. /package/dist/{query-M4VWXBHF.js.map → query-QVK5EN3P.js.map} +0 -0
  134. /package/dist/{query-settings-Y4PWFLYK.js.map → query-settings-2TNLXEL5.js.map} +0 -0
  135. /package/dist/{registry-GLNCV3KP.js.map → registry-BYIWNEFL.js.map} +0 -0
  136. /package/dist/{request-planner-FE3C2QFQ.js.map → request-planner-7HEHLPA3.js.map} +0 -0
  137. /package/dist/{review-candidates-R7QKVGMQ.js.map → review-candidates-NJNMSOCX.js.map} +0 -0
  138. /package/dist/{routing-6J4OHUJS.js.map → routing-HCSXNUOY.js.map} +0 -0
  139. /package/dist/{schedule-tool-FE3TWOGS.js.map → schedule-tool-LJYBLCLV.js.map} +0 -0
  140. /package/dist/{scheduler-XDLJAWGC.js.map → scheduler-74MXJLQS.js.map} +0 -0
  141. /package/dist/{seat-35AZG54F.js.map → seat-CAYDECW2.js.map} +0 -0
  142. /package/dist/{select-6PC26YUI.js.map → select-QUVE6RN2.js.map} +0 -0
  143. /package/dist/{set-enabled-UJOLDPZV.js.map → set-enabled-BWJN4IVG.js.map} +0 -0
  144. /package/dist/{token-tracker-B2UFOH46.js.map → token-tracker-XTHSSPLB.js.map} +0 -0
  145. /package/dist/{tool-QLIJQQ7W.js.map → tool-UC7OZWIB.js.map} +0 -0
  146. /package/dist/{traces-G4HRLRA3.js.map → traces-O4TIZ4SM.js.map} +0 -0
  147. /package/dist/{wiki-W7L5EJTZ.js.map → wiki-KNSPJT2O.js.map} +0 -0
  148. /package/dist/{wiki-enrich-3ZCL5TEC.js.map → wiki-enrich-RVRTAQQF.js.map} +0 -0
  149. /package/dist/{workflow-pilot-25NMZYUO.js.map → workflow-pilot-MKG6CJ6V.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{kb as l,tb as m}from"./chunk-IVTO54EM.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
1
+ import{kb as l,tb as m}from"./chunk-B6GVATMI.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
2
2
  `,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
4
- //# sourceMappingURL=chunk-KVSHZKAL.js.map
4
+ //# sourceMappingURL=chunk-B7QHC7N4.js.map
@@ -0,0 +1,11 @@
1
+ import{readFileSync as O,writeFileSync as v,appendFileSync as U,existsSync as I,mkdirSync as G}from"fs";import{resolve as _}from"path";var w={"claude-fable":{input:10,output:50,cacheRead:1,cacheCreate:12.5},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-8":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-6":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus":{input:15,output:75,cacheRead:1.5,cacheCreate:18.75},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheCreate:2.5},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},F={"gpt-5":{input:1.25,output:10,cacheRead:.125,cacheCreate:1.25},"gpt-5.1":{input:1.25,output:10,cacheRead:.125,cacheCreate:1.25},"gpt-5-mini":{input:.25,output:2,cacheRead:.025,cacheCreate:.25},"gpt-5-nano":{input:.05,output:.4,cacheRead:.005,cacheCreate:.05},"gpt-4.1":{input:2,output:8,cacheRead:.5,cacheCreate:2},"gpt-4.1-mini":{input:.4,output:1.6,cacheRead:.1,cacheCreate:.4},"gpt-4.1-nano":{input:.1,output:.4,cacheRead:.025,cacheCreate:.1},"gpt-4o":{input:2.5,output:10,cacheRead:1.25,cacheCreate:2.5},"gpt-4o-mini":{input:.15,output:.6,cacheRead:.075,cacheCreate:.15},o3:{input:2,output:8,cacheRead:.5,cacheCreate:2},"o4-mini":{input:1.1,output:4.4,cacheRead:.275,cacheCreate:1.1},"gemini-2.5-pro":{input:1.25,output:10,cacheRead:.125,cacheCreate:1.25},"gemini-2.5-flash":{input:.3,output:2.5,cacheRead:.03,cacheCreate:.3},"gemini-2.5-flash-lite":{input:.1,output:.4,cacheRead:.01,cacheCreate:.1},"gemini-3-flash":{input:.5,output:3,cacheRead:.05,cacheCreate:.5},"gemini-3.1-pro":{input:2,output:12,cacheRead:.2,cacheCreate:2},"gemini-3.1-flash-lite":{input:.25,output:1.5,cacheRead:.025,cacheCreate:.25}},E={...w,...F},K=i=>/claude|fable|mythos|opus|sonnet|haiku/i.test(i);function j(i,e=E){if(K(i))return null;let t=i.toLowerCase().replace(/^.*\//,""),n=null;for(let r of Object.keys(e))r.startsWith("claude-")||(t===r||t.startsWith(`${r}-`))&&(!n||r.length>n.length)&&(n=r);return n}var W=2e5,M=1.5;function J(i){let e=i.toLowerCase(),t=(...n)=>n.some(r=>e.includes(r));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function L(i,e,t=E){return i?K(i)||j(i,t)!==null:e==="claude-code"}function B(i){return i.inputTokens+i.cacheReadTokens+i.cacheCreateTokens>W?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:i.inputTokens,tier2OutputTokens:i.outputTokens,tier2CacheReadTokens:i.cacheReadTokens,tier2CacheCreateTokens:i.cacheCreateTokens}:{inputTokens:i.inputTokens,outputTokens:i.outputTokens,cacheReadTokens:i.cacheReadTokens,cacheCreateTokens:i.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var N=500,X=".agentx/pricing/custom.json",D=class{dir;cache=null;pricing;constructor(e=_(process.cwd(),".agentx/usage")){this.dir=e,G(this.dir,{recursive:!0}),this.pricing=V()}getPricing(){return this.pricing}static calculateCost(e,t,n=w){let r=J(t||e.model||"claude-sonnet"),a=n[r]||n["claude-sonnet"],u=e.tier2InputTokens||0,k=e.tier2OutputTokens||0,l=e.tier2CacheReadTokens||0,o=e.tier2CacheCreateTokens||0,p=(e.inputTokens||0)/1e6*a.input+(e.outputTokens||0)/1e6*a.output+(e.cacheReadTokens||0)/1e6*a.cacheRead+(e.cacheCreateTokens||0)/1e6*a.cacheCreate,s=u/1e6*a.input+k/1e6*a.output+l/1e6*a.cacheRead+o/1e6*a.cacheCreate;return p+s*M}cost(e,t){return D.calculateCost(e,t,this.pricing)}runCost(e,t,n){if(!L(t,n,this.pricing))return;let r=t?j(t,this.pricing):null;if(!r)return this.cost({tasks:1,totalDuration:0,errors:0,...B(e)},t);let a=this.pricing[r];return((e.inputTokens||0)*a.input+(e.outputTokens||0)*a.output+(e.cacheReadTokens||0)*a.cacheRead+(e.cacheCreateTokens||0)*a.cacheCreate)/1e6}record(e,t,n,r,a,u,k,l,o){let p=this.today(),s=p.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};s.tasks++,s.totalDuration+=t,k&&(s.model=k);let m=0,R=0,g=0,T=0,h=0,b=0,c=0,f=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>W?(h=n.inputTokens,b=n.outputTokens,c=n.cacheReadTokens,f=n.cacheCreateTokens):(m=n.inputTokens,R=n.outputTokens,g=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&a!==void 0&&(m=Math.ceil(r/4),R=Math.ceil(a/4)),s.inputTokens+=m,s.outputTokens+=R,s.cacheReadTokens+=g,s.cacheCreateTokens+=T,s.tier2InputTokens=(s.tier2InputTokens||0)+h,s.tier2OutputTokens=(s.tier2OutputTokens||0)+b,s.tier2CacheReadTokens=(s.tier2CacheReadTokens||0)+c,s.tier2CacheCreateTokens=(s.tier2CacheCreateTokens||0)+f,u&&s.errors++,s.byChannel||(s.byChannel={});let y=(l||"other").toLowerCase(),C=s.byChannel[y]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};C.tasks++,C.totalDuration+=t,C.inputTokens+=m,C.outputTokens+=R,C.cacheReadTokens+=g,C.cacheCreateTokens+=T,C.tier2InputTokens+=h,C.tier2OutputTokens+=b,C.tier2CacheReadTokens+=c,C.tier2CacheCreateTokens+=f,u&&C.errors++,s.byChannel[y]=C,o&&(s.sessionKeys||(s.sessionKeys=[]),s.sessionKeys.includes(o)||(s.sessionKeys.push(o),s.sessionKeys.length>N&&s.sessionKeys.splice(0,s.sessionKeys.length-N))),p.agents[e]=s,this.save(p)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(I(t))try{return this.cache=JSON.parse(O(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!I(t))return null;try{return JSON.parse(O(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,a=0,u=0,k=0,l=0,o=0,p="",s=0,m={},R={},g={};for(let[T,h]of Object.entries(n.agents)){let b=this.cost(h);m[T]=b,r+=h.tasks,a+=(h.inputTokens||0)+(h.tier2InputTokens||0),u+=(h.outputTokens||0)+(h.tier2OutputTokens||0),k+=(h.cacheReadTokens||0)+(h.tier2CacheReadTokens||0),l+=(h.cacheCreateTokens||0)+(h.tier2CacheCreateTokens||0),o+=b,b>s&&(s=b,p=T);let c=h.sessionKeys?.length||0;R[T]={sessions:c,avgTasksPerSession:c>0?h.tasks/c:h.tasks};for(let[f,y]of Object.entries(h.byChannel||{})){let C=this.cost(y,h.model);g[f]=(g[f]||0)+C}}return{date:t,totalTasks:r,totalInput:a,totalOutput:u,totalCacheRead:k,totalCacheCreate:l,totalCost:o,topAgent:p,topCost:s,agentCosts:m,agentSessionStats:R,byChannel:g}}appendToTokenCosts(e,t){let n=t||_(process.cwd(),".agentx/TOKEN_COSTS.md"),r=o=>o<.01?o.toFixed(4):o.toFixed(2),a=o=>o>=1e6?`${(o/1e6).toFixed(1)}M`:o>=1e3?`${(o/1e3).toFixed(0)}K`:String(o),u=Object.entries(e.agentCosts).sort(([,o],[,p])=>p-o).map(([o,p])=>{let s=e.agentSessionStats[o],m=s&&s.sessions>0?` (${s.sessions}s, ${s.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${o}: $${r(p)}${m}`}).join(", "),k=Object.entries(e.byChannel).sort(([,o],[,p])=>p-o).map(([o,p])=>`${o}: $${r(p)}`).join(", "),l=`| ${e.date} | ${e.totalTasks} | ${a(e.totalInput)} | ${a(e.totalOutput)} | ${a(e.totalCacheRead)} | ${a(e.totalCacheCreate)} | $${r(e.totalCost)} | ${u} | ${k} |`;I(n)?U(n,l+`
2
+ `):v(n,`# Token Costs
3
+
4
+ Daily token cost tracking. Auto-appended at midnight, host time.
5
+ Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
6
+
7
+ | Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
8
+ |------|-------|-------|--------|---------|---------|------|-----------|-------------|
9
+ `+l+`
10
+ `)}hasTokenCostsEntry(e,t){let n=t||_(process.cwd(),".agentx/TOKEN_COSTS.md");if(!I(n))return!1;try{let r=O(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||_(process.cwd(),".agentx/TOKEN_COSTS.md");if(!I(t))return null;try{let r=O(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let a=r.map(u=>u.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(u=>!!u);return a.sort(),a[a.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],a=this.lastTokenCostsDate(t.filePath),u=[],k=new Date(`${e}T00:00:00Z`);for(let l=0;l<n;l++){let o=k.toISOString().slice(0,10);if(a&&o<=a)break;u.push(o),k.setUTCDate(k.getUTCDate()-1)}u.reverse();for(let l of u){if(this.hasTokenCostsEntry(l,t.filePath))continue;let o=this.generateDailyReport(l);!o||o.totalTasks===0||(this.appendToTokenCosts(o,t.filePath),r.push(l))}return r}summary(e=7){let t=0,n=0,r=0,a=0,u=0,k=0,l=0,o={},p={};for(let g=0;g<e;g++){let T=new Date(Date.now()-g*864e5).toISOString().slice(0,10),h=this.getDate(T);if(h)for(let[b,c]of Object.entries(h.agents)){let f=this.cost(c);t+=c.tasks;let y=(c.inputTokens||0)+(c.tier2InputTokens||0),C=(c.outputTokens||0)+(c.tier2OutputTokens||0),S=(c.cacheReadTokens||0)+(c.tier2CacheReadTokens||0),P=(c.cacheCreateTokens||0)+(c.tier2CacheCreateTokens||0);n+=y,r+=C,a+=S,u+=P,k+=c.errors,l+=f;let d=o[b]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};d.tasks+=c.tasks,d.input+=y,d.output+=C,d.cacheRead+=S,d.cacheCreate+=P,d.total=d.input+d.output+d.cacheRead+d.cacheCreate,d.totalDuration+=c.totalDuration,d.avgDuration=d.totalDuration/d.tasks,d.cost+=f,d.sessions+=c.sessionKeys?.length||0,c.model&&(d.model=c.model),o[b]=d;for(let[x,$]of Object.entries(c.byChannel||{})){let H=this.cost($,c.model),A=p[x]||{tasks:0,cost:0};A.tasks+=$.tasks,A.cost+=H,p[x]=A}}}let s=n+r+a+u,m=a+u>0?a/(a+u):0,R={};for(let[g,T]of Object.entries(o))R[g]={sessions:T.sessions,avgTasksPerSession:T.sessions>0?T.tasks/T.sessions:T.tasks};return{totalTasks:t,totalTokens:s,totalInput:n,totalOutput:r,totalCacheRead:a,totalCacheCreate:u,cacheHitRatio:m,totalErrors:k,totalCost:l,byAgent:o,byChannel:p,sessionStats:R}}filePath(e){return _(this.dir,`${e}.json`)}save(e){try{v(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function V(i=X){let e=JSON.parse(JSON.stringify(E));try{let t=_(process.cwd(),i);if(!I(t))return e;let n=JSON.parse(O(t,"utf-8"));for(let[r,a]of Object.entries(n))e[r]||(e[r]={input:0,output:0,cacheRead:0,cacheCreate:0}),Object.assign(e[r],a)}catch{}return e}export{w as a,F as b,j as c,W as d,M as e,J as f,L as g,B as h,D as i,V as j};
11
+ //# sourceMappingURL=chunk-BE64IJWM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/daemon/token-tracker.ts"],"sourcesContent":["import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Token usage tracker ---\n// Tracks token usage per agent per day with cache-aware, tier-aware cost\n// calculation. Persisted to .agentx/usage/{YYYY-MM-DD}.json.\n//\n// Design notes:\n// - Pricing is per-model-FAMILY (opus/sonnet/haiku). Exact model name\n// variants map via getModelFamily(). Override the table by dropping\n// .agentx/pricing/custom.json (same shape) — merged over defaults at\n// construction, lets operators adjust without a rebuild.\n// - Anthropic bills 1.5× input/output when a single request's total input\n// (input + cacheCreate + cacheRead) exceeds 200K tokens. We split each\n// recorded task into tier1/tier2 buckets and bill them separately so\n// long-context sessions are not undercounted.\n// - Per-channel breakdowns let operators see \"GitLab drove 70% of today's\n// spend\" — the lever for channel-specific session + context tuning.\n// - Session tracking (unique chatId:channel pairs seen today per agent)\n// gives an avg-tasks-per-session proxy — when it spikes, it's usually\n// retry/clarification chains, a signal the context budget or model\n// capability is under-sized for that traffic.\n\n// Anthropic pricing per million tokens (as of April 2026, 5-min ephemeral).\n// Keys here must match getModelFamily() output.\n//\n// IMPORTANT: Opus 4.6 is 3× cheaper than Opus 4.1. Haiku 4.5 is more expensive\n// than Haiku 3.5. Our getModelFamily() resolves the exact version so the cost\n// report matches what Anthropic actually bills. Source: LiteLLM pricing cache\n// at ~/.cache/codeburn/litellm-pricing.json + codeburn/src/models.ts.\n//\n// Cache multipliers (consistent across all models):\n// cache write (5-min ephemeral) = 1.25 × input\n// cache read = 0.10 × input\nexport const CACHE_AWARE_PRICING: Record<string, { input: number; output: number; cacheRead: number; cacheCreate: number }> = {\n // Fable 5.1 / 5 — $10/$50 per MTok\n \"claude-fable\": { input: 10, output: 50, cacheRead: 1, cacheCreate: 12.5 },\n // Opus 5 / 4.8 / 4.7 / 4.6 / 4.5 — $5/$25 per MTok\n \"claude-opus-5\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n \"claude-opus-4-8\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n \"claude-opus-4-7\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n \"claude-opus-4-6\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n \"claude-opus-4-5\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n // Opus 4.1 and earlier — $15/$75 per MTok (legacy, keep for historical runs)\n \"claude-opus\": { input: 15, output: 75, cacheRead: 1.5, cacheCreate: 18.75 },\n // Sonnet 5 — $2/$10 per MTok\n \"claude-sonnet-5\": { input: 2, output: 10, cacheRead: 0.2, cacheCreate: 2.5 },\n // Sonnet 4.6 / 4.5 — $3/$15 per MTok\n \"claude-sonnet\": { input: 3, output: 15, cacheRead: 0.3, cacheCreate: 3.75 },\n // Haiku 4.5 — $1/$5 per MTok (more expensive than Haiku 3.5)\n \"claude-haiku\": { input: 1, output: 5, cacheRead: 0.1, cacheCreate: 1.25 },\n}\n\n// List prices of other providers' API models, per million tokens (checked\n// 2026-10-25 against public price lists). Used for budgets only (#1290):\n// getModelFamily() never returns these keys, so the usage report is\n// unchanged. A key matches a model id that equals it or continues with \"-\"\n// (a dated snapshot or variant), longest key first: \"gpt-5-mini-2025-08-07\"\n// is \"gpt-5-mini\", \"gpt-5.5\" matches nothing and stays unpriced. Add a model\n// the same way in .agentx/pricing/custom.json. Neither provider charges for\n// writing the cache, so cacheCreate is the input rate.\nexport const API_MODEL_PRICING: typeof CACHE_AWARE_PRICING = {\n // OpenAI\n \"gpt-5\": { input: 1.25, output: 10, cacheRead: 0.125, cacheCreate: 1.25 },\n \"gpt-5.1\": { input: 1.25, output: 10, cacheRead: 0.125, cacheCreate: 1.25 },\n \"gpt-5-mini\": { input: 0.25, output: 2, cacheRead: 0.025, cacheCreate: 0.25 },\n \"gpt-5-nano\": { input: 0.05, output: 0.4, cacheRead: 0.005, cacheCreate: 0.05 },\n \"gpt-4.1\": { input: 2, output: 8, cacheRead: 0.5, cacheCreate: 2 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6, cacheRead: 0.1, cacheCreate: 0.4 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4, cacheRead: 0.025, cacheCreate: 0.1 },\n \"gpt-4o\": { input: 2.5, output: 10, cacheRead: 1.25, cacheCreate: 2.5 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6, cacheRead: 0.075, cacheCreate: 0.15 },\n \"o3\": { input: 2, output: 8, cacheRead: 0.5, cacheCreate: 2 },\n \"o4-mini\": { input: 1.1, output: 4.4, cacheRead: 0.275, cacheCreate: 1.1 },\n // Google (prompts up to 200K tokens)\n \"gemini-2.5-pro\": { input: 1.25, output: 10, cacheRead: 0.125, cacheCreate: 1.25 },\n \"gemini-2.5-flash\": { input: 0.3, output: 2.5, cacheRead: 0.03, cacheCreate: 0.3 },\n \"gemini-2.5-flash-lite\": { input: 0.1, output: 0.4, cacheRead: 0.01, cacheCreate: 0.1 },\n \"gemini-3-flash\": { input: 0.5, output: 3, cacheRead: 0.05, cacheCreate: 0.5 },\n \"gemini-3.1-pro\": { input: 2, output: 12, cacheRead: 0.2, cacheCreate: 2 },\n \"gemini-3.1-flash-lite\": { input: 0.25, output: 1.5, cacheRead: 0.025, cacheCreate: 0.25 },\n}\n\n/** Claude and API list prices together: the table before any override. */\nconst DEFAULT_PRICING: typeof CACHE_AWARE_PRICING = { ...CACHE_AWARE_PRICING, ...API_MODEL_PRICING }\n\nconst isClaudeModel = (model: string): boolean => /claude|fable|mythos|opus|sonnet|haiku/i.test(model)\n\n/**\n * The key of `table` that prices a non-Claude model, or null. Matches the\n * whole id or a \"-\" continuation, after any \"provider/\" prefix, longest\n * key first.\n */\nexport function apiModelFamily(model: string, table: typeof CACHE_AWARE_PRICING = DEFAULT_PRICING): string | null {\n if (isClaudeModel(model)) return null\n const id = model.toLowerCase().replace(/^.*\\//, \"\")\n let best: string | null = null\n for (const key of Object.keys(table)) {\n if (key.startsWith(\"claude-\")) continue\n if ((id === key || id.startsWith(`${key}-`)) && (!best || key.length > best.length)) best = key\n }\n return best\n}\n\n/** Per-request input size (input + cacheCreate + cacheRead) above this\n * threshold triggers Anthropic's extended-context tier: all four rates\n * get multiplied. Applies to Opus 4.x and Sonnet 4.x 1M variants. */\nexport const CONTEXT_TIER_THRESHOLD = 200_000\nexport const TIER2_MULTIPLIER = 1.5\n\n/** Map a model id onto a pricing family.\n *\n * Version matching is explicit and most-specific-first. Getting this wrong\n * is not a rounding error: an Opus id that falls through to the legacy\n * 4.1 family is priced at $15/$75 instead of $5/$25 and every cost figure\n * derived from it is inflated 3×. That is exactly what happened to the\n * whole fleet once it moved to claude-opus-5 — \"opus\" matched, no version\n * branch did, and the legacy fallback caught it silently.\n *\n * So an UNRECOGNISED Opus version now resolves to the current $5/$25 tier\n * rather than the legacy one. Every Opus from 4.5 onward has been $5/$25;\n * treating tomorrow's release as 4.1-era is the more likely and more\n * expensive mistake, and the genuinely old ids still match explicitly. */\nexport function getModelFamily(model: string): string {\n const lower = model.toLowerCase()\n const has = (...needles: string[]) => needles.some((n) => lower.includes(n))\n\n if (has(\"fable\", \"mythos\")) return \"claude-fable\"\n\n if (lower.includes(\"opus\")) {\n if (has(\"opus-5\", \"opus5\", \"opus-5-\")) return \"claude-opus-5\"\n if (has(\"4-8\", \"4.8\")) return \"claude-opus-4-8\"\n if (has(\"4-7\", \"4.7\")) return \"claude-opus-4-7\"\n if (has(\"4-6\", \"4.6\")) return \"claude-opus-4-6\"\n if (has(\"4-5\", \"4.5\")) return \"claude-opus-4-5\"\n // Named legacy generations, which really are $15/$75.\n if (has(\"4-1\", \"4.1\", \"opus-3\", \"opus3\", \"-3-\")) return \"claude-opus\"\n // Unknown/new Opus — assume the current tier, not the legacy one.\n return \"claude-opus-5\"\n }\n\n if (lower.includes(\"haiku\")) return \"claude-haiku\"\n if (has(\"sonnet-5\", \"sonnet5\")) return \"claude-sonnet-5\"\n return \"claude-sonnet\"\n}\n\n/**\n * Whether `model` is one the pricing table really prices. getModelFamily()\n * maps every unknown model to Sonnet, which is fine for a display estimate\n * but not for spend that pauses an agent (#1162): a local, Codex or Gemini\n * model must not be charged Claude rates. No model counts only on the\n * claude-code tier, whose engine is Claude. Other providers' API models\n * count when the table lists them (#1290); local models never do.\n */\nexport function isPricedModel(model: string | undefined, tier?: string, table: typeof CACHE_AWARE_PRICING = DEFAULT_PRICING): boolean {\n if (!model) return tier === \"claude-code\"\n return isClaudeModel(model) || apiModelFamily(model, table) !== null\n}\n\nexport interface ChannelUsage {\n tasks: number\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheCreateTokens: number\n tier2InputTokens: number\n tier2OutputTokens: number\n tier2CacheReadTokens: number\n tier2CacheCreateTokens: number\n totalDuration: number\n errors: number\n}\n\nexport interface AgentUsage {\n tasks: number\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheCreateTokens: number\n /** Tokens from requests whose input crossed CONTEXT_TIER_THRESHOLD (billed at\n * TIER2_MULTIPLIER × normal rate). Kept separate from the tier1 buckets so\n * cost math stays honest when a session accumulates past 200K. */\n tier2InputTokens?: number\n tier2OutputTokens?: number\n tier2CacheReadTokens?: number\n tier2CacheCreateTokens?: number\n totalDuration: number\n errors: number\n model?: string\n /** Per-channel breakdown so we can attribute cost to Telegram vs GitLab vs WhatsApp. */\n byChannel?: Record<string, ChannelUsage>\n /** Unique session identifiers (channel:chatId) this agent participated in\n * today. Used to derive avg tasks/session. Capped at 500 entries to keep\n * the daily JSON small. */\n sessionKeys?: string[]\n}\n\nexport interface DailyUsage {\n date: string\n agents: Record<string, AgentUsage>\n}\n\nexport interface DailyReport {\n date: string\n totalTasks: number\n totalInput: number\n totalOutput: number\n totalCacheRead: number\n totalCacheCreate: number\n totalCost: number\n topAgent: string\n topCost: number\n agentCosts: Record<string, number>\n /** Per-agent avg tasks/session — high values suggest retry chains. */\n agentSessionStats: Record<string, { sessions: number; avgTasksPerSession: number }>\n /** Aggregate cost by channel across all agents. */\n byChannel: Record<string, number>\n}\n\n/** Shape of a per-request usage report coming from the runtime. Keeps the\n * record() signature tidy and lets callers opt into tier2 accounting. */\nexport interface TaskUsage {\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheCreateTokens: number\n}\n\n/** Split a TaskUsage into tier1 and tier2 buckets using the same\n * CONTEXT_TIER_THRESHOLD that record() applies. Output inherits the\n * tier of its request. Returned as a flat object so callers can spread\n * it directly into bus payloads or DB writes. */\nexport function splitTaskUsageByTier(u: TaskUsage): {\n inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheCreateTokens: number\n tier2InputTokens: number; tier2OutputTokens: number; tier2CacheReadTokens: number; tier2CacheCreateTokens: number\n} {\n const totalInput = u.inputTokens + u.cacheReadTokens + u.cacheCreateTokens\n if (totalInput > CONTEXT_TIER_THRESHOLD) {\n return {\n inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0,\n tier2InputTokens: u.inputTokens, tier2OutputTokens: u.outputTokens,\n tier2CacheReadTokens: u.cacheReadTokens, tier2CacheCreateTokens: u.cacheCreateTokens,\n }\n }\n return {\n inputTokens: u.inputTokens, outputTokens: u.outputTokens,\n cacheReadTokens: u.cacheReadTokens, cacheCreateTokens: u.cacheCreateTokens,\n tier2InputTokens: 0, tier2OutputTokens: 0, tier2CacheReadTokens: 0, tier2CacheCreateTokens: 0,\n }\n}\n\nconst SESSION_KEYS_MAX = 500\nconst PRICING_OVERRIDE_PATH = \".agentx/pricing/custom.json\"\n\nexport class TokenTracker {\n private dir: string\n private cache: DailyUsage | null = null\n private pricing: typeof CACHE_AWARE_PRICING\n\n constructor(baseDir: string = resolve(process.cwd(), \".agentx/usage\")) {\n this.dir = baseDir\n mkdirSync(this.dir, { recursive: true })\n this.pricing = loadPricingWithOverrides()\n }\n\n /** Returns the active pricing table (hardcoded defaults with any per-model\n * overrides merged in). Useful for UI / debugging. */\n getPricing(): typeof CACHE_AWARE_PRICING {\n return this.pricing\n }\n\n /**\n * Calculate cost for a slice of usage. Accepts either a full AgentUsage or\n * a narrowed ChannelUsage — both expose the same token buckets we price on.\n * Tier2 tokens are billed at TIER2_MULTIPLIER × the normal rate.\n */\n static calculateCost(usage: AgentUsage | ChannelUsage, model?: string, pricingTable: typeof CACHE_AWARE_PRICING = CACHE_AWARE_PRICING): number {\n const family = getModelFamily(model || (usage as AgentUsage).model || \"claude-sonnet\")\n const p = pricingTable[family] || pricingTable[\"claude-sonnet\"]\n const tier2In = (usage as any).tier2InputTokens || 0\n const tier2Out = (usage as any).tier2OutputTokens || 0\n const tier2CR = (usage as any).tier2CacheReadTokens || 0\n const tier2CW = (usage as any).tier2CacheCreateTokens || 0\n\n const tier1 =\n ((usage.inputTokens || 0) / 1_000_000) * p.input +\n ((usage.outputTokens || 0) / 1_000_000) * p.output +\n ((usage.cacheReadTokens || 0) / 1_000_000) * p.cacheRead +\n ((usage.cacheCreateTokens || 0) / 1_000_000) * p.cacheCreate\n\n const tier2 =\n (tier2In / 1_000_000) * p.input +\n (tier2Out / 1_000_000) * p.output +\n (tier2CR / 1_000_000) * p.cacheRead +\n (tier2CW / 1_000_000) * p.cacheCreate\n\n return tier1 + tier2 * TIER2_MULTIPLIER\n }\n\n /**\n * Instance-level cost calculation — uses the tracker's resolved pricing\n * table so any custom override file is honored. Prefer this over the\n * static variant when available.\n */\n cost(usage: AgentUsage | ChannelUsage, model?: string): number {\n return TokenTracker.calculateCost(usage, model, this.pricing)\n }\n\n /**\n * What one run cost at list price, for budgets (#1162, #1290): Claude\n * models through cost(), other providers' API models at their flat rate\n * (no long-prompt surcharge), undefined for a model with no price.\n */\n runCost(usage: TaskUsage, model: string | undefined, tier?: string): number | undefined {\n if (!isPricedModel(model, tier, this.pricing)) return undefined\n const family = model ? apiModelFamily(model, this.pricing) : null\n if (!family) return this.cost({ tasks: 1, totalDuration: 0, errors: 0, ...splitTaskUsageByTier(usage) }, model)\n const p = this.pricing[family]\n return ((usage.inputTokens || 0) * p.input +\n (usage.outputTokens || 0) * p.output +\n (usage.cacheReadTokens || 0) * p.cacheRead +\n (usage.cacheCreateTokens || 0) * p.cacheCreate) / 1_000_000\n }\n\n /**\n * Record a task execution with real or estimated token counts.\n *\n * `channel` attributes the cost to a surface (telegram/gitlab/whatsapp/cron).\n * `sessionKey` is an opaque \"this chat on this day\" identifier — we use it\n * to count unique sessions so an avg-tasks-per-session metric falls out.\n */\n record(\n agentId: string,\n duration: number,\n realUsage?: TaskUsage,\n messageLength?: number,\n responseLength?: number,\n error?: boolean,\n model?: string,\n channel?: string,\n sessionKey?: string,\n ): void {\n const daily = this.today()\n const agent = daily.agents[agentId] || {\n tasks: 0, inputTokens: 0, outputTokens: 0,\n cacheReadTokens: 0, cacheCreateTokens: 0,\n tier2InputTokens: 0, tier2OutputTokens: 0,\n tier2CacheReadTokens: 0, tier2CacheCreateTokens: 0,\n totalDuration: 0, errors: 0, byChannel: {}, sessionKeys: [],\n }\n\n agent.tasks++\n agent.totalDuration += duration\n if (model) agent.model = model\n\n // Split this request into tier1/tier2 based on its TOTAL input size\n // (input + cacheCreate + cacheRead). Output inherits the tier of its\n // request. Estimated paths (no realUsage) are always tier1 — they're\n // too small to reach the threshold.\n let i1 = 0, o1 = 0, cr1 = 0, cw1 = 0, i2 = 0, o2 = 0, cr2 = 0, cw2 = 0\n if (realUsage) {\n const totalInput = realUsage.inputTokens + realUsage.cacheReadTokens + realUsage.cacheCreateTokens\n if (totalInput > CONTEXT_TIER_THRESHOLD) {\n i2 = realUsage.inputTokens\n o2 = realUsage.outputTokens\n cr2 = realUsage.cacheReadTokens\n cw2 = realUsage.cacheCreateTokens\n } else {\n i1 = realUsage.inputTokens\n o1 = realUsage.outputTokens\n cr1 = realUsage.cacheReadTokens\n cw1 = realUsage.cacheCreateTokens\n }\n } else if (messageLength !== undefined && responseLength !== undefined) {\n i1 = Math.ceil(messageLength / 4)\n o1 = Math.ceil(responseLength / 4)\n }\n\n agent.inputTokens += i1\n agent.outputTokens += o1\n agent.cacheReadTokens += cr1\n agent.cacheCreateTokens += cw1\n agent.tier2InputTokens = (agent.tier2InputTokens || 0) + i2\n agent.tier2OutputTokens = (agent.tier2OutputTokens || 0) + o2\n agent.tier2CacheReadTokens = (agent.tier2CacheReadTokens || 0) + cr2\n agent.tier2CacheCreateTokens = (agent.tier2CacheCreateTokens || 0) + cw2\n\n if (error) agent.errors++\n\n // Per-channel attribution. Unknown channel falls into \"other\".\n if (!agent.byChannel) agent.byChannel = {}\n const chKey = (channel || \"other\").toLowerCase()\n const ch = agent.byChannel[chKey] || {\n tasks: 0, inputTokens: 0, outputTokens: 0,\n cacheReadTokens: 0, cacheCreateTokens: 0,\n tier2InputTokens: 0, tier2OutputTokens: 0,\n tier2CacheReadTokens: 0, tier2CacheCreateTokens: 0,\n totalDuration: 0, errors: 0,\n }\n ch.tasks++\n ch.totalDuration += duration\n ch.inputTokens += i1; ch.outputTokens += o1\n ch.cacheReadTokens += cr1; ch.cacheCreateTokens += cw1\n ch.tier2InputTokens += i2; ch.tier2OutputTokens += o2\n ch.tier2CacheReadTokens += cr2; ch.tier2CacheCreateTokens += cw2\n if (error) ch.errors++\n agent.byChannel[chKey] = ch\n\n // Session tracking — dedup sessions by opaque key (normally channel:chatId).\n if (sessionKey) {\n if (!agent.sessionKeys) agent.sessionKeys = []\n if (!agent.sessionKeys.includes(sessionKey)) {\n agent.sessionKeys.push(sessionKey)\n if (agent.sessionKeys.length > SESSION_KEYS_MAX) {\n agent.sessionKeys.splice(0, agent.sessionKeys.length - SESSION_KEYS_MAX)\n }\n }\n }\n\n daily.agents[agentId] = agent\n this.save(daily)\n }\n\n /**\n * Get today's usage summary.\n */\n today(): DailyUsage {\n const date = new Date().toISOString().slice(0, 10)\n\n if (this.cache?.date === date) return this.cache\n\n const path = this.filePath(date)\n if (existsSync(path)) {\n try {\n this.cache = JSON.parse(readFileSync(path, \"utf-8\"))\n return this.cache!\n } catch {}\n }\n\n this.cache = { date, agents: {} }\n return this.cache\n }\n\n /**\n * Get usage for a specific date.\n */\n getDate(date: string): DailyUsage | null {\n const path = this.filePath(date)\n if (!existsSync(path)) return null\n try {\n return JSON.parse(readFileSync(path, \"utf-8\"))\n } catch {\n return null\n }\n }\n\n /**\n * Generate a daily cost report for a given date. Includes per-agent,\n * per-channel costs and session statistics.\n */\n generateDailyReport(date?: string): DailyReport | null {\n const targetDate = date || new Date().toISOString().slice(0, 10)\n const usage = this.getDate(targetDate)\n if (!usage) return null\n\n let totalTasks = 0, totalInput = 0, totalOutput = 0\n let totalCacheRead = 0, totalCacheCreate = 0, totalCost = 0\n let topAgent = \"\", topCost = 0\n const agentCosts: Record<string, number> = {}\n const agentSessionStats: Record<string, { sessions: number; avgTasksPerSession: number }> = {}\n const byChannel: Record<string, number> = {}\n\n for (const [id, agent] of Object.entries(usage.agents)) {\n const cost = this.cost(agent)\n agentCosts[id] = cost\n totalTasks += agent.tasks\n totalInput += (agent.inputTokens || 0) + (agent.tier2InputTokens || 0)\n totalOutput += (agent.outputTokens || 0) + (agent.tier2OutputTokens || 0)\n totalCacheRead += (agent.cacheReadTokens || 0) + (agent.tier2CacheReadTokens || 0)\n totalCacheCreate += (agent.cacheCreateTokens || 0) + (agent.tier2CacheCreateTokens || 0)\n totalCost += cost\n if (cost > topCost) { topCost = cost; topAgent = id }\n\n const sessions = agent.sessionKeys?.length || 0\n agentSessionStats[id] = {\n sessions,\n avgTasksPerSession: sessions > 0 ? agent.tasks / sessions : agent.tasks,\n }\n\n for (const [chKey, ch] of Object.entries(agent.byChannel || {})) {\n const chCost = this.cost(ch, agent.model)\n byChannel[chKey] = (byChannel[chKey] || 0) + chCost\n }\n }\n\n return {\n date: targetDate, totalTasks, totalInput, totalOutput,\n totalCacheRead, totalCacheCreate, totalCost, topAgent, topCost, agentCosts,\n agentSessionStats, byChannel,\n }\n }\n\n /**\n * Append a daily report row to TOKEN_COSTS.md. Adds channel + session\n * breakdown inline for at-a-glance spend attribution.\n */\n appendToTokenCosts(report: DailyReport, filePath?: string): void {\n const file = filePath || resolve(process.cwd(), \".agentx/TOKEN_COSTS.md\")\n const fmt = (n: number) => n < 0.01 ? n.toFixed(4) : n.toFixed(2)\n const fmtTok = (n: number) =>\n n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` :\n n >= 1_000 ? `${(n / 1_000).toFixed(0)}K` :\n String(n)\n\n const agentBreakdown = Object.entries(report.agentCosts)\n .sort(([, a], [, b]) => b - a)\n .map(([id, cost]) => {\n const stats = report.agentSessionStats[id]\n const sessTag = stats && stats.sessions > 0 ? ` (${stats.sessions}s, ${stats.avgTasksPerSession.toFixed(1)}t/s)` : \"\"\n return `${id}: $${fmt(cost)}${sessTag}`\n })\n .join(\", \")\n\n const channelBreakdown = Object.entries(report.byChannel)\n .sort(([, a], [, b]) => b - a)\n .map(([ch, cost]) => `${ch}: $${fmt(cost)}`)\n .join(\", \")\n\n const row = `| ${report.date} | ${report.totalTasks} | ${fmtTok(report.totalInput)} | ${fmtTok(report.totalOutput)} | ${fmtTok(report.totalCacheRead)} | ${fmtTok(report.totalCacheCreate)} | $${fmt(report.totalCost)} | ${agentBreakdown} | ${channelBreakdown} |`\n\n if (!existsSync(file)) {\n const header =\n \"# Token Costs\\n\\n\" +\n \"Daily token cost tracking. Auto-appended at midnight, host time.\\n\" +\n \"Agent breakdown: `agent: $cost (Ns, T.Tt/s)` — sessions, tasks/session.\\n\\n\" +\n \"| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |\\n\" +\n \"|------|-------|-------|--------|---------|---------|------|-----------|-------------|\\n\"\n writeFileSync(file, header + row + \"\\n\")\n } else {\n appendFileSync(file, row + \"\\n\")\n }\n }\n\n /**\n * Return true if TOKEN_COSTS.md already has a row for `date`. Lets callers\n * skip duplicate appends after daemon restarts or timer-edge double fires.\n */\n hasTokenCostsEntry(date: string, filePath?: string): boolean {\n const file = filePath || resolve(process.cwd(), \".agentx/TOKEN_COSTS.md\")\n if (!existsSync(file)) return false\n try {\n const content = readFileSync(file, \"utf-8\")\n // Rows look like: `| 2026-04-18 | ...`\n return new RegExp(`^\\\\|\\\\s*${date}\\\\s*\\\\|`, \"m\").test(content)\n } catch {\n return false\n }\n }\n\n /**\n * Find the most recent date already logged to TOKEN_COSTS.md (YYYY-MM-DD).\n * Returns null when the file doesn't exist or has no rows.\n */\n lastTokenCostsDate(filePath?: string): string | null {\n const file = filePath || resolve(process.cwd(), \".agentx/TOKEN_COSTS.md\")\n if (!existsSync(file)) return null\n try {\n const content = readFileSync(file, \"utf-8\")\n const dates = content.match(/^\\|\\s*(\\d{4}-\\d{2}-\\d{2})\\s*\\|/gm) ?? []\n if (dates.length === 0) return null\n // Extract the date portion and pick the max — rows can be out of order\n // after a catch-up, so don't rely on file order.\n const parsed = dates\n .map((m) => m.match(/(\\d{4}-\\d{2}-\\d{2})/)?.[1])\n .filter((d): d is string => !!d)\n parsed.sort()\n return parsed[parsed.length - 1] ?? null\n } catch {\n return null\n }\n }\n\n /**\n * Append reports for any days between (lastLogged + 1) and `throughDate`\n * that have usage on disk but no row in TOKEN_COSTS.md. Idempotent —\n * safe to call on every daemon startup. Bounded to `maxDays` to avoid\n * a stalled daemon backfilling a year's worth on first start.\n *\n * Returns the list of dates actually appended, for logging.\n */\n catchUpTokenCosts(\n throughDate: string,\n opts: { maxDays?: number; filePath?: string } = {},\n ): string[] {\n const maxDays = opts.maxDays ?? 30\n const appended: string[] = []\n\n const last = this.lastTokenCostsDate(opts.filePath)\n // Walk backward from throughDate, collecting dates to fill. Stop at the\n // last-logged date (exclusive) or after maxDays, whichever comes first.\n const candidates: string[] = []\n const cursor = new Date(`${throughDate}T00:00:00Z`)\n for (let i = 0; i < maxDays; i++) {\n const date = cursor.toISOString().slice(0, 10)\n if (last && date <= last) break\n candidates.push(date)\n cursor.setUTCDate(cursor.getUTCDate() - 1)\n }\n // Oldest-first so the file stays chronological.\n candidates.reverse()\n\n for (const date of candidates) {\n if (this.hasTokenCostsEntry(date, opts.filePath)) continue\n const report = this.generateDailyReport(date)\n if (!report || report.totalTasks === 0) continue\n this.appendToTokenCosts(report, opts.filePath)\n appended.push(date)\n }\n return appended\n }\n\n /**\n * Get summary across last N days.\n */\n summary(days: number = 7): {\n totalTasks: number\n totalTokens: number\n totalInput: number\n totalOutput: number\n totalCacheRead: number\n totalCacheCreate: number\n cacheHitRatio: number\n totalErrors: number\n totalCost: number\n byAgent: Record<string, { tasks: number; input: number; output: number; cacheRead: number; cacheCreate: number; total: number; avgDuration: number; cost: number }>\n byChannel: Record<string, { tasks: number; cost: number }>\n sessionStats: Record<string, { sessions: number; avgTasksPerSession: number }>\n } {\n let totalTasks = 0\n let totalInput = 0\n let totalOutput = 0\n let totalCacheRead = 0\n let totalCacheCreate = 0\n let totalErrors = 0\n let totalCost = 0\n const byAgent: Record<string, { tasks: number; input: number; output: number; cacheRead: number; cacheCreate: number; total: number; avgDuration: number; totalDuration: number; cost: number; model?: string; sessions: number }> = {}\n const byChannel: Record<string, { tasks: number; cost: number }> = {}\n\n for (let i = 0; i < days; i++) {\n const date = new Date(Date.now() - i * 86400_000).toISOString().slice(0, 10)\n const usage = this.getDate(date)\n if (!usage) continue\n\n for (const [id, agent] of Object.entries(usage.agents)) {\n const cost = this.cost(agent)\n totalTasks += agent.tasks\n const agentInput = (agent.inputTokens || 0) + (agent.tier2InputTokens || 0)\n const agentOutput = (agent.outputTokens || 0) + (agent.tier2OutputTokens || 0)\n const agentCR = (agent.cacheReadTokens || 0) + (agent.tier2CacheReadTokens || 0)\n const agentCW = (agent.cacheCreateTokens || 0) + (agent.tier2CacheCreateTokens || 0)\n totalInput += agentInput\n totalOutput += agentOutput\n totalCacheRead += agentCR\n totalCacheCreate += agentCW\n totalErrors += agent.errors\n totalCost += cost\n\n const existing = byAgent[id] || { tasks: 0, input: 0, output: 0, cacheRead: 0, cacheCreate: 0, total: 0, avgDuration: 0, totalDuration: 0, cost: 0, sessions: 0 }\n existing.tasks += agent.tasks\n existing.input += agentInput\n existing.output += agentOutput\n existing.cacheRead += agentCR\n existing.cacheCreate += agentCW\n existing.total = existing.input + existing.output + existing.cacheRead + existing.cacheCreate\n existing.totalDuration += agent.totalDuration\n existing.avgDuration = existing.totalDuration / existing.tasks\n existing.cost += cost\n existing.sessions += agent.sessionKeys?.length || 0\n if (agent.model) existing.model = agent.model\n byAgent[id] = existing\n\n for (const [chKey, ch] of Object.entries(agent.byChannel || {})) {\n const chCost = this.cost(ch, agent.model)\n const acc = byChannel[chKey] || { tasks: 0, cost: 0 }\n acc.tasks += ch.tasks\n acc.cost += chCost\n byChannel[chKey] = acc\n }\n }\n }\n\n const totalTokens = totalInput + totalOutput + totalCacheRead + totalCacheCreate\n const cacheHitRatio = (totalCacheRead + totalCacheCreate) > 0\n ? totalCacheRead / (totalCacheRead + totalCacheCreate)\n : 0\n\n const sessionStats: Record<string, { sessions: number; avgTasksPerSession: number }> = {}\n for (const [id, a] of Object.entries(byAgent)) {\n sessionStats[id] = {\n sessions: a.sessions,\n avgTasksPerSession: a.sessions > 0 ? a.tasks / a.sessions : a.tasks,\n }\n }\n\n return { totalTasks, totalTokens, totalInput, totalOutput, totalCacheRead, totalCacheCreate, cacheHitRatio, totalErrors, totalCost, byAgent, byChannel, sessionStats }\n }\n\n private filePath(date: string): string {\n return resolve(this.dir, `${date}.json`)\n }\n\n private save(usage: DailyUsage): void {\n try {\n writeFileSync(this.filePath(usage.date), JSON.stringify(usage, null, 2))\n } catch {}\n }\n}\n\n/**\n * Load CACHE_AWARE_PRICING and merge any operator-supplied override. The\n * override file is optional; operators tweak rates (e.g. when Anthropic\n * publishes a price change) without rebuilding the daemon.\n */\nexport function loadPricingWithOverrides(\n overridePath: string = PRICING_OVERRIDE_PATH,\n): typeof CACHE_AWARE_PRICING {\n const result = JSON.parse(JSON.stringify(DEFAULT_PRICING))\n try {\n const p = resolve(process.cwd(), overridePath)\n if (!existsSync(p)) return result\n const raw = JSON.parse(readFileSync(p, \"utf-8\"))\n for (const [family, rates] of Object.entries(raw)) {\n if (!result[family]) result[family] = { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 }\n Object.assign(result[family], rates as object)\n }\n } catch {\n // Malformed override file — stay with defaults rather than crash at boot.\n }\n return result\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,EAAc,iBAAAC,EAAe,kBAAAC,EAAgB,cAAAC,EAAY,aAAAC,MAAiB,KACnF,OAAS,WAAAC,MAAe,OAiCjB,IAAMC,EAAiH,CAE5H,eAAoB,CAAE,MAAO,GAAM,OAAQ,GAAM,UAAW,EAAO,YAAa,IAAK,EAErF,gBAAoB,CAAE,MAAO,EAAM,OAAQ,GAAM,UAAW,GAAO,YAAa,IAAK,EACrF,kBAAoB,CAAE,MAAO,EAAM,OAAQ,GAAM,UAAW,GAAO,YAAa,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,EAAc,KAAK,SAAS+B,EAAM,IAAI,EAAG,KAAK,UAAUA,EAAO,KAAM,CAAC,CAAC,CACzE,MAAE,CAAO,CACX,CACF,EAOO,SAASD,EACdqF,EAAuBxF,EACK,CAC5B,IAAMyF,EAAS,KAAK,MAAM,KAAK,UAAU7G,CAAe,CAAC,EACzD,GAAI,CACF,IAAM2B,EAAI9B,EAAQ,QAAQ,IAAI,EAAG+G,CAAY,EAC7C,GAAI,CAACjH,EAAWgC,CAAC,EAAG,OAAOkF,EAC3B,IAAMC,EAAM,KAAK,MAAMtH,EAAamC,EAAG,OAAO,CAAC,EAC/C,OAAW,CAACD,EAAQqF,CAAK,IAAK,OAAO,QAAQD,CAAG,EACzCD,EAAOnF,CAAM,IAAGmF,EAAOnF,CAAM,EAAI,CAAE,MAAO,EAAG,OAAQ,EAAG,UAAW,EAAG,YAAa,CAAE,GAC1F,OAAO,OAAOmF,EAAOnF,CAAM,EAAGqF,CAAe,CAEjD,MAAE,CAEF,CACA,OAAOF,CACT","names":["readFileSync","writeFileSync","appendFileSync","existsSync","mkdirSync","resolve","CACHE_AWARE_PRICING","API_MODEL_PRICING","DEFAULT_PRICING","isClaudeModel","model","apiModelFamily","table","id","best","key","CONTEXT_TIER_THRESHOLD","TIER2_MULTIPLIER","getModelFamily","lower","has","needles","n","isPricedModel","tier","splitTaskUsageByTier","u","SESSION_KEYS_MAX","PRICING_OVERRIDE_PATH","TokenTracker","baseDir","loadPricingWithOverrides","usage","pricingTable","family","p","tier2In","tier2Out","tier2CR","tier2CW","tier1","tier2","agentId","duration","realUsage","messageLength","responseLength","error","channel","sessionKey","daily","agent","i1","o1","cr1","cw1","i2","o2","cr2","cw2","chKey","ch","date","path","targetDate","totalTasks","totalInput","totalOutput","totalCacheRead","totalCacheCreate","totalCost","topAgent","topCost","agentCosts","agentSessionStats","byChannel","cost","sessions","chCost","report","filePath","file","fmt","fmtTok","agentBreakdown","a","b","stats","sessTag","channelBreakdown","row","content","dates","parsed","m","d","throughDate","opts","maxDays","appended","last","candidates","cursor","i","days","totalErrors","byAgent","agentInput","agentOutput","agentCR","agentCW","existing","acc","totalTokens","cacheHitRatio","sessionStats","overridePath","result","raw","rates"]}
@@ -1,4 +1,4 @@
1
- import{a as k}from"./chunk-IMLAPB7G.js";import{k as y}from"./chunk-LQS27HSV.js";import{d as V}from"./chunk-QPABR72X.js";import{b as z}from"./chunk-KP7KDLZ2.js";import{V as B,W as J,X,Y as K,aa as N,fa as Oe}from"./chunk-IVTO54EM.js";import{existsSync as Q,readFileSync as Ie}from"node:fs";import{dirname as A,join as h}from"node:path";import{fileURLToPath as Ee}from"node:url";import{homedir as Ce}from"node:os";var M="tn.acme.agentx.voice",gt="AgentX Desktop.app",Y="AgentX Helper.app";function yt(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function ht(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function T(e){return`'${e.replace(/'/g,"'\\''")}'`}var Z="/usr/bin:/bin:/usr/sbin:/sbin";function wt(e,t){return t||[...new Set([...e?[A(e)]:[],...Z.split(":")])].join(":")}function R(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function St(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?R(t[1]):Z}var xt=e=>/agentx\.voice.*\.plist$/.test(e);function vt(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,u)=>s.file<u.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],u=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!u||!R(u).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:R(s)}):n={file:o,label:R(s)})}return{keep:n??{file:h(e,`${M}.plist`),label:M},remove:r}}function ee(e,t,n){for(let r of t.split(":"))if(r&&n(h(r,e)))return h(r,e);return null}function bt(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${T(e.cwd)} && ${T(e.node)} ${T(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{a as k}from"./chunk-IMLAPB7G.js";import{k as y}from"./chunk-LQS27HSV.js";import{d as V}from"./chunk-QPABR72X.js";import{b as z}from"./chunk-KP7KDLZ2.js";import{V as B,W as J,X,Y as K,aa as N,fa as Oe}from"./chunk-B6GVATMI.js";import{existsSync as Q,readFileSync as Ie}from"node:fs";import{dirname as A,join as h}from"node:path";import{fileURLToPath as Ee}from"node:url";import{homedir as Ce}from"node:os";var M="tn.acme.agentx.voice",gt="AgentX Desktop.app",Y="AgentX Helper.app";function yt(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function ht(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function T(e){return`'${e.replace(/'/g,"'\\''")}'`}var Z="/usr/bin:/bin:/usr/sbin:/sbin";function wt(e,t){return t||[...new Set([...e?[A(e)]:[],...Z.split(":")])].join(":")}function R(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function St(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?R(t[1]):Z}var xt=e=>/agentx\.voice.*\.plist$/.test(e);function vt(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,u)=>s.file<u.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],u=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!u||!R(u).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:R(s)}):n={file:o,label:R(s)})}return{keep:n??{file:h(e,`${M}.plist`),label:M},remove:r}}function ee(e,t,n){for(let r of t.split(":"))if(r&&n(h(r,e)))return h(r,e);return null}function bt(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${T(e.cwd)} && ${T(e.node)} ${T(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
3
  <plist version="1.0"><dict>
4
4
  <key>Label</key><string>${t(e.label??M)}</string>
@@ -33,4 +33,4 @@ function run(argv) {
33
33
  `),it(r,n)}var ut=5*6e4;function Cn(e,t,n=Date.now()){let r=Ae(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=ut)?!1:r.items[`card:${t}`]?.state!=="failed"}var U=24*36e5;function Re(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function lt(e,t,n,r){let o=Date.parse(e.expires),i=[f(e.ask,y.ask)];return e.choices?.length&&i.push(...e.choices.map((s,u)=>`${u+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${f(e.recommend,y.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:f(e.title,y.title),notes:i.join(`
34
34
  `),due:Re(r,t,o),priority:Number.isFinite(o)&&o-r<=U?"high":"none"}}function ct(e,t,n,r){let o=[f(e.question||e.text,y.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:W(e,y.title).headline,notes:o.join(`
35
35
  `),due:Re(r,t,i),priority:i!==void 0&&i-r<=U?"high":"none"}}async function Tn(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),u={created:0,completed:0,dismissed:0,failed:0},l=Ae(t);delete l.lastError;let p=a=>{l.lastError={at:s,message:a}},S=new Map;try{if(n.include.includes("card"))for(let a of e.cards())a.status==="pending"&&Date.parse(a.expires)>i&&S.set(`card:${a.id}`,lt(a,n,e.answerUrl,i));if(n.include.includes("request"))for(let a of e.requests())a.state==="waiting_owner"&&S.set(`request:${a.id}`,ct(a,n,e.answerUrl,i))}catch(a){return o(`[mirror] could not read what is waiting: ${a?.message??a}`),p(String(a?.message??a)),Ne(t,l),u}let G=!0,v=new Map,Pe=async a=>{if(!v.has(a))try{v.set(a,new Set((await r.listOpen(a)).map(c=>c.id)))}catch(c){o(`[mirror] could not read list "${a}": ${c?.message??c}`),p(String(c?.message??c)),v.set(a,null),G=!1}return v.get(a)};for(let[a,c]of Object.entries(l.items)){if(c.state!=="open"||!c.id)continue;let d=await Pe(c.list);if(d)if(S.has(a))d.has(c.id)||(l.items[a]={...c,state:"dismissed",at:s},u.dismissed++,o(`[mirror] ${a}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(c.id))try{await r.complete(c.id)}catch(g){o(`[mirror] ${a}: could not complete its task: ${g?.message??g}`),p(String(g?.message??g));continue}l.items[a]={...c,state:"completed",at:s},u.completed++}}let E=null,x=[];for(let[a,c]of S){let d=l.items[a];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=j)continue;if(E===null)try{await r.ensureList(n.list),E=!0}catch(m){o(`[mirror] could not make list "${n.list}": ${m?.message??m}`),p(String(m?.message??m)),E=!1}let g=d?.state==="failed"?d.failures:0;try{let{id:m}=await r.add({list:n.list,title:c.title,notes:c.notes,due:c.due,priority:c.priority});l.items[a]={id:m,list:n.list,state:"open",at:s,failures:0},u.created++}catch(m){let b=String(m?.message??m),C=g+1;l.items[a]={list:n.list,state:"failed",at:s,failures:C,lastError:b},p(b),u.failed++,o(`[mirror] ${a}: could not add to Reminders (${C}/${j}): ${b}`),C===j&&x.push({title:c.title,message:b})}}let $e=l.failureToldAt?Date.parse(l.failureToldAt):NaN;if(x.length&&!(i-$e<U)){let a=x[0],c=x.length>1?` (and ${x.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${a.title}${c}: ${f(a.message,200)}. Still on the Desk.`),l.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}G&&(l.checkedAt=s,l.cards=n.include.includes("card"));for(let[a,c]of Object.entries(l.items))c.state!=="open"&&!S.has(a)&&i-Date.parse(c.at)>at&&delete l.items[a];return Ne(t,l),u}export{gn as a,he as b,H as c,F as d,yn as e,hn as f,Ze as g,wn as h,Sn as i,xn as j,W as k,f as l,Rn as m,gt as n,Y as o,yt as p,ht as q,wt as r,St as s,xt as t,vt as u,ee as v,bt as w,Nt as x,Te as y,Me as z,_e as A,_ as B,se as C,q as D,ye as E,un as F,ln as G,cn as H,Ae as I,Cn as J,Tn as K};
36
- //# sourceMappingURL=chunk-T5IGXFSW.js.map
36
+ //# sourceMappingURL=chunk-BQXKTQCX.js.map
@@ -1,8 +1,8 @@
1
- import{f,k as I}from"./chunk-VL74KOR7.js";import{createHash as $}from"crypto";var k="failure:",x=3,p=5,A=["error","timeout"],T=["memory-promote","procedure-miner"];function h(t,s){return(s??"").toLowerCase().replace(/https?:\/\/\S+/g,"<url>").replace(/(["'`]).*?\1/g,"<v>").replace(/(?:~|\.{0,2})?\/[\w.@-]+(?:\/[\w.@-]+)*/g,"<path>").replace(/\b[0-9a-z]*\d[0-9a-z]*\b/g,"<n>").replace(/[^a-z<>\s]+/g," ").replace(/\s+/g," ").trim().split(" ").filter(Boolean).slice(0,8).join(" ")||t}function y(t){return`${t.agentId}|${t.tool??"no-tool"}|${t.status}|${h(t.status,t.error)}`}function S(t){return $("sha1").update(t).digest("hex").slice(0,10)}function w(t,s){return`${k}${S(t)}@${Math.floor(Math.log2(Math.max(1,s)))}`}function F(t){return t.finalSessionId??t.resumeSessionId??t.taskId}function _(t,s={}){return A.flatMap(e=>I(t,{status:e,since:s.since,limit:1e3})).filter(e=>!T.some(i=>(e.chatId??"").startsWith(i))).map(e=>{let{tool:i,error:n}=b(f(t,e.taskId)?.steps??[]);return{taskId:e.taskId,agentId:e.agentId,chatId:e.chatId,sessionId:F(e),status:e.status,startedAt:e.startedAt,error:n??e.error,messagePreview:e.messagePreview,tool:i}})}function b(t){let s=null,a=null;for(let e of t)e.name==="tool_use"&&e.action?(s=e.action,e.status==="error"&&(a={tool:e.action,error:e.error??e.outputSummary})):e.name==="tool_result"&&e.status==="error"&&(a={tool:e.action??s,error:e.error??e.outputSummary});return a??{tool:s,error:null}}function C(t,s={}){let a=Math.max(2,s.minSessions??x),e=new Map;for(let n of t){let r=y(n);e.set(r,[...e.get(r)??[],n])}let i=[];for(let[n,r]of e){let l=[...new Set([...r].sort((c,g)=>g.startedAt-c.startedAt).map(c=>c.sessionId))];if(l.length<a)continue;r.sort((c,g)=>g.startedAt-c.startedAt);let o=r[0],u=o.tool??"no tool",d=h(o.status,o.error),m=`failure-${S(n)}`;i.push({occurrences:l.length,sessions:l.slice(0,p),tasks:r.slice(0,p).map(c=>c.taskId),failure:{tool:u,errorClass:d,runs:r.length},agentId:o.agentId,key:`${o.agentId}/feedback_${m}`,stamp:w(n,l.length),memory:{name:m,type:"feedback",description:`${o.agentId}: ${u} keeps failing (${d}) in ${l.length} sessions`.slice(0,200),body:E(o.agentId,u,d,l.length,r),createdAt:new Date(r[r.length-1].startedAt).toISOString(),updatedAt:new Date(o.startedAt).toISOString()}})}return i.sort((n,r)=>r.occurrences-n.occurrences)}function E(t,s,a,e,i){let n=i.slice(0,p).map(r=>{let l=(r.messagePreview??"").replace(/\s+/g," ").trim().slice(0,120),o=(r.error??r.status).replace(/\s+/g," ").trim().slice(0,160);return`- ${new Date(r.startedAt).toISOString().slice(0,10)} \`${r.taskId}\` (${r.status})${l?` \u2014 task: ${l}`:""}
1
+ import{f,k as I}from"./chunk-VJVXEVZ7.js";import{createHash as $}from"crypto";var k="failure:",x=3,p=5,A=["error","timeout"],T=["memory-promote","procedure-miner"];function h(t,s){return(s??"").toLowerCase().replace(/https?:\/\/\S+/g,"<url>").replace(/(["'`]).*?\1/g,"<v>").replace(/(?:~|\.{0,2})?\/[\w.@-]+(?:\/[\w.@-]+)*/g,"<path>").replace(/\b[0-9a-z]*\d[0-9a-z]*\b/g,"<n>").replace(/[^a-z<>\s]+/g," ").replace(/\s+/g," ").trim().split(" ").filter(Boolean).slice(0,8).join(" ")||t}function y(t){return`${t.agentId}|${t.tool??"no-tool"}|${t.status}|${h(t.status,t.error)}`}function S(t){return $("sha1").update(t).digest("hex").slice(0,10)}function w(t,s){return`${k}${S(t)}@${Math.floor(Math.log2(Math.max(1,s)))}`}function F(t){return t.finalSessionId??t.resumeSessionId??t.taskId}function _(t,s={}){return A.flatMap(e=>I(t,{status:e,since:s.since,limit:1e3})).filter(e=>!T.some(i=>(e.chatId??"").startsWith(i))).map(e=>{let{tool:i,error:n}=b(f(t,e.taskId)?.steps??[]);return{taskId:e.taskId,agentId:e.agentId,chatId:e.chatId,sessionId:F(e),status:e.status,startedAt:e.startedAt,error:n??e.error,messagePreview:e.messagePreview,tool:i}})}function b(t){let s=null,a=null;for(let e of t)e.name==="tool_use"&&e.action?(s=e.action,e.status==="error"&&(a={tool:e.action,error:e.error??e.outputSummary})):e.name==="tool_result"&&e.status==="error"&&(a={tool:e.action??s,error:e.error??e.outputSummary});return a??{tool:s,error:null}}function C(t,s={}){let a=Math.max(2,s.minSessions??x),e=new Map;for(let n of t){let r=y(n);e.set(r,[...e.get(r)??[],n])}let i=[];for(let[n,r]of e){let l=[...new Set([...r].sort((c,g)=>g.startedAt-c.startedAt).map(c=>c.sessionId))];if(l.length<a)continue;r.sort((c,g)=>g.startedAt-c.startedAt);let o=r[0],u=o.tool??"no tool",d=h(o.status,o.error),m=`failure-${S(n)}`;i.push({occurrences:l.length,sessions:l.slice(0,p),tasks:r.slice(0,p).map(c=>c.taskId),failure:{tool:u,errorClass:d,runs:r.length},agentId:o.agentId,key:`${o.agentId}/feedback_${m}`,stamp:w(n,l.length),memory:{name:m,type:"feedback",description:`${o.agentId}: ${u} keeps failing (${d}) in ${l.length} sessions`.slice(0,200),body:E(o.agentId,u,d,l.length,r),createdAt:new Date(r[r.length-1].startedAt).toISOString(),updatedAt:new Date(o.startedAt).toISOString()}})}return i.sort((n,r)=>r.occurrences-n.occurrences)}function E(t,s,a,e,i){let n=i.slice(0,p).map(r=>{let l=(r.messagePreview??"").replace(/\s+/g," ").trim().slice(0,120),o=(r.error??r.status).replace(/\s+/g," ").trim().slice(0,160);return`- ${new Date(r.startedAt).toISOString().slice(0,10)} \`${r.taskId}\` (${r.status})${l?` \u2014 task: ${l}`:""}
2
2
  error: ${o}`});return[`**${t}** hit the same failure in ${e} separate sessions (${i.length} runs).`,`- Tool: \`${s}\`
3
3
  - Error class: \`${a}\``,"Recurrence across sessions is the finding: any one of these runs is session state. Propose the fix that stops it recurring \u2014 what fails, the likely cause, and what to do instead (a missing fact, a better approach, or a tool or configuration change to make) \u2014 or skip it if the examples do not share a cause.",`**Examples (newest first):**
4
4
  ${n.join(`
5
5
  `)}`].join(`
6
6
 
7
7
  `)}export{k as a,x as b,p as c,h as d,y as e,w as f,F as g,_ as h,b as i,C as j};
8
- //# sourceMappingURL=chunk-AYK2MO3B.js.map
8
+ //# sourceMappingURL=chunk-CTN4KYE6.js.map
@@ -1,7 +1,7 @@
1
- import{ib as b,jb as k,lb as x,tb as S}from"./chunk-IVTO54EM.js";S();import{readFileSync as w,writeFileSync as v,existsSync as P}from"fs";import{resolve as d}from"path";function O(r){if(r)return d(r);let e=[d(process.cwd(),"agentx.json"),d(process.cwd(),".agentx/config.json")];for(let n of e)if(P(n))return n;return e[0]}function R(r){return JSON.parse(JSON.stringify(r))}async function C(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 N(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:l,daemonUrl:c}=e,o=O(l);if(!P(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let g;try{g=w(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let p;try{p=JSON.parse(g)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=R(p);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=k(i),u=b.safeParse(a);if(!u.success){let f=u.error.issues.map($=>` ${$.path.join(".")||"<root>"}: ${$.message}`).join(`
1
+ import{ib as b,jb as k,lb as x,tb as S}from"./chunk-B6GVATMI.js";S();import{readFileSync as w,writeFileSync as v,existsSync as P}from"fs";import{resolve as d}from"path";function O(r){if(r)return d(r);let e=[d(process.cwd(),"agentx.json"),d(process.cwd(),".agentx/config.json")];for(let n of e)if(P(n))return n;return e[0]}function R(r){return JSON.parse(JSON.stringify(r))}async function C(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 N(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:l,daemonUrl:c}=e,o=O(l);if(!P(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let g;try{g=w(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let p;try{p=JSON.parse(g)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=R(p);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=k(i),u=b.safeParse(a);if(!u.success){let f=u.error.issues.map($=>` ${$.path.join(".")||"<root>"}: ${$.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${f}`,after:i}}let m=x(u.data);if(m.length)return{success:!1,path:o,error:`Validation failed:
4
4
  ${m.map(f=>` ${f}`).join(`
5
5
  `)}`,after:i}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{v(o,JSON.stringify(i,null,2)+`
6
6
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let h=!1,y;if(s){let a=c||M(i),u=await C(a);u.ok?h=!0:y=u.reason}return{success:!0,path:o,after:i,reloaded:h,reloadSkipped:y}}function M(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 A(r,e,n){let t=e.split("."),s=r;for(let l=0;l<t.length-1;l++){let c=t[l];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function F(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function U(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{O as a,N as b,A as c,F as d,U as e};
7
- //# sourceMappingURL=chunk-CRUNUMVO.js.map
7
+ //# sourceMappingURL=chunk-G3T73GGF.js.map
@@ -1,6 +1,6 @@
1
- import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-QT63Q6C5.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-6QLRRSKU.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-QGKNDGH5.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-6QLRRSKU.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
6
- //# sourceMappingURL=chunk-BC7VOHNH.js.map
6
+ //# sourceMappingURL=chunk-IJZNM5PS.js.map
@@ -1,7 +1,7 @@
1
- import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-T5IGXFSW.js";import{a as E}from"./chunk-OSH2PEBH.js";import{kb as j,tb as F}from"./chunk-IVTO54EM.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{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.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{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==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().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 Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
1
+ import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-BQXKTQCX.js";import{a as E}from"./chunk-OSH2PEBH.js";import{kb as j,tb as F}from"./chunk-B6GVATMI.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{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.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{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==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().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 Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
2
2
  `):ue(n),process.exit(e.errors>0?1:0)});async function J(t,n,e=P){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})}async function K(t,n,e){let i;try{i=await(e??k(n)).describe()}catch(s){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:s?.message??String(s)});return}let o=["tasks","notes","banner","sound","focus"].filter(s=>i[s]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${o.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function V(t,n,e=process.cwd(),i=k(n)){let o=n.native?.mirror;if(!o?.enabled)return;if(!i.tasks){t.push({severity:"warn",group:"Native",title:"Reminders mirror is on, but this machine has no task app",detail:"native.mirror.enabled is set; nothing is mirrored here.",fix:"Turn it on on the machine that holds the owner's cards (the Mac), or set native.mirror.enabled to false here."});return}let s=I(e),a=Object.values(s.items),l=a.filter(g=>g.state==="open").length,u=a.filter(g=>g.state==="failed").length;t.push({severity:s.lastError||u?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${o.list}"${u?`, ${u} could not be added`:""}`,detail:s.lastError?`Last error ${s.lastError.at}: ${s.lastError.message}`:void 0,fix:s.lastError?"Run remindctl status, and allow Reminders for the app that runs the daemon in System Settings \u203A Privacy & Security \u203A Reminders.":void 0})}function U(t,n,e=process.platform,i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}}){let o=n.reminders;if(!o?.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 s=o.command||"remindctl",a=s.includes("/")?i(s)?s:null:x(s,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(o.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${s} 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 Q(t){let n=E(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return m(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
3
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 o=e("claude");if(o){let l;try{l=m("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:o})}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 s=e("codex");if(s){let l;try{l=m("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:s})}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=m("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{G(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 Y(t){if(process.platform!=="darwin")return;let n=H(z(),"Library/LaunchAgents"),e=[];try{e=C(n).filter(o=>/agentx\.voice.*\.plist$/.test(o))}catch{return}let i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}};for(let o of e){let s=R(b(H(n,o),"utf-8")),a=x("ffmpeg",s,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${o})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${o} sets PATH to ${s}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function ee(t){let n=y(process.cwd(),"agentx.json");if(!w(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{j(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 m(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 o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return s.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function te(t,n){let e=new Set;if(A(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=_(),o=[],s=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?o.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&s.push(a)}o.length===0&&s.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(o.length>0&&t.push({severity:"fail",group:"Secrets",title:`${o.length} env var(s) referenced in agentx.json but missing`,detail:o.join(", "),fix:`Add to .env \u2014 e.g. ${o[0]}=<value>`}),s.length>0&&t.push({severity:"warn",group:"Secrets",title:`${s.length} env var(s) set but empty`,detail:s.join(", ")}))}function _(){let t=y(process.cwd(),".env"),n={};if(w(t))for(let e of b(t,"utf-8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(n[i[1]]=i[2])}return n}function ne(t,n){let e="With a shared token this node cannot tell which peer is calling. For example, closing an approval card forwarded from that peer is refused, and its stop/resume signals are judged as the owner's.",i="Give this pair a token of its own: set the same new value as mesh.peers[].token here and on the peer.",o=[];for(let s of t){let a=(s.token??"").trim();a?n&&a===n&&o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&o.length===0&&o.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),o}function ie(t,n){t.push(...oe(n))}function oe(t,n=process.env,e=_()){let i=a=>(n[a]||e[a]||"").trim(),o=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,u)=>i(u)):void 0,s=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:o(a.token)}));return ne(s,i("MESH_TOKEN")||void 0)}function A(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)A(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))A(e,n)}function se(t,n){let e=[];for(let[i,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let s=o.workspace.startsWith("/")?o.workspace:y(process.cwd(),o.workspace);try{B(s).isDirectory()||e.push(`${i}: ${s} (exists but not a directory)`)}catch{e.push(`${i}: ${s}`)}}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
4
  `),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function re(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[o,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let a=s.workspace.startsWith("/")?s.workspace:y(process.cwd(),s.workspace);for(let l of["settings.json","settings.local.json"]){let u=y(a,".claude",l);if(!w(u))continue;let g;try{g=JSON.parse(b(u,"utf-8"))}catch(c){i.push({severity:"fail",agent:o,msg:`${l}: JSON parse error \u2014 ${c.message}`});continue}let $=g.env||{};for(let[c,h]of Object.entries($)){if(typeof h!="string")continue;let p=h.match(e);p&&i.push({severity:"fail",agent:o,msg:`${l} env.${c} contains unexpanded ${[...new Set(p)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=$.PATH;if(typeof r=="string"){let c=r.split(":").filter(Boolean);c.includes("/usr/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),c.includes("/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let d=g.permissions;if(d&&typeof d=="object"&&"allow"in d){let c=d.allow,h=d.deny;Array.isArray(c)&&c.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:o,msg:`${l} permissions.allow is explicitly [] with ${h.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 o of i)t.push({severity:o.severity,group:"Workspace settings",title:`${o.agent}: ${o.msg}`,fix:o.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 ae(t,n){let e=n.webhooks??[],i=[],o=y(process.cwd(),n.workflows?.dir||".agentx/workflows"),s=new Set;try{if(w(o))for(let r of C(o))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&s.add(r.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let r of e){if(!r.enabled||!a.has(r.source))continue;!(r.triggers&&Object.keys(r.triggers).length>0)&&!r.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${r.id}" (${r.source} -> ${r.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 r of e)if(!(!r.enabled||!r.triggers)){for(let[d,c]of Object.entries(r.triggers))s.size>0&&!s.has(c)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${c}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&s.size>0&&!s.has(r.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${r.id}".defaultWorkflow -> "${r.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(w(o)){for(let r of C(o))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse(b(y(o,r),"utf-8"));d?.status==="active"&&d?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${d.id??r}" 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(r=>r.name));for(let r of e)!r.enabled||!r.node||l.has(r.node)||i.push({severity:"fail",title:`webhook "${r.id}" routes to mesh peer "${r.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 r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,c=u.get(d);c?i.push({severity:"warn",title:`webhook entries "${c}" and "${r.id}" both enabled for ${r.source} -> ${r.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(d,r.id)}let g=new Set(Object.keys(n.agents??{}));for(let r of n.channels?.gitlab?.agentMappings??[])if(r?.agentId){if(r.node){l.has(r.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${r.agentId}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}g.has(r.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${r.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[r,d]of Object.entries(n.channels?.telegram?.accounts??{}))d.agentBinding?g.has(d.agentBinding)||i.push({severity:"fail",title:`telegram account "${r}".agentBinding -> "${d.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${r}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let $=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[r,d]of Object.entries(n.agents??{})){let c=d.integrations??[];if(!c.length)continue;let h=new Set;for(let p of c){let S=`${p.kind}::${p.label}`;h.has(S)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${p.kind}, ${p.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(S),$.has(p.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${p.kind}" on integration "${p.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let L=p.credentials||{};for(let[q,v]of Object.entries(L))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${p.kind}/${p.label}].${q} -> $${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 r of i)t.push({severity:r.severity,group:"Routing",title:r.title,fix:r.fix})}function le(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 de(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 o=new AbortController,s=setTimeout(()=>o.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:o.signal});if(clearTimeout(s),!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=le(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 ce(t,n){let e=Object.entries(n.agents||{}).filter(([,o])=>o?.codegraph===!0&&(o.tier==="claude-code"||o.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=m(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
5
5
  `)[0]||null}catch{i=null}if(i){let o;try{o=m("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${o||"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[o,s]of e){if(!s.workspace||!w(s.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${o}: workspace missing`,detail:`Workspace path ${s.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=y(s.workspace,".codegraph","codegraph.db");w(a)?t.push({severity:"ok",group:"CodeGraph",title:`${o}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${o}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${s.workspace}\` to build it now.`})}}function D(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 ue(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,o]of n){console.log(f.bold(" "+i));for(let s of o){let a=s.severity==="ok"?f.green("\u2713"):s.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${s.title}`),s.detail&&console.log(f.dim(" "+s.detail.replace(/\n/g,`
6
6
  `))),s.fix&&console.log(f.dim(" \u2192 "+s.fix))}console.log()}let e=D(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{P as a,Z as b,Ne as c,J as d,K as e,V as f,U as g,ne as h,oe as i,le as j};
7
- //# sourceMappingURL=chunk-S6ZZKRDB.js.map
7
+ //# sourceMappingURL=chunk-JMZNI257.js.map
@@ -1,5 +1,5 @@
1
- import{kb as m,tb as b}from"./chunk-IVTO54EM.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
1
+ import{kb as m,tb as b}from"./chunk-B6GVATMI.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
2
2
 
3
3
  `))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
4
4
  `))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
5
- //# sourceMappingURL=chunk-CGE5EAWC.js.map
5
+ //# sourceMappingURL=chunk-L7RPH3T7.js.map
@@ -1,4 +1,4 @@
1
- import{a as He,b as w,c as z,d as qe,e as pe,f as ue,g as M,h as ge,i as O,j as U,n as Fe,o as Ke,p as Ge,q as Je}from"./chunk-XVTD6I34.js";import{e as Be,i as je}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Le}from"./chunk-KVSHZKAL.js";import{c as Ue,d as le,e as P,f as de,g as q}from"./chunk-AU3VT7BD.js";import{kb as Oe,ma as Me}from"./chunk-EXJGRK2N.js";import{a as We}from"./chunk-VUEQ4SL5.js";import{a as Te}from"./chunk-IMLAPB7G.js";import{c as De,e as _e}from"./chunk-LQE73AZR.js";import{b as Ne}from"./chunk-MRIVENBY.js";import{n as se,p as ze}from"./chunk-LQS27HSV.js";import{b as Y}from"./chunk-2VDO2HEK.js";import{O as J}from"./chunk-AXDNFXYU.js";import{a as H,b as G}from"./chunk-CRUNUMVO.js";import{a as Re}from"./chunk-NCEYJFF5.js";import{c as Ie,d as Ee}from"./chunk-OWNQ2FD4.js";import{a as Pe}from"./chunk-ROLSSYXE.js";import{a as Ce}from"./chunk-QUFIUXMQ.js";import{Ia as Ae,Pa as Lt,Y as ae,Z as $e,fa as Ut,gb as oe,jb as j,kb as Se,tb as ie}from"./chunk-IVTO54EM.js";import{existsSync as F,readFileSync as Ve,writeFileSync as Qe,appendFileSync as Ht,mkdirSync as qt}from"fs";import{dirname as Ft,resolve as N}from"path";import{fileURLToPath as Kt}from"url";import{hostname as Gt}from"os";import{spawn as Jt}from"child_process";function Ye(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
1
+ import{a as He,b as w,c as z,d as qe,e as pe,f as ue,g as M,h as ge,i as O,j as U,n as Fe,o as Ke,p as Ge,q as Je}from"./chunk-XVTD6I34.js";import{e as Be,i as je}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Le}from"./chunk-B7QHC7N4.js";import{c as Ue,d as le,e as P,f as de,g as q}from"./chunk-AU3VT7BD.js";import{kb as Oe,ma as Me}from"./chunk-A2D3PNDA.js";import{a as We}from"./chunk-VUEQ4SL5.js";import{a as Te}from"./chunk-IMLAPB7G.js";import{c as De,e as _e}from"./chunk-LQE73AZR.js";import{b as Ne}from"./chunk-MRIVENBY.js";import{n as se,p as ze}from"./chunk-LQS27HSV.js";import{b as Y}from"./chunk-2VDO2HEK.js";import{_ as J}from"./chunk-XQ2EFLQW.js";import{a as H,b as G}from"./chunk-G3T73GGF.js";import{a as Re}from"./chunk-7O43PB6O.js";import{c as Ie,d as Ee}from"./chunk-OWNQ2FD4.js";import{a as Pe}from"./chunk-ROLSSYXE.js";import{a as Ce}from"./chunk-QUFIUXMQ.js";import{Ia as Ae,Pa as Lt,Y as ae,Z as $e,fa as Ut,gb as oe,jb as j,kb as Se,tb as ie}from"./chunk-B6GVATMI.js";import{existsSync as F,readFileSync as Ve,writeFileSync as Qe,appendFileSync as Ht,mkdirSync as qt}from"fs";import{dirname as Ft,resolve as N}from"path";import{fileURLToPath as Kt}from"url";import{hostname as Gt}from"os";import{spawn as Jt}from"child_process";function Ye(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
2
2
  <div class="ax-topbar__left">
3
3
  <div class="ax-brand">
4
4
  <span class="ax-brand__mark">AX</span>
@@ -866,4 +866,4 @@ ${t}=${n}
866
866
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
867
867
  ${r}`).all(t,...n,...a).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function to(e,t){return Rt(e,t,ae,"ORDER BY created_at")}function no(e,t,n=50){return Rt(e,t,[...ae,...$e],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}Lt();var we="member:",Xn=90,Vn="members",Qn="tailscale-user-login",Zn=400,er=60*60*1e3;function tr(e){let t=e.scopes.find(n=>n.startsWith(we));return t?t.slice(we.length):null}function Dt(e,t){if(!e)return null;let n=t.verify(e),r=n?tr(n):null;return n&&r?{rec:n,personId:r}:null}function co(e,t){let n=e.people().find(s=>s.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:r,record:a}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${we}${n.id}`],expiresInDays:Xn}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:a.id,name:n.id});return e.members.log({person:n.id,device:a.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:a.id,person:n}}var nr=Math.round(De/6e4);function rr(e){return e==="client"?"Your project":"My work"}function po(e){let t=rr(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${_e(e.code)}`,` The code works once, for ${nr} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
868
868
  `)}var ar="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",or="Too many machines are waiting for the owner's answer. Try again later.",Tt="That code didn't work. Check it, or ask the person who invited you for a new one.",_t=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function zt(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function ir(e){if(!zt(e))return null;let t=_t(e,Qn).toLowerCase();return t?t.slice(0,80):null}function sr(e){let t=e.socket?.remoteAddress||"unknown";if(!zt(e))return t;let n=_t(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function lr(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function dr(e){return e.identities.map(Ae).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function uo(e,t){let n=Date.now(),r=t.now??Date.now,a=t.log??(b=>console.log(b)),o=sr(e),i=t.limiter.retryAfter(o);if(i>0)return a(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,l="";try{let b=await Y(e,2048);s=b.code,l=lr(b.machine)}catch{}let d=t.codes.redeem(s),c=d?Dt(d.token,t.tokens):null;if(await pr(n,t.minMs??Zn),!d||!c)return t.limiter.fail(o),a(`[member] pair-code failed from ${o}`),{status:401,body:{error:Tt}};t.limiter.succeed(o);let{rec:f,personId:g}=c,m=t.people().find(b=>b.id===g);if(!m)return t.tokens.revoke(f.id),t.members.log({person:g,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),a(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Tt}};let u=ir(e),h=dr(m);if(h.length&&(!u||!h.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:g,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${h.join(" or ")}`}),a(`[member] ${g}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${h.join(" or ")}`),{status:403,body:{error:ar}};let C=l||"Unnamed machine",y=m.name.slice(0,40),x=ze(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${y}'s own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:Vn},{now:r()});return x.ok?(t.members.add({tokenId:f.id,personId:g,name:C,state:"pending",cardId:x.card.id,address:o,...u?{network:u}:{},createdAt:new Date(r()).toISOString()}),t.members.log({person:g,device:f.id,event:"paired",address:o,detail:C}),a(`[member] ${g} paired "${C}" from ${o}; waiting for the owner (card ${x.card.id})`),{status:200,body:{person:g,name:C,state:"pending"},token:d.token}):(t.tokens.revoke(f.id),t.members.log({person:g,device:f.id,event:"refused",address:o,detail:x.error}),a(`[member] ${g}: pairing from ${o} refused: ${x.error}`),{status:503,body:{error:or}})}var re="this machine is not paired",cr="waiting for the owner to approve this machine";function Nt(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function go(e,t){return t.state==="pending"&&t.cardId?Nt(se(e,t.cardId)):null}function mo(e,t,n){let r=t.now??Date.now,a=t.log??(c=>console.log(c)),o=Dt(e,t.tokens);if(!o)return{ok:!1,status:401,error:re};let{rec:i,personId:s}=o,l=t.members.byToken(i.id);if(!l||l.state==="removed"||l.personId!==s)return{ok:!1,status:401,error:re};if(t.people&&!t.people().some(c=>c.id===s))return Wt(t,i.id,"person no longer listed"),a(`[member] ${s}: "${l.name}" ended: person no longer listed`),{ok:!1,status:401,error:re};if(l.state==="pending"){let c=l.cardId?se(t.root,l.cardId):null,f=Nt(c);if(f==="yes")l=t.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??l,t.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),a(`[member] ${s}: "${l.name}" approved`);else if(f==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(i.id),t.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),t.members.log({person:s,device:i.id,event:"refused",detail:g}),a(`[member] ${s}: "${l.name}" refused: ${g}`),{ok:!1,status:401,error:re}}else return{ok:!1,status:403,error:cr,waiting:!0}}let d=l.lastSeenAt?Date.parse(l.lastSeenAt):0;return n&&(r()-d>=er||l.lastAddress!==n)&&(l=t.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:n})??l,t.members.log({person:s,device:i.id,event:"signed-in",address:n})),{ok:!0,device:l,personId:s,rec:i}}function Wt(e,t,n="removed by the owner"){let r=e.members.byToken(t);if(!r)return null;e.tokens.revoke(t);let a=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:r.personId,device:t,event:"removed",detail:n}),a}function fo(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Wt(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function pr(e,t){let n=e+t-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}var Mt=["gitlab","github"];function ur(e,t,n){let r=String(t||"").trim().toLowerCase();if(!Mt.includes(r))throw new Error(`Request status works on ${Mt.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let a=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...a,r])]:a.filter(o=>o!==r),`request status on ${r} is ${n?"on":"off"}`}function bo(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function xo(e){let{summary:t}=X(n=>ur(n,e?.channel,!!e?.enabled));return{summary:t}}function ko(e){return new Set(Object.entries(e).filter(([,t])=>t?.wiki?.absorb?.enabled===!1).map(([t])=>t))}function wo(e,t){return t.only?{agents:[t.only],skipped:[]}:{agents:e.filter(n=>!t.off.has(n)),skipped:e.filter(n=>t.off.has(n))}}function $o(e,t){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===t?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Ao(e,t){if(t){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var gr="https://ntfy.sh";function Co(e){return{enabled:!!e?.enabled,server:e?.server||gr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Io(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let r=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");n.server=r}if("topic"in t){let r=String(t.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");n.topic=r}if("token"in t){let r=String(t.token??"").trim();r?n.token=r:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{Ze as a,Yt as b,Ar as c,Sr as d,Cr as e,ka as f,Hn as g,Sa as h,Pa as i,_r as j,zr as k,cn as l,gn as m,me as n,Nr as o,Wr as p,Pt as q,Xa as r,Va as s,mn as t,jr as u,Hr as v,qr as w,eo as x,to as y,no as z,Xn as A,co as B,nr as C,rr as D,po as E,sr as F,uo as G,go as H,mo as I,Wt as J,fo as K,Mt as L,ur as M,bo as N,xo as O,ko as P,wo as Q,$o as R,Ao as S,Co as T,Io as U,_n as V,ua as W,ba as X,xa as Y};
869
- //# sourceMappingURL=chunk-DAWJHJKD.js.map
869
+ //# sourceMappingURL=chunk-LM3K7U6H.js.map
@@ -1,4 +1,4 @@
1
- import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-BC7VOHNH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{y as N,z as ot}from"./chunk-QT63Q6C5.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{b as E,c as L}from"./chunk-QOYAX2FT.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
1
+ import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-IJZNM5PS.js";import{a as H}from"./chunk-LUOW2YHY.js";import{y as N,z as ot}from"./chunk-QGKNDGH5.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{b as E,c as L}from"./chunk-QOYAX2FT.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
2
2
 
3
3
  ## Shared wiki (other agents' articles)
4
4
 
@@ -51,5 +51,5 @@ ${o}
51
51
 
52
52
  Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
53
53
 
54
- Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-OTO56OCX.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
- //# sourceMappingURL=chunk-ON7Y3JSP.js.map
54
+ Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-WCEFYQL4.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
+ //# sourceMappingURL=chunk-LQTTLXZY.js.map
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-GLNCV3KP.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-BYIWNEFL.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-Y6JSB5II.js.map
126
+ //# sourceMappingURL=chunk-NHWYEIET.js.map