agentix-cli 0.133.0 → 0.135.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 (199) hide show
  1. package/dist/{App-WQPA77VJ.js → App-4UVAI5C5.js} +2 -2
  2. package/dist/{ChatApp-TGW66I4Y.js → ChatApp-COO67WIR.js} +2 -2
  3. package/dist/absorb-eval-WY3YMLS4.js +2 -0
  4. package/dist/{agent-FWHYHXWC.js → agent-3R5NY7I3.js} +2 -2
  5. package/dist/{board-dashboard-GKE4KWJH.js → board-dashboard-U3ZSCO62.js} +24 -8
  6. package/dist/board-dashboard-U3ZSCO62.js.map +1 -0
  7. package/dist/{chunk-ZN5DC6WS.js → chunk-3XVST5XX.js} +2 -2
  8. package/dist/{note-reader-LPPIYYLT.js → chunk-4LWFJ4MZ.js} +3 -3
  9. package/dist/{note-reader-LPPIYYLT.js.map → chunk-4LWFJ4MZ.js.map} +1 -1
  10. package/dist/{chunk-F5PVUB4Y.js → chunk-4XMALK7X.js} +2 -2
  11. package/dist/{chunk-VH2ASPFQ.js → chunk-5NT44FKL.js} +2 -2
  12. package/dist/{chunk-HIUHKOKK.js → chunk-6WF56ME6.js} +2 -2
  13. package/dist/{chunk-MCBTVNPX.js → chunk-BQIWMQNU.js} +2 -2
  14. package/dist/{chunk-2BF6HJJD.js → chunk-DYGQF3MI.js} +4 -4
  15. package/dist/chunk-DYGQF3MI.js.map +1 -0
  16. package/dist/{chunk-4NEO5KB2.js → chunk-EEBK4F6E.js} +15 -15
  17. package/dist/chunk-EEBK4F6E.js.map +1 -0
  18. package/dist/{chunk-JA5Y4LDP.js → chunk-ERULJ2ZL.js} +2 -2
  19. package/dist/{chunk-RJFPCW7T.js → chunk-FWDRBUMS.js} +2 -2
  20. package/dist/{chunk-SJPQQ4OF.js → chunk-GSKJ57XY.js} +234 -234
  21. package/dist/chunk-GSKJ57XY.js.map +1 -0
  22. package/dist/{chunk-4XPVU3N2.js → chunk-H6VWU2HN.js} +2 -2
  23. package/dist/chunk-JRS5QRZG.js +2 -0
  24. package/dist/chunk-JRS5QRZG.js.map +1 -0
  25. package/dist/{chunk-5BI2T3WD.js → chunk-JTDUTCUE.js} +3 -3
  26. package/dist/chunk-JTDUTCUE.js.map +1 -0
  27. package/dist/{chunk-KUOH5MFS.js → chunk-K445URSN.js} +2 -2
  28. package/dist/{chunk-4VVHGR7H.js → chunk-KEXBEUSU.js} +1 -1
  29. package/dist/{chunk-4VVHGR7H.js.map → chunk-KEXBEUSU.js.map} +1 -1
  30. package/dist/chunk-L5UGH4T4.js +160 -0
  31. package/dist/chunk-L5UGH4T4.js.map +1 -0
  32. package/dist/{chunk-V4IFJLQS.js → chunk-LU7GDHGD.js} +2 -2
  33. package/dist/{chunk-D5IHICX3.js → chunk-LUYN6RAC.js} +2 -2
  34. package/dist/chunk-MI7WOGH6.js +4 -0
  35. package/dist/chunk-MI7WOGH6.js.map +1 -0
  36. package/dist/chunk-NY7NHGVT.js +105 -0
  37. package/dist/chunk-NY7NHGVT.js.map +1 -0
  38. package/dist/chunk-NZQBS7GN.js +2 -0
  39. package/dist/{chunk-KBJNJGBP.js.map → chunk-NZQBS7GN.js.map} +1 -1
  40. package/dist/{chunk-3TETB22A.js → chunk-P3I7AATX.js} +2 -2
  41. package/dist/chunk-QAWKN2N4.js +3 -0
  42. package/dist/chunk-QAWKN2N4.js.map +1 -0
  43. package/dist/chunk-QDWEM4DG.js +41 -0
  44. package/dist/chunk-QDWEM4DG.js.map +1 -0
  45. package/dist/{chunk-JP5OAMWQ.js → chunk-RGZARSHV.js} +1 -1
  46. package/dist/{chunk-JP5OAMWQ.js.map → chunk-RGZARSHV.js.map} +1 -1
  47. package/dist/{chunk-GZY5DYXT.js → chunk-RRGITX5B.js} +2 -2
  48. package/dist/{chunk-PHCWYKQW.js → chunk-RVEMX5MJ.js} +2 -2
  49. package/dist/{chunk-PHCWYKQW.js.map → chunk-RVEMX5MJ.js.map} +1 -1
  50. package/dist/{chunk-GUEIF7ZF.js → chunk-SMAI7U6H.js} +2 -2
  51. package/dist/{chunk-S2UXDEGW.js → chunk-SSQMFHSM.js} +2 -2
  52. package/dist/chunk-WWDYDLY2.js +55 -0
  53. package/dist/chunk-WWDYDLY2.js.map +1 -0
  54. package/dist/{chunk-ANC5QXFB.js → chunk-XOUO4XNA.js} +2 -2
  55. package/dist/chunk-YA3P77LV.js +87 -0
  56. package/dist/chunk-YA3P77LV.js.map +1 -0
  57. package/dist/{chunk-OQV3LWJI.js → chunk-ZFRXFUP7.js} +2 -2
  58. package/dist/{chunk-F7GKG5ZO.js → chunk-ZGVVYJIK.js} +3 -3
  59. package/dist/chunk-ZGVVYJIK.js.map +1 -0
  60. package/dist/cli.js +1 -1
  61. package/dist/{client-7UW2ELPP.js → client-NFPBE6L4.js} +2 -2
  62. package/dist/{config-TNYVPT4R.js → config-GHMRBRDL.js} +2 -2
  63. package/dist/{config-mutate-GV7BVG3I.js → config-mutate-2XV27EFV.js} +2 -2
  64. package/dist/config-mutator-6ITNU5DT.js +2 -0
  65. package/dist/{contributions-J57B3KIX.js → contributions-KLRJ4ZXV.js} +2 -2
  66. package/dist/{contributions-J57B3KIX.js.map → contributions-KLRJ4ZXV.js.map} +1 -1
  67. package/dist/{doctor-ROKIYJRT.js → doctor-UBXVMGJG.js} +2 -2
  68. package/dist/{enrich-NH3WHKD6.js → enrich-ZB5I7KHN.js} +2 -2
  69. package/dist/event-levels-CQWHSLMT.js +3 -0
  70. package/dist/event-levels-CQWHSLMT.js.map +1 -0
  71. package/dist/{follow-up-tool-S2U7DFSW.js → follow-up-tool-EARVITTS.js} +2 -2
  72. package/dist/graph-ZVKV3JBD.js +2 -0
  73. package/dist/hub-TILTOOSS.js +2 -0
  74. package/dist/index.d.ts +281 -84
  75. package/dist/index.js +1 -1
  76. package/dist/index.js.map +1 -1
  77. package/dist/load-EOZUZK7U.js +2 -0
  78. package/dist/model-call-PKV5UAQ7.js +2 -0
  79. package/dist/note-reader-IDE6RI34.js +2 -0
  80. package/dist/notes-settings-VPXI5IIS.js +2 -0
  81. package/dist/{program-LAOU5DQ3.js → program-U3HJY7E5.js} +262 -264
  82. package/dist/program-U3HJY7E5.js.map +1 -0
  83. package/dist/{promote-FVWRM4BE.js → promote-RHVZB2QZ.js} +2 -2
  84. package/dist/push-bridge-325SXDGN.js +1 -1
  85. package/dist/query-OZXZVLO7.js +2 -0
  86. package/dist/query-runs-7VX3YAC3.js +4 -0
  87. package/dist/query-runs-7VX3YAC3.js.map +1 -0
  88. package/dist/query-settings-2MGUS6AY.js +3 -0
  89. package/dist/query-settings-2MGUS6AY.js.map +1 -0
  90. package/dist/registry-LZLIPP7N.js +2 -0
  91. package/dist/{request-planner-JOXSAAHO.js → request-planner-MFAIVLUQ.js} +2 -2
  92. package/dist/{review-candidates-6N5435V7.js → review-candidates-6WMDVVIZ.js} +2 -2
  93. package/dist/roster-BZGKG2ZA.js +2 -0
  94. package/dist/{routing-6G2QVFIG.js → routing-OPCLHIYW.js} +2 -2
  95. package/dist/schedule-tool-KPVTMYL3.js +2 -0
  96. package/dist/{scheduler-WOH2O3EP.js → scheduler-G3WWYETY.js} +2 -2
  97. package/dist/score-DZGPLHCL.js +3 -0
  98. package/dist/score-DZGPLHCL.js.map +1 -0
  99. package/dist/{seat-I2FBJDTV.js → seat-3HM4J7IX.js} +2 -2
  100. package/dist/{select-5YZQJLLD.js → select-VEFE2ESF.js} +2 -2
  101. package/dist/{set-enabled-CQEUZLHU.js → set-enabled-US5BYKFZ.js} +2 -2
  102. package/dist/{tool-PIJXUBEC.js → tool-HUSCHORN.js} +2 -2
  103. package/dist/{tool-R77KFLZ3.js → tool-XLWLXGB5.js} +2 -2
  104. package/dist/types-ARP27T6T.js +2 -0
  105. package/dist/types-LJZ2YY5W.js +2 -0
  106. package/dist/types-LJZ2YY5W.js.map +1 -0
  107. package/dist/wiki-GCRRINW3.js +2 -0
  108. package/dist/wiki-GCRRINW3.js.map +1 -0
  109. package/dist/wiki-enrich-P5TNWACZ.js +2 -0
  110. package/dist/wiki-enrich-P5TNWACZ.js.map +1 -0
  111. package/package.json +1 -1
  112. package/dist/absorb-eval-37XZJACN.js +0 -2
  113. package/dist/board-dashboard-GKE4KWJH.js.map +0 -1
  114. package/dist/chunk-2BF6HJJD.js.map +0 -1
  115. package/dist/chunk-4NEO5KB2.js.map +0 -1
  116. package/dist/chunk-57Y2WZT2.js +0 -55
  117. package/dist/chunk-57Y2WZT2.js.map +0 -1
  118. package/dist/chunk-5BI2T3WD.js.map +0 -1
  119. package/dist/chunk-7VLLZQ3N.js +0 -2
  120. package/dist/chunk-7VLLZQ3N.js.map +0 -1
  121. package/dist/chunk-BI6VG4DV.js +0 -37
  122. package/dist/chunk-BI6VG4DV.js.map +0 -1
  123. package/dist/chunk-F7GKG5ZO.js.map +0 -1
  124. package/dist/chunk-IDZXAOBC.js +0 -156
  125. package/dist/chunk-IDZXAOBC.js.map +0 -1
  126. package/dist/chunk-IZDKRNXC.js +0 -52
  127. package/dist/chunk-IZDKRNXC.js.map +0 -1
  128. package/dist/chunk-KBJNJGBP.js +0 -2
  129. package/dist/chunk-KFIJDLQ5.js +0 -3
  130. package/dist/chunk-KFIJDLQ5.js.map +0 -1
  131. package/dist/chunk-RTHZQGFC.js +0 -105
  132. package/dist/chunk-RTHZQGFC.js.map +0 -1
  133. package/dist/chunk-SJPQQ4OF.js.map +0 -1
  134. package/dist/config-mutator-AKCR3VKM.js +0 -2
  135. package/dist/graph-EXDH7EPZ.js +0 -2
  136. package/dist/hub-HOVJC4HR.js +0 -2
  137. package/dist/load-5DNMGHFW.js +0 -2
  138. package/dist/model-call-BGTDPWZD.js +0 -2
  139. package/dist/notes-settings-WMOH2V75.js +0 -2
  140. package/dist/program-LAOU5DQ3.js.map +0 -1
  141. package/dist/query-HBCL3FHO.js +0 -2
  142. package/dist/query-settings-RD6GEN2V.js +0 -3
  143. package/dist/query-settings-RD6GEN2V.js.map +0 -1
  144. package/dist/registry-NT4H7HYP.js +0 -2
  145. package/dist/roster-IRXP32XF.js +0 -2
  146. package/dist/schedule-tool-3NYUPKSC.js +0 -2
  147. package/dist/score-KDNIUTNV.js +0 -3
  148. package/dist/score-KDNIUTNV.js.map +0 -1
  149. package/dist/types-ROL44T62.js +0 -2
  150. package/dist/wiki-GCOFERTB.js +0 -2
  151. /package/dist/{App-WQPA77VJ.js.map → App-4UVAI5C5.js.map} +0 -0
  152. /package/dist/{ChatApp-TGW66I4Y.js.map → ChatApp-COO67WIR.js.map} +0 -0
  153. /package/dist/{absorb-eval-37XZJACN.js.map → absorb-eval-WY3YMLS4.js.map} +0 -0
  154. /package/dist/{agent-FWHYHXWC.js.map → agent-3R5NY7I3.js.map} +0 -0
  155. /package/dist/{chunk-ZN5DC6WS.js.map → chunk-3XVST5XX.js.map} +0 -0
  156. /package/dist/{chunk-F5PVUB4Y.js.map → chunk-4XMALK7X.js.map} +0 -0
  157. /package/dist/{chunk-VH2ASPFQ.js.map → chunk-5NT44FKL.js.map} +0 -0
  158. /package/dist/{chunk-HIUHKOKK.js.map → chunk-6WF56ME6.js.map} +0 -0
  159. /package/dist/{chunk-MCBTVNPX.js.map → chunk-BQIWMQNU.js.map} +0 -0
  160. /package/dist/{chunk-JA5Y4LDP.js.map → chunk-ERULJ2ZL.js.map} +0 -0
  161. /package/dist/{chunk-RJFPCW7T.js.map → chunk-FWDRBUMS.js.map} +0 -0
  162. /package/dist/{chunk-4XPVU3N2.js.map → chunk-H6VWU2HN.js.map} +0 -0
  163. /package/dist/{chunk-KUOH5MFS.js.map → chunk-K445URSN.js.map} +0 -0
  164. /package/dist/{chunk-V4IFJLQS.js.map → chunk-LU7GDHGD.js.map} +0 -0
  165. /package/dist/{chunk-D5IHICX3.js.map → chunk-LUYN6RAC.js.map} +0 -0
  166. /package/dist/{chunk-3TETB22A.js.map → chunk-P3I7AATX.js.map} +0 -0
  167. /package/dist/{chunk-GZY5DYXT.js.map → chunk-RRGITX5B.js.map} +0 -0
  168. /package/dist/{chunk-GUEIF7ZF.js.map → chunk-SMAI7U6H.js.map} +0 -0
  169. /package/dist/{chunk-S2UXDEGW.js.map → chunk-SSQMFHSM.js.map} +0 -0
  170. /package/dist/{chunk-ANC5QXFB.js.map → chunk-XOUO4XNA.js.map} +0 -0
  171. /package/dist/{chunk-OQV3LWJI.js.map → chunk-ZFRXFUP7.js.map} +0 -0
  172. /package/dist/{client-7UW2ELPP.js.map → client-NFPBE6L4.js.map} +0 -0
  173. /package/dist/{config-TNYVPT4R.js.map → config-GHMRBRDL.js.map} +0 -0
  174. /package/dist/{config-mutate-GV7BVG3I.js.map → config-mutate-2XV27EFV.js.map} +0 -0
  175. /package/dist/{config-mutator-AKCR3VKM.js.map → config-mutator-6ITNU5DT.js.map} +0 -0
  176. /package/dist/{doctor-ROKIYJRT.js.map → doctor-UBXVMGJG.js.map} +0 -0
  177. /package/dist/{enrich-NH3WHKD6.js.map → enrich-ZB5I7KHN.js.map} +0 -0
  178. /package/dist/{follow-up-tool-S2U7DFSW.js.map → follow-up-tool-EARVITTS.js.map} +0 -0
  179. /package/dist/{graph-EXDH7EPZ.js.map → graph-ZVKV3JBD.js.map} +0 -0
  180. /package/dist/{hub-HOVJC4HR.js.map → hub-TILTOOSS.js.map} +0 -0
  181. /package/dist/{load-5DNMGHFW.js.map → load-EOZUZK7U.js.map} +0 -0
  182. /package/dist/{model-call-BGTDPWZD.js.map → model-call-PKV5UAQ7.js.map} +0 -0
  183. /package/dist/{notes-settings-WMOH2V75.js.map → note-reader-IDE6RI34.js.map} +0 -0
  184. /package/dist/{promote-FVWRM4BE.js.map → notes-settings-VPXI5IIS.js.map} +0 -0
  185. /package/dist/{query-HBCL3FHO.js.map → promote-RHVZB2QZ.js.map} +0 -0
  186. /package/dist/{registry-NT4H7HYP.js.map → query-OZXZVLO7.js.map} +0 -0
  187. /package/dist/{roster-IRXP32XF.js.map → registry-LZLIPP7N.js.map} +0 -0
  188. /package/dist/{request-planner-JOXSAAHO.js.map → request-planner-MFAIVLUQ.js.map} +0 -0
  189. /package/dist/{review-candidates-6N5435V7.js.map → review-candidates-6WMDVVIZ.js.map} +0 -0
  190. /package/dist/{routing-6G2QVFIG.js.map → roster-BZGKG2ZA.js.map} +0 -0
  191. /package/dist/{schedule-tool-3NYUPKSC.js.map → routing-OPCLHIYW.js.map} +0 -0
  192. /package/dist/{scheduler-WOH2O3EP.js.map → schedule-tool-KPVTMYL3.js.map} +0 -0
  193. /package/dist/{seat-I2FBJDTV.js.map → scheduler-G3WWYETY.js.map} +0 -0
  194. /package/dist/{types-ROL44T62.js.map → seat-3HM4J7IX.js.map} +0 -0
  195. /package/dist/{select-5YZQJLLD.js.map → select-VEFE2ESF.js.map} +0 -0
  196. /package/dist/{set-enabled-CQEUZLHU.js.map → set-enabled-US5BYKFZ.js.map} +0 -0
  197. /package/dist/{tool-PIJXUBEC.js.map → tool-HUSCHORN.js.map} +0 -0
  198. /package/dist/{tool-R77KFLZ3.js.map → tool-XLWLXGB5.js.map} +0 -0
  199. /package/dist/{wiki-GCOFERTB.js.map → types-ARP27T6T.js.map} +0 -0
