agentix-cli 0.153.1 → 0.154.1

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 (126) hide show
  1. package/dist/{App-2SWSYFED.js → App-6T6NVB7O.js} +2 -2
  2. package/dist/{ChatApp-NYTNFLIB.js → ChatApp-QZBJ4NHC.js} +2 -2
  3. package/dist/{absorb-eval-SYX5QN4H.js → absorb-eval-EVX7LDXR.js} +2 -2
  4. package/dist/{agent-UCYQELAQ.js → agent-F2NT6B25.js} +2 -2
  5. package/dist/{board-dashboard-UZF7MQZA.js → board-dashboard-642BO7GV.js} +4 -4
  6. package/dist/{chunk-Z2KGUEB6.js → chunk-37I654UJ.js} +2 -2
  7. package/dist/{chunk-2J2OES2S.js → chunk-4CWACHEH.js} +2 -2
  8. package/dist/{chunk-HVNWI63Z.js → chunk-743RAKLP.js} +2 -2
  9. package/dist/{chunk-MM3ABEOW.js → chunk-ABCQ6QMJ.js} +2 -2
  10. package/dist/{chunk-ZQONMM3B.js → chunk-AKCEMKQM.js} +2 -2
  11. package/dist/{chunk-FVRREIVV.js → chunk-B75BLZ2M.js} +2 -2
  12. package/dist/{chunk-CFPRIE6F.js → chunk-CUAS4ITR.js} +2 -2
  13. package/dist/{chunk-DPSHY7GN.js → chunk-E76HREC7.js} +3 -3
  14. package/dist/{chunk-DZRD6BE4.js → chunk-EGTANAFI.js} +2 -2
  15. package/dist/{chunk-GDLO7FC7.js → chunk-GFRAHUAQ.js} +2 -2
  16. package/dist/{chunk-BFONYVOM.js → chunk-GRVTLUQ6.js} +2 -2
  17. package/dist/{chunk-VAK4LT62.js → chunk-HSCZSNOX.js} +3 -3
  18. package/dist/chunk-HSCZSNOX.js.map +1 -0
  19. package/dist/{chunk-IFOFBI3U.js → chunk-HUN6COOF.js} +2 -2
  20. package/dist/{chunk-JPZBWHNZ.js → chunk-IA4J3YLB.js} +2 -2
  21. package/dist/{chunk-3OPW64OM.js → chunk-IWWEUXZQ.js} +2 -2
  22. package/dist/{chunk-RJCHFDF3.js → chunk-KA2NV7H4.js} +2 -2
  23. package/dist/{chunk-5DPN2HIR.js → chunk-MLC5INGD.js} +5 -5
  24. package/dist/{chunk-XQ2VU6MM.js → chunk-OKVQYPPF.js} +119 -119
  25. package/dist/chunk-OKVQYPPF.js.map +1 -0
  26. package/dist/{chunk-3LU2ZQZJ.js → chunk-S3EX64LR.js} +2 -2
  27. package/dist/{chunk-UUVJX6WD.js → chunk-SD3CC4EX.js} +2 -2
  28. package/dist/{chunk-RUQMUDSX.js → chunk-U4YTTWR6.js} +2 -2
  29. package/dist/chunk-VKEH4IBA.js +76 -0
  30. package/dist/chunk-VKEH4IBA.js.map +1 -0
  31. package/dist/{chunk-I45WFYGM.js → chunk-VRF4YW46.js} +2 -2
  32. package/dist/{chunk-LH3GOBZP.js → chunk-W2RB5XG7.js} +2 -2
  33. package/dist/{chunk-ZAH74SFX.js → chunk-XOUK5ZIQ.js} +2 -2
  34. package/dist/{chunk-MWYPW5XP.js → chunk-YJNUVAM4.js} +2 -2
  35. package/dist/{chunk-S5FRIHWM.js → chunk-YL26FRKJ.js} +2 -2
  36. package/dist/cli.js +1 -1
  37. package/dist/{client-PBIUMGDL.js → client-OCLSGJYQ.js} +2 -2
  38. package/dist/{config-VLH5DJTH.js → config-FZTWI3VG.js} +2 -2
  39. package/dist/{config-mutate-G7HW2R6H.js → config-mutate-X5IKMROK.js} +2 -2
  40. package/dist/config-mutator-C5BMIBZO.js +2 -0
  41. package/dist/{contributions-GZVKJXSJ.js → contributions-KHGGVSR6.js} +2 -2
  42. package/dist/{doctor-QWVUVWTF.js → doctor-KNCRQ3YO.js} +2 -2
  43. package/dist/{follow-up-tool-PTKDMFA7.js → follow-up-tool-TGKEPA5C.js} +2 -2
  44. package/dist/{hub-BHCBRQZP.js → hub-HQUAH5H6.js} +2 -2
  45. package/dist/index.d.ts +8 -0
  46. package/dist/index.js +1 -1
  47. package/dist/{program-2YK3YCBX.js → program-HFN24YLA.js} +24 -24
  48. package/dist/program-HFN24YLA.js.map +1 -0
  49. package/dist/{promote-73ZGTRDV.js → promote-VD4OVQGL.js} +2 -2
  50. package/dist/{query-KHW4AERR.js → query-5CPK6G2H.js} +2 -2
  51. package/dist/{query-settings-P6RUUEFO.js → query-settings-35GDM3HU.js} +2 -2
  52. package/dist/{registry-RQBXAPUZ.js → registry-JCHKHCRE.js} +2 -2
  53. package/dist/{request-planner-EUIMJ7R3.js → request-planner-ZIG4YVXC.js} +2 -2
  54. package/dist/{review-candidates-KKGDAZIB.js → review-candidates-LPZWOR2K.js} +2 -2
  55. package/dist/{routing-FQNGOTMV.js → routing-BLOYDLU4.js} +2 -2
  56. package/dist/schedule-tool-7KFO3NPD.js +2 -0
  57. package/dist/{scheduler-JXZBVPOS.js → scheduler-BEJRDQR3.js} +2 -2
  58. package/dist/{seat-DZB3NSZ7.js → seat-NU3UJC6C.js} +2 -2
  59. package/dist/{select-YD4CA7FP.js → select-IWAFX4XJ.js} +2 -2
  60. package/dist/{set-enabled-UK4SE5MZ.js → set-enabled-JF75TSFU.js} +2 -2
  61. package/dist/{tool-DIJN4XBY.js → tool-PQBQJWM5.js} +2 -2
  62. package/dist/{tool-2PA2USUG.js → tool-WTOOPTGC.js} +2 -2
  63. package/dist/{wiki-CQBXLZ2Y.js → wiki-DXG655NP.js} +2 -2
  64. package/dist/wiki-enrich-5VQCT6BT.js +2 -0
  65. package/package.json +1 -1
  66. package/dist/chunk-5VPU5FHB.js +0 -67
  67. package/dist/chunk-5VPU5FHB.js.map +0 -1
  68. package/dist/chunk-VAK4LT62.js.map +0 -1
  69. package/dist/chunk-XQ2VU6MM.js.map +0 -1
  70. package/dist/config-mutator-XWWW3PSV.js +0 -2
  71. package/dist/program-2YK3YCBX.js.map +0 -1
  72. package/dist/schedule-tool-2OWGAK4H.js +0 -2
  73. package/dist/wiki-enrich-PA6JS2YN.js +0 -2
  74. /package/dist/{App-2SWSYFED.js.map → App-6T6NVB7O.js.map} +0 -0
  75. /package/dist/{ChatApp-NYTNFLIB.js.map → ChatApp-QZBJ4NHC.js.map} +0 -0
  76. /package/dist/{absorb-eval-SYX5QN4H.js.map → absorb-eval-EVX7LDXR.js.map} +0 -0
  77. /package/dist/{agent-UCYQELAQ.js.map → agent-F2NT6B25.js.map} +0 -0
  78. /package/dist/{board-dashboard-UZF7MQZA.js.map → board-dashboard-642BO7GV.js.map} +0 -0
  79. /package/dist/{chunk-Z2KGUEB6.js.map → chunk-37I654UJ.js.map} +0 -0
  80. /package/dist/{chunk-2J2OES2S.js.map → chunk-4CWACHEH.js.map} +0 -0
  81. /package/dist/{chunk-HVNWI63Z.js.map → chunk-743RAKLP.js.map} +0 -0
  82. /package/dist/{chunk-MM3ABEOW.js.map → chunk-ABCQ6QMJ.js.map} +0 -0
  83. /package/dist/{chunk-ZQONMM3B.js.map → chunk-AKCEMKQM.js.map} +0 -0
  84. /package/dist/{chunk-FVRREIVV.js.map → chunk-B75BLZ2M.js.map} +0 -0
  85. /package/dist/{chunk-CFPRIE6F.js.map → chunk-CUAS4ITR.js.map} +0 -0
  86. /package/dist/{chunk-DPSHY7GN.js.map → chunk-E76HREC7.js.map} +0 -0
  87. /package/dist/{chunk-DZRD6BE4.js.map → chunk-EGTANAFI.js.map} +0 -0
  88. /package/dist/{chunk-GDLO7FC7.js.map → chunk-GFRAHUAQ.js.map} +0 -0
  89. /package/dist/{chunk-BFONYVOM.js.map → chunk-GRVTLUQ6.js.map} +0 -0
  90. /package/dist/{chunk-IFOFBI3U.js.map → chunk-HUN6COOF.js.map} +0 -0
  91. /package/dist/{chunk-JPZBWHNZ.js.map → chunk-IA4J3YLB.js.map} +0 -0
  92. /package/dist/{chunk-3OPW64OM.js.map → chunk-IWWEUXZQ.js.map} +0 -0
  93. /package/dist/{chunk-RJCHFDF3.js.map → chunk-KA2NV7H4.js.map} +0 -0
  94. /package/dist/{chunk-5DPN2HIR.js.map → chunk-MLC5INGD.js.map} +0 -0
  95. /package/dist/{chunk-3LU2ZQZJ.js.map → chunk-S3EX64LR.js.map} +0 -0
  96. /package/dist/{chunk-UUVJX6WD.js.map → chunk-SD3CC4EX.js.map} +0 -0
  97. /package/dist/{chunk-RUQMUDSX.js.map → chunk-U4YTTWR6.js.map} +0 -0
  98. /package/dist/{chunk-I45WFYGM.js.map → chunk-VRF4YW46.js.map} +0 -0
  99. /package/dist/{chunk-LH3GOBZP.js.map → chunk-W2RB5XG7.js.map} +0 -0
  100. /package/dist/{chunk-ZAH74SFX.js.map → chunk-XOUK5ZIQ.js.map} +0 -0
  101. /package/dist/{chunk-MWYPW5XP.js.map → chunk-YJNUVAM4.js.map} +0 -0
  102. /package/dist/{chunk-S5FRIHWM.js.map → chunk-YL26FRKJ.js.map} +0 -0
  103. /package/dist/{client-PBIUMGDL.js.map → client-OCLSGJYQ.js.map} +0 -0
  104. /package/dist/{config-VLH5DJTH.js.map → config-FZTWI3VG.js.map} +0 -0
  105. /package/dist/{config-mutate-G7HW2R6H.js.map → config-mutate-X5IKMROK.js.map} +0 -0
  106. /package/dist/{config-mutator-XWWW3PSV.js.map → config-mutator-C5BMIBZO.js.map} +0 -0
  107. /package/dist/{contributions-GZVKJXSJ.js.map → contributions-KHGGVSR6.js.map} +0 -0
  108. /package/dist/{doctor-QWVUVWTF.js.map → doctor-KNCRQ3YO.js.map} +0 -0
  109. /package/dist/{follow-up-tool-PTKDMFA7.js.map → follow-up-tool-TGKEPA5C.js.map} +0 -0
  110. /package/dist/{hub-BHCBRQZP.js.map → hub-HQUAH5H6.js.map} +0 -0
  111. /package/dist/{promote-73ZGTRDV.js.map → promote-VD4OVQGL.js.map} +0 -0
  112. /package/dist/{query-KHW4AERR.js.map → query-5CPK6G2H.js.map} +0 -0
  113. /package/dist/{query-settings-P6RUUEFO.js.map → query-settings-35GDM3HU.js.map} +0 -0
  114. /package/dist/{registry-RQBXAPUZ.js.map → registry-JCHKHCRE.js.map} +0 -0
  115. /package/dist/{request-planner-EUIMJ7R3.js.map → request-planner-ZIG4YVXC.js.map} +0 -0
  116. /package/dist/{review-candidates-KKGDAZIB.js.map → review-candidates-LPZWOR2K.js.map} +0 -0
  117. /package/dist/{routing-FQNGOTMV.js.map → routing-BLOYDLU4.js.map} +0 -0
  118. /package/dist/{schedule-tool-2OWGAK4H.js.map → schedule-tool-7KFO3NPD.js.map} +0 -0
  119. /package/dist/{scheduler-JXZBVPOS.js.map → scheduler-BEJRDQR3.js.map} +0 -0
  120. /package/dist/{seat-DZB3NSZ7.js.map → seat-NU3UJC6C.js.map} +0 -0
  121. /package/dist/{select-YD4CA7FP.js.map → select-IWAFX4XJ.js.map} +0 -0
  122. /package/dist/{set-enabled-UK4SE5MZ.js.map → set-enabled-JF75TSFU.js.map} +0 -0
  123. /package/dist/{tool-DIJN4XBY.js.map → tool-PQBQJWM5.js.map} +0 -0
  124. /package/dist/{tool-2PA2USUG.js.map → tool-WTOOPTGC.js.map} +0 -0
  125. /package/dist/{wiki-CQBXLZ2Y.js.map → wiki-DXG655NP.js.map} +0 -0
  126. /package/dist/{wiki-enrich-PA6JS2YN.js.map → wiki-enrich-5VQCT6BT.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as Le,b as k,c as z,d as Be,e as pe,f as ue,g as N,h as ge,i as O,j as U,n as je,o as He,p as qe,q as Fe}from"./chunk-XVTD6I34.js";import{e as Oe,i as Ue}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Ne}from"./chunk-CFPRIE6F.js";import{c as Me,d as le,e as P,f as de,g as j}from"./chunk-B2QYMUTD.js";import{a as We}from"./chunk-7LN4VKDU.js";import{a as Te}from"./chunk-IMLAPB7G.js";import{c as Re,e as De}from"./chunk-LQE73AZR.js";import{b as ze}from"./chunk-MRIVENBY.js";import{n as se,p as _e}from"./chunk-LQS27HSV.js";import{b as Y}from"./chunk-YMX3QCV7.js";import{G as J}from"./chunk-S5FRIHWM.js";import{a as G,b as K}from"./chunk-BFONYVOM.js";import{a as Pe}from"./chunk-RUQMUDSX.js";import{c as Ce,d as Ie}from"./chunk-OWNQ2FD4.js";import{a as Ee}from"./chunk-ROLSSYXE.js";import{Ia as oe,Ka as F,L as ae,La as Se,M as $e,T as Rt,Ua as ie,ia as Ae,pa as Dt}from"./chunk-5VPU5FHB.js";import{existsSync as H,readFileSync as Je,writeFileSync as Ye,appendFileSync as Wt,mkdirSync as Mt}from"fs";import{dirname as Nt,resolve as W}from"path";import{fileURLToPath as Ot}from"url";import{hostname as Ut}from"os";import{spawn as Lt}from"child_process";function Ge(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
1
+ import{a as Le,b as k,c as z,d as Be,e as pe,f as ue,g as N,h as ge,i as O,j as U,n as je,o as He,p as qe,q as Fe}from"./chunk-XVTD6I34.js";import{e as Oe,i as Ue}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Ne}from"./chunk-CUAS4ITR.js";import{c as Me,d as le,e as P,f as de,g as j}from"./chunk-B2QYMUTD.js";import{a as We}from"./chunk-7LN4VKDU.js";import{a as Te}from"./chunk-IMLAPB7G.js";import{c as Re,e as De}from"./chunk-LQE73AZR.js";import{b as ze}from"./chunk-MRIVENBY.js";import{n as se,p as _e}from"./chunk-LQS27HSV.js";import{b as Y}from"./chunk-YMX3QCV7.js";import{G as J}from"./chunk-YL26FRKJ.js";import{a as G,b as K}from"./chunk-GRVTLUQ6.js";import{a as Pe}from"./chunk-U4YTTWR6.js";import{c as Ce,d as Ie}from"./chunk-OWNQ2FD4.js";import{a as Ee}from"./chunk-ROLSSYXE.js";import{Ia as oe,Ka as F,L as ae,La as Se,M as $e,T as Rt,Ua as ie,ia as Ae,pa as Dt}from"./chunk-VKEH4IBA.js";import{existsSync as H,readFileSync as Je,writeFileSync as Ye,appendFileSync as Wt,mkdirSync as Mt}from"fs";import{dirname as Nt,resolve as W}from"path";import{fileURLToPath as Ot}from"url";import{hostname as Ut}from"os";import{spawn as Lt}from"child_process";function Ge(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
2
2
  <div class="ax-topbar__left">
3
3
  <div class="ax-brand">
4
4
  <span class="ax-brand__mark">AX</span>
@@ -859,4 +859,4 @@ tr:hover td { background: var(--bg-hover); }
859
859
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
860
860
  ${r}`).all(t,...n,...a).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Ta(e,t){return wt(e,t,ae,"ORDER BY created_at")}function Ra(e,t,n=50){return wt(e,t,[...ae,...$e],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}Dt();var we="member:",Mn=90,Nn="members",On="tailscale-user-login",Un=400,Ln=60*60*1e3;function Bn(e){let t=e.scopes.find(n=>n.startsWith(we));return t?t.slice(we.length):null}function At(e,t){if(!e)return null;let n=t.verify(e),r=n?Bn(n):null;return n&&r?{rec:n,personId:r}:null}function Oa(e,t){let n=e.people().find(s=>s.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:r,record:a}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${we}${n.id}`],expiresInDays:Mn}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:a.id,name:n.id});return e.members.log({person:n.id,device:a.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:a.id,person:n}}var jn=Math.round(Re/6e4);function Hn(e){return e==="client"?"Your project":"My work"}function Ua(e){let t=Hn(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${De(e.code)}`,` The code works once, for ${jn} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
861
861
  `)}var qn="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",Fn="Too many machines are waiting for the owner's answer. Try again later.",$t="That code didn't work. Check it, or ask the person who invited you for a new one.",St=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Ct(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function Gn(e){if(!Ct(e))return null;let t=St(e,On).toLowerCase();return t?t.slice(0,80):null}function Kn(e){let t=e.socket?.remoteAddress||"unknown";if(!Ct(e))return t;let n=St(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function Jn(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function Yn(e){return e.identities.map(Ae).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function La(e,t){let n=Date.now(),r=t.now??Date.now,a=t.log??(v=>console.log(v)),o=Kn(e),i=t.limiter.retryAfter(o);if(i>0)return a(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,l="";try{let v=await Y(e,2048);s=v.code,l=Jn(v.machine)}catch{}let d=t.codes.redeem(s),c=d?At(d.token,t.tokens):null;if(await Vn(n,t.minMs??Un),!d||!c)return t.limiter.fail(o),a(`[member] pair-code failed from ${o}`),{status:401,body:{error:$t}};t.limiter.succeed(o);let{rec:m,personId:p}=c,w=t.people().find(v=>v.id===p);if(!w)return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),a(`[member] pair-code for ${p} refused from ${o}: person no longer listed`),{status:403,body:{error:$t}};let g=Gn(e),f=Yn(w);if(f.length&&(!g||!f.includes(g)))return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:o,detail:`network login ${g??"missing"}; expected ${f.join(" or ")}`}),a(`[member] ${p}: pairing from ${o} refused: the network says "${g??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:qn}};let C=l||"Unnamed machine",x=w.name.slice(0,40),b=_e(t.root,{title:`New machine for ${x}`,ask:`From ${o}, ${g?`network login ${g}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${x}'s own work?`,recommend:`Yes if ${x} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:Nn},{now:r()});return b.ok?(t.members.add({tokenId:m.id,personId:p,name:C,state:"pending",cardId:b.card.id,address:o,...g?{network:g}:{},createdAt:new Date(r()).toISOString()}),t.members.log({person:p,device:m.id,event:"paired",address:o,detail:C}),a(`[member] ${p} paired "${C}" from ${o}; waiting for the owner (card ${b.card.id})`),{status:200,body:{person:p,name:C,state:"pending"},token:d.token}):(t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:o,detail:b.error}),a(`[member] ${p}: pairing from ${o} refused: ${b.error}`),{status:503,body:{error:Fn}})}var re="this machine is not paired",Xn="waiting for the owner to approve this machine";function It(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function Ba(e,t){return t.state==="pending"&&t.cardId?It(se(e,t.cardId)):null}function ja(e,t,n){let r=t.now??Date.now,a=t.log??(c=>console.log(c)),o=At(e,t.tokens);if(!o)return{ok:!1,status:401,error:re};let{rec:i,personId:s}=o,l=t.members.byToken(i.id);if(!l||l.state==="removed"||l.personId!==s)return{ok:!1,status:401,error:re};if(t.people&&!t.people().some(c=>c.id===s))return Et(t,i.id,"person no longer listed"),a(`[member] ${s}: "${l.name}" ended: person no longer listed`),{ok:!1,status:401,error:re};if(l.state==="pending"){let c=l.cardId?se(t.root,l.cardId):null,m=It(c);if(m==="yes")l=t.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??l,t.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),a(`[member] ${s}: "${l.name}" approved`);else if(m==="no"){let p=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(i.id),t.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:p}),t.members.log({person:s,device:i.id,event:"refused",detail:p}),a(`[member] ${s}: "${l.name}" refused: ${p}`),{ok:!1,status:401,error:re}}else return{ok:!1,status:403,error:Xn,waiting:!0}}let d=l.lastSeenAt?Date.parse(l.lastSeenAt):0;return n&&(r()-d>=Ln||l.lastAddress!==n)&&(l=t.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:n})??l,t.members.log({person:s,device:i.id,event:"signed-in",address:n})),{ok:!0,device:l,personId:s,rec:i}}function Et(e,t,n="removed by the owner"){let r=e.members.byToken(t);if(!r)return null;e.tokens.revoke(t);let a=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:r.personId,device:t,event:"removed",detail:n}),a}function Ha(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Et(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function Vn(e,t){let n=e+t-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}var Pt=["gitlab","github"];function Qn(e,t,n){let r=String(t||"").trim().toLowerCase();if(!Pt.includes(r))throw new Error(`Request status works on ${Pt.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let a=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...a,r])]:a.filter(o=>o!==r),`request status on ${r} is ${n?"on":"off"}`}function Ga(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function Ka(e){let{summary:t}=X(n=>Qn(n,e?.channel,!!e?.enabled));return{summary:t}}function Ya(e){return new Set(Object.entries(e).filter(([,t])=>t?.wiki?.absorb?.enabled===!1).map(([t])=>t))}function Xa(e,t){return t.only?{agents:[t.only],skipped:[]}:{agents:e.filter(n=>!t.off.has(n)),skipped:e.filter(n=>t.off.has(n))}}function Va(e,t){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===t?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Qa(e,t){if(t){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Zn="https://ntfy.sh";function eo(e){return{enabled:!!e?.enabled,server:e?.server||Zn,topicSet:!!e?.topic,tokenSet:!!e?.token}}function to(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let r=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");n.server=r}if("topic"in t){let r=String(t.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");n.topic=r}if("token"in t){let r=String(t.token??"").trim();r?n.token=r:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{Xe as a,cr as b,pr as c,ur as d,xr as e,yr as f,tn as g,an as h,me as i,kr as j,wr as k,kt as l,Sa as m,Ca as n,Ir as o,Er as p,Pr as q,Pa as r,Ta as s,Ra as t,Mn as u,Oa as v,jn as w,Hn as x,Ua as y,Kn as z,La as A,Ba as B,ja as C,Et as D,Ha as E,Pt as F,Qn as G,Ga as H,Ka as I,Ya as J,Xa as K,Va as L,Qa as M,eo as N,to as O,Cn as P,Vr as Q,ra as R,aa as S};
862
- //# sourceMappingURL=chunk-IFOFBI3U.js.map
862
+ //# sourceMappingURL=chunk-HUN6COOF.js.map
@@ -1,4 +1,4 @@
1
- import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-RJCHFDF3.js";import{y as C,z as K}from"./chunk-HVNWI63Z.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
1
+ import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-KA2NV7H4.js";import{y as C,z as K}from"./chunk-743RAKLP.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
2
2
  `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
3
3
  `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
4
4
  `));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
@@ -102,4 +102,4 @@ We use GitLab for version control.
102
102
  There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
103
 
104
104
  ${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
105
- //# sourceMappingURL=chunk-JPZBWHNZ.js.map
105
+ //# sourceMappingURL=chunk-IA4J3YLB.js.map
@@ -1,5 +1,5 @@
1
- import{La as m,Ua as b}from"./chunk-5VPU5FHB.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
1
+ import{La as m,Ua as b}from"./chunk-VKEH4IBA.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
2
2
 
3
3
  `))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