@@ -0,0 +1,160 @@
1
+ import{$ as $r,H as mr,I as hr,J as yr,L as wr,M as br,N as xr,O as Ir,R as Sr,S as Tr,V as kr,W as vr,a as Zs,b as er,ba as Ar,d as nr,f as ze,l as kt,m as pr,t as vt,v as fr}from"./chunk-QDWEM4DG.js";import{a as Vs}from"./chunk-QSKG754X.js";import{b as tr}from"./chunk-MEFPXHQJ.js";import{a as gr}from"./chunk-W4YR2RO2.js";import{b as rr,c as pn,d as ir,e as Tt,h as ar}from"./chunk-SSQMFHSM.js";import{e as Xs,f as Ys}from"./chunk-36AXN6ZB.js";import{a as ln,b as sr}from"./chunk-J3SOEFRE.js";import{a as gn,b as or}from"./chunk-SIU6STB2.js";import{e as dr,i as cr,j as ur,k as lr}from"./chunk-X5C5W3E4.js";import{a as zs}from"./chunk-6WF56ME6.js";import{g as Js,h as Qs}from"./chunk-ERULJ2ZL.js";import{c as Ns,f as Ls}from"./chunk-K445URSN.js";import{s as Ds,v as St,w as Os,y as ye,z as un}from"./chunk-4XMALK7X.js";import{a as Qe,b as Ee,f as It}from"./chunk-72SZI2UW.js";import{a as _e,b as rn}from"./chunk-FCPTN6NF.js";import{a as Fs,c as Us}from"./chunk-MYVHVJWZ.js";import{d as De,h as Ae}from"./chunk-6TURWSMN.js";import{a as Hs,b as Bs,c as js,d as Ws,l as qs}from"./chunk-AV7T3SYT.js";import{a as Gs,b as Ks}from"./chunk-Y5MFVVTM.js";import{c as Ss,d as Ts}from"./chunk-QOYAX2FT.js";import{e as $e}from"./chunk-DSYKYZMT.js";import{D as As,F as dn,H as ka,K as Cs,O as va,U as Ms,V as cn,W as Ps,X as Je,Y as Rs,Z as _s,da as Es,xa as $a}from"./chunk-DYGQF3MI.js";import{g as Ke,h as Sa}from"./chunk-BRK6M6LA.js";import{f as an,n as Ta}from"./chunk-UIBUZ2N3.js";import{a as ks,b as le,c as vs,d as $s,e as on}from"./chunk-2QNT5JDS.js";un();It();var $t="tool-set",Cr=["answer","code","full"],Mr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Aa=.1;function Rr(n){return{task:Pr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Pr(n.agentPrompt,600)}:{}}}var _r={bundle:Ee({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Er(n,e=Aa){let s=n?.bundle?.probabilities;if(!s)return"full";let r=fn(s.answer),o=fn(s.code),i=fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Dr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Mr.answer.includes(t))?"answer":e.every(t=>Mr.code.includes(t))?"code":"full"}function Or(n,e){return Cr.indexOf(n)<Cr.indexOf(e)}function fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Pr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Nr=!1;function Lr(n,e){let t=St($t);if(t!=="off")return t==="active"&&!Nr&&(Nr=!0,e(`[decisions] seat "${$t}" is set to active, but only shadow is built: it records and changes nothing`)),ye($t,Rr(n),_r,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Er(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Fr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Dr(r);Os(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Or(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Ca(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Ur(n,e){let t=Ca(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function mn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}un();It();var Hr="session-continuity",Br={continues:Qe("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Qe("Does the new request refer to something stated earlier in the conversation?")};function jr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:hn(n.message,1200),previousRequest:n.previousMessage?hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Wr(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ot}from"execa";import{spawn as Ma}from"node:child_process";import{createHash as Pa}from"node:crypto";import{createInterface as Ra}from"node:readline";var we=class extends Error{},_a=n=>Ma("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),yn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Ra({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
2
+ `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},wn=class{constructor(e=_a,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=Pa("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[P])=>w.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new we("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let w=[...this.entries].find(([,P])=>!P.connection.busy);if(!w)throw new we("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:s,connection:new yn(e,this.launchProcess)}}catch{throw new we("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,g,m,h=!1,p=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",p,{once:!0});let x=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),S=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let w={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(S),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let _=new Promise((L,M)=>{i.failTurn=M,i.notify=(D,U)=>{if(U?.threadId!==u)return;let N=U.item,q={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...U,type:D.replace("/","."),...N?{item:{...N,type:q[N.type]||N.type}}:{}}),D==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),D==="item/agentMessage/delta"&&(h||(h=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=U.delta,e.onDelta?.(U.delta,c)),D==="thread/tokenUsage/updated"){let H=U.tokenUsage.last;m=H.inputTokens;let K=H.cachedInputTokens||0;g={inputTokens:(g?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-K),outputTokens:(g?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(g?.cacheReadTokens||0)+K,cacheCreateTokens:(g?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}D==="turn/completed"&&(U.turn.status==="completed"?L():M(new Error(U.turn.error?.message||`Codex turn ${U.turn.status}`)))}});return _.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await _,{content:d??c,codexSessionId:u,billedModel:e.model,usage:g,contextTokens:m,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new we(w.message);return{content:c,codexSessionId:u,usage:g,contextTokens:m,error:w.message,duration:Date.now()-t}}finally{clearTimeout(S),clearTimeout(x),e.signal?.removeEventListener("abort",p),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},qr=new wn;import{execFile as Za}from"child_process";import{StringDecoder as et}from"string_decoder";import{mkdtempSync as co,readFileSync as uo,rmSync as lo}from"fs";import{join as Et}from"path";import{tmpdir as go}from"os";function At(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Ct(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Mt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var Gr=null;function Pt(){return Gr}function fl(n){Gr=n}function Xe(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Ea(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Oe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},Kr=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=Xe(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Ea(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new Oe(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new Oe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Xe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Xe(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Xe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<s&&(s=i,t=o)}if(!t)return!1;let r=Xe(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(s.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Da}from"child_process";import{randomUUID as Oa}from"crypto";import{existsSync as Na,readFileSync as La}from"fs";import{resolve as Fa}from"path";function Ua(n){let e=Fa(n,"CLAUDE.md");if(!Na(e))return null;try{let t=La(e,"utf8");return qs(t)}catch{return null}}var Ha=20*60*1e3,Ba=5e3,Ye=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ve=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function ja(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var Jr=class{constructor(e={}){this.opts=e}spawn(e,t){return new bn(e,t,this.opts)}},bn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=Da(r,o,{cwd:t.workspace,env:Ae(ja({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:Ua(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(h=>{t=h}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=Oa(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
+ `);let c=e.deadlineMs??Ha,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new Ye(c)),g=!1,m=null;try{for(;;){let h=d-Date.now();if(h<=0)throw u();let p=await this.nextEvent(h);if(p===null&&this.killReason)throw new Ve(this.killReason);if(p===null&&!this.exited)throw u();if(p===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!g){if(p.type==="user"&&p.uuid===i)g=!0,m&&(yield{type:m.type,raw:m});else if(p.type==="system"&&p.subtype==="init")m=p;else if(p.type==="result"){m=null;let x=typeof p.result=="string"?p.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${x.length} chars): ${x.slice(0,120)}`)}continue}if(yield{type:p.type,raw:p},p.type==="result"){this.onResultEvent(p);return}}}finally{let h=this.snap.state==="busy";this.snap={...this.snap,...h?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ba);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
+ `))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};on();Ta();rn();import{resolve as Qr,join as zr}from"path";var Wa=4e3;function Rt(n){try{let e=zr(Qr(n.root),".agentx","db.sqlite"),t=an({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=_e(),r=n.input.command?n.input.command.slice(0,Wa):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
5
+ (id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
6
+ verdict, effective_action, mode, severity, approver, ms)
7
+ VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
8
+ @verdict, @effective_action, @mode, @severity, @approver, @ms)`).run({id:s,ts:Date.now(),agent_id:n.input.agentId??null,task_id:n.taskId??null,tool:n.input.tool,command:r,resolved_target:n.verdict.resolvedTarget,matched_rule:n.verdict.ruleId,verdict:n.verdict.action,effective_action:n.verdict.effectiveAction,mode:n.mode,severity:n.verdict.severity,approver:n.approver??null,ms:n.ms??null}),s}catch(e){return process.stderr.write(`[agentx-guard] audit write failed: ${e?.message}
9
+ `),null}}function Al(n){let e=zr(Qr(n.root),".agentx","db.sqlite"),t=an({path:e});if(!t)return[];let s=[],r={};n.verdict&&(s.push("verdict = @verdict"),r.verdict=n.verdict),n.agentId&&(s.push("agent_id = @agentId"),r.agentId=n.agentId),n.taskId&&(s.push("task_id = @taskId"),r.taskId=n.taskId);let o="SELECT * FROM guardrail_decisions"+(s.length?` WHERE ${s.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=n.limit??50,t.prepare(o).all(r)}on();var qa=50,Ga=6*60*60*1e3,_t=null,Ne=new Map;function Rl(n){_t=n===null?null:String(n)}function Yr(){return _t}function Ka(n,e,t,s){let r=new URLSearchParams({agent:e,autonomy:t,task:s}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function Vr(n,e,t){if(!le(n))return{args:[]};if(!_t)return{error:`autonomy "${n}" cannot be enforced: guard hook endpoint is not configured`};let s={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:Ka(_t,e,n,t),timeout:15}]}]}},r=[];return n==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(s)),{args:r}}function Zr(n,e){return!le(n)||e==="claude-code"?null:`autonomy "${n}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function Ja(n){for(let[e,t]of Ne)n-t.at>Ga&&Ne.delete(e)}function Qa(n,e){let t=Date.now();Ja(t);let s=Ne.get(n)??{at:t,blocks:[]};s.blocks.length<qa&&s.blocks.push(e),s.at=t,Ne.set(n,s)}function eo(n){if(!n)return[];let e=Ne.get(n);return Ne.delete(n),e?.blocks??[]}function Xr(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function _l(n,e){let t=n.tool_name??"unknown",s=typeof n.tool_input?.command=="string"?n.tool_input.command:void 0,r=typeof n.tool_input?.file_path=="string"?n.tool_input.file_path:typeof n.tool_input?.notebook_path=="string"?n.tool_input.notebook_path:void 0;try{let o=ks.safeParse(e.level),i=o.success?vs(o.data,{tool:t,command:s,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",c=i.ruleId??"autonomy",d=i.reason??"blocked",u={ts:Date.now(),tool:t,target:(s??r??null)?.slice(0,300)??null,ruleId:c,reason:d},g={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:d,resolvedTarget:null};return Rt({root:e.root,input:{tool:t,command:s??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:g,mode:"enforce",taskId:e.taskId??null}),e.taskId&&Qa(e.taskId,u),{stdout:Xr(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${d} (rule: ${c}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:u}}catch(o){return{stdout:Xr(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}_s();var za=6*60*60*1e3,Ze=new Map;function Xa(n){for(let[e,t]of Ze)n-t.at>za&&Ze.delete(e)}function to(n,e){let t=Date.now();Xa(t),Ze.set(n,{at:t,limits:e})}function no(n){Ze.delete(n)}function Ya(n,e,t){let s=new URLSearchParams({person:"1",task:e,...t?{agent:t}:{}}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${n}/guard/check?${s}`}' || { echo '[agentx-people] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function so(n,e,t){let s=Yr();if(!s)return{error:"this person's tool and skill limits cannot be enforced: guard hook endpoint is not configured"};let r={matcher:"*",hooks:[{type:"command",command:Ya(s,e,t),timeout:15}]},o=[...n],i=o.indexOf("--settings");if(i===-1)return o.push("--settings",JSON.stringify({hooks:{PreToolUse:[r]}})),{args:o};let a=JSON.parse(o[i+1]);return a.hooks=a.hooks??{},a.hooks.PreToolUse=[...a.hooks.PreToolUse??[],r],o[i+1]=JSON.stringify(a),{args:o}}function ro(n){return n==="claude-code"?null:`this person's tool and skill limits are only enforceable on the claude-code tier (agent tier: ${n??"unknown"}); refusing to run without them`}function xn(n){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:n}})}function Va(n,e,t){if(n.tools.some(s=>Je(s,e)))return{skill:null,what:e};if(e==="Skill"){let s=typeof t.skill=="string"?t.skill:typeof t.command=="string"?t.command:"";if(s&&n.skills.some(r=>Je(r,s)))return{skill:s,what:`the skill ${s}`}}return null}function Ll(n,e){let t=n.tool_name??"unknown",s=n.tool_input??{};try{let r=e.taskId?Ze.get(e.taskId):void 0;if(!r)return{stdout:xn("[agentx-people] No limits are on record for this run, so the call is blocked (fail-closed)."),blocked:null};let{limits:o}=r,i=Va(o,t,s);if(!i)return{stdout:"",blocked:null};let a=`${o.name} may not use ${i.what}`,c={matched:!0,action:"deny",effectiveAction:"deny",ruleId:"people.deny",severity:"high",message:a,resolvedTarget:null};return Rt({root:e.root,input:{tool:t,command:typeof s.command=="string"?s.command:t,agentId:e.agentId},verdict:c,mode:"enforce",taskId:e.taskId??null}),{stdout:xn(`[agentx-people] Blocked: ${a} here (set by the owner). Do not work around it. Finish what you can without it and say in your answer what was not done and why.`),blocked:{personId:o.personId,tool:t,skill:i.skill,reason:a}}}catch(r){return{stdout:xn(`[agentx-people] Guard error (fail-closed): ${r?.message??r}`),blocked:null}}}var ed=5e3;function V(n){let e=At(n);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(n||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
10
+ `)}return{error:Ct(e),errorKind:e.kind}}function po(){return`Claude Code CLI not found on PATH. Install it before starting an agent: https://docs.claude.com/en/docs/claude-code . On Linux/macOS: npm i -g @anthropic-ai/claude-code then verify with claude --version. If you don't intend to use the claude-code engine, set the agent's tier to "sdk" or "orchestrator" in agentx.json.`}function Dt(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function oo(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function xe(n,e,t){let s=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of r.peers){let d=c.handle?` (mention: ${c.handle})`:"",u=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${d}${u}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}s.push(o.join(`
11
+ `))}return e.context?.replyToText&&(s.push(""),s.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(s.push(""),s.push(`[Attached file: ${e.context.mediaPath}]`),s.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?s.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?s.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?s.push("A video file is attached. Describe what you can determine about it."):s.push("Please read this file and respond based on its content.")),t&&(s.push(""),s.push(t)),s.push(""),s.push(e.message),s.join(`
12
+ `)}function fo(n,e,t,s,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),s&&a.push("--resume",s);let c=r||n.model;return c&&a.push("--model",c),n.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Sn(n,e){return!e||e.trim().length===0?n:`[System]
13
+ ${e.trim()}
14
+
15
+ [User]
16
+ ${n}`}function td(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n.model;return i&&o.push("--model",i),r&&o.push("--session",r),n.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(Sn(e,s)),o}function nd(n){if(!n||typeof n!="object"||n.type!=="error")return;let e=n.error?.message??n.error??n.message??n.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function io(n){return JSON.stringify(n)}function mo(){let n=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${io(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[n,"serve","--stdio","--cwd",process.cwd()].map(io).join(",")}]`]}function ho(n,e,t,s,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...mo()),i||a.push("--color","never");let c=s||n.model;return c&&a.push("--model",c),n.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(Sn(e,r)),a}function Nt(n,e){let t=De(n.workspace),s=t.HOME||process.env.HOME,r=[t.PATH||"",s?`${s}/.bun/bin`:"",s?`${s}/.local/bin`:"",s?`${s}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(r.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),tt(t,e)}function tt(n,e){return n.AGENTX_AGENT_ID=e.agentId,e.runningTaskId&&(n.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(n.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(n.AGENTX_CHAT_ID=e.context.chatId),n}function Lt(n={}){return{channel:n.channel||"api",chatId:n.chatId||n.group||n.sender||"default"}}function sd(n,e){let t=Nt(n,e),s={};if(t.OPENCODE_CONFIG_CONTENT)try{s=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...s.mcp||{}};for(let[i,a]of Object.entries(n.mcp||{}))r[i]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return r.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...s,mcp:r}),t}function rd(n){if(!n||typeof n!="object")return;if(typeof n.delta=="string")return n.delta;if(typeof n.text_delta=="string")return n.text_delta;if(typeof n.message=="string"&&/message|delta/i.test(String(n.type||"")))return n.message;if(typeof n.text=="string"&&/message|delta|response/i.test(String(n.type||"")))return n.text;let e=n.item||n.msg||n.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(n.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let s=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(s)return s}}function be(...n){for(let e of n)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Tn(n,e=0){if(!n||typeof n!="object"||e>4)return;let t=n.usage||n.token_usage||n.tokenUsage||n.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:be(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:be(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:be(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:be(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let s of[n.msg,n.message,n.response,n.result,n.item]){let r=Tn(s,e+1);if(r)return r}}function yo(n){if(!(!n||typeof n!="object"))return typeof n.model=="string"&&n.model||typeof n.msg?.model=="string"&&n.msg.model||typeof n.message?.model=="string"&&n.message.model||typeof n.response?.model=="string"&&n.response.model||void 0}function kn(n,e=0){if(!(!n||typeof n!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let s=n[t];if(typeof s=="string"&&s.trim())return s.trim()}for(let t of[n.msg,n.message,n.response,n.result,n.item]){let s=kn(t,e+1);if(s)return s}}}function od(n){let e=typeof n=="string"?n:n?.toString("utf8")||"",t,s,r,o;for(let i of e.split(`
17
+ `))if(i.trim())try{let a=JSON.parse(i);t=Tn(a)||t,s=yo(a)||s,r=kn(a)||r,o=wo(a)||o}catch{}return{usage:t,billedModel:s,sessionId:r,apiError:o}}function wo(n){if(!(!n||typeof n!="object")){if(n.type==="error"&&typeof n.message=="string")return ao(n.message);if(n.type==="turn.failed"){let e=n.error?.message??n.error;if(typeof e=="string")return ao(e)}}}function ao(n){let e=n.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),s=t?.error?.message??t?.message;if(typeof s=="string"&&s.trim())return s.trim()}catch{}return e}function id(n){let e=n.permissionMode||"default",t=e==="bypassPermissions",s=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:s}}function vn(n,e,t,s,r){let o=id(e),i=t||e.model||"<default>",a=s?` resume=${s.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${n} via=${r} model=${i} perm=${o.summary}${a}
18
+ `)}function ad(n){try{let e=JSON.parse(n);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function dd(n){try{let e=JSON.parse(n),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,s=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||Mt(e.modelUsage)||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:s,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0,costUsd:typeof e.total_cost_usd=="number"?e.total_cost_usd:void 0}}catch{return{text:n}}}async function bo(n,e,t,s,r){let o=Date.now(),i=xe(n,e,t),a=Io(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=fo(n,i,!1,s,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...a.args]);if(vn(e.agentId,n,e.model,s,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let d;try{let u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),{stdout:g,stderr:m,exitCode:h,killed:p}=await new Promise(w=>{let P=Ae(tt(De(n.workspace),e),n.billing),_=!1,L=Za("claude",c,{cwd:n.workspace,timeout:u,maxBuffer:10*1024*1024,env:{...P,HOME:P.HOME||"/home/"+(P.USER||"user")}},(M,D,U)=>{w({stdout:D||"",stderr:U||"",exitCode:M?M.code??1:0,killed:_})});if(L.stdin?.end(),r){let M=()=>{_=!0,d=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{L.kill("SIGTERM")}catch{}setTimeout(()=>{try{L.killed||L.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?M():r.addEventListener("abort",M,{once:!0})}});if(p)return{content:"",error:d||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!g&&h!==0){let w,P=Date.now()-o;return h===143&&P<u-ed?{content:"",error:`Claude Code was stopped (SIGTERM) after ${Math.round(P/1e3)}s, before its ${Math.round(u/6e4)}m time limit`,errorKind:"interrupted",duration:P}:(h===143?w=`Claude Code timed out after ${Math.round(u/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h==="ENOENT"||/ENOENT|spawn claude/i.test(m||"")?w=po():w=m?.trim()||`Claude Code exited with code ${h}`,{content:"",...V(w),duration:Date.now()-o})}let x=ad(g);if(x)return{content:"",...V(x),duration:Date.now()-o};let S=dd(g);return{content:S.text,duration:Date.now()-o,claudeSessionId:S.sessionId,usage:S.usage,numTurns:S.numTurns,costUsd:S.costUsd,billedModel:S.billedModel}}catch(u){return console.error(`[runtime] execFile threw: ${u.message}`),{content:"",error:u.message||"Claude Code failed",duration:Date.now()-o}}}async function xo(n,e,t,s,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=xe(n,e,s),d=Io(e);if("error"in d)return{content:"",error:d.error,duration:Date.now()-a};let u=fo(n,c,!0,r,e.model,e.systemPromptAppend,[...e.claudeArgs??[],...d.args]);vn(e.agentId,n,e.model,r,"stream");let g="",m="",h="",p=N=>{let q=m&&!h?`
19
+
20
+ `:"";h+=N,g=m+(m?`
21
+
22
+ `:"")+h,t(q+N,g)},x=new In,S=!1,w,P,_,L,M,D,U;try{let N=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),q=Ae(tt(De(n.workspace),e),n.billing),H=Ot("claude",u,{cwd:n.workspace,timeout:N,reject:!1,env:q,extendEnv:!1,buffer:!1,stdin:"ignore"}),K=()=>{},X=new Promise(W=>{K=W}),A=!1,T;if(i){let W=()=>{A=!0,T=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{H.kill("SIGTERM")}catch{}setTimeout(()=>{try{H.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?W():i.addEventListener("abort",W,{once:!0})}let b="",O=new et("utf8");H.stdout&&H.stdout.on("data",W=>{b+=O.write(W);let te=b.split(`
23
+ `);b=te.pop()||"";for(let ne of te)if(ne.trim())try{let R=JSON.parse(ne);if(o)try{o(R)}catch{}if(R.type==="assistant"&&R.message?.usage){let se=R.message.usage,ie=(se.input_tokens||0)+(se.cache_read_input_tokens||0)+(se.cache_creation_input_tokens||0);ie>0&&(L=ie)}if(R.type==="assistant"&&R.message?.content){for(let se of R.message.content)if(se.type==="text"&&se.text){let ie=se.text.slice(h.length);ie&&p(ie)}}if(R.type==="content_block_delta"&&R.delta?.text&&p(R.delta.text),x.observe(R),R.type==="result"&&R.result){if(R.is_error&&typeof R.result=="string")U=R.result;else{let se=(typeof R.result=="string",R.result);if(typeof se=="string"&&se.length>h.length){let ie=se.slice(h.length);ie&&p(ie)}}R.usage&&(P={inputTokens:R.usage.input_tokens||0,outputTokens:R.usage.output_tokens||0,cacheReadTokens:R.usage.cache_read_input_tokens||0,cacheCreateTokens:R.usage.cache_creation_input_tokens||0}),typeof R.model=="string"?w=R.model:w=Mt(R.modelUsage)||w,typeof R.session_id=="string"&&(_=R.session_id),typeof R.num_turns=="number"&&(M=R.num_turns),typeof R.total_cost_usd=="number"&&(D=R.total_cost_usd)}R.type==="result"&&(x.pending===0?K():(S||process.stderr.write(`[claude-stream] agent=${e.agentId} task=${e.taskId??"?"} turn ended with ${x.pending} background task(s) running; the task stays open until they end
24
+ `),S=!0,h&&(m=g,h=""))),R.type==="system"&&R.subtype==="init"&&(typeof R.model=="string"&&(w=R.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${R.apiKeySource} version=${R.claude_code_version} model=${R.model} permMode=${R.permissionMode}
25
+ `))}catch{ne.trim()&&!ne.startsWith("{")&&p(ne+`
26
+ `)}});let B=await md(H,X),C=O.end();if(C&&(b+=C),A)return{content:"",error:T||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!g&&B.stdout&&(g=typeof B.stdout=="string"?B.stdout:""),B.exitCode!==0&&!g){let W=typeof B.stderr=="string"?B.stderr:"",te=B,ne;return te.timedOut?ne=`Claude Code timed out after ${Math.round(N/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:te.signal?ne=W.trim()||`Claude Code killed by signal ${te.signal}`:te.code==="ENOENT"||/ENOENT|spawn claude/i.test((te.shortMessage||"")+" "+W)?ne=po():ne=W.trim()||`Claude Code exited with code ${te.exitCode??"unknown"}`,{content:"",...V(ne),duration:Date.now()-a}}return U?{content:"",...V(U),duration:Date.now()-a,usage:P,contextTokens:L,numTurns:M,billedModel:w,claudeSessionId:_}:{content:g,duration:Date.now()-a,usage:P,contextTokens:L,numTurns:M,costUsd:D,billedModel:w,claudeSessionId:_}}catch(N){return{content:g||"",...V(N.message),duration:Date.now()-a,usage:P,contextTokens:L,numTurns:M,billedModel:w,claudeSessionId:_}}}async function cd(n,e,t,s){let r=Date.now(),o=xe(n,e,t),i=co(Et(go(),"agentx-codex-")),a=Et(i,"last-message.txt"),c=ho(n,o,!1,e.model,e.systemPromptAppend,a,s);try{let d=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),u=await Ot("codex",c,{cwd:n.workspace,timeout:d,reject:!1,env:Nt(n,e),extendEnv:!1,stdin:"ignore"}),g=od(u.stdout);if(u.exitCode!==0||g.apiError){let h=u,p;return h.timedOut?p=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:g.apiError?p=g.apiError:h.signal?p=u.stderr.trim()||`Codex CLI killed by signal ${h.signal}`:h.code==="ENOENT"||/ENOENT|spawn codex/i.test((h.shortMessage||"")+" "+u.stderr)?p=Dt():p=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${h.exitCode??"unknown"}`,{content:"",...V(p),duration:Date.now()-r,usage:g.usage,billedModel:g.billedModel,codexSessionId:g.sessionId||s}}let m="";try{m=uo(a,"utf8").trim()}catch{}return m||(m=u.stdout.trim()),{content:m,duration:Date.now()-r,usage:g.usage,billedModel:g.billedModel,codexSessionId:g.sessionId||s}}catch(d){let u=/ENOENT|spawn codex/i.test(d?.message||"")?Dt():d?.message;return{content:"",...V(u||"Codex CLI failed"),duration:Date.now()-r}}finally{lo(i,{recursive:!0,force:!0})}}async function ud(n,e,t,s,r,o){let i=Date.now(),a=xe(n,e,s),c=co(Et(go(),"agentx-codex-")),d=Et(c,"last-message.txt"),u=ho(n,a,!0,e.model,e.systemPromptAppend,d,r),g="",m,h,p,x;try{let S=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),w=Ot("codex",u,{cwd:n.workspace,timeout:S,reject:!1,env:Nt(n,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let P="",_="",L=!1,M=new et("utf8"),D=new et("utf8"),U=Math.min(S,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),N,q=()=>{N&&clearTimeout(N),N=setTimeout(()=>{L=!0,w.kill("SIGTERM",{forceKillAfterTimeout:5e3})},U)};q(),w.stderr?.on("data",T=>{q(),_+=D.write(T),_.length>16e3&&(_=_.slice(-16e3))}),w.stdout?.on("data",T=>{q(),P+=M.write(T);let b=P.split(`
27
+ `);P=b.pop()||"";for(let O of b)if(O.trim())try{let B=JSON.parse(O);if(o)try{o(B)}catch{}m=Tn(B)||m,h=yo(B)||h,p=kn(B)||p,x=wo(B)||x;let C=rd(B);if(C&&C!==g){let W=C.startsWith(g)?C.slice(g.length):C;g=C.startsWith(g)?C:g+C,W&&t(W,g)}}catch{g+=O+`
28
+ `,t(O+`
29
+ `,g)}});let H=await w;N&&clearTimeout(N);let K=M.end();K&&(P+=K);let X=D.end();if(X&&(_+=X),H.exitCode!==0&&!g||x){let T=_||(typeof H.stderr=="string"?H.stderr:""),b=H,O;return L?O=`Codex CLI produced no output for ${Math.round(U/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:b.timedOut?O=`Codex CLI timed out after ${Math.round(S/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:x?O=x:b.signal?O=T.trim()||`Codex CLI killed by signal ${b.signal}`:b.code==="ENOENT"||/ENOENT|spawn codex/i.test((b.shortMessage||"")+" "+T)?O=Dt():O=T.trim()||`Codex CLI exited with code ${b.exitCode??"unknown"}`,{content:"",...V(O),duration:Date.now()-i,usage:m,billedModel:h,codexSessionId:p||r}}let A="";try{A=uo(d,"utf8").trim()}catch{}if(A&&A!==g){let T=A.startsWith(g)?A.slice(g.length):A;g=A,T&&t(T,g)}return{content:g,duration:Date.now()-i,usage:m,billedModel:h,codexSessionId:p||r}}catch(S){let w=/ENOENT|spawn codex/i.test(S?.message||"")?Dt():S?.message;return{content:g,...V(w||"Codex CLI failed"),duration:Date.now()-i,usage:m,billedModel:h,codexSessionId:p||r}}finally{lo(c,{recursive:!0,force:!0})}}async function ld(n,e,t,s,r,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=xe(n,e,s),u=td(n,d,e.model,e.systemPromptAppend,e.freshSession?void 0:r),g="",m,h=e.freshSession?void 0:r,p,x,S=!0,w;try{let P=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),_=sd(n,e);if(n.persistentProcess)try{x=await Us.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:n.workspace,env:_,model:e.model||n.model,permission:n.permissionMode,fresh:e.freshSession,signal:i}),u.splice(1,0,"--server",x.url),_=x.env,o?.({type:"opencode.ready",reused:x.reused,startupMs:Date.now()-c})}catch(T){if(!(T instanceof Fs))throw T;T.standalone&&u.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:T.message})}if(i?.aborted)throw new Error("task cancelled by operator");let L=Ot("opencode",u,{cwd:n.workspace,timeout:P,reject:!1,env:_,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||n.model,resumeSessionId:r})}catch{}let M=!1,D,U=()=>{x?.invalidate(),M=!0,D=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{L.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",U,{once:!0}),w=()=>i?.removeEventListener("abort",U),i?.aborted&&U();let N="",q="",H=new et("utf8"),K=new et("utf8"),X=T=>{if(T.trim())try{let b=JSON.parse(T);try{o?.(b)}catch{}typeof b.sessionID=="string"&&(h=b.sessionID);let O=b.type==="text"&&typeof b.part?.text=="string"?b.part.text:void 0;O&&(g||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:x?.reused??!1}),g+=O,t?.(O,g));let B=b.type==="reasoning"&&typeof b.part?.text=="string"?b.part.text:void 0;B&&a?.(B);let C=b.type==="step_finish"?b.part?.tokens:void 0;C&&(m={inputTokens:be(C.input),outputTokens:be(C.output),cacheReadTokens:be(C.cache?.read),cacheCreateTokens:be(C.cache?.write)}),p=nd(b)||p}catch{g+=T+`
30
+ `,t?.(T+`
31
+ `,g)}};L.stdout?.on("data",T=>{N+=H.write(T);let b=N.split(`
32
+ `);N=b.pop()||"";for(let O of b)X(O)}),L.stderr?.on("data",T=>{q+=K.write(T)});let A=await L;if(i&&i.removeEventListener("abort",U),N+=H.end(),N.trim()&&X(N),q+=K.end(),M)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(A.exitCode!==0||p){let T=A,b;return T.timedOut?b=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?b=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+q)?b=oo():b=q.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...V(b),duration:Date.now()-c,usage:m,opencodeSessionId:h}}return S=!1,{content:g.trim(),duration:Date.now()-c,usage:m,billedModel:e.model||n.model,opencodeSessionId:h}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(P?.message||"")?oo():P?.message;return{content:g,...V(_||"OpenCode failed"),duration:Date.now()-c,usage:m,opencodeSessionId:h}}finally{w?.(),x?.release(S)}}async function gd(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=xe(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function pd(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),g=new AbortController,m=!1,h=()=>{let S=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{g.abort(new Error(S))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{m=!0;try{g.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let x=()=>({content:"",...V(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let S=n.provider||"claude-code",w=s?`${s}
33
+
34
+ ${e.message}`:e.message,P=e.context?.sender,_=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),L=e.context?.channel==="web-chat"&&_?{userId:P,agentId:e.agentId||"acme-public"}:void 0,M=Ws(n),D=Object.keys(M).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:L,providerOpts:o,abortSignal:g.signal,mcpServers:D?M:void 0};if(r){let{generateStream:X}=await import("./agent-3R5NY7I3.js"),A="",T,b,O,B;for await(let C of X(U)){if(c)try{c(C)}catch{}if(C.type==="text_delta")A+=C.text,r(C.text,A);else if(C.type==="thinking_delta")C.text&&i&&i(C.text);else if(C.type==="generate_result"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}T=C.result.tokensUsed,C.result.inputTokens!=null&&(b=C.result.inputTokens),C.result.outputTokens!=null&&(O=C.result.outputTokens)}else if(C.type==="done"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}C.result.tokensUsed!=null&&(T=C.result.tokensUsed)}else C.type==="error"&&(B=C.error)}return B&&!A?m?x():B==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${B}`),duration:Date.now()-d}:((b===void 0||O===void 0)&&T&&(b=Math.round(T*.7),O=T-b),{content:A||"Done.",tokensUsed:T,usage:b!==void 0||O!==void 0?{inputTokens:b||0,outputTokens:O||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:N}=await import("./agent-3R5NY7I3.js"),q=await N(U),H=q.inputTokens,K=q.outputTokens;if((H===void 0||K===void 0)&&q.tokensUsed){let X=q.tokensUsed;H=Math.round(X*.7),K=X-H}return{content:q.content||"Done.",tokensUsed:q.tokensUsed,usage:H!==void 0||K!==void 0?{inputTokens:H||0,outputTokens:K||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(S){return m?x():S?.message==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var In=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},fd=1e3;async function md(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),fd),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function hd(n,e,t,s,r,o,i){let a=Pt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Lt(e.context),g={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(g,"freshSession=true")}catch{}let m,h=!1;try{let A=a.list().length;m=a.acquire(g,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>A}catch(A){return A instanceof Oe,null}h&&vn(e.agentId,n,e.model,s,"persistent");let p=xe(n,e,t),x="",S,w,P,_,L,M,D,U="",N="",q=A=>{if(!i||!A)return;let T;if(N&&A.startsWith(N)?T=A.slice(N.length):T=U&&!U.endsWith(`
35
+ `)?`
36
+
37
+ ${A}`:A,N=A,!!T){U+=T;try{i(T,U)}catch{}}},H=!1,K=()=>{H=!0,a.kill(g,"operator-cancel").catch(()=>{})};o&&(o.aborted?K():o.addEventListener("abort",K,{once:!0}));let X=!1;try{let A=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of m.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:A})){if(X=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let b=T.raw.message?.content??[];for(let B of b)B.type==="text"&&typeof B.text=="string"?(x=B.text,q(B.text)):B.type==="tool_use"&&(N="");let O=T.raw.message?.usage;if(O){let B=(O.input_tokens||0)+(O.cache_read_input_tokens||0)+(O.cache_creation_input_tokens||0);B>0&&(_=B)}}if(T.type==="result"){let b=T.raw;if(b.is_error){let O=V(typeof b.result=="string"?b.result:"claude error");S=O.error,w=O.errorKind}else typeof b.result=="string"&&b.result.length>0&&(x=b.result,U||q(b.result));typeof b.session_id=="string"&&(D=b.session_id),b.usage&&(P={inputTokens:b.usage.input_tokens||0,outputTokens:b.usage.output_tokens||0,cacheReadTokens:b.usage.cache_read_input_tokens||0,cacheCreateTokens:b.usage.cache_creation_input_tokens||0}),typeof b.num_turns=="number"&&(L=b.num_turns),typeof b.message?.model=="string"?M=b.message.model:typeof b.model=="string"?M=b.model:M=Mt(b.modelUsage)||M}}}catch(A){if(H)S="task cancelled by operator",w="cancelled";else if(X)if(A instanceof Ve)S=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,w="interrupted";else if(A instanceof Ye){let T=V(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);S=T.error,w=T.errorKind}else{let T=V(`persistent claude process error: ${A?.message||String(A)}`);S=T.error,w=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(g,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",K),null}finally{o&&o.removeEventListener("abort",K)}return H&&!S&&(S="task cancelled by operator",w="cancelled"),{content:H?"":x,error:S,errorKind:w,duration:Date.now()-c,usage:P,contextTokens:_,numTurns:L,billedModel:M,claudeSessionId:D}}function Io(n){let e=le(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?Vr(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:so(t.args,n.taskId,n.agentId)}function yd(n){return le(n.autonomy)||!!n.personLimits}async function wd(n,e,t,s,r,o,i){let a=le(e.autonomy)?e.autonomy:void 0,c=a&&Zr(a,n.tier)||e.personLimits&&ro(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${$s(a)}
38
+
39
+ ${e.message}`:e.message},g=[a?`level=${a}`:"",e.personLimits?`person=${e.personLimits.personId}`:""].filter(Boolean).join(" ");process.stderr.write(`[claude-guarded] agent=${e.agentId} ${g} task=${d} via=spawn (persistent process bypassed)
40
+ `),e.personLimits&&to(d,e.personLimits);try{let m=t?await xo(n,u,t,s,r,o,i):await bo(n,u,s,r,i);if(!a)return m;let h=eo(d);return{...m,autonomy:a,...h.length?{autonomyBlocks:h}:{}}}finally{e.personLimits&&no(d)}}async function So(n,e,t,s,r,o,i,a,c){if(yd(e))return wd(n,e,s,r,o,i,a);switch(n.tier){case"claude-code":if(n.persistentProcess){let d=await hd(n,e,r,o,i,a,s);if(d!==null)return d}return s?xo(n,e,s,r,o,i,a):bo(n,e,r,o,a);case"codex-cli":if(n.persistentProcess)try{let d=await qr.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:n.workspace,env:Nt(n,e),args:mo(),model:e.model||n.model,bypass:n.permissionMode==="bypassPermissions",prompt:Sn(xe(n,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:s});return{...d,...d.error?V(d.error):{}}}catch(d){if(!(d instanceof we))throw d;if(i?.({type:"codex.fallback",reason:d.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return s?ud(n,e,s,r,o,i):cd(n,e,r,o);case"opencode":return ld(n,e,s,r,o,i,a,c);case"sdk":{let d=n.provider||"claude",u=t[d]?.apiKey;return u?gd(n,e,u,r):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=n.provider||"claude-code",u=t[d],g=u?.apiKey;return pd(n,e,g,r,s,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${n.tier}`}}}import{readFileSync as Le,writeFileSync as To,mkdirSync as bd,existsSync as $n,readdirSync as An}from"fs";import{resolve as Fe}from"path";var Cn=12e3,nt=30,xd=720,Id=40,Sd=18e4,Td="[Compacted conversation summary",kd=7*864e5,vd=[/\bearlier\b/i,/\bbefore\b/i,/\bjust said\b/i,/\btold (?:me|you|us|him|her|them)\b/i,/\bmention(?:ed|ing)?\b/i,/\bask(?:ed)? (?:me|you|him|her|them|about)\b/i,/\bping(?:ed)?\b/i,/\bdm\b/i,/\bdirect message\b/i,/\bother (?:chat|group|conversation|thread)\b/i,/\bthat (?:chat|group|conversation|thread)\b/i,/\bsame (?:issue|thread|conversation)\b/i,/\bcontinuing\b/i,/@\w{2,}_?(?:bot|agent)\b/i,/قلت/,/قال(?:لك|لي|له|لها|لنا)?/,/قبل/,/الحين/,/الثاني/,/المجموعة/];function $d(n){return n?vd.some(e=>e.test(n)):!1}var Ad=[{re:/\byesterday\b/i,days:2},{re:/\bأمس\b/,days:2},{re:/\bcouple (?:of )?days\b/i,days:4},{re:/\bfew days\b/i,days:4},{re:/\blast week\b/i,days:8},{re:/\bالأسبوع الماضي\b/,days:8},{re:/\bweek ago\b/i,days:8},{re:/\bremember\b/i,days:3},{re:/\bpreviously\b/i,days:3},{re:/\bwe (?:discussed|talked|agreed|decided)\b/i,days:3},{re:/\bas (?:i|we) (?:said|told|mentioned)\b/i,days:3},{re:/\bcontinue from\b/i,days:3},{re:/\bتذكر\b/,days:3}];function vo(n){if(!n)return null;let e=0;for(let t of Ad)t.re.test(n)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function ko(n,e,t,s){if(n.length===0)return!1;let r=n[n.length-1];return r.role===e&&(r.name??"")===t&&r.content===s}function $o(n,e){let t=(n??[]).filter(o=>o.role==="user"),s=t[t.length-1];return s?(s.content===e?t[t.length-2]:s)?.content??null:null}function Ao(n,e,t){if(t<=0)return[];let s=(n??[]).filter(i=>i.role==="user"),r=s[s.length-1],o=(r&&r.content===e?s.length-1:s.length)-1;return o<=0?[]:s.slice(Math.max(0,o-t),o).map(i=>i.content)}function Cd(n){let e=n.slice(11,16),t=e.slice(0,2),s=parseInt(e.slice(3,5),10);if(Number.isNaN(s))return e;let r=Math.floor(s/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var Ft=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;tierTwoThresholdTokensByChannel;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=Fe(e,".agentx/sessions"),$n(this.sessionsDir)||bd(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??xd),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??Id),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Sd),this.tierTwoThresholdTokensByChannel=Object.fromEntries(Object.entries(t.tierTwoThresholdTokensByChannel??{}).map(([s,r])=>[s,Math.max(5e4,r)]))}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,s,r){if(r?.length){let u=this.getSession(e,t,s);u.messages.length===0&&this.appendSeededMessages(u,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,s),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,s);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let d=(async()=>{try{let u=await c.seedHistory(s,{maxMessages:nt,maxChars:Cn});u.length>0&&this.appendSeededMessages(a,u)}catch{}})();this.seedingPromises.set(o,d);try{await d}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let s=new Set;for(let o of e.messages)o.externalId&&s.add(o.externalId);let r=0;for(let o of t)o.externalId&&s.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,s){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${s}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Fe(this.sessionsDir,`${t}.json`)}getSession(e,t,s){let r=this.sessionKey(e,t,s);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if($n(o))try{let d=JSON.parse(Le(o,"utf-8"));return this.cache.set(r,d),d}catch{}let i=this.loadPreviousDaySession(e,t,s),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:s,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,c),this.save(c),c}loadPreviousDaySession(e,t,s){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${s}:${r}`,i=this.sessionFile(o);if(!$n(i))return null;try{return JSON.parse(Le(i,"utf-8"))}catch{return null}}addUserMessage(e,t,s,r,o){let i=this.getSession(e,t,s);ko(i.messages,"user",r,o)||(i.messages.push({role:"user",name:r,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,s,r){let o=this.getSession(e,t,s),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(r||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,s,r){let o=this.getSession(e,t,s);ko(o.messages,"agent",e,r)||(o.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,s){return this.getSession(e,t,s).claudeSessionId}setClaudeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,s){return this.getSession(e,t,s).codexSessionId}setCodexSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,s){return this.getSession(e,t,s).opencodeSessionId}setOpenCodeSessionId(e,t,s,r){let o=this.getSession(e,t,s);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,s,r={}){let o=this.getSession(e,t,s);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??nt),a=Math.max(200,r.maxChars??Cn),c=[],d=0;for(let m=o.messages.length-1;m>=0&&c.length<i;m--){let h=o.messages[m];if(d+=h.content.length,c.push(h),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],g="";for(let m of c){let h=Cd(m.timestamp);h!==g&&(u.push(`\u2014 ${h} \u2014`),g=h);let p=m.name||(m.role==="user"?"User":"Agent");u.push(`${p}: ${m.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
41
+ `)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),s=new Date;s.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():s.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=An(this.sessionsDir).filter(L=>L.startsWith(`${a}:`)&&L.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),u=i.slice(0,10),g=/:(\d{4}-\d{2}-\d{2})\.json$/,m=c.filter(L=>{let M=L.match(g);if(!M)return!1;let D=M[1];return D>=d&&D<=u}),h=[],p=0,x=e.query?.toLowerCase(),S=e.participants?.length?new Set(e.participants):void 0;for(let L of m){let M;try{M=JSON.parse(Le(Fe(this.sessionsDir,L),"utf-8"))}catch{continue}if(M.agentId===e.agentId&&!(e.channel&&M.channel!==e.channel)&&!(e.chatId&&M.chatId!==e.chatId))for(let D of M.messages)p++,!(!D.timestamp||D.timestamp<o||D.timestamp>=i)&&(S&&D.role==="user"&&!S.has(D.name??"")||x&&!D.content.toLowerCase().includes(x)||h.push({ts:D.timestamp,role:D.role,senderName:D.name??"",content:D.content,channel:M.channel,chatId:M.chatId,day:M.day,sessionFile:L}))}h.sort((L,M)=>M.ts.localeCompare(L.ts));let w=h.slice(0,t),P=w.length>0?w[w.length-1].ts:null,_=h.length>t;return{turns:w,oldestTs:P,hasMore:_,totalScanned:p}}recentByChatId(e){let t=Math.min(Math.max(e.limit??nt,1),200),s=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=s.slice(0,10),o;try{o=An(this.sessionsDir).filter(g=>g.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,a=o.filter(g=>{if(!g.includes(i))return!1;let m=g.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return m?m[1]>=r:!1}),c=[];for(let g of a){let m;try{m=JSON.parse(Le(Fe(this.sessionsDir,g),"utf-8"))}catch{continue}if(!(m.channel!==e.channel||m.chatId!==e.chatId))for(let h of m.messages)!h.timestamp||h.timestamp<s||c.push({ts:h.timestamp,role:h.role,senderName:h.name??"",content:h.content,agentId:m.agentId,sessionFile:g})}let d=new Set,u=[];for(let g of c){let m=`${g.ts}|${g.role}|${g.senderName}|${g.content}`;d.has(m)||(d.add(m),u.push(g))}return u.sort((g,m)=>g.ts.localeCompare(m.ts)),u.slice(-t)}sessionIdleMs(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,s,r){let o=this.getSession(e,t,s);return!o.claudeSessionId&&!o.codexSessionId&&!o.opencodeSessionId?!1:(r??Date.now()-new Date(o.updatedAt).getTime())>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,s,r){if(r!==void 0&&r!==""&&!$d(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,s);try{let a=An(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let u=JSON.parse(Le(Fe(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let g=u.messages.slice(-4),h=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,p=g.map(x=>` [${x.timestamp.slice(11,16)}] ${x.name||x.role}: ${x.content.slice(0,200)}`);c.push(`From ${h} (${u.channel}):
42
+ ${p.join(`
43
+ `)}`)}catch{}return c.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...c,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
44
+ `)}catch{return""}}async compactIfNeeded(e,t,s,r){let o=this.getSession(e,t,s),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-FS6XNRLM.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,r,{channel:t,chatId:s});return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,s){let r=this.getSession(e,t,s);return r.messages.length>0&&r.messages[0].content.startsWith(Td)}clearClaudeSessionId(e,t,s){let r=this.getSession(e,t,s);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,s){let r=this.getSession(e,t,s);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,s){let r=this.getSession(e,t,s);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.getTierTwoThresholdTokens(t)}recordTurnUsage(e,t,s,r,o){let i=this.getSession(e,t,s);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return Fe(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(Le(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,s,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${s}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},To(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,s){let r=this.readRotationMemos()[`${e}:${t}:${s}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>kd?null:r}getTurnCount(e,t,s){return this.getSession(e,t,s).turnCount??0}getLastTurnInputTokens(e,t,s){return this.getSession(e,t,s).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,s){let r=this.getSession(e,t,s);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getRawLastTurnContextTokens(e,t,s){return this.getSession(e,t,s).lastTurnContextTokens??null}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(e){return(e?this.tierTwoThresholdTokensByChannel[e]:void 0)??this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>nt&&(e.messages=e.messages.slice(-nt));let s=e.messages.reduce((o,i)=>o+i.content.length,0);for(;s>Cn&&e.messages.length>2;){let o=e.messages.shift();s-=o.content.length}let r=t-e.messages.length;r>0&&$e.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${s}c)`)}save(e){try{let t=this.sessionFile(e.id);To(t,JSON.stringify(e,null,2))}catch{}}};var Ut=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),s=this.windows.get(e)||[],r=t-36e5,o=s.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let s=t.maxWaitMs??3e5,r=Date.now()+s,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(s/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),s=this.windows.get(e)||[];return{lastMinute:s.filter(r=>r>t-6e4).length,lastHour:s.filter(r=>r>t-36e5).length}}};var Md={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,"workflow-run":200,memory:400,history:1200,"cross-chat":800,wiki:2500}},Co=4;function Mo(n,e=Md){let t=Pd(n,e);t.sort((i,a)=>i.priority-a.priority);let s=[],r=0,o=e.totalBudget*Co;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Co,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(r+c.length>o){let d=o-r;d>100&&s.push(c.slice(0,d)+"...");break}s.push(c),r+=c.length}return s.join(`
45
+
46
+ `)}function Pd(n,e){let t=(i,a)=>e.layerBudgets?.[i]??a,s=[];if(s.push(Rd(n,t("channel",200))),s.push(_d(n,t("scope",200))),n.landscape&&s.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:n.landscape,tags:["landscape","world-model"]}),n.systemPrompt&&s.push({name:"identity",priority:4,maxTokens:t("identity",200),content:n.systemPrompt.split(`
47
+ `)[0],tags:["identity",n.agentId]}),n.bootstrapContext&&s.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:n.bootstrapContext,tags:["bootstrap","identity","personality"]}),n.references&&s.push({name:"references",priority:4.7,maxTokens:t("references",500),content:n.references,tags:["references","verified","deterministic"]}),n.intent&&n.intent.path.length>0){let i=[`[Intent path: ${n.intent.pathLabel}${n.intent.status==="pending"?" (pending approval)":""}]`],a=n.intent.path[n.intent.path.length-1],c=n.intent.axes?.[a];if(c&&Object.keys(c).length){let d=Object.entries(c).map(([u,g])=>` ${u}: ${g}`).join(`
48
+ `);i.push(d)}n.intent.leaf?.input&&i.push(` input: ${n.intent.leaf.input}`),s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
49
+ `),tags:["intent",...n.intent.path]})}else{let i=Ed(n.message);i.length&&s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];n.replyToText&&r.push(`[Replying to]: ${n.replyToText.slice(0,300)}`),n.mediaPath&&(r.push(`[Attached file: ${n.mediaPath}]`),r.push(`[File type: ${n.mediaType||"unknown"}]`),n.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):n.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),n.issueMR&&r.push(`[${n.issueMR.type} #${n.issueMR.iid}: ${n.issueMR.title}]`),r.length&&s.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
50
+ `),tags:["artifacts",...n.mediaType?["media"]:[]]}),n.skillInjection&&s.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:n.skillInjection,tags:["skills","auto-inject"]}),n.patternContext&&s.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:n.patternContext,tags:["patterns","behavioral","self-improving"]}),n.procedureContext&&s.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:n.procedureContext,tags:["procedures","sop"]}),n.workflowRunContext&&s.push({name:"workflow-run",priority:6.55,maxTokens:t("workflow-run",200),content:n.workflowRunContext,tags:["workflow","plan"]}),n.memoryContext&&s.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:n.memoryContext,tags:["memory","persistent"]});let o=n.groupHistory||n.sessionHistory;if(o&&s.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"]}),n.crossChatContext&&s.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:n.crossChatContext,tags:["history","cross-chat"]}),n.contextOnDemand&&s.push({name:"on-demand",priority:7,maxTokens:t("on-demand",150),content:n.contextOnDemand,tags:["history","on-demand","lean"]}),n.longMemoryRecall&&s.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:n.longMemoryRecall,tags:["history","long-memory"]}),n.handoverNote){let i=[`[Handover] You are taking over this conversation from ${n.handoverNote.fromAgent}.`];n.handoverNote.summary&&i.push(`Operator summary: ${n.handoverNote.summary}`),i.push(`Handover time: ${n.handoverNote.at}`),s.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
51
+ `),tags:["handover",n.handoverNote.fromAgent]})}return n.rotationMemo&&s.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${n.rotationMemo.reason}, ${n.rotationMemo.capturedAt}). Carry on from this work state; do not claim you lack prior context. It is a summary, not checked facts: re-check account, billing, outage or deploy state before stating it, or say it is unverified and ask the owner:]`,n.rotationMemo.memo].join(`
52
+ `),tags:["continuity","rotation-memo"]}),n.eventDigest&&s.push({name:"events",priority:7.7,maxTokens:t("events",500),content:n.eventDigest,tags:["events","subscriptions"]}),n.attachHint&&s.push({name:"attachments",priority:2.5,maxTokens:t("attachments",250),content:n.attachHint,tags:["channel","attachments"]}),n.wikiContext&&s.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:n.wikiContext,tags:["wiki","knowledge"]}),s}function Rd(n,e){let t=[`Channel: ${n.channel}`];n.chatId&&t.push(`Chat ID: ${n.chatId} (use this verbatim in /recall, /send)`);let s=[],r=[n.channel];switch(n.channel){case"telegram":n.agentHandle&&t.push(`Your handle: ${n.agentHandle}`),t.push(`From: ${n.sender}`),n.senderId&&t.push(`Telegram user ID: ${n.senderId}`),n.senderUsername&&t.push(`Username: @${n.senderUsername}`),s.push("Format responses using Telegram-compatible markdown"),s.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),s.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${n.sender}`),s.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),s.push("No rich formatting \u2014 plain text only"),s.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${n.sender}`),s.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),s.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),s.push("Do NOT delegate to other agents"),s.push("Reference issues with #IID and merge requests with !IID"),s.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),s.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${n.sender}`),s.push("Use Discord markdown for formatting"),s.push("Be brief \u2014 2-4 sentences for the main point");break;default:n.channel.startsWith("webhook:")&&(s.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return s.length&&(t.push(""),t.push("[Rules]"),t.push(...s.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
53
+ `),tags:r,rules:s}}function _d(n,e){let t=[],s=[];if(n.channelScope==="group"&&n.groupName?(t.push(`Group: ${n.groupName}`),s.push("group",n.groupName)):n.channelScope==="project"&&n.projectPath?(t.push(`Project: ${n.projectPath}`),s.push("project",n.projectPath)):n.channelScope==="personal"&&(t.push("Direct message"),s.push("dm")),n.channelMeta){let r=n.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
54
+ `),tags:s}}function Ed(n){let e=[],t=n.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}var Dd="resumeDelivery";function lg(n){if(!n||n.kind!=="direct"||!n.context||n.context[Dd]||String(n.context.channel??"").toLowerCase().split("@")[0]!=="a2a")return null;let s=String(n.context.sender??"").match(/^agent:([^\s]+)$/);return s?s[1]:null}var Od=32e3;function Po(n){if(!n)return null;try{let e=JSON.stringify(n);return e.length<=Od?e:null}catch{return null}}function gg(n){if(!n)return null;try{let e=JSON.parse(n);if(e?.kind==="router"&&typeof e.adapter=="string"&&e.message&&typeof e.message=="object"||e?.kind==="mesh"&&typeof e.channel=="string"&&typeof e.chatId=="string"||e?.kind==="direct")return e}catch{}return null}function Ro(n){return new Date(n).toISOString().slice(11,16)}function _o(n,e=Date.now()){return!Number.isFinite(n)||e-n<=6e4?null:`[queued at ${Ro(n)} UTC, running at ${Ro(e)} UTC \u2014 anything it refers to (PR head, issue state, files) may have changed; re-check the current state before acting or replying]`}var Ht=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,s){return`${e}:${t}:${s}`}getOrCreate(e,t,s){let r=this.key(e,t,s);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,s,r){this.getOrCreate(e,t,s).mode=r}onFlush(e,t,s,r){this.getOrCreate(e,t,s).onFlush=r}isBusy(e,t,s){return this.getOrCreate(e,t,s).running}markRunning(e,t,s){let r=this.getOrCreate(e,t,s);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,s,r){let o=this.getOrCreate(e,t,s);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,s){let r=this.getOrCreate(e,t,s);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
55
+ `),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext,queuedAt:Math.min(...o.map(c=>c.queuedAt??c.timestamp))};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,s){return this.getOrCreate(e,t,s).pending.length}clear(e,t,s){let r=this.key(e,t,s);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as Nd,writeFileSync as Eo,appendFileSync as Ld,mkdirSync as Fd,existsSync as Do}from"fs";import{resolve as Mn}from"path";var Oo=50,Ud="claude-haiku-4-5-20251001",Hd=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
56
+
57
+ Extract patterns like:
58
+ - "When asked about X, the approach that works is Y"
59
+ - "User prefers Z style of communication"
60
+ - "For deployment tasks, always check A before doing B"
61
+ - "This codebase uses pattern X, so generate code following X"
62
+
63
+ SKIP:
64
+ - Factual information (names, dates, URLs)
65
+ - Routine task completions
66
+ - Greetings or small talk
67
+
68
+ Output a JSON array:
69
+ [{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
70
+
71
+ If nothing worth extracting, output: []`,Bt=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Mn(e,".agentx/patterns"),Do(this.patternsDir)||Fd(this.patternsDir,{recursive:!0})}filePath(e){return Mn(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!Do(t))return[];try{return Nd(t,"utf-8").split(`
72
+ `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}addPattern(e,t){let s={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};Ld(this.filePath(e),JSON.stringify(s)+`
73
+ `)}findRelevant(e,t,s=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(u=>`${u.context} ${u.pattern}`),i=Mn(this.patternsDir,`${t}_bm25_cache.json`),a=Ts(o,i),d=Ss(e,a).slice(0,s).map(u=>r[u.docIndex]).filter(u=>u.confidence>=.3);return d.length>0&&this.recordAccess(t,d.map(u=>u.id)),d}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let s of e)t.push(`- ${s.pattern} (context: ${s.context}, confidence: ${Math.round(s.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
74
+ `)}hasSimilar(e,t){let s=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return s.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let s=this.getAll(e),r=new Set(t),o=!1;for(let i of s)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&Eo(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
75
+ `)+`
76
+ `)}prune(e){let t=this.getAll(e);t.length<=Oo||(t.sort((s,r)=>r.confidence*r.accessCount-s.confidence*s.accessCount),t=t.slice(0,Oo),Eo(this.filePath(e),t.map(s=>JSON.stringify(s)).join(`
77
+ `)+`
78
+ `))}};async function No(n,e,t,s,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-55NC2SFN.js"),c=(await o("claude").generate([{role:"system",content:Hd},{role:"user",content:`User: ${e.slice(0,500)}
79
+
80
+ Agent: ${t.slice(0,1e3)}`}],{model:Ud,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let d=JSON.parse(c[0]);if(!(!Array.isArray(d)||d.length===0)){for(let u of d)r.hasSimilar(n,u.pattern)||r.addPattern(n,{agentId:n,pattern:u.pattern,context:u.context,confidence:u.confidence||.5,source:s});Math.random()<.05&&r.prune(n)}}import{EventEmitter as Bd}from"events";var jd=2e4,Rn=class{inner=new Bd;envelopeListeners=new Set;ring=new ar;node="local";seen=new Map;constructor(){this.inner.setMaxListeners(50)}configure(e){return e.node&&(this.node=e.node),e.ringSize&&this.ring.resize(e.ringSize),this}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){let s=this.inner.emit(e,t);try{this.publish(Wd(e,t))}catch{}return s}publish(e){let t=Tt(),s=e.id??ir(),r={id:s,rootId:e.rootId??t?.rootId??s,node:this.node,kind:e.kind,type:e.type,at:e.at??new Date().toISOString(),summary:pn(e.summary)},o=e.parentId??t?.parentId;o&&(r.parentId=o),e.agentId&&(r.agentId=e.agentId),e.ref&&(r.ref=e.ref),this.ring.push(r);for(let i of this.envelopeListeners)try{i(r,e.data)}catch{}return r}get nodeName(){return this.node}isLocal(e){return e.node===this.node}ingest(e){if(!e.node||e.node===this.node)return!1;let t=`${e.node}:${e.id}`;if(this.seen.has(t))return!1;this.seen.set(t,!0),this.seen.size>jd&&this.seen.delete(this.seen.keys().next().value);let s={id:e.id,rootId:e.rootId||e.id,node:e.node,kind:e.kind,type:e.type,at:e.at,summary:pn(e.summary??"")};e.parentId&&(s.parentId=e.parentId),e.agentId&&(s.agentId=e.agentId),e.ref&&(s.ref=e.ref),this.ring.push(s);for(let r of this.envelopeListeners)try{r(s)}catch{}return!0}hasRecent(e){return this.ring.has(e)}subscribe(e){return this.envelopeListeners.add(e),()=>{this.envelopeListeners.delete(e)}}recent(e){return this.ring.recent(e)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this.envelopeListeners.clear(),this.ring.clear(),this.seen.clear(),this}};function Wd(n,e){let t=e,s={type:n,at:t.at,agentId:t.agentId,ref:t.taskId};switch(n){case"message:matched":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} \u2192 ${t.agentId} (${t.decidingStage})`};case"message:dropped":return{...s,kind:"message",ref:t.msgId,summary:`${t.channel} ${t.chatId} dropped at ${t.decidingStage}: ${t.reason}`};case"task:queued":return{...s,kind:"agent",summary:`queued on ${t.channel} ${t.chatId}`};case"task:queue-flushed":return{...s,kind:"agent",summary:`${t.count} queued message(s) handed over on ${t.channel} ${t.chatId}`};case"task:queue-ended":return{...s,kind:"agent",summary:`queued turn ended on ${t.channel} ${t.chatId}`};case"task:started":return{...s,kind:"agent",summary:`started on ${t.channel} ${t.chatId}`};case"task:step":return{...s,kind:"agent",summary:[t.name,t.action,t.status].filter(Boolean).join(" ")};case"task:completed":return{...s,kind:"agent",summary:t.stopped?`stopped after ${t.durationMs}ms: ${t.error??"stop signal"}`:t.error?`failed after ${t.durationMs}ms: ${t.error}`:`completed in ${t.durationMs}ms`};case"session:rotated":return{...s,kind:"agent",summary:`session rotated (${t.reason})`};default:return{...s,kind:"agent",summary:String(n)}}}var Pn;function Z(){return Pn||(Pn=new Rn),Pn}rn();rn();var Lo=["manual","notify","auto"];function qd(n){return typeof n=="string"&&Lo.includes(n)}var _n={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var Gd=7*24*60*6e4,st=class{constructor(e={},t){this.store=t;this.opts={..._n,...e};let s={};try{s=t?.load()??{}}catch{s={}}let r=Date.now()-Gd;for(let[o,i]of Object.entries(s))i&&Array.isArray(i.agentIds)&&(i.agentIds.length>0||i.watch)&&i.savedAt>=r&&this.saved.set(o,i)}sessions=new Map;items=new Map;waiters=new Map;saved=new Map;opts;options(){return this.opts}register(e,t={}){let s=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=s,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let o=this.saved.get(e),i={sessionId:e,cwd:t.cwd??o?.cwd??"",agentIds:o?o.agentIds.filter(a=>!this.sessionFor(a)):[],mode:o?.mode??"notify",lastSeenAt:s,registeredAt:s,model:t.model,drainedThisTurn:0};return o?.watch&&(i.watch={...o.watch}),this.sessions.set(e,i),o&&this.remember(i,s),i}touch(e,t=Date.now()){let s=this.sessions.get(e);return s?(s.lastSeenAt=t,s):this.saved.has(e)?this.register(e,{now:t}):void 0}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,s){let r=this.sessions.get(e);if(r){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));for(let[o,i]of this.saved)o!==e&&(i.agentIds=i.agentIds.filter(a=>a!==t));return r.agentIds.includes(t)||r.agentIds.push(t),s&&(r.mode=s),r.watch=void 0,this.remember(r),r}}unbind(e,t){let s=this.sessions.get(e);if(s)return s.agentIds=t?s.agentIds.filter(r=>r!==t):[],t||(s.watch=void 0),this.remember(s),s}watch(e,t,s=Date.now()){let r=this.sessions.get(e);if(r)return r.agentIds=[],r.awaitingAnswer=void 0,this.expireItemsOf(e,s,"session switched to watch mode"),r.watch={subscriptions:t.subscriptions,cursor:t.cursor,startedAt:s},this.remember(r,s),r}advanceWatch(e,t){let s=this.sessions.get(e);s?.watch&&(s.watch.cursor.id===t.id&&s.watch.cursor.at===t.at||(s.watch.cursor=t,this.remember(s)))}setMode(e,t){let s=this.sessions.get(e);if(s)return s.mode=t,this.remember(s),s}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now(),s={}){this.sessions.delete(e),s.forget&&this.saved.delete(e)&&this.persist(),this.expireItemsOf(e,t,"session ended")}expireItemsOf(e,t,s){for(let r of this.items.values())r.sessionId===e&&(r.state==="pending"||r.state==="claimed")&&this.settle(r,"expired",t,s)}offer(e,t=Date.now()){let s=this.sessionFor(e.agentId);if(!s)return null;if(t-s.lastSeenAt>this.opts.staleSessionMs)return this.deregister(s.sessionId,t),null;let r={id:_e(t),agentId:e.agentId,sessionId:s.sessionId,state:"pending",text:Kd(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(o=>{this.waiters.set(r.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,s)=>t.createdAt-s.createdAt)}pendingCount(e){let t=0;for(let s of this.items.values())s.sessionId===e&&s.state==="pending"&&t++;return t}claim(e,t=Date.now()){let s=this.sessions.get(e);if(!s||s.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,s.awaitingAnswer=r.id,s.lastSeenAt=t,s.drainedThisTurn++,r}answer(e,t,s=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",s),o}release(e,t=Date.now()){let s=this.sessions.get(e);if(!s?.awaitingAnswer)return;let r=this.items.get(s.awaitingAnswer);if(s.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,s.lastSeenAt=t,r}expire(e,t,s=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.awaitingAnswer=void 0),this.settle(r,"expired",s,t),!0}sweep(e=Date.now()){let t=0;for(let s of this.items.values())s.state==="pending"&&e-s.createdAt>=this.opts.claimTimeoutMs?this.expire(s.id,"not claimed in time",e)&&t++:s.state==="claimed"&&e-(s.claimedAt??s.createdAt)>=this.opts.claimTimeoutMs&&this.expire(s.id,"claimed but never answered",e)&&t++;for(let s of this.sessions.values())e-s.lastSeenAt>this.opts.staleSessionMs&&this.deregister(s.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}savedBindings(){return Object.fromEntries(this.saved)}remember(e,t=Date.now()){if(e.agentIds.length===0&&!e.watch)this.saved.delete(e.sessionId);else{let s={agentIds:[...e.agentIds],mode:e.mode,cwd:e.cwd||void 0,savedAt:t};e.watch&&(s.watch={...e.watch}),this.saved.set(e.sessionId,s)}for(let[s,r]of this.saved)r.agentIds.length===0&&!r.watch&&this.saved.delete(s);this.persist()}persist(){try{this.store?.save(Object.fromEntries(this.saved))}catch{}}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let s=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),s++);return s}settle(e,t,s,r){e.state=t,e.settledAt=s;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function Kd(n,e){return n.length<=e?n:`${n.slice(0,e)}
81
+ \u2026[truncated ${n.length-e} chars]`}$a();import{z as Jd}from"zod";var Uo=[{kinds:["task:completed"]},{kinds:["failed","timeout","completed"]},{kinds:["paused"],match:"checkpoint"},{kinds:["lost"]}];function Qd(n){if(n==null)return{ok:!0,subscriptions:Uo};let e=Jd.array(Es).min(1).safeParse(n);if(!e.success){let t=e.error.issues[0];return{ok:!1,error:`invalid subscriptions: ${t?.path.join(".")||"value"} ${t?.message??""}`.trim()}}return{ok:!0,subscriptions:e.data}}var zd=15,Xd=1500,Fo=200;function Ho(n,e=Date.now()){let t=n[n.length-1];return t?{id:t.id,at:t.at}:{at:new Date(e).toISOString()}}function Yd(n,e){if(e.id){let s=n.findIndex(r=>r.id===e.id);if(s>=0)return n.slice(s+1)}let t=Date.parse(e.at);return Number.isNaN(t)?n:e.id?n.filter(s=>Date.parse(s.at)>t):n.filter(s=>Date.parse(s.at)>=t)}function Mg(n,e,t={}){let s=Yd(e,n.cursor),r=s.length?Ho(s):n.cursor,o=s.filter(d=>n.subscriptions.some(u=>dr(u,d)));if(o.length===0)return{cursor:r,matched:0,shown:0};let i=n.cursor.id??n.cursor.at,{text:a,shown:c}=Vd(o,i,t);return{text:a,cursor:r,matched:o.length,shown:c}}function Vd(n,e,t={}){let s=Math.max(3,t.maxLines??zd),r=Math.max(200,t.maxChars??Xd),o=n.map(a=>Zd(`- ${ur(a)}`)),i=o.length;for(let a=Math.min(i,s-1);a>=0;a--){let c=i-a,u=[c?`[agentx watch] ${i} events since your last turn, newest ${a} shown:`:`[agentx watch] ${i} event${i===1?"":"s"} since your last turn:`,...o.slice(i-a)];c&&u.push(`+${c} more \u2014 \`agentx events --since ${e}\``);let g=u.join(`
82
+ `);if(u.length<=s&&g.length<=r)return{text:g,shown:a}}return{text:`[agentx watch] ${i} events since your last turn \u2014 \`agentx events --since ${e}\``,shown:0}}function Zd(n){return n.length<=Fo?n:`${n.slice(0,Fo-1)}\u2026`}import{existsSync as ec,mkdirSync as tc,readFileSync as nc,renameSync as sc,writeFileSync as rc}from"node:fs";import{homedir as oc}from"node:os";import{dirname as ic,join as ac}from"node:path";function dc(n){return{load:()=>ec(n)?JSON.parse(nc(n,"utf-8")):{},save:e=>{tc(ic(n),{recursive:!0});let t=`${n}.tmp`;rc(t,JSON.stringify(e,null,2),{mode:384}),sc(t,n)}}}function cc(){if(!process.env.VITEST)return dc(process.env.AGENTX_ATTACH_BINDINGS_FILE??ac(oc(),".agentx","attach-bindings.json"))}var En;function Bo(){return En||(En=new st({},cc())),En}on();import{readFileSync as uc}from"fs";import{homedir as lc}from"os";import{join as gc}from"path";var rt=null,pc=6e4;function fc(){try{let n=gc(lc(),".claude.json"),e=uc(n,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function mc(n,e=Date.now()){if(!n)return{available:!0,checkedAt:e,unknown:!0};let t=typeof n.cachedExtraUsageDisabledReason=="string"?n.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function hc(n=!1){let e=Date.now();return!n&&rt&&e-rt.checkedAt<pc||(rt=mc(fc(),e)),rt}function jo(n){let e=hc();return e.available||n?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var qo={warnRatio:.8},Ue={...qo},yc=5*60*60*1e3,wc=60*60*1e3,Ce=[];function Go(n){Ue={...qo,...n||{}}}function Ko(n){let e=n-yc,t=0;for(;t<Ce.length&&Ce[t]<e;)t++;t>0&&Ce.splice(0,t)}function Jo(n=Date.now()){Ko(n),Ce.push(n)}var He=new Map,bc=15*60*1e3;function Qo(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""&&Number.isFinite(Number(n)))return Number(n)}function xc(n){let e=Qo(n);if(!(e===void 0||e<=0))return e<1e12?e*1e3:e}function Ic(n,e=Date.now()){if(!n||typeof n!="object")return null;let t=n;if(t.type!=="rate_limit_event")return null;let s=t.rate_limit_info??t.rateLimitInfo;if(!s||typeof s!="object")return null;let r=s.status;if(r!=="allowed"&&r!=="allowed_warning"&&r!=="rejected")return null;let o=String(s.rateLimitType??s.rate_limit_type??"unknown"),i=xc(s.resetsAt??s.resets_at),a=Qo(s.utilization),c=s.overageStatus??s.overage_status,d=r==="rejected"&&((s.isUsingOverage??s.is_using_overage)===!0||c==="allowed"||c==="allowed_warning");return{status:r,window:o,resetsAt:i,utilization:a,...d&&{usingOverage:d},seenAt:e}}function zo(n){return/_(opus|sonnet|haiku)$/.exec(n)?.[1]??null}function Xo(n,e){let t=zo(n);return!t||!e||e.toLowerCase().includes(t)}function Dn(n,e=Date.now(),t){let s=Ic(n,e);if(!s)return null;if(s.status!=="rejected")for(let[r,o]of He)o.status!=="rejected"||r===s.window||(!zo(r)||t&&Xo(r,t))&&He.delete(r);return He.set(s.window,s),s}function Yo(n=Date.now()){return[...He.values()].filter(e=>e.status!=="rejected"||e.usingOverage?!1:(e.resetsAt??e.seenAt+bc)>n)}function Sc(n=Date.now(),e){return Yo(n).find(t=>Xo(t.window,e))??null}function Wg(n=Date.now()){let e=Yo(n);for(let t of e)He.delete(t.window);return e}function Tc(){return[...He.values()].sort((n,e)=>e.seenAt-n.seenAt)}function Wo(n){return typeof n=="number"&&n>0}function Vo(n=Date.now()){Ko(n);let e=n-wc,t=0;for(let o=Ce.length-1;o>=0&&Ce[o]>=e;o--)t++;let s=Ce.length,r={lastHour:t,last5h:s,maxPerHour:Wo(Ue.maxPerHour)?Ue.maxPerHour:void 0,maxPer5h:Wo(Ue.maxPer5h)?Ue.maxPer5h:void 0,provider:Tc()};return r.maxPerHour&&(r.hourlyRatio=t/r.maxPerHour),r.maxPer5h&&(r.fiveHourRatio=s/r.maxPer5h),r}function Zo(n){return n.replace(/_/g," ")}function ei(n,e){return n?`in about ${Math.max(1,Math.round((n-e)/6e4))} min (${new Date(n).toISOString()})`:"shortly"}function ti(n,e=Date.now(),t){let s=Vo(e);if(n)return null;let r=Sc(e,t);return r?{abort:!0,reason:"provider_rate_limit",message:`Claude plan limit reached: Claude Code reports the ${Zo(r.window)} window as rejected. Cold dispatches are held until it resets ${ei(r.resetsAt,e)}; open conversations still go through. To try again now, run: agentx usage plan --lift`,usage:s}:s.maxPerHour&&s.lastHour>=s.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Local dispatch cap reached: ${s.lastHour}/${s.maxPerHour} claude-code runs in the last hour. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPerHour in agentx.json (applies on save).`,usage:s}:s.maxPer5h&&s.last5h>=s.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Local dispatch cap reached: ${s.last5h}/${s.maxPer5h} claude-code runs in the last 5h. Cold dispatches are held; open conversations still go through. Raise or remove session.maxClaudeCodeDispatchesPer5h in agentx.json (applies on save).`,usage:s}:null}function ni(n=Date.now()){let e=Vo(n),t=e.provider.find(r=>r.status==="allowed_warning");if(t){let r=t.utilization!==void 0?` (${Math.round(t.utilization*100)}% used)`:"";return`claude plan ${Zo(t.window)} window nearing its limit${r}, resets ${ei(t.resetsAt,n)}`}let s=Ue.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=s&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of local cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=s&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of local cap)`:null}var On=new Map;function si(n,e,t){return t?`${n}:${e}:${t}`:`${n}:${e}`}function ri(n,e,t,s=Date.now()){let r=On.get(n);r||(r={key:n,samples:0,baseline:e,current:e,peak:e,lastAt:s,ring:[]},On.set(n,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=s,r.ring.push({key:n,timestamp:s,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function oi(n){let e=On.get(n);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let s=e.current/e.baseline;return`prompt-size drift for ${n}: ${e.current} bytes is ${s.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as Mc,readFileSync as Pc}from"fs";import{resolve as Rc}from"path";import{existsSync as kc,readFileSync as vc,unlinkSync as $c,writeFileSync as Ac}from"fs";import{resolve as ai}from"path";var ii="_agentxManaged";function jt(n=process){let e=n.argv[1]?ai(n.argv[1]):"";return/\.[cm]?js$/.test(e)?{type:"stdio",command:n.execPath,args:[e,"serve","--stdio","--cwd",n.cwd()]}:{type:"stdio",command:"agentx",args:["serve","--stdio","--cwd",n.cwd()]}}function Qg(n,e){return!e||n.agentx?n:{...n,agentx:e}}function zg(n,e){let t=ai(n,".mcp.json"),s=kc(t),r=s?Cc(t):null,o=r!==null&&r[ii]===!0;if(s&&!o)return"skipped-operator-owned";let i=Object.keys(e).length>0;if(!i&&!s)return"noop";if(!i&&o)return $c(t),"removed";let a={[ii]:!0,mcpServers:e};return Ac(t,JSON.stringify(a,null,2)+`
83
+ `),s?"updated":"installed"}function Cc(n){try{return JSON.parse(vc(n,"utf-8"))}catch{return null}}var _c=["github","a2a","workflow","cron"],Ec=["claude-code","codex-cli"],Dc={mcpServers:["agentx"],settingSources:["project","local"],contextOnDemand:!0,tools:[],toolsByChannel:{},agentxTools:[],agentxToolsByChannel:{}},Oc="AGENTX_MCP_TOOLS",Nc=["agentx_approval","agentx_request","agentx_events","agentx_attach_next","agentx_workflow"],Lc=["agentx_agents","agentx_recent","agentx_wiki_query"];function ci(n,e){let t=e?n.toolsByChannel?.[e]:void 0,s=t&&t.length?t:n.tools??[];return Array.from(new Set(s.map(r=>r.trim()).filter(Boolean)))}function ui(n,e){let t=e?n.agentxToolsByChannel?.[e]:void 0,s=(t&&t.length?t:n.agentxTools??[]).map(o=>o.trim()).filter(Boolean);if(!s.length)return[];let r=[...Nc,...n.contextOnDemand?Lc:[],...s];return Array.from(new Set(r))}function Fc(n,e){return!e.length||n.type==="http"?n:{...n,env:{...n.env??{},[Oc]:e.join(",")}}}function li(n,e,t){if(!Ec.includes(t))return"full";let s=n?.profileByChannel?.[e];return s||(_c.includes(e)?"lean":"full")}function gi(n){return{...Dc,...n?.lean??{}}}function pi(n){return n.settingSources.includes("project")}function Uc(n,e,t=jt(),s){let r=fi(n),o={};for(let i of e.mcpServers)r[i]&&(o[i]=r[i]);return o.agentx=Fc(o.agentx??r.agentx??t,ui(e,s)),o}function fi(n){let e=Rc(n,".mcp.json");if(!Mc(e))return{};try{let s=JSON.parse(Pc(e,"utf-8"))?.mcpServers;return s&&typeof s=="object"?s:{}}catch{return{}}}function mi(n,e,t=jt(),s){let r=Uc(n,e,t,s),o=["--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:r}),"--setting-sources",e.settingSources.join(",")],i=ci(e,s);return i.length&&o.push("--tools",hi(i).join(",")),o}var di="ToolSearch";function hi(n){return n.includes(di)?n:[...n,di]}function yi(n,e=jt()){let t=fi(n);return["--mcp-config",JSON.stringify({mcpServers:{agentx:t.agentx??e}})]}function wi(n,e){return["[Context on demand]",`Not pushed into this prompt, fetch with agentx MCP tools when the task needs them: the agent landscape (agentx_agents with landscape=true), earlier messages on this chat (agentx_recent with channel="${n}", chatId="${e}"), today's other chats of yours (agentx_recent without chatId), and stored knowledge (agentx_wiki_query).`].join(`
84
+ `)}function bi(n,e,t){if(n==="full")return"full";let s=[`mcp=${e.mcpServers.join("+")||"agentx"}`,`settings=${e.settingSources.join(",")||"none"}`,e.contextOnDemand?"context=on-demand":"context=pushed"],r=ci(e,t);r.length&&s.push(`tools=${hi(r).join("+")}`);let o=ui(e,t);return o.length&&s.push(`agentx-tools=${o.length}`),`lean (${s.join(" ")})`}import{existsSync as de,mkdirSync as Ou,readdirSync as ge,readFileSync as it,rmSync as Nu,writeFileSync as Lu}from"fs";import{resolve as Q}from"path";import{randomUUID as Fu}from"crypto";import{existsSync as Pe,mkdirSync as Nn,readFileSync as Hc,readdirSync as Bc,renameSync as jc,unlinkSync as Wc,writeFileSync as Wt}from"fs";import{resolve as Ie,relative as qt}from"path";import{z}from"zod";var Me=z.object({id:z.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:z.string().min(1),trigger:z.string().min(1,"procedures must describe when they apply"),inputs:z.array(z.string()).default([]),expected:z.string().optional(),kpis:z.array(z.string()).default([]),owner:z.string().optional(),tags:z.array(z.string()).default([]),status:z.enum(["draft","active","deprecated"]).default("active"),source:z.string().optional(),evidence:z.array(z.string()).default([]),created:z.string().optional(),updated:z.string().optional(),related:z.array(z.string()).default([])});function qc(n){let e=n.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:n};let t={};for(let s of e[1].split(`
85
+ `)){let r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let o=r[1],i=r[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function Gt(n){let e=["---"];return e.push(`id: ${n.id}`),e.push(`title: "${n.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${n.trigger.replace(/"/g,'\\"')}"`),n.inputs?.length&&e.push(`inputs: ${JSON.stringify(n.inputs)}`),n.expected&&e.push(`expected: "${n.expected.replace(/"/g,'\\"')}"`),n.kpis?.length&&e.push(`kpis: ${JSON.stringify(n.kpis)}`),n.owner&&e.push(`owner: ${n.owner}`),n.tags?.length&&e.push(`tags: ${JSON.stringify(n.tags)}`),e.push(`status: ${n.status}`),n.source&&e.push(`source: "${n.source.replace(/"/g,'\\"')}"`),n.evidence?.length&&e.push(`evidence: ${JSON.stringify(n.evidence)}`),n.related?.length&&e.push(`related: ${JSON.stringify(n.related)}`),n.created&&e.push(`created: ${n.created}`),n.updated&&e.push(`updated: ${n.updated}`),e.push("---"),e.join(`
86
+ `)}var ot=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??Ie(process.cwd(),".agentx/procedures"),Nn(this.baseDir,{recursive:!0})}pathFor(e){return Ie(this.baseDir,`${e}.md`)}get draftsDir(){return Ie(this.baseDir,"_drafts")}draftPathFor(e){return Ie(this.draftsDir,`${e}.md`)}parseFile(e){let t=Hc(e,"utf-8"),{meta:s,body:r}=qc(t),o=Me.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[],evidence:s.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:qt(this.baseDir,e)}:null}listDir(e){if(!Pe(e))return[];let t=[];for(let s of Bc(e,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name.startsWith("_"))continue;let r=this.parseFile(Ie(e,s.name));r&&t.push(r)}return t.sort((s,r)=>s.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return Pe(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return Pe(t)?this.parseFile(t):null}add(e,t){let s=Me.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(s.id);if(Pe(r))throw new Error(`Procedure already exists: ${s.id}`);return Wt(r,Gt(s)+`
87
+
88
+ `+t.trim()+`
89
+ `),{meta:s,body:t.trim(),path:qt(this.baseDir,r)}}update(e,t,s){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=Me.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=s!==void 0?s:r.body;return Wt(this.pathFor(e),Gt(o)+`
90
+
91
+ `+i.trim()+`
92
+ `),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let s=Me.parse({...e,status:"draft",created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)});if(this.get(s.id))throw new Error(`Procedure already exists: ${s.id}`);let r=this.draftPathFor(s.id);if(Pe(r))throw new Error(`Draft already exists: ${s.id}`);return Nn(this.draftsDir,{recursive:!0}),Wt(r,Gt(s)+`
93
+
94
+ `+t.trim()+`
95
+ `),{meta:s,body:t.trim(),path:qt(this.baseDir,r)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let s=Me.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return Wt(this.pathFor(e),Gt(s)+`
96
+
97
+ `+t.body+`
98
+ `),Wc(this.draftPathFor(e)),{meta:s,body:t.body,path:qt(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!Pe(t))throw new Error(`Draft not found: ${e}`);let s=Ie(this.draftsDir,"_rejected");Nn(s,{recursive:!0}),jc(t,Ie(s,`${e}.md`))}isRejected(e){return Pe(Ie(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as Gc,mkdirSync as Kc,readFileSync as Jc,writeFileSync as Qc}from"fs";import{dirname as zc,resolve as Xc}from"path";import{z as oe}from"zod";var Yc=oe.object({key:oe.string(),count:oe.number().int().min(0).default(0),firstSeen:oe.string(),lastSeen:oe.string(),taskIds:oe.array(oe.string()).default([]),sampleMessage:oe.string().default(""),status:oe.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:oe.string().optional()}),Vc=oe.object({minedThrough:oe.string().optional(),candidates:oe.array(Yc).default([])});function xi(n){return Xc(n,"_candidates.json")}function Zc(n){let e=xi(n);if(!Gc(e))return{candidates:[]};try{let t=Vc.safeParse(JSON.parse(Jc(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function eu(n,e){let t=xi(n);Kc(zc(t),{recursive:!0}),Qc(t,JSON.stringify(e,null,2)+`
99
+ `)}function tu(n,e,t,s,r){let o=n.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:s,lastSeen:s,taskIds:[],sampleMessage:r,status:"counting"},n.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,s<o.firstSeen&&(o.firstSeen=s),s>o.lastSeen&&(o.lastSeen=s),o.sampleMessage||(o.sampleMessage=r)),o}function nu(n,e){return n.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,s)=>s.count-t.count)}function su(n,e,t,s){let r=n.candidates.find(o=>o.key===e);r&&(r.status=t,s&&(r.procedureId=s))}function Ln(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Ii(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let s of n)e.has(s)&&t++;return t/Math.max(n.size,e.size)}function Fn(n,e,t={}){let s=Math.max(1,t.limit??3),r=t.minScore??.2,o=Ln(n),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=Ii(o,Ln(a.meta.trigger));d>0&&c.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),g=Ii(o,Ln(u));g>0&&c.push("title/tags");let m=Math.min(1,d*.7+g*.5);m>=r&&i.push({procedure:a,score:m,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,s)}function Un(n){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...n.map(t=>{let s=t.procedure,r=[`[Known procedure: ${s.meta.title}]`,s.meta.trigger];return s.meta.inputs.length&&r.push(`Inputs: ${s.meta.inputs.join(", ")}`),r.push(s.body),s.meta.expected&&r.push(`Done when: ${s.meta.expected}`),r.push(`(details: agentx procedure show ${s.meta.id})`),r.join(`
100
+ `)})].join(`
101
+
102
+ `)}un();It();var Bn="turn-progress",Si={progress:Ee({progressing:"Recent steps move the task forward: new files, commands or checks, results that differ from earlier ones, or a long step whose output shows it advancing.",looping:"The agent repeats the same or near-identical step (same command, same check, same edit retried with small tweaks) and gets the same failure or result each time.",blocked:"Progress depends on something the agent cannot change from here: missing access or credentials, a service that is down, or a decision only the user can make."},"How the agent's current turn is going, judged from its most recent steps.")},Hn=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n;function Ti(n){return{agent:n.agent,request:Hn(n.request,1500),elapsedMinutes:Math.round(n.elapsedMinutes),budgetMinutes:n.budgetMinutes,trigger:n.trigger,recentSteps:n.steps.map(e=>({tool:e.tool,input:Hn(e.input,300),...e.result!==void 0?{result:Hn(e.result,300)}:{},...e.error?{failed:!0}:{}})),...n.repeated?{mostRepeatedCall:n.repeated}:{}}}It();var ki="turn-handoff",vi="approval-binding",$i={nextStep:Ee({proceed:"The question asks permission for a local, reversible next step that is already inside what the user asked for, such as writing or testing code in the working copy, reading, or running checks.",ask_outward:"The next step changes something outside the working copy or is hard to undo: pushing, publishing, merging, deploying, deleting, spending money, or messaging someone other than the user.",ask_ambiguous:"The agent cannot tell what the user wants: several different goals are plausible, or the user must choose between options with different results."},"What the agent should do with the question it ended its turn on.")},Ai={approves:Qe("The user's message approves the plan or step the agent proposed at the end of its previous reply.",{true:'The message accepts the proposal, including terse replies such as "yes", "go ahead" or "ok do it", possibly with small additions that do not change the plan.',false:"The message declines, changes the plan, asks something new, or answers a different question than the one the agent asked."})},ru=(n,e)=>n.length>e?`${n.slice(0,e)}\u2026`:n,Ci=(n,e)=>n.length>e?`\u2026${n.slice(-e)}`:n,ou=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function jn(n){let e=n.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:ou.test(e.split(`
103
+ `).slice(-3).join(" ")):!1}var iu=/^\s*(yes|yep|yeah|ok(ay)?|sure|go( ahead)?|proceed|do it|please do|confirmed?|approved?|go-ahead|let'?s go|oui|نعم)\b/i;function Mi(n){return n.trim().length<=160&&iu.test(n)}function Pi(n){return n.trim().length<=160}function Ri(n){return{agent:n.agent,channel:n.channel,request:ru(n.request,1500),agentReplyEnding:Ci(n.reply,1200)}}function _i(n){return{agent:n.agent,channel:n.channel,userMessage:n.message,agentPreviousReplyEnding:Ci(n.previousReply,1200)}}var au=5*6e4,du=3,cu=12,uu=24*60*6e4,Ei=new Set(["cron","heartbeat","bench","a2a","business"]),lu={observe(){},stop(){}};function Di(n){if(St(Bn)==="off")return lu;let e=n.now??Date.now,t=e(),s=[],r=new Map,o=new Map,i=new Set,a=0,c=!1,d=()=>{let m;for(let[h,p]of o)p>1&&(!m||p>m.times)&&(m={call:h,times:p});return m},u=m=>{if(c)return;c=!0,a=s.length;let h=Ti({agent:n.agent,request:n.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:n.budgetMinutes,steps:s.slice(-cu),repeated:d(),trigger:m});ye(Bn,h,Si,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,trigger:m}}).finally(()=>{c=!1})},g=setInterval(()=>{s.length>a&&u("checkpoint")},n.checkpointMs??au);return g.unref?.(),{observe(m){let h=Array.isArray(m?.message?.content)?m.message.content:[];if(m?.type==="assistant")for(let p of h){if(p?.type!=="tool_use")continue;let x=p.input?JSON.stringify(p.input):"",S={tool:p.name||"tool",input:x};s.push(S),typeof p.id=="string"&&r.set(p.id,S);let w=`${S.tool}(${x})`,P=(o.get(w)??0)+1;o.set(w,P),P>=du&&!i.has(w)&&(i.add(w),u("repetition"))}else if(m?.type==="user")for(let p of h){if(p?.type!=="tool_result")continue;let x=r.get(p.tool_use_id);x&&(x.result=Array.isArray(p.content)?p.content.map(S=>typeof S?.text=="string"?S.text:"").join(""):typeof p.content=="string"?p.content:"",p.is_error&&(x.error=!0))}},stop(){clearInterval(g)}}}var Wn=new Map,Oi=(n,e,t)=>`${n}\0${e}\0${t}`;function Ni(n){if(Ei.has(n.channel)||!jn(n.reply))return;let e=Oi(n.agent,n.channel,n.chatId);ye(ki,Ri(n),$i,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}}).then(t=>{t?.callId&&Wn.set(e,{callId:t.callId,at:Date.now()})})}function Li(n){if(Ei.has(n.channel))return;let e=Oi(n.agent,n.channel,n.chatId),t=Wn.get(e);if(t){Wn.delete(e);let s=Ds().store;if(s&&Date.now()-t.at<uu)try{s.label(t.callId,"userReply",Mi(n.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!n.previousReply||!Pi(n.message)||!jn(n.previousReply)||ye(vi,_i({agent:n.agent,channel:n.channel,message:n.message,previousReply:n.previousReply}),Ai,{links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel}})}Sa();ka();va();_s();function Fi(n,e,t=0){return new Promise((s,r)=>{let o,i=()=>{o=setTimeout(()=>r(Re(e)),t)},a=()=>{e.removeEventListener("abort",i),o&&clearTimeout(o)};n.then(c=>{a(),s(c)},c=>{a(),r(c)}),e.aborted?i():e.addEventListener("abort",i,{once:!0})})}function Re(n){let e=n.reason;return e instanceof Error?e:new Error(typeof e=="string"?e:"task cancelled")}var Be=class extends Error{constructor(t,s){super(`step "${t}" exceeded its ${Math.round(s/1e3)}s budget`);this.step=t;this.budgetMs=s;this.name="StepBudgetExceeded"}};function Ui(n,e,t){return e>0?new Promise((s,r)=>{let o=setTimeout(()=>r(new Be(t,e)),e);o.unref?.(),n.then(i=>{clearTimeout(o),s(i)},i=>{clearTimeout(o),r(i)})}):n}import{execFileSync as gu,spawn as pu}from"child_process";import{existsSync as fu,mkdirSync as mu,readFileSync as hu,renameSync as yu,writeFileSync as wu}from"fs";import{dirname as bu}from"path";var Jt={enabled:!1,maxPerDay:0,openHours:24,launchTimeoutSeconds:120};function xu(n){if(!n)return;let t=n.trim().match(/^(?:(?:https?|ssh|git)(?::\/\/)(?:[^@\/]+@)?|git@|)(?:www\.)?github\.com[\/:]([^\/\s]+)\/([^\/\s]+?)(?:\.git)?\/?$/i);if(t)return`${t[1]}/${t[2]}`}function Iu(n){try{return!n||!fu(n)?void 0:gu("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||void 0}catch{return}}function qn(n){if(!n)return;let e=n.split(":");if(e.length<3)return;let t=Number(e[e.length-1]),s=e[e.length-2],r=e.slice(0,-2).join(":");if(!(!Number.isInteger(t)||t<=0)&&!(s!=="issue"&&s!=="pull")&&/^[^\/\s]+\/[^\/\s]+$/.test(r))return{repo:r,kind:s,number:t}}function Hi(n){let e={...Jt,...n.agent.cloudSessions??{}};if(!e.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let t=n.context?.channel;if(t!=="github")return{route:"local",reason:`channel "${t||"api"}" does not send tasks to the cloud (GitHub only)`};if(!n.channelEnabled)return{route:"local",reason:"cloud sessions are off for the github channel"};if(n.agent.tier!=="claude-code")return{route:"local",reason:`agent tier "${n.agent.tier}" cannot run cloud sessions (claude-code only)`};let s=qn(n.context?.chatId);if(!s)return{route:"local",reason:`task is not for a GitHub issue or pull request (chat "${n.context?.chatId||""}")`};if(n.openSession)return{route:"follow-up",session:n.openSession};if(e.maxPerDay>0&&(n.launchesToday??0)>=e.maxPerDay)return{route:"local",reason:`daily cap of ${e.maxPerDay} cloud launches reached`};let r=n.remoteOf??Iu,o=[n.context?.runbookPath,n.agent.workspace].filter(a=>!!a),i=s.repo.toLowerCase();for(let a of o){let c=xu(r(a));if(c&&c.toLowerCase()===i)return{route:"cloud",repo:s.repo,kind:s.kind,number:s.number,cwd:a}}return{route:"local",reason:`no checkout of ${s.repo} on this node (looked in ${o.join(", ")||"nothing"}); set the project rule's runbook path to a clone whose origin is github.com/${s.repo}`}}var Su=24*60*60*1e3,Tu=7*Su,Kt=class{constructor(e){this.file=e}sessions=[];loaded=!1;load(){if(!this.loaded){this.loaded=!0;try{let e=JSON.parse(hu(this.file,"utf8")),t=Array.isArray(e?.sessions)?e.sessions:[];this.sessions=t.filter(s=>s&&typeof s.repo=="string"&&typeof s.sessionId=="string"&&Number.isFinite(s.startedAt))}catch{this.sessions=[]}}}save(){let e=Date.now();this.sessions=this.sessions.filter(t=>e-t.startedAt<Tu);try{mu(bu(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.tmp`;wu(t,JSON.stringify({sessions:this.sessions},null,2)),yu(t,this.file)}catch{}}open(e,t,s,r=Date.now()){this.load();let o=e.toLowerCase();return this.sessions.find(i=>i.repo.toLowerCase()===o&&i.number===t&&r-i.startedAt<s*60*60*1e3)}record(e){this.load(),this.sessions=this.sessions.filter(t=>!(t.repo.toLowerCase()===e.repo.toLowerCase()&&t.number===e.number)),this.sessions.push(e),this.save()}touch(e,t=Date.now()){this.load();let s=this.sessions.find(r=>r.sessionId===e);s&&(s.lastMessageAt=t,this.save())}close(e,t){this.load();let s=this.sessions.length;return this.sessions=this.sessions.filter(r=>!(r.repo.toLowerCase()===e.toLowerCase()&&r.number===t)),this.sessions.length===s?!1:(this.save(),!0)}launchesToday(e,t=Date.now()){this.load();let s=new Date(t);return s.setHours(0,0,0,0),this.sessions.filter(r=>r.agentId===e&&r.startedAt>=s.getTime()&&r.startedAt<=t).length}all(){return this.load(),[...this.sessions]}},ku=["import os, pty, sys","status = pty.spawn(sys.argv[1:])","sys.exit(os.waitstatus_to_exitcode(status) if isinstance(status, int) else 0)"].join(`
104
+ `);function vu(n,e){return e?["-p",n,"--cloud",e]:["--cloud",n]}var $u=/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\r/g;function Bi(n){return n.replace($u,"")}function Au(n){let e=Bi(n),t=e.match(/https:\/\/claude\.ai\/code\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-]+)*/)?.[0],s=e.match(/\bsession_[A-Za-z0-9]{6,}\b/)?.[0];if(!s&&t){let r=t.split("/").filter(Boolean).pop();r&&r!=="code"&&(s=r)}return{sessionId:s,url:t}}async function ji(n){let e=n.spawn??((c,d,u)=>pu(c,d,u)),t=n.python??"python3",s=["-c",ku,"claude",...vu(n.prompt,n.sessionId)],r={...n.env,NO_COLOR:"1",FORCE_COLOR:"0"},o="",i=c=>{o+=c.toString(),o.length>64e3&&(o=o.slice(-64e3))},a=()=>Bi(o).trim().split(`
105
+ `).slice(-5).join(`
106
+ `).slice(-600);return new Promise(c=>{let d=!1,u=p=>{d||(d=!0,c(p))},g;try{g=e(t,s,{cwd:n.cwd,env:r,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(p){u({ok:!1,reason:`could not start ${t}: ${p?.message||p}`,output:o});return}let m=p=>{try{g.pid&&process.kill(-g.pid,p)}catch{try{g.kill(p)}catch{}}},h=setTimeout(()=>{m("SIGTERM"),setTimeout(()=>m("SIGKILL"),3e3).unref?.(),u({ok:!1,reason:`claude --cloud did not print a session within ${Math.round(n.timeoutMs/1e3)}s${a()?`; last output: ${a()}`:""}`,output:o})},n.timeoutMs);h.unref?.(),g.stdout?.on("data",i),g.stderr?.on("data",i),g.on("error",p=>{clearTimeout(h);let x=p?.code==="ENOENT";u({ok:!1,reason:x?`${t} is not installed (needed to give claude --cloud a terminal)`:`launch failed: ${p?.message||p}`,output:o})}),g.on("close",p=>{if(clearTimeout(h),d)return;let x=Au(o);if(n.sessionId){if(p===0){u({ok:!0,sessionId:n.sessionId,url:x.url||"",output:o});return}u({ok:!1,reason:`claude -p --cloud exited with code ${p??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}if(x.sessionId&&x.url){u({ok:!0,sessionId:x.sessionId,url:x.url,output:o});return}if(p!==0){u({ok:!1,reason:`claude --cloud exited with code ${p??"unknown"}${a()?`: ${a()}`:""}`,output:o});return}u({ok:!1,reason:`claude --cloud printed no session id or URL${a()?`; last output: ${a()}`:""}`,output:o})})})}var Cu=1e5;function Mu(n,e){let s=`
107
+
108
+ ---
109
+ This task comes from GitHub ${e.kind==="pull"?"pull request":"issue"} #${e.number} in ${e.repo}. Work in this repository and open or update a pull request that references #${e.number}.`,r=Cu-s.length;return`${n.length>r?`${n.slice(0,r)}
110
+ [message cut at ${r} characters]`:n}${s}`}function Pu(n,e,t){return[`Started a Claude cloud session for this ${e==="pull"?"pull request":"issue"}. The result arrives as a pull request.`,`Session: \`${n.sessionId}\``,n.url,`Comments here are forwarded to that session for the next ${t} hours.`].join(`
111
+ `)}function Ru(n){return`Forwarded to the open Claude cloud session \`${n.sessionId}\` (${n.url}).`}async function Wi(n){let{route:e}=n,t=n.now??Date.now;if(e.route==="local")return n.trace({action:"skipped",status:"ok",summary:e.reason}),null;if(e.route==="follow-up"){let i=e.session,a=await n.launch({cwd:i.cwd||process.cwd(),prompt:n.message,sessionId:i.sessionId});return a.ok?(n.store.touch(i.sessionId,t()),n.log(`[${n.agentId}] forwarded to open cloud session ${i.sessionId} for ${i.repo}#${i.number}`),n.trace({action:"follow-up",status:"ok",summary:JSON.stringify({sessionId:i.sessionId,url:i.url})}),{content:Ru(i),cloudSession:{id:i.sessionId,url:i.url,followUp:!0}}):(n.log(`[${n.agentId}] forwarding to cloud session ${i.sessionId} failed: ${a.reason}`),n.trace({action:"follow-up",status:"error",summary:a.reason}),{content:"",error:`Claude cloud session \`${i.sessionId}\` is still open for this ${i.kind==="pull"?"pull request":"issue"} (${i.url}); forwarding this comment to it failed: ${a.reason}. No local run starts while the session is open.`,cloudSession:{id:i.sessionId,url:i.url,followUp:!0}})}let s=Mu(n.message,e),r=await n.launch({cwd:e.cwd,prompt:s});if(!r.ok)return n.log(`[${n.agentId}] cloud session launch for ${e.repo}#${e.number} failed, running locally: ${r.reason}`),n.trace({action:"fallback",status:"error",summary:r.reason}),null;let o={repo:e.repo,number:e.number,kind:e.kind,sessionId:r.sessionId,url:r.url,agentId:n.agentId,startedAt:t(),cwd:e.cwd,traceId:n.traceId};return n.store.record(o),n.log(`[${n.agentId}] cloud session ${r.sessionId} started for ${e.repo}#${e.number}: ${r.url}`),n.trace({action:"launched",status:"ok",summary:JSON.stringify({sessionId:r.sessionId,url:r.url,repo:e.repo,number:e.number})}),{content:Pu(o,e.kind,n.settings.openHours),cloudSession:{id:r.sessionId,url:r.url}}}var Eu=250,Du=5e3,Uu={"request-gate":5e3,"seed-history":3e4,skills:1e4,rotate:8e3,compact:3e4,references:1e4,"plan-context":12e3,"select-context":5e3,"route-model":5e3},qi=`[Operating principle]
112
+ Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`,Hu="Change files with the Edit tool, one exact replacement per edit, not with sed, awk or a shell rewrite: a pattern that misses or matches twice leaves the file broken and costs another round. Several edits can go in one turn, and the tests can run in that same turn.";function Bu(n){return n==="claude-code"?`${qi}
113
+ ${Hu}`:n==="codex-cli"?qi:""}function Gi(n,e){return e!=="claude-code"&&e!=="codex-cli"?!1:n==="github"||n==="gitlab"}var Yi;function Ff(n){Yi=n}function Uf(){return Yi}var Ki=64*1024,ju=5*60*1e3,Wu=3e4,qu=300,je=".agentx/task-history",Gu=30;function at(n,e=800){return n.length<=e?n:n.slice(0,e)+` \u2026[+${n.length-e} chars]`}function Ku(n,e){let t={};return n?.path?.length&&(t.intentPath=n.path,t.intentPathLabel=n.pathLabel),e?.sender&&(t.sender=e.sender),e?.senderId&&(t.senderId=e.senderId),e?.senderUsername&&(t.senderUsername=e.senderUsername),e?.group&&e?.sender&&(t.group=e.group),Object.keys(t).length>0?t:void 0}function Ju(n,e){if(!e?.some(r=>r.delivery==="digest"))return;let{shown:t,more:s}=cr(n,e,Z().recent());return lr(t,s)}function Qu(n){let e=n.wikiNotes;if(!e?.enabled||!e.inbox)return;let[t,s]=(n.node?.bind||"127.0.0.1:18800").split(":");return{inbox:e.inbox,daemonUrl:`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s||"18800"}`}}function zu(n,e,t={}){let s;try{s=n.listArticles(e)}catch{return""}if(s.length===0)return"";let r=new Map;for(let u of s){let g=u.meta.type||"untyped",m=r.get(g)||[];m.push(u.meta.title),r.set(g,m)}let o=t.maxArticles??400,i=s.length<=o,a=Array.from(r.entries()).sort().map(([u,g])=>i?`**${u}** (${g.length}) \u2014 ${g.sort().join(" \xB7 ")}`:`**${u}** \u2014 ${g.length} article${g.length===1?"":"s"}`).join(`
114
+ `),c=process.argv[1]||"dist/cli.js",d=n.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${s.length} article${s.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
115
+ node ${c} wiki query "the question" --dir ${d} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","",`Facts about outside systems (billing, accounts, outages, deploys) carry a source and a check date: \`node ${c} wiki facts list --dir ${d}\`. Past its time limit a fact must be re-checked at the source before you state it; record what you checked with \`wiki facts set ... --checked-at now\`. If you can't check, say it is unverified and ask the owner.`,...t.notesInbox&&t.notesInbox.inbox!==e?["",`When you learn something the wiki should know (a change, a correction, a fact that went stale), leave a short note for the wiki run: \`node ${c} wiki notes add --from ${e} --change "what changed" --source "where you saw it" --date YYYY-MM-DD --daemon ${t.notesInbox.daemonUrl}\`. The run checks it before it changes anything. Notes stay inside the fleet; never put secrets in one.`]:[],"[End Institutional Wiki]"].join(`
116
+ `)}var Gn=8*1024;function Xu(n,e){if(n)try{Ar(n)}catch{}return e}function Ji(n){if(n.length<=Gn)return n;let e=n.length-Gn;return n.slice(0,Gn)+`\u2026[+${e}]`}function Qi(n,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let s of t){if(s?.type!=="tool_use")continue;let r=typeof s.name=="string"?s.name:"";r&&n.set(r,(n.get(r)??0)+1)}}function Yu(n,e){if(!n||n.length===0)return null;for(let t of n)if((e.get(t)??0)===0)return t;return null}function zi(n,e,t){if(!t||typeof t!="object")return;let s=t.type,r=new Date().toISOString(),o=Z();if(s==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?Ji(a):null,at:r})}return}if(s==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:n,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?Ji(a):null,at:r})}return}}function Vu(){let n="",e="";return t=>{if(!t||typeof t!="object")return"";let s=t.type;if(s==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
117
+ `;if(s==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
118
+ `;if(s==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
119
+ `;if(s==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
120
+ `;if(s==="codex.first_output")return`. codex first output=${t.elapsedMs}ms
121
+ `;if(s==="codex.fallback")return`. codex using CLI fallback: ${t.reason}
122
+ `;if(s==="codex.spawned"){let r=t.model?` model=${t.model}`:"",o=t.resumeSessionId?` resume=${String(t.resumeSessionId).slice(0,8)}`:"";return`. codex started${r}${o}
123
+ `}if(s==="thread.started")return`. codex thread started${t.thread_id?` thread=${String(t.thread_id).slice(0,8)}`:""}
124
+ `;if(s==="turn.started")return`. codex turn started
125
+ `;if(s==="turn.completed"){let r=t.usage||{},o=r.input_tokens??r.inputTokens,i=r.output_tokens??r.outputTokens;return`. codex turn completed${o||i?` input=${o||0} output=${i||0}`:""}
126
+ `}if(s==="item.started"||s==="item.completed"){let r=t.item||{};if(r.type==="agent_message"&&typeof r.text=="string"){let c=r.text,d=c.startsWith(e)?c.slice(e.length):c;return e=c.startsWith(e)?c:e+c,d}let o=r.type||"item",i=r.name||r.command||r.tool_name||r.id||"";if(s==="item.started")return`
127
+ > codex ${o}${i?` ${i}`:""}
128
+ `;let a=r.output||r.result||r.text||r.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${at(String(a),800)}`:""}
129
+ `}if(s==="error"||s==="turn.failed"){let r=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${at(String(r),800)}
130
+ `}if(s==="system"&&t.subtype==="init"){let r=t.model?` model=${t.model}`:"",o=t.session_id?` session=${t.session_id.slice(0,8)}`:"";return`\xB7 init${r}${o}
131
+ `}if(s==="assistant"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="text"&&typeof o.text=="string")o.text.length>n.length&&(r+=o.text.slice(n.length),n=o.text);else if(o.type==="thinking"&&typeof o.thinking=="string")r+=`
132
+ \u{1F4AD} ${at(o.thinking,600)}
133
+ `;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?at(JSON.stringify(o.input),400):"";r+=`
134
+ \u2192 ${i}(${a})
135
+ `}return r}if(s==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${at(i,800)}
136
+ `}return r}return s==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
137
+ `:""}}var Xi=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new tr;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;workflowRuns;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new Zs;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;stoppedRuns=new Map;runEndWaiters=new Map;cloudSessions;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new Ft(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new zs(void 0,void 0,"graph"),this.memoryStore=new er,this.patternStore=new Bt,this.rateLimiter=new Ut,this.tokenTracker=new Ys,this.messageQueue=new Ht,Go({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Js({baseDir:Q(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Qs({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:s,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[s,r]of Object.entries(e.agents))this.agents.set(s,{id:s,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowRunStore(e){this.workflowRuns=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}setWorkflows(e){this.config={...this.config,workflows:e}}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let s=Ps(this.config.people,e,t);return s?(this.log(`[${e}] refused: ${s.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:s.person.id,event:"agent-refused",detail:e}),s.note):null}logToolRefusal(e,t,s){this.log(`[${t??"?"}] blocked for ${e}: ${s} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:s})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new vr(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;buildHandoverNote(e,t,s){let r=this.handoverStore.get(t,s);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,s);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let s=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();s.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){s.push(r);break}return s}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,s,r,o){let i=null,a=null,c=[];try{let m=this.sessions.getSession(e.agentId,s,r);i=$o(m.messages,e.message??""),c=Ao(m.messages,e.message??"",this.config.session.continuityStateTurns),m.updatedAt&&(a=Math.round((Date.now()-Date.parse(m.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,s,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,s,r)||null,agentId:e.agentId,channel:s},u=await ye(Hr,jr(d),Br,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${s}:${r}`}],features:{agent:e.agentId,channel:s},timeoutMs:1500});return!u||u.mode!=="active"||!Wr(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${s}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,s,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,s,r),Z().emit("session:rotated",{agentId:e.agentId,channel:s,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,s,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-2G6N3VF3.js"),c=await a(t,s);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-A4YW6FSK.js"),u=d(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:c.memo});u.error&&this.log(`[${e}] memo claims not proposed: ${u.error}`),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars, ${u.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let s=[];for(let[r,o]of this.agents)r!==e&&s.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
138
+ `)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new Kt(Q(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...Jt,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=qn(t.context?.chatId),a=this.cloudSessionStore();return Hi({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...Jt,...e.cloudSessions??{}},i=Date.now(),a=Ae(tt(De(e.workspace),t),e.billing),c=await Wi({route:s,agentId:t.agentId,message:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d=>ji({...d,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),log:d=>this.log(d),trace:d=>{try{Z().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:d.action,status:d.status,outputSummary:d.status==="ok"?d.summary:void 0,error:d.status==="error"?d.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});return c?{content:c.content,error:c.error,cloudSession:c.cloudSession,duration:Date.now()-i}:null}callerGone(e,t){let s=Re(e.callerSignal).message;return this.log(`[${e.agentId}] caller gone during ${t} \u2014 not starting (${s})`),{content:"",error:`Caller gone before agent "${e.agentId}" was free \u2014 not started`}}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(u){i={content:"",error:u?.message??String(u)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"});let c=!a&&e.runningTaskId?this.stoppedRuns.get(e.runningTaskId):void 0;c&&(this.stoppedRuns.delete(e.runningTaskId),i={...i,content:"",error:c,errorKind:"stopped"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&!c&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,s,r);if(d){let u=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${u}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let u=i.error?ze(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";rr().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:u,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(u){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${u?.message??u}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=le(e.autonomy),a=Rs(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:Bo().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(c){let l=await c;if(l.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${l.sessionId}`),{content:l.text,viaAttachedSession:l.sessionId};this.log(`[${e.agentId}] attached session did not take it (${l.reason}) \u2014 spawning`)}let d=this.agents.get(e.agentId);if(!d){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let l=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(v=>v.id===e.agentId));if(l){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${l.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(l.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:l.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${l.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:g}=Lt(e.context),m;if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||i){let l=Date.now(),f=25*6e4,v=500;for(;d.activeTasks>=d.def.maxConcurrent;){if(e.callerSignal?.aborted)return this.callerGone(e,"slot wait");if(Date.now()-l>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(k=>setTimeout(k,v))}}else if(u==="voice"){let l=Date.now(),f=25*6e4,v=`${e.agentId}\0${g}`;for(;this.messageQueue.isBusy(e.agentId,u,g)||this.voiceClaims.has(v);){if(Date.now()-l>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(k=>setTimeout(k,500))}m=v,this.voiceClaims.add(v)}else{let l=d.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,u,g,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:g,originalContext:e.context,queuedAt:e.queuedAt});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let v=this.messageQueue.pendingCount(e.agentId,u,g);return Z().emit("task:queued",{agentId:e.agentId,channel:u,chatId:g,at:new Date().toISOString(),sender:dn(e.context),humanRoot:Ke(e.context),person:cn(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${v}) behind=${d.runningTasks.map(k=>k.id).join(",")||"-"} chat=${u}:${g} at=${new Date().toISOString()}`),{content:"",error:nr(f,v)}}}let h=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(l,f)=>{this.log(`[${e.agentId}] ${l} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(m&&this.voiceClaims.delete(m),!h.ok)return this.log(`[${e.agentId}] ${h.reason}`),{content:"",error:h.reason};if(e.callerSignal?.aborted)return this.callerGone(e,"rate-limit wait");if(e.queuedAt!==void 0){let l=_o(e.queuedAt);l&&(e.message=`${l}
139
+ ${e.message}`),e.queuedAt=void 0}d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let p={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(p),e.runningTaskId=p.id;let x=cn(this.config.people,e.context);if(e.context&&(x?e.context.person=x.id:delete e.context.person),this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let S=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:S,sender:e.context?.sender,rootId:Tt()?.rootId,workflowRunId:e.workflowRunId??(typeof p.chatId=="string"&&p.chatId.startsWith("workflow:")&&p.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let w={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,w);let P=l=>{if(l){w.buffer+=l,w.buffer.length>Ki&&(w.buffer=w.buffer.slice(w.buffer.length-Ki));for(let f of w.subscribers)try{f(l)}catch{}}},_=_e();e.taskId=_;let L=this.taskAborts.get(p.id);L&&(L.traceId=_);let M=new Map,D=(l,f,v)=>{try{Z().emit("task:step",{taskId:_,agentId:e.agentId,name:"pipeline",action:l,status:v,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},U=0,N=!1,q=()=>{N||(N=!0,U&&D("first-event",U,"ok"))},H;if(t){let l=Vu();H=f=>{q();let v=l(f);if(v&&P(v),zi(_,e.agentId,f),Qi(M,f),Dn(f,void 0,e.model||d.def.model),r)try{r(f)}catch{}}}else H=l=>{if(q(),zi(_,e.agentId,l),Qi(M,l),Dn(l,void 0,e.model||d.def.model),r)try{r(l)}catch{}};let K=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,X=K?setTimeout(()=>S.abort(new Error(`timed out after ${Math.round(K/1e3)}s`)),K):void 0;X?.unref?.();let A=(d.def.preSpawnTimeoutSec??qu)*1e3,T=setTimeout(()=>{S.abort(new Error(`timed out before spawn after ${Math.round(A/1e3)}s in step "${p.step??"start"}"`))},A);T.unref?.();let b=()=>{T&&clearTimeout(T),T=void 0},O=()=>`task=${p.id} chat=${u}:${g} at=${new Date().toISOString()}`,B;S.signal.addEventListener("abort",()=>{let l=Re(S.signal).message;/^timed out/.test(l)&&(B=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${l} ${O()}`)},{once:!0});let C=l=>{p.step=l,this.log(`[${e.agentId}] step ${l} ${O()}`)},W=(l,f,v=0)=>{if(S.signal.aborted)return Promise.reject(Re(S.signal));C(l),(l==="agent"||l==="workflow-auto-run")&&(b(),U=Date.now());let k=Date.now(),j=Ui(f(),Uu[l]??0,l);return Fi(j,S.signal,v).then(G=>(D(l,k,"ok"),G),G=>{throw D(l,k,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${O()}`),G})},te=async(l,f,v,k=0)=>{try{return await W(l,f,k)}catch(j){if(j instanceof Be)return v();throw j}},ne=!1,R=!1,se=l=>{if(!(!ne||R)){R=!0;try{Z().emit("task:completed",{taskId:_,agentId:e.agentId,channel:u,chatId:g,durationMs:Date.now()-p.startedAt.getTime(),error:l?.error||(S.signal.aborted?Re(S.signal).message:"run ended before completion"),errorKind:l?.errorKind,interrupted:this.interruptedRuns.has(p.id)?!0:void 0,stopped:!this.interruptedRuns.has(p.id)&&(this.stoppedRuns.has(p.id)||l?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ie=!1,Kn=l=>{if(ie)return;ie=!0,se(l),this.runReleases.delete(p.id),X&&clearTimeout(X),b(),d.activeTasks--;let f=d.runningTasks.findIndex(k=>k.id===p.id);f!==-1&&d.runningTasks.splice(f,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id);let v=this.runEndWaiters.get(p.id);this.runEndWaiters.delete(p.id);for(let k of v??[])try{k()}catch{}w.done=!0,w.endedAt=new Date;for(let k of w.subscribers)try{k(`
140
+ [task finished]
141
+ `)}catch{}w.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),ju).unref?.();try{let k=w.endedAt,j={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-p.startedAt.getTime(),ok:!l?.error,error:l?.error,...this.stoppedRuns.has(p.id)||l?.errorKind==="stopped"?{status:"stopped"}:B?{status:"timeout",step:B}:{},responseText:l?.content||"",transcript:w.buffer};this.persistTaskRecord(j);let G=(j.responseText||j.error||"").trim();if(G){let Y=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Y,at:k,ok:j.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,g).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${p.id} chat=${u}:${g} at=${new Date().toISOString()}`);let j=Date.now();Z().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,count:k.length,at:new Date().toISOString()});let G=()=>Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,at:new Date().toISOString()});for(let Y of k){let ve=Y.originalContext||{channel:Y.channel,sender:Y.sender,chatId:Y.chatId};this.execute({message:Y.text,agentId:e.agentId,context:ve,queuedAt:Y.queuedAt??Y.timestamp}).then(fe=>(ze(fe.error)||G(),this.postQueuedResponseToChannel(e.agentId,ve,fe)),fe=>{throw G(),fe}).catch(fe=>{this.log(`[${e.agentId}] queued message failed: ${fe.message}`)})}}).catch(k=>{Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(p.id,Kn),this.messageQueue.markRunning(e.agentId,u,g),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${O()}`);let y=e.context?.channel||"api",{evaluateRequest:Vi,selectRequestContext:Zi}=await import("./request-planner-MFAIVLUQ.js"),Jn=te("request-gate",()=>Vi(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Qt=!1;Jn.then(()=>{Qt=!0},()=>{Qt=!0});let I=g,zt=e.context?.sender||"User",ce=d.def.tier==="codex-cli",We=li(this.config.session,y,d.def.tier),dt=gi(this.config.session),qe=We==="lean"&&dt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${I}`),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}));let ct=this.sessions.sessionIdleMs(e.agentId,y,I);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,I,e.seedHistory),()=>{});let ea=[...this.sessions.getSession(e.agentId,y,I).messages].reverse().find(l=>l.role==="agent")?.content;Li({agent:e.agentId,channel:y,chatId:I,message:e.message,previousReply:ea,taskId:_}),this.sessions.addUserMessage(e.agentId,y,I,zt,e.message);let Qn=Date.now();Z().emit("task:started",{agentId:e.agentId,channel:y,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Qn).toISOString(),taskId:_,resumeOrigin:Po(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:dn(e.context),...x?{person:x}:{},humanRoot:Ke(e.context),pickup:As(e.context),operator:Cs(e.context)}),ne=!0;let ee,Xt,zn=this.classifier;if(zn&&y!=="a2a"&&!ce){C("classify");let l=Date.now();Xt=zn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{ee=f||void 0,ee?.path?.length&&(p.intentPath=ee.path.slice()),D("classify",l,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),D("classify",l,"error")})}let Xn=async l=>{if(!Xt)return;let f;await Promise.race([Xt,new Promise(v=>{f=setTimeout(v,l),f.unref?.()})]),f&&clearTimeout(f)};await Xn(Eu);let Se=this.config.workflows?.matching,pe,Yn,Vn=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Vn?.enabled&&(Vn.agents[e.agentId]??!0)&&!i&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=(Se?.suggestThreshold??.65)&&(Yn=fr(f.workflow))}catch(l){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${l?.message||l}`)}if(this.config.workflows?.enabled&&Se?.enabled&&!i)try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=Se.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Se.mode} reasons=${f.reasons.join(",")||"n/a"}`),Se.mode==="auto"&&f.confidence>=Se.autoRunThreshold&&(this.workflowAutoRunner?pe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(l){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${l?.message||l}`)}let Te=mr(this.config.workflows,e.agentId)&&hr(e)?this.workflowRuns:void 0;if(Te&&!pe&&!i&&this.workflowAutoRunner&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list()),v=Se?.autoRunThreshold??.85;f&&f.confidence>=v&&(pe={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(l){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${l?.message||l}`)}let ae=Te?Fu():void 0,ta=ae?yr(ae):void 0,na=this.wikiHub.getAgentWiki(e.agentId),Zn=this.memoryStore.findRelevant(e.message,e.agentId,ce?3:8),es=this.memoryStore.buildContext(Zn),ts=this.memoryStore.contextFacts(Zn),sa=this.patternStore.findRelevant(e.message,e.agentId,5),ra=this.patternStore.buildContext(sa),ns="";if(!ce)try{let{loadLocalSkills:l,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),v=await W("skills",()=>l(d.def.workspace)),k=e.personLimits?.skills??[],j=k.length?v.filter(G=>!k.some(Y=>Je(Y,G.frontmatter.name))):v;ns=f(j,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,I):void 0;if(F&&this.sessions.isSessionStale(e.agentId,y,I,ct)&&(this.log(`[${e.agentId}] session stale for ${y}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,y,I)){let l=this.sessions.getLastTurnContextTokens(e.agentId,y,I);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${I} (last turn context: ${l} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"tier-2",lastTurnInputTokens:l,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,y,I)){let l=this.sessions.getTurnCount(e.agentId,y,I);this.log(`[${e.agentId}] max-turns rotation for ${y}:${I} (${l} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let l=this.config.session?.resumeGate;if(l&&l.mode!=="off"){let f=Ur({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,I),idleMs:ct??0},l);if(f.rotate&&l.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${I}: ${mn(f)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"cost");let v=this.sessions.getLastTurnInputTokens(e.agentId,y,I);this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"cost",lastTurnInputTokens:v,at:new Date().toISOString()}),F=void 0}else l.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${I}: would ${mn(f)}`)}}if(F&&d.def.tier==="claude-code"){let l=F;await te("rotate",()=>this.maybeRotateForContinuity(e,d,y,I,l),()=>!1)&&(F=void 0)}try{let l=await W("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,I,this.memoryStore));if(l.compacted){let f=l.qualityScore??"?",v=l.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${I} (quality: ${f}%, ${v} entities lost)`),l.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${l.lostEntities.slice(0,5).join(", ")}`),l.drift){let k=l.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(l){this.log(`[${e.agentId}] compaction failed (non-fatal): ${l.message}`)}let oa=process.env.AGENTX_CONTEXT_SURGERY==="1",ia=ce?{maxMessages:8,maxChars:2400}:oa&&Gi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,aa=!F&&!ce?zu(na,e.agentId,{notesInbox:Qu(this.config)}):void 0,ut=!F&&!qe?this.sessions.buildHistoryContext(e.agentId,y,I,ia):void 0,da=F?void 0:this.sessions.getRotationMemo(e.agentId,y,I)??void 0,ss,rs=[];if(this.config.procedures?.injection?.enabled&&!F&&!ce)try{let l=new ot({baseDir:Q(process.cwd(),this.config.procedures.dir)}),f=Fn(e.message,l.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){ss=Un(f),rs=f.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of f)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(l){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${l?.message||l}`)}if($e&&$e.cat)try{let f=this.sessions.getSession(e.agentId,y,I).messages,v=f[0],k=f[f.length-1],j=ut===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${ut.length}c/${ut.split(`
142
+ `).length}L`,G=`[${e.agentId}] ${y}:${I} ${j} | session.messages=${f.length}`+(f.length>0?` first=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")}) last=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")})`:"");$e.cat("context",G)}catch(l){$e.cat("context",`[${e.agentId}] context-diag error: ${l?.message??l}`)}let os;if(d.def.contextReferences&&!F)try{let l=d.def.workspace,f=this.referencesCache.get(l);if(!f){let[k,j]=await W("references",()=>Promise.all([ln(d.def.workspace),gn(d.def.workspace)]));if(k.byId.size===0&&j.recipes.length===0){let[G,Y]=await W("references",()=>Promise.all([ln(process.cwd()),gn(process.cwd())]));f={refs:G,recipes:Y}}else f={refs:k,recipes:j};this.referencesCache.set(l,f)}let v=or({agentId:e.agentId,intentTags:ee?.path,message:e.message},f.recipes,f.refs);v.cards.length>0&&(os=sr(v.cards,500*4)),v.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${v.unresolvedIds.join(", ")}`)}catch(l){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${l?.message||l}`)}let is=qe?"":this.sessions.getCrossSessionSummary(e.agentId,y,I,e.message),as,lt=vo(e.message);if(lt)try{let l=this.sessions.recallTurns({agentId:e.agentId,channel:y,chatId:I,lookbackDays:lt.lookbackDays,limit:12});if(l.turns.length>0){let f=[`[Long-memory recall \u2014 last ${lt.lookbackDays}d on this chat (cue-triggered)]`],v=[...l.turns].sort((k,j)=>k.ts.localeCompare(j.ts));for(let k of v){let j=k.ts.slice(11,16)+" "+k.day,G=k.role==="user"?k.senderName||"User":k.senderName||"Agent";f.push(`${j} ${G}: ${k.content}`)}l.hasMore&&f.push(`[\u2026${l.totalScanned-l.turns.length}+ older turns available \u2014 call /recall with before=${l.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),as=f.join(`
143
+ `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${lt.lookbackDays}d, turns=${l.turns.length}, scanned=${l.totalScanned}`)}}catch(l){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${l.message}`)}let ca=ce?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",ds,cs,us=!1;Qt||C("request-gate");let ke=await Jn;if(ke.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),ca==="planner"&&!ke.active&&!qe&&y!=="voice"&&y!=="desktop"){try{let{planContext:l}=await import("./context-planner-3JDA7FNR.js"),f=await W("plan-context",()=>l({agentId:e.agentId,channel:y,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(us=!0,ds=f.sessionHistory,es=f.memoryContext,ts=f.memoryFacts,is=f.crossChatContext,cs=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(l){this.log(`[${e.agentId}] planner failed (non-fatal): ${l.message} \u2014 falling back to layered (keeping --resume for continuity)`)}us&&F&&(this.sessions.clearClaudeSessionId(e.agentId,y,I),F=void 0)}let Yt=`${e.agentId}:${y}:${I}`,gt=js(e.message);gt&&(gt==="default"?(this.activeSouls.delete(Yt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Yt,gt),this.log(`[${e.agentId}] Soul switched to: ${gt}`)));let ua=this.activeSouls.get(Yt),la=Hs(d.def.workspace,ua),ga=Bs(la),pa=this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),fa=Bu(d.def.tier),ma=Zu(d.def.richMessages,y),ha=d.def.tier==="claude-code"&&(We!=="lean"||pi(dt)),ls="";if(d.def.workspace&&!ha){let l=Q(d.def.workspace,"CLAUDE.md");if(de(l))try{let f=it(l,"utf-8");ls=`[Project CLAUDE.md]
144
+ ${f.length>4e3?f.slice(0,4e3)+`
145
+
146
+ [CLAUDE.md truncated to 4KB]`:f}`}catch{}}let pt=e.context?.runbookPath,Vt=[];if(pt&&de(pt)){let l=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,v=4e3,k=16e3;for(let j of l){if(f>=k)break;let G=Q(pt,j);if(de(G))try{let Y=it(G,"utf-8"),ve=Y.length>v?Y.slice(0,v)+`
147
+
148
+ [${j} truncated to ${v} bytes]`:Y;Vt.push(`[Project Runbook \u2014 ${j} from ${pt}]
149
+ ${ve}`),f+=ve.length}catch{}}}let ya=Vt.length>0?Vt.join(`
150
+
151
+ `):"",Zt=[d.def.systemPrompt||"",fa,ma,ls,ya,ga||"",pa||""].filter(l=>l.trim().length>0).join(`
152
+
153
+ `)||void 0,en={channel:y,chatId:I,channelScope:e.context?.group?"group":y==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,y),systemPrompt:d.def.systemPrompt,sender:zt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ce||qe||Gi(y,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ce?void 0:ra||void 0,procedureContext:[ss,Yn].filter(Boolean).join(`
154
+
155
+ `)||void 0,workflowRunContext:ta,references:os,skillInjection:ns||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ds??ut,memoryContext:es||void 0,crossChatContext:is||void 0,longMemoryRecall:as||void 0,contextOnDemand:qe&&!F?wi(y,I):void 0,wikiContext:aa,handoverNote:this.buildHandoverNote(e.agentId,y,I),rotationMemo:da,eventDigest:F?void 0:Ju(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let l=$r(y,!F,d.def.richMessages);return l?Xu(d.def.workspace,l):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message},ft=e.model?void 0:Ls({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?ct:null});ft?.downgraded&&this.log(`[${e.agentId}] ${ft.reason}`);let gs=Ns(d.def.tier,this.config.decisions.routing),ps=ft?.downgraded?Promise.resolve(ft.model):!e.model&&gs&&(!ke.active||ke.preprocess)?(async()=>{try{let{routeTaskModel:l}=await import("./routing-OPCLHIYW.js"),f=await W("route-model",()=>l({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!F,sessionIdleMs:F?ct:null,cheapModel:gs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),fs=!1;ps.then(()=>{fs=!0});let mt=ke.active&&ke.preprocess?await te("select-context",()=>Zi(en),()=>({input:en,excluded:[]})):{input:en,excluded:[]};mt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${mt.excluded.join(", ")}`);let ht=Mo(mt.input,ce?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),wa=Vs(ht,{memory:ts,procedures:rs,wikiContext:mt.input.wikiContext}),tn=(ht?.length??0)+(Zt?.length??0)+(e.message?.length??0),yt={history:ht?.length??0,sysPrompt:Zt?.length??0,message:e.message?.length??0},ms=si(e.agentId,y,I);ri(ms,tn,yt);let hs=oi(ms);hs&&this.log(`[${e.agentId}] ${hs}`),tn>16e3&&this.log(`[${e.agentId}] large context for ${y}:${I}: ${tn} bytes (history=${yt.history}, sysPrompt=${yt.sysPrompt}, message=${yt.message})`),fs||C("route-model");let ys=await ps,ws=d.def.tier!=="claude-code"?void 0:We==="lean"?mi(d.def.workspace,dt,void 0,y):yi(d.def.workspace);We==="lean"&&!F&&this.log(`[${e.agentId}] session profile for ${y}: ${bi(We,dt,y)}`);let bs=d.def.tier==="claude-code"&&!F?Lr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:_},l=>this.log(l)):void 0,ba={...e,systemPromptAppend:Zt,...ws?{claudeArgs:ws}:{},...ys?{model:ys}:{}},re,xs=Di({agent:e.agentId,request:e.message,taskId:_,budgetMinutes:d.def.maxExecutionMinutes??20}),xa=H,Is=!1,nn=!0;H=l=>{if(xs.observe(l),ae&&nn)for(let f of br(l))wr(f.name,f.input)||(nn=!1);xa?.(l)};try{let l=this.workflowAutoRunner;if(pe&&l){let E=pe;try{let J=await W("workflow-auto-run",()=>l({workflowId:E.workflowId,agentId:e.agentId,channel:y,chatId:I,message:e.message,...E.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:y,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:E.workflowId,matchConfidence:E.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${pe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:E.follow?`Started the workflow "${J.title??E.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:pe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:pe.confidence}},re}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&Te)try{let E=Ir(Te,e.resumedFrom);xr(Te,{runId:ae,agentId:e.agentId,channel:y,chatId:I,message:e.message,taskId:_,...E?{continues:E}:{}}),Is=!0,p.workflow={runId:ae,workflowId:pr}}catch(E){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${E?.message||E}`)}let f=()=>{if(d.def.tier!=="claude-code")return null;C("dispatch-gate");let E=d.def.persistentProcess?Pt():null,J=E!=null&&E.hasLive({agentId:e.agentId,channel:y,chatId:I}),he=!!F||J,ue=[jo(he),ti(he,void 0,e.model||d.def.model)].find(xt=>xt&&xt.abort);if(ue){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ue.reason}`);let xt={content:"",error:ue.message,duration:0};if(!t){w.buffer=`[error] ${ue.message}`;for(let Ia of w.subscribers)try{Ia(w.buffer)}catch{}}return xt}Jo();let Ge=ni();return Ge&&this.log(`[${e.agentId}] ${Ge}`),null},v=this.planCloudSession(d.def,e);if(v.route==="local"){let E=f();if(E)return d.errors++,re=E,E}let k=d.def.tier==="claude-code",j=k?t:(E,J)=>{E&&P(E),t&&t(E,J)},G=!1,Y=k?s:E=>{E&&(G?P(E):(P(`\u{1F4AD} ${E}`),G=!0)),s&&s(E)},ve=()=>{G&&(P(`
156
+ `),G=!1)},fe=k?j:j?(E,J)=>{ve(),j(E,J)}:void 0,$=await W("agent",async()=>{if(v.route!=="local"){let E=await this.runCloudSession(d.def,e,v,_);if(E)return E;let J=f();if(J)return J}return So(d.def,ba,this.providers,fe,ht,F,H,S.signal,Y)},Wu);if(!$.error){let E=Yu(d.def.toolUseRequired,M);if(E){let J=Array.from(M.entries()).map(([he,bt])=>`${he}=${bt}`).join(", ")||"none";$.error=`tool_required_not_called: ${E} (invoked: ${J})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${E}, observed ${J}`)}}bs&&Fr(bs,{toolUses:M,eventsSeen:N,error:$.error,agentId:e.agentId},E=>this.log(E));let wt=this.interruptedRuns.get(p.id);wt&&($.content="",$.error=wt,$.errorKind="interrupted");let sn=wt?void 0:this.stoppedRuns.get(p.id);sn&&($.content="",$.error=sn,$.errorKind="stopped"),re=$;let me=$.usage?Xs($.usage):void 0;if(R=!0,Z().emit("task:completed",{taskId:_,agentId:e.agentId,channel:y,chatId:I,durationMs:Date.now()-Qn,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:wt?!0:void 0,stopped:sn?!0:void 0,inputTokens:me?.inputTokens,outputTokens:me?.outputTokens,cacheReadTokens:me?.cacheReadTokens,cacheCreateTokens:me?.cacheCreateTokens,tier2InputTokens:me?.tier2InputTokens,tier2OutputTokens:me?.tier2OutputTokens,tier2CacheReadTokens:me?.tier2CacheReadTokens,tier2CacheCreateTokens:me?.tier2CacheCreateTokens,resumed:!!F,resumeSessionId:F||void 0,jevArm:ke.arm,numTurns:$.numTurns,injectedContext:wa,finalResponse:$.content||void 0,billedModel:$.billedModel||d.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let E=$.error?`[error] ${$.error}`:$.content;w.buffer=E;for(let J of w.subscribers)try{J(E)}catch{}}if($.error)d.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,y,I,$.content),Ni({agent:e.agentId,channel:y,chatId:I,request:e.message,reply:$.content,taskId:_}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,y,I,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,y,I,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,y,I,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,y,I,$.usage,$.contextTokens),$.usage){let ue=$.contextTokens,Ge=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ue??Ge)>=this.sessions.getTierTwoThresholdTokens(y)&&this.log(`[${e.agentId}] TIER-2 HIT on ${y}:${I}: context=${ue??"n/a"} tokens (cumulative turn total=${Ge}) \u2014 next turn will rotate`)}if(Gs({channel:y,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await Xn(Du);try{let ue=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ue,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:y,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
157
+
158
+ Agent: ${$.content}`,meta:Ku(ee,e.context)})}catch{}Ks(e.agentId,e.message,$.content,{channel:y,chatId:I,sender:zt},this.memoryStore).catch(()=>{}),No(e.agentId,e.message,$.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=$.billedModel||e.model||d.def.model,he=e.context?.channel,bt=he&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${he}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,J,he,bt),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${O()}`)}return $}catch(l){d.errors++,this.log(`[${e.agentId}] unexpected error: ${l.message}`);let f=At(l.message);return re={content:"",error:Ct(f),errorKind:f.kind},re}finally{if(xs.stop(),Is&&ae&&Te)try{let l=re?.usage,f=Sr(Te,ae,{error:re?re.error||void 0:S.signal.aborted?Re(S.signal).message:"run ended before completion",canceled:Tr(re?.errorKind)||this.stoppedRuns.has(p.id)||this.interruptedRuns.has(p.id)||!re&&S.signal.aborted,durationMs:Date.now()-p.startedAt.getTime(),...l?{inputTokens:l.inputTokens,outputTokens:l.outputTokens}:{},readOnly:nn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(l){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${l?.message||l}`)}se(re),Kn(re)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withWorkflowSteps(e.runningTasks),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:kr(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=Q(process.cwd(),je,this.safe(e.agentId),t);de(s)||Ou(s,{recursive:!0});let r=Q(s,`${this.safe(e.id)}.json`);Lu(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=Q(process.cwd(),je,this.safe(e));if(!de(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let g of[d,c]){let m=Q(a,g);if(de(m))try{for(let h of ge(m)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],x=parseInt(p,10);if(!Number.isFinite(x)||x<i||x>s)continue;let S=Math.floor((s-x)/36e5),w=t-1-S;w>=0&&w<t&&o[w]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=Q(process.cwd(),je);if(!de(e))return 0;let t=0;for(let s of ge(e)){let r=Q(e,s),o;try{o=ge(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=Q(r,i),c;try{c=ge(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(it(Q(a,d),"utf-8")),g=(u.responseText||u.error||"").trim();if(!g)continue;let m=g.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:m,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Gu){let t=Q(process.cwd(),je);if(!de(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ge(t)){let i=Q(t,o),a;try{a=ge(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Nu(Q(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=Q(process.cwd(),je,this.safe(e));if(!de(s))return[];let r=ge(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=Q(s,i),c;try{c=ge(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(it(Q(a,d),"utf-8")),{transcript:g,responseText:m,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=Q(process.cwd(),je,this.safe(e));if(!de(s))return null;let r=this.safe(t),o=ge(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=Q(s,i,`${r}.json`);if(de(a))try{return JSON.parse(it(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=gr();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||ze(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Lt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let r=[...this.taskAborts].filter(([,o])=>o.agentId===e.agentId&&o.channel===e.channel&&o.chatId===e.chatId).map(([o])=>o);t=r.length===1?r[0]:void 0}let s=t?this.taskAborts.get(t):void 0;return!t||!s?null:{taskId:t,traceId:s.traceId,agentId:s.agentId,channel:s.channel,chatId:s.chatId,sender:s.sender,rootId:s.rootId,originalMessage:s.originalMessage,origin:s.origin??null,...s.workflowRunId?{workflowRunId:s.workflowRunId}:{}}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,g=!1;u&&d&&(g=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let m=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:m,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);Z().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(m).toISOString(),sender:{name:s},humanRoot:!1,person:Ms(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:m});let p=!1;if(r.replace){let x=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(x))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${x}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${g?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:g,pending:h}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,g=m=>{u||(u=!0,d(m))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:m=>g({ok:!0,agentId:e,channel:a,chatId:c,taskId:m,queued:!1})}).then(m=>{ze(m.error)?g({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):m.error?g({ok:!1,status:500,error:m.error||"run did not start"}):g({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:m.viaAttachedSession?"attached":"other"})}).catch(m=>g({ok:!1,status:500,error:m?.message??String(m)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Zu(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
159
+ `)}export{qr as a,fl as b,Kr as c,Ua as d,Jr as e,Rt as f,Al as g,Rl as h,_l as i,Ll as j,Lt as k,id as l,bo as m,ld as n,gd as o,pd as p,So as q,Ft as r,Ut as s,Dd as t,lg as u,gg as v,Rn as w,Z as x,Lo as y,qd as z,Qd as A,Ho as B,Mg as C,Bo as D,Go as E,Yo as F,Wg as G,Vo as H,jt as I,Qg as J,zg as K,ot as L,Zc as M,eu as N,tu as O,nu as P,su as Q,Fn as R,Hu as S,Bu as T,Ff as U,Uf as V,Ku as W,Ju as X,zu as Y,Gn as Z,Ji as _,Qi as $,Yu as aa,zi as ba,Xi as ca,Zu as da};
160
+ //# sourceMappingURL=chunk-L5UGH4T4.js.map