4
4
  `))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
5
- //# sourceMappingURL=chunk-3OPW64OM.js.map
5
+ //# sourceMappingURL=chunk-IWWEUXZQ.js.map
@@ -1,6 +1,6 @@
1
- import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-HVNWI63Z.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-JNG3P5V2.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-743RAKLP.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-JNG3P5V2.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
6
- //# sourceMappingURL=chunk-RJCHFDF3.js.map
6
+ //# sourceMappingURL=chunk-KA2NV7H4.js.map
@@ -1,4 +1,4 @@
1
- import{$ as Hr,H as Mr,I as Rr,J as Pr,L as _r,M as Er,N as Or,O as Dr,R as Nr,S as Lr,V as Ur,W as Fr,a as pr,b as fr,ba as jr,d as hr,f as Xe,l as At,m as Ar,t as Ct,v as Cr}from"./chunk-S5FRIHWM.js";import{b as mr}from"./chunk-MEFPXHQJ.js";import{a as $r}from"./chunk-W4YR2RO2.js";import{a as gr}from"./chunk-5TTHN7DP.js";import{b as wr,c as xn,d as xr,e as $t,h as Sr}from"./chunk-LH3GOBZP.js";import{e as ur,f as lr}from"./chunk-36AXN6ZB.js";import{a as wn,b as yr}from"./chunk-J3SOEFRE.js";import{a as bn,b as br}from"./chunk-SIU6STB2.js";import{e as Ir,i as Tr,j as kr,k as vr}from"./chunk-X5C5W3E4.js";import{a as dr}from"./chunk-RUQMUDSX.js";import{g as ar,h as cr}from"./chunk-RJCHFDF3.js";import{c as Qs,f as Xs}from"./chunk-Z2KGUEB6.js";import{s as Js,v as vt,w as zs,y as we,z as yn}from"./chunk-HVNWI63Z.js";import{a as Qe,b as Oe,f as kt}from"./chunk-72SZI2UW.js";import{a as Ee,b as gn}from"./chunk-FCPTN6NF.js";import{a as Ys,c as Zs}from"./chunk-MYVHVJWZ.js";import{d as De,g as Vs,h as Ce}from"./chunk-6TURWSMN.js";import{a as er,b as tr,c as nr,d as sr,l as rr}from"./chunk-AV7T3SYT.js";import{a as or,b as ir}from"./chunk-U23LVMMZ.js";import{c as Ds,d as Ns}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Ua as gc,V as Hs,X as mn,Z as uc,aa as js,ea as lc,ka as Bs,la as hn,ma as Ws,na as ze,oa as qs,pa as Gs,va as Ks}from"./chunk-5VPU5FHB.js";import{g as Je,h as cc}from"./chunk-BRK6M6LA.js";import{f as fn,n as dc}from"./chunk-UIBUZ2N3.js";import{a as Ls,b as ge,c as Us,d as Fs,e as pn}from"./chunk-2QNT5JDS.js";yn();kt();var Mt="tool-set",Br=["answer","code","full"],Wr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},pc=.1;function Gr(n){return{task:qr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:qr(n.agentPrompt,600)}:{}}}var Kr={bundle:Oe({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 Jr(n,e=pc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Sn(s.answer),o=Sn(s.code),i=Sn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function zr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Wr.answer.includes(t))?"answer":e.every(t=>Wr.code.includes(t))?"code":"full"}function Qr(n,e){return Br.indexOf(n)<Br.indexOf(e)}function Sn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function qr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Xr=!1;function Yr(n,e){let t=vt(Mt);if(t!=="off")return t==="active"&&!Xr&&(Xr=!0,e(`[decisions] seat "${Mt}" is set to active, but only shadow is built: it records and changes nothing`)),we(Mt,Gr(n),Kr,{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=Jr(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Zr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=zr(r);zs(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}`+(Qr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function fc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Vr(n,e){let t=fc(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 In(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)`}yn();kt();var eo="session-continuity",to={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 no(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Tn(n.message,1200),previousRequest:n.previousMessage?Tn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Tn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function so(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 Tn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ut}from"execa";import{spawn as mc}from"node:child_process";import{createHash as hc}from"node:crypto";import{createInterface as yc}from"node:readline";var be=class extends Error{},wc=n=>mc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),kn=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(),yc({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
1
+ import{$ as Hr,H as Mr,I as Rr,J as Pr,L as _r,M as Er,N as Or,O as Dr,R as Nr,S as Lr,V as Ur,W as Fr,a as pr,b as fr,ba as jr,d as hr,f as Xe,l as At,m as Ar,t as Ct,v as Cr}from"./chunk-YL26FRKJ.js";import{b as mr}from"./chunk-MEFPXHQJ.js";import{a as $r}from"./chunk-W4YR2RO2.js";import{a as gr}from"./chunk-5TTHN7DP.js";import{b as wr,c as xn,d as xr,e as $t,h as Sr}from"./chunk-W2RB5XG7.js";import{e as ur,f as lr}from"./chunk-36AXN6ZB.js";import{a as wn,b as yr}from"./chunk-J3SOEFRE.js";import{a as bn,b as br}from"./chunk-SIU6STB2.js";import{e as Ir,i as Tr,j as kr,k as vr}from"./chunk-X5C5W3E4.js";import{a as dr}from"./chunk-U4YTTWR6.js";import{g as ar,h as cr}from"./chunk-KA2NV7H4.js";import{c as Qs,f as Xs}from"./chunk-37I654UJ.js";import{s as Js,v as vt,w as zs,y as we,z as yn}from"./chunk-743RAKLP.js";import{a as Qe,b as Oe,f as kt}from"./chunk-72SZI2UW.js";import{a as Ee,b as gn}from"./chunk-FCPTN6NF.js";import{a as Ys,c as Zs}from"./chunk-MYVHVJWZ.js";import{d as De,g as Vs,h as Ce}from"./chunk-6TURWSMN.js";import{a as er,b as tr,c as nr,d as sr,l as rr}from"./chunk-AV7T3SYT.js";import{a as or,b as ir}from"./chunk-U23LVMMZ.js";import{c as Ds,d as Ns}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Ua as gc,V as Hs,X as mn,Z as uc,aa as js,ea as lc,ka as Bs,la as hn,ma as Ws,na as ze,oa as qs,pa as Gs,va as Ks}from"./chunk-VKEH4IBA.js";import{g as Je,h as cc}from"./chunk-BRK6M6LA.js";import{f as fn,n as dc}from"./chunk-UIBUZ2N3.js";import{a as Ls,b as ge,c as Us,d as Fs,e as pn}from"./chunk-2QNT5JDS.js";yn();kt();var Mt="tool-set",Br=["answer","code","full"],Wr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},pc=.1;function Gr(n){return{task:qr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:qr(n.agentPrompt,600)}:{}}}var Kr={bundle:Oe({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 Jr(n,e=pc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Sn(s.answer),o=Sn(s.code),i=Sn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function zr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Wr.answer.includes(t))?"answer":e.every(t=>Wr.code.includes(t))?"code":"full"}function Qr(n,e){return Br.indexOf(n)<Br.indexOf(e)}function Sn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function qr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Xr=!1;function Yr(n,e){let t=vt(Mt);if(t!=="off")return t==="active"&&!Xr&&(Xr=!0,e(`[decisions] seat "${Mt}" is set to active, but only shadow is built: it records and changes nothing`)),we(Mt,Gr(n),Kr,{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=Jr(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Zr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=zr(r);zs(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}`+(Qr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function fc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Vr(n,e){let t=fc(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 In(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)`}yn();kt();var eo="session-continuity",to={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 no(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Tn(n.message,1200),previousRequest:n.previousMessage?Tn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Tn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function so(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 Tn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ut}from"execa";import{spawn as mc}from"node:child_process";import{createHash as hc}from"node:crypto";import{createInterface as yc}from"node:readline";var be=class extends Error{},wc=n=>mc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),kn=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(),yc({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
2
2
  `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let 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()}},vn=class{constructor(e=wc,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=hc("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[$])=>x.localeCompare($))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new be("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 x=[...this.entries].find(([,$])=>!$.connection.busy);if(!x)throw new be("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new kn(e,this.launchProcess)}}catch{throw new be("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,d="",c,u,l,p,m=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),y=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 x={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",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(y),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let R=new Promise((E,k)=>{i.failTurn=k,i.notify=(L,N)=>{if(N?.threadId!==u)return;let O=N.item,B={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:L.replace("/","."),...O?{item:{...O,type:B[O.type]||O.type}}:{}}),L==="item/completed"&&O?.type==="agentMessage"&&O.phase==="final_answer"&&(c=O.text),L==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=N.delta,e.onDelta?.(N.delta,d)),L==="thread/tokenUsage/updated"){let F=N.tokenUsage.last;p=F.inputTokens;let q=F.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}L==="turn/completed"&&(N.turn.status==="completed"?E():k(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return R.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await R,{content:c??d,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new be(x.message);return{content:d,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(y),clearTimeout(b),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},ro=new vn;import{execFile as Fc}from"child_process";import{StringDecoder as tt}from"string_decoder";import{mkdtempSync as To,readFileSync as ko,rmSync as vo}from"fs";import{join as Nt}from"path";import{tmpdir as $o}from"os";function Rt(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 c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[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),d=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"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===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"||d===529||d===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"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,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 Pt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function _t(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,d=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&d>s)&&(e=r,t=a,s=d)}return e}var oo=null;function Et(){return oo}function Fg(n){oo=n}function Ye(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function bc(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 Ne=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},io=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=Ye(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=bc(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 Ne(`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 Ne(`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=Ye(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=Ye(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Ye(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=Ye(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(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";s.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as xc}from"child_process";import{randomUUID as Sc}from"crypto";import{existsSync as Ic,readFileSync as Tc}from"fs";import{resolve as kc}from"path";function vc(n){let e=kc(n,"CLAUDE.md");if(!Ic(e))return null;try{let t=Tc(e,"utf8");return rr(t)}catch{return null}}var $c=20*60*1e3,Ac=5e3,Ze=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 Cc(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 ao=class{constructor(e={}){this.opts=e}spawn(e,t){return new $n(e,t,this.opts)}},$n=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=xc(r,o,{cwd:t.workspace,env:Ce(Cc({...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:vc(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 d=this.waiters.splice(0);for(let c of d)c(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(m=>{t=m}),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=Sc(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
3
  `);let d=e.deadlineMs??$c,c=o+d,u=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new Ze(d)),l=!1,p=null;try{for(;;){let m=c-Date.now();if(m<=0)throw u();let h=await this.nextEvent(m);if(h===null&&this.killReason)throw new Ve(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let b=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${b.length} chars): ${b.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let m=this.snap.state==="busy";this.snap={...this.snap,...m?{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)},Ac);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
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"}}};pn();dc();gn();import{resolve as co,join as uo}from"path";var Mc=4e3;function Ot(n){try{let e=uo(co(n.root),".agentx","db.sqlite"),t=fn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ee(),r=n.input.command?n.input.command.slice(0,Mc):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -31,7 +31,7 @@ ${n}`}function jc(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
31
31
  `,l)}};E.stdout?.on("data",T=>{O+=F.write(T);let S=O.split(`
32
32
  `);O=S.pop()||"";for(let U of S)z(U)}),E.stderr?.on("data",T=>{B+=q.write(T)});let A=await E;if(i&&i.removeEventListener("abort",N),O+=F.end(),O.trim()&&z(O),B+=q.end(),k)return{content:"",error:L||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:m};if(A.exitCode!==0||h){let T=A,S;return T.timedOut?S=`OpenCode timed out after ${Math.round($/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+B)?S=xo():S=B.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...V(S),duration:Date.now()-d,usage:p,opencodeSessionId:m}}return y=!1,{content:l.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||n.model,opencodeSessionId:m}}catch($){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let R=/ENOENT|spawn opencode/i.test($?.message||"")?xo():$?.message;return{content:l,...V(R||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:m}}finally{x?.(),b?.release(y)}}async function Zc(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),d="",c=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of c)u.type==="result"&&u.subtype==="success"&&(d=u.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Vc(n,e,t,s,r,o,i,a,d){let c=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,m=()=>{let y=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(y))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let b=()=>({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()-c});try{let y=n.provider||"claude-code",x=s?`${s}
33
33
 
34
- ${e.message}`:e.message,$=e.context?.sender,R=typeof $=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test($),E=e.context?.channel==="web-chat"&&R?{userId:$,agentId:e.agentId||"acme-public"}:void 0,k=sr(n),L=Object.keys(k).length>0,N={task:x,cwd:n.workspace,provider:y,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:E,providerOpts:o,abortSignal:l.signal,mcpServers:L?k:void 0};if(r){let{generateStream:z}=await import("./agent-UCYQELAQ.js"),A="",T,S,U,j;for await(let P of z(N)){if(d)try{d(P)}catch{}if(P.type==="text_delta")A+=P.text,r(P.text,A);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==A){let Q=P.result.content.slice(A.length);Q?(A=P.result.content,r(Q,A)):A=P.result.content}T=P.result.tokensUsed,P.result.inputTokens!=null&&(S=P.result.inputTokens),P.result.outputTokens!=null&&(U=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==A){let Q=P.result.content.slice(A.length);Q?(A=P.result.content,r(Q,A)):A=P.result.content}P.result.tokensUsed!=null&&(T=P.result.tokensUsed)}else P.type==="error"&&(j=P.error)}return j&&!A?p?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${j}`),duration:Date.now()-c}:((S===void 0||U===void 0)&&T&&(S=Math.round(T*.7),U=T-S),{content:A||"Done.",tokensUsed:T,usage:S!==void 0||U!==void 0?{inputTokens:S||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:O}=await import("./agent-UCYQELAQ.js"),B=await O(N),F=B.inputTokens,q=B.outputTokens;if((F===void 0||q===void 0)&&B.tokensUsed){let z=B.tokensUsed;F=Math.round(z*.7),q=z-F}return{content:B.content||"Done.",tokensUsed:B.tokensUsed,usage:F!==void 0||q!==void 0?{inputTokens:F||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(y){return p?b():y?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${y.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var Cn=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}},ed=1e3;async function td(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"}),ed),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 nd(n,e,t,s,r,o,i){let a=Et();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=Ht(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,m=!1;try{let A=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:c,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>A}catch(A){return A instanceof Ne,null}m&&_n(e.agentId,n,e.model,s,"persistent");let h=Se(n,e,t),b="",y,x,$,R,E,k,L,N="",O="",B=A=>{if(!i||!A)return;let T;if(O&&A.startsWith(O)?T=A.slice(O.length):T=N&&!N.endsWith(`
34
+ ${e.message}`:e.message,$=e.context?.sender,R=typeof $=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test($),E=e.context?.channel==="web-chat"&&R?{userId:$,agentId:e.agentId||"acme-public"}:void 0,k=sr(n),L=Object.keys(k).length>0,N={task:x,cwd:n.workspace,provider:y,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:E,providerOpts:o,abortSignal:l.signal,mcpServers:L?k:void 0};if(r){let{generateStream:z}=await import("./agent-F2NT6B25.js"),A="",T,S,U,j;for await(let P of z(N)){if(d)try{d(P)}catch{}if(P.type==="text_delta")A+=P.text,r(P.text,A);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==A){let Q=P.result.content.slice(A.length);Q?(A=P.result.content,r(Q,A)):A=P.result.content}T=P.result.tokensUsed,P.result.inputTokens!=null&&(S=P.result.inputTokens),P.result.outputTokens!=null&&(U=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==A){let Q=P.result.content.slice(A.length);Q?(A=P.result.content,r(Q,A)):A=P.result.content}P.result.tokensUsed!=null&&(T=P.result.tokensUsed)}else P.type==="error"&&(j=P.error)}return j&&!A?p?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${j}`),duration:Date.now()-c}:((S===void 0||U===void 0)&&T&&(S=Math.round(T*.7),U=T-S),{content:A||"Done.",tokensUsed:T,usage:S!==void 0||U!==void 0?{inputTokens:S||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:O}=await import("./agent-F2NT6B25.js"),B=await O(N),F=B.inputTokens,q=B.outputTokens;if((F===void 0||q===void 0)&&B.tokensUsed){let z=B.tokensUsed;F=Math.round(z*.7),q=z-F}return{content:B.content||"Done.",tokensUsed:B.tokensUsed,usage:F!==void 0||q!==void 0?{inputTokens:F||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(y){return p?b():y?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${y.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var Cn=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}},ed=1e3;async function td(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"}),ed),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 nd(n,e,t,s,r,o,i){let a=Et();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=Ht(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,m=!1;try{let A=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:c,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>A}catch(A){return A instanceof Ne,null}m&&_n(e.agentId,n,e.model,s,"persistent");let h=Se(n,e,t),b="",y,x,$,R,E,k,L,N="",O="",B=A=>{if(!i||!A)return;let T;if(O&&A.startsWith(O)?T=A.slice(O.length):T=N&&!N.endsWith(`
35
35
  `)?`
36
36
 
37
37
  ${A}`:A,O=A,!!T){N+=T;try{i(T,N)}catch{}}},F=!1,q=()=>{F=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let z=!1;try{let A=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:A})){if(z=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let S=T.raw.message?.content??[];for(let j of S)j.type==="text"&&typeof j.text=="string"?(b=j.text,B(j.text)):j.type==="tool_use"&&(O="");let U=T.raw.message?.usage;if(U){let j=(U.input_tokens||0)+(U.cache_read_input_tokens||0)+(U.cache_creation_input_tokens||0);j>0&&(R=j)}}if(T.type==="result"){let S=T.raw;if(S.is_error){let U=V(typeof S.result=="string"?S.result:"claude error");y=U.error,x=U.errorKind}else typeof S.result=="string"&&S.result.length>0&&(b=S.result,N||B(S.result));typeof S.session_id=="string"&&(L=S.session_id),S.usage&&($={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(E=S.num_turns),typeof S.message?.model=="string"?k=S.message.model:typeof S.model=="string"?k=S.model:k=_t(S.modelUsage)||k}}}catch(A){if(F)y="task cancelled by operator",x="cancelled";else if(z)if(A instanceof Ve)y=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,x="interrupted";else if(A instanceof Ze){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.`);y=T.error,x=T.errorKind}else{let T=V(`persistent claude process error: ${A?.message||String(A)}`);y=T.error,x=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return F&&!y&&(y="task cancelled by operator",x="cancelled"),{content:F?"":b,error:y,errorKind:x,duration:Date.now()-d,usage:$,contextTokens:R,numTurns:E,billedModel:k,claudeSessionId:L}}function No(n){let e=ge(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?po(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:wo(t.args,n.taskId,n.agentId)}function sd(n){return ge(n.autonomy)||!!n.personLimits}async function rd(n,e,t,s,r,o,i){let a=ge(e.autonomy)?e.autonomy:void 0,d=a&&fo(a,n.tier)||e.personLimits&&bo(n.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:c,message:a?`${Fs(a)}
@@ -159,7 +159,7 @@ ${Ta(c.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.c
159
159
  ${e.message}`),e.queuedAt=void 0}let h=ei({message:e.message,home:e.context?.home}),b=Vo(c.runningTasks,h,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});b&&(this.log(`[${e.agentId}] ${b.slice(0,160)}`),e.message=`${b}
160
160
  ${e.message}`),c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let y={...h.length?{homes:h}:{},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}}:{}};c.runningTasks.push(y),e.runningTaskId=y.id;let x=hn(this.config.people,e.context);if(e.context&&(x?e.context.person=x.id:delete e.context.person),this.runningContexts.set(y.id,e.context??{}),e.onStart)try{e.onStart(y.id)}catch{}let $=new AbortController;this.taskAborts.set(y.id,{agentId:e.agentId,channel:y.channel,chatId:typeof y.chatId=="string"?y.chatId:"",originalMessage:e.message||"",controller:$,sender:e.context?.sender,rootId:$t()?.rootId,workflowRunId:e.workflowRunId??(typeof y.chatId=="string"&&y.chatId.startsWith("workflow:")&&y.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let R={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(y.id,R);let E=g=>{if(g){R.buffer+=g,R.buffer.length>_a&&(R.buffer=R.buffer.slice(R.buffer.length-_a));for(let f of R.subscribers)try{f(g)}catch{}}},k=Ee();e.taskId=k,y.traceId=k;let L=this.taskAborts.get(y.id);L&&(L.traceId=k);let N=new Map,O=(g,f,C)=>{try{ee().emit("task:step",{taskId:k,agentId:e.agentId,name:"pipeline",action:g,status:C,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},B=0,F=!1,q=()=>{F||(F=!0,B&&O("first-event",B,"ok"))},z;if(t){let g=Tg();z=f=>{q();let C=g(f);if(C&&E(C),Da(k,e.agentId,f),Oa(N,f),Hn(f,void 0,e.model||c.def.model),r)try{r(f)}catch{}}}else z=g=>{if(q(),Da(k,e.agentId,g),Oa(N,g),Hn(g,void 0,e.model||c.def.model),r)try{r(g)}catch{}};let A=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,T=A?setTimeout(()=>$.abort(new Error(`timed out after ${Math.round(A/1e3)}s`)),A):void 0;T?.unref?.();let S=(c.def.preSpawnTimeoutSec??mg)*1e3,U=setTimeout(()=>{$.abort(new Error(`timed out before spawn after ${Math.round(S/1e3)}s in step "${y.step??"start"}"`))},S);U.unref?.();let j=()=>{U&&clearTimeout(U),U=void 0},P=()=>`task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`,Q;$.signal.addEventListener("abort",()=>{let g=_e($.signal).message;/^timed out/.test(g)&&(Q=y.step??"start"),this.log(`[${e.agentId}] task ${y.id} aborted in step "${y.step??"start"}" \u2014 ${g} ${P()}`)},{once:!0});let ne=g=>{y.step=g,this.log(`[${e.agentId}] step ${g} ${P()}`)},X=(g,f,C=0)=>{if($.signal.aborted)return Promise.reject(_e($.signal));ne(g),(g==="agent"||g==="workflow-auto-run")&&(j(),B=Date.now());let v=Date.now(),W=da(f(),ug[g]??0,g);return ca(W,$.signal,C).then(G=>(O(g,v,"ok"),G),G=>{throw O(g,v,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${P()}`),G})},_=async(g,f,C,v=0)=>{try{return await X(g,f,v)}catch(W){if(W instanceof Be)return C();throw W}},se=!1,ie=!1,ns=g=>{if(!(!se||ie)){ie=!0;try{ee().emit("task:completed",{taskId:k,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-y.startedAt.getTime(),error:g?.error||($.signal.aborted?_e($.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(y.id)?!0:void 0,stopped:!this.interruptedRuns.has(y.id)&&(this.stoppedRuns.has(y.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ss=!1,rs=g=>{if(ss)return;ss=!0,ns(g),this.runReleases.delete(y.id),T&&clearTimeout(T),j(),c.activeTasks--;let f=c.runningTasks.findIndex(v=>v.id===y.id);f!==-1&&c.runningTasks.splice(f,1),this.runningContexts.delete(y.id),this.taskAborts.delete(y.id);let C=this.runEndWaiters.get(y.id);this.runEndWaiters.delete(y.id);for(let v of C??[])try{v()}catch{}R.done=!0,R.endedAt=new Date;for(let v of R.subscribers)try{v(`
161
161
  [task finished]
162
- `)}catch{}R.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(y.id),pg).unref?.();try{let v=R.endedAt,W={id:y.id,agentId:e.agentId,channel:y.channel,chatId:y.chatId,sender:y.sender,message:e.message||"",startedAt:y.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-y.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(y.id)||g?.errorKind==="stopped"?{status:"stopped"}:Q?{status:"timeout",step:Q}:{},responseText:g?.content||"",transcript:R.buffer};this.persistTaskRecord(W);let G=(W.responseText||W.error||"").trim();if(G){let Z=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Z,at:v,ok:W.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(v=>{if(v.length===0)return;this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`);let W=Date.now();ee().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,count:v.length,at:new Date().toISOString()});let G=()=>ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,at:new Date().toISOString()});for(let Z of v){let $e=Z.originalContext||{channel:Z.channel,sender:Z.sender,chatId:Z.chatId};this.execute({message:Z.text,agentId:e.agentId,context:$e,queuedAt:Z.queuedAt??Z.timestamp}).then(me=>(Xe(me.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,me)),me=>{throw G(),me}).catch(me=>{this.log(`[${e.agentId}] queued message failed: ${me.message}`)})}}).catch(v=>{ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(y.id,rs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${P()}`);let w=e.context?.channel||"api",{evaluateRequest:Ua,selectRequestContext:Fa}=await import("./request-planner-EUIMJ7R3.js"),os=_("request-gate",()=>Ua(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),nn=!1;os.then(()=>{nn=!0},()=>{nn=!0});let I=l,sn=e.context?.sender||"User",de=c.def.tier==="codex-cli",qe=Ei(this.config.session,w,c.def.tier),ut=Oi(this.config.session),ue=e.isolated===!0,Ge=!ue&&qe==="lean"&&ut.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let lt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await _("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let Ha=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;ia({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:Ha,taskId:k}),this.sessions.addUserMessage(e.agentId,w,I,sn,e.message);let is=Date.now(),as={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(is).toISOString(),taskId:k,resumeOrigin:zo(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:mn(e.context),...x?{person:x}:{},humanRoot:Je(e.context),pickup:Hs(e.context),operator:js(e.context),dueAt:aa(e.context),taskType:Yt(e.context)};ee().emit("task:started",as),se=!0;let te,rn,cs=this.classifier;if(cs&&w!=="a2a"&&!de){ne("classify");let g=Date.now();rn=cs.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{te=f||void 0,te?.path?.length&&(y.intentPath=te.path.slice()),O("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),O("classify",g,"error")})}let ds=async g=>{if(!rn)return;let f;await Promise.race([rn,new Promise(C=>{f=setTimeout(C,g),f.unref?.()})]),f&&clearTimeout(f)};await ds(rg);let Te=this.config.workflows?.matching,fe,us,ls=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&ls?.enabled&&(ls.agents[e.agentId]??!0)&&!i&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&(us=Cr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?fe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Mr(this.config.workflows,e.agentId)&&Rr(e)?this.workflowRuns:void 0;if(ke&&!fe&&!i&&this.workflowAutoRunner&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list()),C=Te?.autoRunThreshold??.85;f&&f.confidence>=C&&(fe={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(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?dg():void 0,ja=ae?Pr(ae):void 0,Ba=this.wikiHub.getAgentWiki(e.agentId),gs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),ps=this.memoryStore.buildContext(gs),fs=this.memoryStore.contextFacts(gs),Wa=this.patternStore.findRelevant(e.message,e.agentId,5),qa=this.patternStore.buildContext(Wa),ms="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),C=await X("skills",()=>g(c.def.workspace)),v=e.personLimits?.skills??[],W=v.length?C.filter(G=>!v.some(Z=>ze(Z,G.frontmatter.name))):C;ms=f(W,e.message)}catch{}let H=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,I,lt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=Vr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:lt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${In(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"cost");let C=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:C,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${In(f)}`)}}if(H&&c.def.tier==="claude-code"){let g=H;await _("rotate",()=>this.maybeRotateForContinuity(e,c,w,I,g),()=>!1)&&(H=void 0)}try{let g=await X("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",C=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${f}%, ${C} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let v=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${v.overallScore} (lexicon=${v.lexiconDecay}, tools=${v.toolShift}, semantic=${v.semanticDrift})`),v.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${v.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Ga=process.env.AGENTX_CONTEXT_SURGERY==="1",Ka=de?{maxMessages:8,maxChars:2400}:Ga&&Pa(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ja=!H&&!de?xg(Ba,e.agentId,{notesInbox:bg(this.config)}):void 0,gt=!H&&!Ge?this.sessions.buildHistoryContext(e.agentId,w,I,Ka):void 0,za=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,hs,ys=[];if(this.config.procedures?.injection?.enabled&&!H&&!de)try{let g=new it({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=qn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){hs=Gn(f),ys=f.map(C=>({id:C.procedure.meta.id,title:C.procedure.meta.title}));for(let C of f)this.log(`[${e.agentId}] procedure match ${C.procedure.meta.id} score=${C.score.toFixed(2)} (${C.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,I).messages,C=f[0],v=f[f.length-1],W=gt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${gt.length}c/${gt.split(`
162
+ `)}catch{}R.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(y.id),pg).unref?.();try{let v=R.endedAt,W={id:y.id,agentId:e.agentId,channel:y.channel,chatId:y.chatId,sender:y.sender,message:e.message||"",startedAt:y.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-y.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(y.id)||g?.errorKind==="stopped"?{status:"stopped"}:Q?{status:"timeout",step:Q}:{},responseText:g?.content||"",transcript:R.buffer};this.persistTaskRecord(W);let G=(W.responseText||W.error||"").trim();if(G){let Z=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Z,at:v,ok:W.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(v=>{if(v.length===0)return;this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`);let W=Date.now();ee().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,count:v.length,at:new Date().toISOString()});let G=()=>ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,at:new Date().toISOString()});for(let Z of v){let $e=Z.originalContext||{channel:Z.channel,sender:Z.sender,chatId:Z.chatId};this.execute({message:Z.text,agentId:e.agentId,context:$e,queuedAt:Z.queuedAt??Z.timestamp}).then(me=>(Xe(me.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,me)),me=>{throw G(),me}).catch(me=>{this.log(`[${e.agentId}] queued message failed: ${me.message}`)})}}).catch(v=>{ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(y.id,rs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${P()}`);let w=e.context?.channel||"api",{evaluateRequest:Ua,selectRequestContext:Fa}=await import("./request-planner-ZIG4YVXC.js"),os=_("request-gate",()=>Ua(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),nn=!1;os.then(()=>{nn=!0},()=>{nn=!0});let I=l,sn=e.context?.sender||"User",de=c.def.tier==="codex-cli",qe=Ei(this.config.session,w,c.def.tier),ut=Oi(this.config.session),ue=e.isolated===!0,Ge=!ue&&qe==="lean"&&ut.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let lt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await _("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let Ha=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;ia({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:Ha,taskId:k}),this.sessions.addUserMessage(e.agentId,w,I,sn,e.message);let is=Date.now(),as={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(is).toISOString(),taskId:k,resumeOrigin:zo(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:mn(e.context),...x?{person:x}:{},humanRoot:Je(e.context),pickup:Hs(e.context),operator:js(e.context),dueAt:aa(e.context),taskType:Yt(e.context)};ee().emit("task:started",as),se=!0;let te,rn,cs=this.classifier;if(cs&&w!=="a2a"&&!de){ne("classify");let g=Date.now();rn=cs.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{te=f||void 0,te?.path?.length&&(y.intentPath=te.path.slice()),O("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),O("classify",g,"error")})}let ds=async g=>{if(!rn)return;let f;await Promise.race([rn,new Promise(C=>{f=setTimeout(C,g),f.unref?.()})]),f&&clearTimeout(f)};await ds(rg);let Te=this.config.workflows?.matching,fe,us,ls=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&ls?.enabled&&(ls.agents[e.agentId]??!0)&&!i&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&(us=Cr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?fe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Mr(this.config.workflows,e.agentId)&&Rr(e)?this.workflowRuns:void 0;if(ke&&!fe&&!i&&this.workflowAutoRunner&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list()),C=Te?.autoRunThreshold??.85;f&&f.confidence>=C&&(fe={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(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?dg():void 0,ja=ae?Pr(ae):void 0,Ba=this.wikiHub.getAgentWiki(e.agentId),gs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),ps=this.memoryStore.buildContext(gs),fs=this.memoryStore.contextFacts(gs),Wa=this.patternStore.findRelevant(e.message,e.agentId,5),qa=this.patternStore.buildContext(Wa),ms="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),C=await X("skills",()=>g(c.def.workspace)),v=e.personLimits?.skills??[],W=v.length?C.filter(G=>!v.some(Z=>ze(Z,G.frontmatter.name))):C;ms=f(W,e.message)}catch{}let H=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,I,lt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=Vr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:lt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${In(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"cost");let C=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:C,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${In(f)}`)}}if(H&&c.def.tier==="claude-code"){let g=H;await _("rotate",()=>this.maybeRotateForContinuity(e,c,w,I,g),()=>!1)&&(H=void 0)}try{let g=await X("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",C=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${f}%, ${C} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let v=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${v.overallScore} (lexicon=${v.lexiconDecay}, tools=${v.toolShift}, semantic=${v.semanticDrift})`),v.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${v.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Ga=process.env.AGENTX_CONTEXT_SURGERY==="1",Ka=de?{maxMessages:8,maxChars:2400}:Ga&&Pa(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ja=!H&&!de?xg(Ba,e.agentId,{notesInbox:bg(this.config)}):void 0,gt=!H&&!Ge?this.sessions.buildHistoryContext(e.agentId,w,I,Ka):void 0,za=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,hs,ys=[];if(this.config.procedures?.injection?.enabled&&!H&&!de)try{let g=new it({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=qn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){hs=Gn(f),ys=f.map(C=>({id:C.procedure.meta.id,title:C.procedure.meta.title}));for(let C of f)this.log(`[${e.agentId}] procedure match ${C.procedure.meta.id} score=${C.score.toFixed(2)} (${C.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,I).messages,C=f[0],v=f[f.length-1],W=gt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${gt.length}c/${gt.split(`
163
163
  `).length}L`,G=`[${e.agentId}] ${w}:${I} ${W} | session.messages=${f.length}`+(f.length>0?` first=${C.timestamp.slice(11,19)}(${C.role}:${(C.content||"").slice(0,40).replace(/\n/g," ")}) last=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ae.cat("context",G)}catch(g){Ae.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let ws;if(c.def.contextReferences&&!H)try{let g=c.def.workspace,f=this.referencesCache.get(g);if(!f){let[v,W]=await X("references",()=>Promise.all([wn(c.def.workspace),bn(c.def.workspace)]));if(v.byId.size===0&&W.recipes.length===0){let[G,Z]=await X("references",()=>Promise.all([wn(process.cwd()),bn(process.cwd())]));f={refs:G,recipes:Z}}else f={refs:v,recipes:W};this.referencesCache.set(g,f)}let C=br({agentId:e.agentId,intentTags:te?.path,message:e.message},f.recipes,f.refs);C.cards.length>0&&(ws=yr(C.cards,500*4)),C.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${C.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let bs=ue||Ge?"":this.sessions.getCrossSessionSummary(e.agentId,w,I,e.message),xs,pt=ue?null:Ho(e.message);if(pt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:I,lookbackDays:pt.lookbackDays,limit:12});if(g.turns.length>0){let f=[`[Long-memory recall \u2014 last ${pt.lookbackDays}d on this chat (cue-triggered)]`],C=[...g.turns].sort((v,W)=>v.ts.localeCompare(W.ts));for(let v of C){let W=v.ts.slice(11,16)+" "+v.day,G=v.role==="user"?v.senderName||"User":v.senderName||"Agent";f.push(`${W} ${G}: ${v.content}`)}g.hasMore&&f.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),xs=f.join(`
164
164
  `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${pt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Qa=de?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",Ss,Is,Ts=!1;nn||ne("request-gate");let ve=await os;if(ve.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Qa==="planner"&&!ue&&!ve.active&&!Ge&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-DJB6CKY6.js"),f=await X("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Ts=!0,Ss=f.sessionHistory,ps=f.memoryContext,fs=f.memoryFacts,bs=f.crossChatContext,Is=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(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Ts&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,I),H=void 0)}let on=`${e.agentId}:${w}:${I}`,ft=nr(e.message);ft&&(ft==="default"?(this.activeSouls.delete(on),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(on,ft),this.log(`[${e.agentId}] Soul switched to: ${ft}`)));let Xa=this.activeSouls.get(on),Ya=er(c.def.workspace,Xa),Za=tr(Ya),Va=ue?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),ec=gg(c.def.tier),tc=kg(c.def.richMessages,w),nc=c.def.tier==="claude-code"&&(ue||qe!=="lean"||Di(ut)),ks="";if(c.def.workspace&&!nc){let g=K(c.def.workspace,"CLAUDE.md");if(ce(g))try{let f=ct(g,"utf-8");ks=`[Project CLAUDE.md]
165
165
  ${f.length>4e3?f.slice(0,4e3)+`
@@ -173,9 +173,9 @@ ${$e}`),f+=$e.length}catch{}}}let sc=an.length>0?an.join(`
173
173
 
174
174
  `)||void 0,ht={channel:w,chatId:I,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:c.def.systemPrompt,sender:sn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:de||Ge||Pa(w,c.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:de?void 0:qa||void 0,procedureContext:[hs,us].filter(Boolean).join(`
175
175
 
176
- `)||void 0,workflowRunContext:ja,references:ws,skillInjection:ms||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ss??gt,memoryContext:ps||void 0,crossChatContext:bs||void 0,longMemoryRecall:xs||void 0,contextOnDemand:Ge&&!H?ji(w,I):void 0,wikiContext:Ja,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(as)}catch{return}})(),rotationMemo:za,eventDigest:H?void 0:wg(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Hr(w,!H,c.def.richMessages);return g?Sg(c.def.workspace,g):void 0})(),intent:te?{path:te.path,pathLabel:te.pathLabel,pathId:te.pathId,axes:te.axes,leaf:te.leaf,status:te.status}:void 0,message:e.message};ue&&Object.assign(ht,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let yt=e.model?void 0:Xs({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?lt:null});yt?.downgraded&&this.log(`[${e.agentId}] ${yt.reason}`);let vs=Qs(c.def.tier,this.config.decisions.routing),$s=yt?.downgraded?Promise.resolve(yt.model):!e.model&&vs&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-FQNGOTMV.js"),f=await X("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?lt:null,cheapModel:vs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),As=!1;$s.then(()=>{As=!0});let wt=ve.active&&ve.preprocess?await _("select-context",()=>Fa(ht),()=>({input:ht,excluded:[]})):{input:ht,excluded:[]};wt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${wt.excluded.join(", ")}`);let bt=Jo(wt.input,de?{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),rc=gr(bt,{memory:fs,procedures:ys,wikiContext:wt.input.wikiContext}),dn=(bt?.length??0)+(cn?.length??0)+(e.message?.length??0),xt={history:bt?.length??0,sysPrompt:cn?.length??0,message:e.message?.length??0},Cs=vi(e.agentId,w,I);$i(Cs,dn,xt);let Ms=Ai(Cs);Ms&&this.log(`[${e.agentId}] ${Ms}`),dn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${dn} bytes (history=${xt.history}, sysPrompt=${xt.sysPrompt}, message=${xt.message})`),As||ne("route-model");let Rs=await $s,Ps=c.def.tier!=="claude-code"?void 0:ue?Ui():qe==="lean"?Li(c.def.workspace,ut,void 0,w):Hi(c.def.workspace);qe==="lean"&&!ue&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${Bi(qe,ut,w)}`);let _s=c.def.tier==="claude-code"&&!H?Yr({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:c.def.systemPrompt??null,taskId:k},g=>this.log(g)):void 0,oc={...e,systemPromptAppend:cn,...Ps?{claudeArgs:Ps}:{},...Rs?{model:Rs}:{}},re,Es=sa({agent:e.agentId,request:e.message,taskId:k,budgetMinutes:c.def.maxExecutionMinutes??20}),ic=z,Os=!1,un=!0;z=g=>{if(Es.observe(g),ae&&un)for(let f of Er(g))_r(f.name,f.input)||(un=!1);ic?.(g)};try{let g=this.workflowAutoRunner;if(fe&&g){let D=fe;try{let J=await X("workflow-auto-run",()=>g({workflowId:D.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...D.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:te?.path,matchedWorkflowId:D.workflowId,matchConfidence:D.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${fe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:D.follow?`Started the workflow "${J.title??D.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:fe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:fe.confidence}},re}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&ke)try{let D=Dr(ke,e.resumedFrom);Or(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:k,...D?{continues:D}:{}}),Os=!0,y.workflow={runId:ae,workflowId:Ar}}catch(D){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${D?.message||D}`)}let f=()=>{if(c.def.tier!=="claude-code")return null;ne("dispatch-gate");let D=c.def.persistentProcess?Et():null,J=D!=null&&D.hasLive({agentId:e.agentId,channel:w,chatId:I}),ye=!!H||J,le=[ui(ye),Ti(ye,void 0,e.model||c.def.model)].find(Tt=>Tt&&Tt.abort);if(le){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${le.reason}`);let Tt={content:"",error:le.message,duration:0};if(!t){R.buffer=`[error] ${le.message}`;for(let ac of R.subscribers)try{ac(R.buffer)}catch{}}return Tt}mi();let Ke=ki();return Ke&&this.log(`[${e.agentId}] ${Ke}`),null},C=this.planCloudSession(c.def,e);if(C.route==="local"){let D=f();if(D)return c.errors++,re=D,D}let v=c.def.tier==="claude-code",W=v?t:(D,J)=>{D&&E(D),t&&t(D,J)},G=!1,Z=v?s:D=>{D&&(G?E(D):(E(`\u{1F4AD} ${D}`),G=!0)),s&&s(D)},$e=()=>{G&&(E(`
176
+ `)||void 0,workflowRunContext:ja,references:ws,skillInjection:ms||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ss??gt,memoryContext:ps||void 0,crossChatContext:bs||void 0,longMemoryRecall:xs||void 0,contextOnDemand:Ge&&!H?ji(w,I):void 0,wikiContext:Ja,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(as)}catch{return}})(),rotationMemo:za,eventDigest:H?void 0:wg(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Hr(w,!H,c.def.richMessages);return g?Sg(c.def.workspace,g):void 0})(),intent:te?{path:te.path,pathLabel:te.pathLabel,pathId:te.pathId,axes:te.axes,leaf:te.leaf,status:te.status}:void 0,message:e.message};ue&&Object.assign(ht,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let yt=e.model?void 0:Xs({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?lt:null});yt?.downgraded&&this.log(`[${e.agentId}] ${yt.reason}`);let vs=Qs(c.def.tier,this.config.decisions.routing),$s=yt?.downgraded?Promise.resolve(yt.model):!e.model&&vs&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-BLOYDLU4.js"),f=await X("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?lt:null,cheapModel:vs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),As=!1;$s.then(()=>{As=!0});let wt=ve.active&&ve.preprocess?await _("select-context",()=>Fa(ht),()=>({input:ht,excluded:[]})):{input:ht,excluded:[]};wt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${wt.excluded.join(", ")}`);let bt=Jo(wt.input,de?{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),rc=gr(bt,{memory:fs,procedures:ys,wikiContext:wt.input.wikiContext}),dn=(bt?.length??0)+(cn?.length??0)+(e.message?.length??0),xt={history:bt?.length??0,sysPrompt:cn?.length??0,message:e.message?.length??0},Cs=vi(e.agentId,w,I);$i(Cs,dn,xt);let Ms=Ai(Cs);Ms&&this.log(`[${e.agentId}] ${Ms}`),dn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${dn} bytes (history=${xt.history}, sysPrompt=${xt.sysPrompt}, message=${xt.message})`),As||ne("route-model");let Rs=await $s,Ps=c.def.tier!=="claude-code"?void 0:ue?Ui():qe==="lean"?Li(c.def.workspace,ut,void 0,w):Hi(c.def.workspace);qe==="lean"&&!ue&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${Bi(qe,ut,w)}`);let _s=c.def.tier==="claude-code"&&!H?Yr({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:c.def.systemPrompt??null,taskId:k},g=>this.log(g)):void 0,oc={...e,systemPromptAppend:cn,...Ps?{claudeArgs:Ps}:{},...Rs?{model:Rs}:{}},re,Es=sa({agent:e.agentId,request:e.message,taskId:k,budgetMinutes:c.def.maxExecutionMinutes??20}),ic=z,Os=!1,un=!0;z=g=>{if(Es.observe(g),ae&&un)for(let f of Er(g))_r(f.name,f.input)||(un=!1);ic?.(g)};try{let g=this.workflowAutoRunner;if(fe&&g){let D=fe;try{let J=await X("workflow-auto-run",()=>g({workflowId:D.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...D.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:te?.path,matchedWorkflowId:D.workflowId,matchConfidence:D.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${fe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:D.follow?`Started the workflow "${J.title??D.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:fe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:fe.confidence}},re}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&ke)try{let D=Dr(ke,e.resumedFrom);Or(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:k,...D?{continues:D}:{}}),Os=!0,y.workflow={runId:ae,workflowId:Ar}}catch(D){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${D?.message||D}`)}let f=()=>{if(c.def.tier!=="claude-code")return null;ne("dispatch-gate");let D=c.def.persistentProcess?Et():null,J=D!=null&&D.hasLive({agentId:e.agentId,channel:w,chatId:I}),ye=!!H||J,le=[ui(ye),Ti(ye,void 0,e.model||c.def.model)].find(Tt=>Tt&&Tt.abort);if(le){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${le.reason}`);let Tt={content:"",error:le.message,duration:0};if(!t){R.buffer=`[error] ${le.message}`;for(let ac of R.subscribers)try{ac(R.buffer)}catch{}}return Tt}mi();let Ke=ki();return Ke&&this.log(`[${e.agentId}] ${Ke}`),null},C=this.planCloudSession(c.def,e);if(C.route==="local"){let D=f();if(D)return c.errors++,re=D,D}let v=c.def.tier==="claude-code",W=v?t:(D,J)=>{D&&E(D),t&&t(D,J)},G=!1,Z=v?s:D=>{D&&(G?E(D):(E(`\u{1F4AD} ${D}`),G=!0)),s&&s(D)},$e=()=>{G&&(E(`
177
177
  `),G=!1)},me=v?W:W?(D,J)=>{$e(),W(D,J)}:void 0,M=await X("agent",async()=>{if(C.route!=="local"){let D=await this.runCloudSession(c.def,e,C,k);if(D)return D;let J=f();if(J)return J}return Lo(c.def,oc,this.providers,me,bt,H,z,$.signal,Z)},fg);if(!M.error){let D=Ig(c.def.toolUseRequired,N);if(D){let J=Array.from(N.entries()).map(([ye,It])=>`${ye}=${It}`).join(", ")||"none";M.error=`tool_required_not_called: ${D} (invoked: ${J})`,M.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${D}, observed ${J}`)}}_s&&Zr(_s,{toolUses:N,eventsSeen:F,error:M.error,agentId:e.agentId},D=>this.log(D));let St=this.interruptedRuns.get(y.id);St&&(M.content="",M.error=St,M.errorKind="interrupted");let ln=St?void 0:this.stoppedRuns.get(y.id);ln&&(M.content="",M.error=ln,M.errorKind="stopped"),re=M;let he=M.usage?ur(M.usage):void 0;if(ie=!0,ee().emit("task:completed",{taskId:k,agentId:e.agentId,channel:w,chatId:I,durationMs:Date.now()-is,error:M.error||void 0,errorKind:M.error?M.errorKind:void 0,interrupted:St?!0:void 0,stopped:ln?!0:void 0,inputTokens:he?.inputTokens,outputTokens:he?.outputTokens,cacheReadTokens:he?.cacheReadTokens,cacheCreateTokens:he?.cacheCreateTokens,tier2InputTokens:he?.tier2InputTokens,tier2OutputTokens:he?.tier2OutputTokens,tier2CacheReadTokens:he?.tier2CacheReadTokens,tier2CacheCreateTokens:he?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:ve.arm,numTurns:M.numTurns,injectedContext:rc,finalResponse:M.content||void 0,billedModel:M.billedModel||e.model||c.def.model||void 0,at:new Date().toISOString()}),!t&&(M.content||M.error)){let D=M.error?`[error] ${M.error}`:M.content;R.buffer=D;for(let J of R.subscribers)try{J(D)}catch{}}if(M.error)c.errors++,this.log(`[${e.agentId}] error: ${M.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,I,M.content),oa({agent:e.agentId,channel:w,chatId:I,request:e.message,reply:M.content,taskId:k}),M.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,I,M.claudeSessionId),M.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,I,M.codexSessionId),M.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,I,M.opencodeSessionId),(M.claudeSessionId||M.codexSessionId||M.opencodeSessionId)&&M.usage&&this.sessions.recordTurnUsage(e.agentId,w,I,M.usage,M.contextTokens),M.usage){let le=M.contextTokens,Ke=(M.usage.inputTokens||0)+(M.usage.cacheReadTokens||0)+(M.usage.cacheCreateTokens||0);(le??Ke)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${I}: context=${le??"n/a"} tokens (cumulative turn total=${Ke}) \u2014 next turn will rotate`)}if(or({channel:w,content:`User: ${e.message}`,responseLength:M.content.length}).capture){await ds(og);try{let le=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:le,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
178
178
 
179
179
  Agent: ${M.content}`,meta:yg(te,e.context)})}catch{}ir(e.agentId,e.message,M.content,{channel:w,chatId:I,sender:sn},this.memoryStore).catch(()=>{}),ri(e.agentId,e.message,M.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=M.billedModel||e.model||c.def.model,ye=e.context?.channel,It=ye&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ye}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,M.duration||0,M.usage,e.message.length,M.content.length,!1,J,ye,It),this.log(`[${e.agentId}] completed in ${M.duration}ms`+(M.tokensUsed?` (${M.tokensUsed} tokens)`:"")+` ${P()}`)}return M}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let f=Rt(g.message);return re={content:"",error:Pt(f),errorKind:f.kind},re}finally{if(Es.stop(),Os&&ae&&ke)try{let g=re?.usage,f=Nr(ke,ae,{error:re?re.error||void 0:$.signal.aborted?_e($.signal).message:"run ended before completion",canceled:Lr(re?.errorKind)||this.stoppedRuns.has(y.id)||this.interruptedRuns.has(y.id)||!re&&$.signal.aborted,durationMs:Date.now()-y.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:un,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(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${g?.message||g}`)}ns(re),rs(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:Ur(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),We,this.safe(e.agentId),t);ce(s)||ig(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);cg(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=K(process.cwd(),We,this.safe(e));if(!ce(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let d=new Date(s).toISOString().slice(0,10),c=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[c,d]){let p=K(a,l);if(ce(p))try{for(let m of pe(p)){if(!m.endsWith(".json"))continue;let h=m.split("-")[0],b=parseInt(h,10);if(!Number.isFinite(b)||b<i||b>s)continue;let y=Math.floor((s-b)/36e5),x=t-1-y;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),We);if(!ce(e))return 0;let t=0;for(let s of pe(e)){let r=K(e,s),o;try{o=pe(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),d;try{d=pe(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let u=JSON.parse(ct(K(a,c),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=hg){let t=K(process.cwd(),We);if(!ce(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of pe(t)){let i=K(t,o),a;try{a=pe(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=s))try{ag(K(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),We,this.safe(e));if(!ce(s))return[];let r=pe(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=K(s,i),d;try{d=pe(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let u=JSON.parse(ct(K(a,c),"utf-8")),{transcript:l,responseText:p,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),We,this.safe(e));if(!ce(s))return null;let r=this.safe(t),o=pe(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(ce(a))try{return JSON.parse(ct(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=$r();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||Xe(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(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}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}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??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 d=Ht(a);return d.channel===t.channel&&d.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:d,originalMessage:c}=o,u=o.controller.signal.aborted,l=!1;u&&c&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,d,c));let p=Date.now();this.messageQueue.enqueue(i,a,d,{text:t,sender:s,timestamp:p,channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:s}});let m=this.messageQueue.pendingCount(i,a,d);ee().emit("task:queued",{agentId:i,channel:a,chatId:d,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:Bs(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:h,edited:l,pending:m}}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,d=i.chatId;return new Promise(c=>{let u=!1,l=p=>{u||(u=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Xe(p.error)?l({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}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 kg(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(`
180
180
  `)}export{ro as a,Fg as b,io as c,vc as d,ao as e,Ot as f,Zg as g,np as h,sp as i,cp as j,Ht as k,Kc as l,Oo as m,Yc as n,Zc as o,Vc as p,Lo as q,Bt as r,Wt as s,Sd as t,Np as u,Lp as v,Gt as w,Hp as x,Ln as y,ee as z,oi as A,Dd as B,Fd as C,ci as D,nf as E,di as F,pi as G,bi as H,yf as I,xi as J,Jt as K,If as L,Tf as M,it as N,qu as O,Gu as P,Ku as Q,Ju as R,zu as S,qn as T,Yt as U,Vf as V,fa as W,at as X,ma as Y,im as Z,am as _,cm as $,dm as aa,um as ba,lm as ca,gm as da,vl as ea,lg as fa,gg as ga,Ph as ha,_h as ia,yg as ja,wg as ka,xg as la,ts as ma,Ea as na,Oa as oa,Ig as pa,Da as qa,Na as ra,kg as sa};
181
- //# sourceMappingURL=chunk-5DPN2HIR.js.map
181
+ //# sourceMappingURL=chunk-MLC5INGD.js.map