agentix-cli 0.129.0 → 0.130.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/{App-G37JNRBW.js → App-DWSHIDN6.js} +2 -2
  2. package/dist/{ChatApp-NCKC7C3L.js → ChatApp-CROSI7JM.js} +2 -2
  3. package/dist/{absorb-eval-ZCWHWKAD.js → absorb-eval-MNGQ752C.js} +2 -2
  4. package/dist/{agent-LJ4SUQCC.js → agent-4AQOFPRD.js} +2 -2
  5. package/dist/{board-dashboard-LZJT4YWV.js → board-dashboard-54A3XTV5.js} +10 -6
  6. package/dist/board-dashboard-54A3XTV5.js.map +1 -0
  7. package/dist/{chunk-VJRITDSQ.js → chunk-242MPMJX.js} +2 -2
  8. package/dist/{chunk-Z5CBUZIW.js → chunk-5KKXJZZ4.js} +2 -2
  9. package/dist/{chunk-AMW2R676.js → chunk-5VKFIBXY.js} +3 -3
  10. package/dist/{chunk-AMW2R676.js.map → chunk-5VKFIBXY.js.map} +1 -1
  11. package/dist/{chunk-ZF5U5KPB.js → chunk-AERIU4AH.js} +2 -2
  12. package/dist/{chunk-AOFTTIZZ.js → chunk-HF4OXA5L.js} +2 -2
  13. package/dist/{chunk-R6UCPHUD.js → chunk-I4GT27UO.js} +2 -2
  14. package/dist/{chunk-M7IJVOJA.js → chunk-I4OQQRY2.js} +3 -3
  15. package/dist/{chunk-BWSB7NOX.js → chunk-J4I5ZJ2V.js} +2 -2
  16. package/dist/chunk-JE5EJGGD.js +4 -0
  17. package/dist/chunk-JE5EJGGD.js.map +1 -0
  18. package/dist/chunk-KBJNJGBP.js +2 -0
  19. package/dist/chunk-KBJNJGBP.js.map +1 -0
  20. package/dist/{chunk-I3RAUJCD.js → chunk-LJWEJ6UZ.js} +23 -14
  21. package/dist/{chunk-I3RAUJCD.js.map → chunk-LJWEJ6UZ.js.map} +1 -1
  22. package/dist/{chunk-X5JTG52Q.js → chunk-LLLBH2HH.js} +2 -2
  23. package/dist/{chunk-ARSVKSC4.js → chunk-MZJY26FW.js} +2 -2
  24. package/dist/{chunk-XIA2ACKX.js → chunk-N2YSVZML.js} +2 -2
  25. package/dist/{chunk-BCUR2TJ7.js → chunk-NR7WLMNI.js} +2 -2
  26. package/dist/{chunk-DVR6PFCJ.js → chunk-Q5FEWCS5.js} +2 -2
  27. package/dist/{chunk-XOQNDWVW.js → chunk-QPYN2UTV.js} +2 -2
  28. package/dist/{chunk-4FMZTM3W.js → chunk-QXZLYCEZ.js} +2 -2
  29. package/dist/{chunk-SCC7HBFZ.js → chunk-RKB7FQJF.js} +2 -2
  30. package/dist/{chunk-4O4GZBKZ.js → chunk-TJDNS5G6.js} +2 -2
  31. package/dist/{chunk-PVUNDNT3.js → chunk-TN5A7PLU.js} +2 -2
  32. package/dist/{chunk-4ZFLYY5P.js → chunk-U2EHJZAZ.js} +2 -2
  33. package/dist/{chunk-YHD4PHFX.js → chunk-UBA2QJCY.js} +6 -6
  34. package/dist/chunk-UBA2QJCY.js.map +1 -0
  35. package/dist/{chunk-EOLEKSN6.js → chunk-UUFJQMHE.js} +2 -2
  36. package/dist/chunk-UUFJQMHE.js.map +1 -0
  37. package/dist/{chunk-CDLJOGVZ.js → chunk-W2HEJKJR.js} +5 -5
  38. package/dist/{chunk-XZN7QBRH.js → chunk-WX67I2KN.js} +2 -2
  39. package/dist/{chunk-CPMQZ6Z7.js → chunk-YHCPBMRH.js} +2 -2
  40. package/dist/cli.js +1 -1
  41. package/dist/{client-A5OK3IFO.js → client-KGWYROLX.js} +2 -2
  42. package/dist/{config-DQ5SILHX.js → config-FNTLKUGA.js} +2 -2
  43. package/dist/{config-mutate-62FCJ3S6.js → config-mutate-7BLOYRZF.js} +2 -2
  44. package/dist/config-mutator-NCLHYPJ3.js +2 -0
  45. package/dist/{contributions-L2YS4AH2.js → contributions-DLUQEAGL.js} +2 -2
  46. package/dist/{doctor-7TPSMMFA.js → doctor-32YP26SJ.js} +2 -2
  47. package/dist/{follow-up-tool-FKWIRFPW.js → follow-up-tool-AQ7NYZZR.js} +2 -2
  48. package/dist/{hub-EU5ECAJB.js → hub-Q3I4ALQ2.js} +2 -2
  49. package/dist/index.d.ts +12 -0
  50. package/dist/index.js +1 -1
  51. package/dist/{notes-2VC47RCK.js → notes-TMAGEDUS.js} +2 -2
  52. package/dist/notes-settings-WMOH2V75.js +2 -0
  53. package/dist/{program-UTSXNAHM.js → program-FESSM5TY.js} +252 -229
  54. package/dist/program-FESSM5TY.js.map +1 -0
  55. package/dist/{promote-XBDWCHLU.js → promote-R7FKN5SY.js} +2 -2
  56. package/dist/{query-UI6GQEL7.js → query-YTKTNXCQ.js} +2 -2
  57. package/dist/{registry-JW6ETTBA.js → registry-7L4RUATA.js} +2 -2
  58. package/dist/{request-planner-SEXYQN7D.js → request-planner-LEUMSI2K.js} +2 -2
  59. package/dist/{review-candidates-PIJWPPHQ.js → review-candidates-MOSGA4IS.js} +2 -2
  60. package/dist/{routing-2V3Y6ZR5.js → routing-FSJ42RZH.js} +2 -2
  61. package/dist/schedule-tool-4T2VZIDW.js +2 -0
  62. package/dist/{scheduler-SVZKDKJV.js → scheduler-6AQDHQI4.js} +2 -2
  63. package/dist/{seat-C6TMCJWI.js → seat-O37EQRHE.js} +2 -2
  64. package/dist/{select-DP64KWO4.js → select-XO2STSQN.js} +2 -2
  65. package/dist/{set-enabled-WCH6FU4N.js → set-enabled-ZNEPEFGF.js} +2 -2
  66. package/dist/{tool-TWQRBV4Y.js → tool-6KMEAY4U.js} +2 -2
  67. package/dist/{tool-WUK3ZOWG.js → tool-PH45YCO5.js} +2 -2
  68. package/dist/wiki-4HD4FZ4W.js +2 -0
  69. package/package.json +1 -1
  70. package/dist/board-dashboard-LZJT4YWV.js.map +0 -1
  71. package/dist/chunk-A347YHEW.js +0 -4
  72. package/dist/chunk-A347YHEW.js.map +0 -1
  73. package/dist/chunk-EOLEKSN6.js.map +0 -1
  74. package/dist/chunk-QUXMLLX5.js +0 -2
  75. package/dist/chunk-QUXMLLX5.js.map +0 -1
  76. package/dist/chunk-YHD4PHFX.js.map +0 -1
  77. package/dist/config-mutator-3ZL5YQSO.js +0 -2
  78. package/dist/notes-settings-X63D5HPM.js +0 -2
  79. package/dist/program-UTSXNAHM.js.map +0 -1
  80. package/dist/schedule-tool-KFZ27JTH.js +0 -2
  81. package/dist/wiki-4LAJ36XR.js +0 -2
  82. /package/dist/{App-G37JNRBW.js.map → App-DWSHIDN6.js.map} +0 -0
  83. /package/dist/{ChatApp-NCKC7C3L.js.map → ChatApp-CROSI7JM.js.map} +0 -0
  84. /package/dist/{absorb-eval-ZCWHWKAD.js.map → absorb-eval-MNGQ752C.js.map} +0 -0
  85. /package/dist/{agent-LJ4SUQCC.js.map → agent-4AQOFPRD.js.map} +0 -0
  86. /package/dist/{chunk-VJRITDSQ.js.map → chunk-242MPMJX.js.map} +0 -0
  87. /package/dist/{chunk-Z5CBUZIW.js.map → chunk-5KKXJZZ4.js.map} +0 -0
  88. /package/dist/{chunk-ZF5U5KPB.js.map → chunk-AERIU4AH.js.map} +0 -0
  89. /package/dist/{chunk-AOFTTIZZ.js.map → chunk-HF4OXA5L.js.map} +0 -0
  90. /package/dist/{chunk-R6UCPHUD.js.map → chunk-I4GT27UO.js.map} +0 -0
  91. /package/dist/{chunk-M7IJVOJA.js.map → chunk-I4OQQRY2.js.map} +0 -0
  92. /package/dist/{chunk-BWSB7NOX.js.map → chunk-J4I5ZJ2V.js.map} +0 -0
  93. /package/dist/{chunk-X5JTG52Q.js.map → chunk-LLLBH2HH.js.map} +0 -0
  94. /package/dist/{chunk-ARSVKSC4.js.map → chunk-MZJY26FW.js.map} +0 -0
  95. /package/dist/{chunk-XIA2ACKX.js.map → chunk-N2YSVZML.js.map} +0 -0
  96. /package/dist/{chunk-BCUR2TJ7.js.map → chunk-NR7WLMNI.js.map} +0 -0
  97. /package/dist/{chunk-DVR6PFCJ.js.map → chunk-Q5FEWCS5.js.map} +0 -0
  98. /package/dist/{chunk-XOQNDWVW.js.map → chunk-QPYN2UTV.js.map} +0 -0
  99. /package/dist/{chunk-4FMZTM3W.js.map → chunk-QXZLYCEZ.js.map} +0 -0
  100. /package/dist/{chunk-SCC7HBFZ.js.map → chunk-RKB7FQJF.js.map} +0 -0
  101. /package/dist/{chunk-4O4GZBKZ.js.map → chunk-TJDNS5G6.js.map} +0 -0
  102. /package/dist/{chunk-PVUNDNT3.js.map → chunk-TN5A7PLU.js.map} +0 -0
  103. /package/dist/{chunk-4ZFLYY5P.js.map → chunk-U2EHJZAZ.js.map} +0 -0
  104. /package/dist/{chunk-CDLJOGVZ.js.map → chunk-W2HEJKJR.js.map} +0 -0
  105. /package/dist/{chunk-XZN7QBRH.js.map → chunk-WX67I2KN.js.map} +0 -0
  106. /package/dist/{chunk-CPMQZ6Z7.js.map → chunk-YHCPBMRH.js.map} +0 -0
  107. /package/dist/{client-A5OK3IFO.js.map → client-KGWYROLX.js.map} +0 -0
  108. /package/dist/{config-DQ5SILHX.js.map → config-FNTLKUGA.js.map} +0 -0
  109. /package/dist/{config-mutate-62FCJ3S6.js.map → config-mutate-7BLOYRZF.js.map} +0 -0
  110. /package/dist/{config-mutator-3ZL5YQSO.js.map → config-mutator-NCLHYPJ3.js.map} +0 -0
  111. /package/dist/{contributions-L2YS4AH2.js.map → contributions-DLUQEAGL.js.map} +0 -0
  112. /package/dist/{doctor-7TPSMMFA.js.map → doctor-32YP26SJ.js.map} +0 -0
  113. /package/dist/{follow-up-tool-FKWIRFPW.js.map → follow-up-tool-AQ7NYZZR.js.map} +0 -0
  114. /package/dist/{hub-EU5ECAJB.js.map → hub-Q3I4ALQ2.js.map} +0 -0
  115. /package/dist/{notes-2VC47RCK.js.map → notes-TMAGEDUS.js.map} +0 -0
  116. /package/dist/{notes-settings-X63D5HPM.js.map → notes-settings-WMOH2V75.js.map} +0 -0
  117. /package/dist/{promote-XBDWCHLU.js.map → promote-R7FKN5SY.js.map} +0 -0
  118. /package/dist/{query-UI6GQEL7.js.map → query-YTKTNXCQ.js.map} +0 -0
  119. /package/dist/{registry-JW6ETTBA.js.map → registry-7L4RUATA.js.map} +0 -0
  120. /package/dist/{request-planner-SEXYQN7D.js.map → request-planner-LEUMSI2K.js.map} +0 -0
  121. /package/dist/{review-candidates-PIJWPPHQ.js.map → review-candidates-MOSGA4IS.js.map} +0 -0
  122. /package/dist/{routing-2V3Y6ZR5.js.map → routing-FSJ42RZH.js.map} +0 -0
  123. /package/dist/{schedule-tool-KFZ27JTH.js.map → schedule-tool-4T2VZIDW.js.map} +0 -0
  124. /package/dist/{scheduler-SVZKDKJV.js.map → scheduler-6AQDHQI4.js.map} +0 -0
  125. /package/dist/{seat-C6TMCJWI.js.map → seat-O37EQRHE.js.map} +0 -0
  126. /package/dist/{select-DP64KWO4.js.map → select-XO2STSQN.js.map} +0 -0
  127. /package/dist/{set-enabled-WCH6FU4N.js.map → set-enabled-ZNEPEFGF.js.map} +0 -0
  128. /package/dist/{tool-TWQRBV4Y.js.map → tool-6KMEAY4U.js.map} +0 -0
  129. /package/dist/{tool-WUK3ZOWG.js.map → tool-PH45YCO5.js.map} +0 -0
  130. /package/dist/{wiki-4LAJ36XR.js.map → wiki-4HD4FZ4W.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{F as rr,K as or,M as ir,a as js,b as Ws,d as Gs,f as He,l as en,s as tn,u as sr}from"./chunk-AOFTTIZZ.js";import{a as Bs}from"./chunk-GLQLCBJS.js";import{b as qs}from"./chunk-MEFPXHQJ.js";import{b as Js,c as Zt,d as zs,e as Xs,h as Ys}from"./chunk-CPMQZ6Z7.js";import{e as Vs,i as Zs,j as er,k as tr}from"./chunk-X5C5W3E4.js";import{a as nr}from"./chunk-W4YR2RO2.js";import{a as Fs}from"./chunk-4O4GZBKZ.js";import{a as ke,d as ye}from"./chunk-VD7IO653.js";import{g as Ns,h as Ls}from"./chunk-XIA2ACKX.js";import{e as Us,f as Hs}from"./chunk-36AXN6ZB.js";import{a as Yt,b as Ks}from"./chunk-J3SOEFRE.js";import{a as Vt,b as Qs}from"./chunk-SIU6STB2.js";import{c as ks,f as As}from"./chunk-XZN7QBRH.js";import{s as Ts,v as pt,w as vs,y as ue,z as Xt}from"./chunk-R6UCPHUD.js";import{a as Ue,b as ve,f as gt}from"./chunk-72SZI2UW.js";import{a as Te,b as Gt}from"./chunk-FCPTN6NF.js";import{a as $s,c as Cs}from"./chunk-MYVHVJWZ.js";import{a as Ms,b as Ps,c as _s,d as Rs,l as Es}from"./chunk-AV7T3SYT.js";import{a as Ds,b as Os}from"./chunk-Y5MFVVTM.js";import{c as ls,d as gs}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{D as hs,F as Qt,H as sa,K as ys,O as ra,U as ws,V as zt,W as bs,X as Fe,Y as xs,Z as Ss,da as Is,ua as oa}from"./chunk-EOLEKSN6.js";import{g as lt,h as ta}from"./chunk-BRK6M6LA.js";import{f as Jt,n as na}from"./chunk-UIBUZ2N3.js";import{a as ps,b as ie,c as fs,d as ms,e as Kt}from"./chunk-2QNT5JDS.js";Xt();gt();var ft="tool-set",ar=["answer","code","full"],dr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},ia=.1;function ur(n){return{task:cr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:cr(n.agentPrompt,600)}:{}}}var lr={bundle:ve({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 gr(n,e=ia){let s=n?.bundle?.probabilities;if(!s)return"full";let r=nn(s.answer),o=nn(s.code),i=nn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function pr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>dr.answer.includes(t))?"answer":e.every(t=>dr.code.includes(t))?"code":"full"}function fr(n,e){return ar.indexOf(n)<ar.indexOf(e)}function nn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function cr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var mr=!1;function hr(n,e){let t=pt(ft);if(t!=="off")return t==="active"&&!mr&&(mr=!0,e(`[decisions] seat "${ft}" is set to active, but only shadow is built: it records and changes nothing`)),ue(ft,ur(n),lr,{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=gr(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function yr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=pr(r);vs(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}`+(fr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function aa(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function wr(n,e){let t=aa(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 sn(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)`}Xt();gt();var br="session-continuity",xr={continues:Ue("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:Ue("Does the new request refer to something stated earlier in the conversation?")};function Sr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:rn(n.message,1200),previousRequest:n.previousMessage?rn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>rn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Ir(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 rn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Tt}from"execa";import{spawn as da}from"node:child_process";import{createHash as ca}from"node:crypto";import{createInterface as ua}from"node:readline";var le=class extends Error{},la=n=>da("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),on=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(),ua({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{F as rr,K as or,M as ir,a as js,b as Ws,d as Gs,f as He,l as en,s as tn,u as sr}from"./chunk-HF4OXA5L.js";import{a as Bs}from"./chunk-GLQLCBJS.js";import{b as qs}from"./chunk-MEFPXHQJ.js";import{b as Js,c as Zt,d as zs,e as Xs,h as Ys}from"./chunk-YHCPBMRH.js";import{e as Vs,i as Zs,j as er,k as tr}from"./chunk-X5C5W3E4.js";import{a as nr}from"./chunk-W4YR2RO2.js";import{a as Fs}from"./chunk-TJDNS5G6.js";import{a as ke,d as ye}from"./chunk-VD7IO653.js";import{g as Ns,h as Ls}from"./chunk-N2YSVZML.js";import{e as Us,f as Hs}from"./chunk-36AXN6ZB.js";import{a as Yt,b as Ks}from"./chunk-J3SOEFRE.js";import{a as Vt,b as Qs}from"./chunk-SIU6STB2.js";import{c as ks,f as As}from"./chunk-WX67I2KN.js";import{s as Ts,v as pt,w as vs,y as ue,z as Xt}from"./chunk-I4GT27UO.js";import{a as Ue,b as ve,f as gt}from"./chunk-72SZI2UW.js";import{a as Te,b as Gt}from"./chunk-FCPTN6NF.js";import{a as $s,c as Cs}from"./chunk-MYVHVJWZ.js";import{a as Ms,b as Ps,c as _s,d as Rs,l as Es}from"./chunk-AV7T3SYT.js";import{a as Ds,b as Os}from"./chunk-Y5MFVVTM.js";import{c as ls,d as gs}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{D as hs,F as Qt,H as sa,K as ys,O as ra,U as ws,V as zt,W as bs,X as Fe,Y as xs,Z as Ss,da as Is,ua as oa}from"./chunk-UUFJQMHE.js";import{g as lt,h as ta}from"./chunk-BRK6M6LA.js";import{f as Jt,n as na}from"./chunk-UIBUZ2N3.js";import{a as ps,b as ie,c as fs,d as ms,e as Kt}from"./chunk-2QNT5JDS.js";Xt();gt();var ft="tool-set",ar=["answer","code","full"],dr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},ia=.1;function ur(n){return{task:cr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:cr(n.agentPrompt,600)}:{}}}var lr={bundle:ve({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 gr(n,e=ia){let s=n?.bundle?.probabilities;if(!s)return"full";let r=nn(s.answer),o=nn(s.code),i=nn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function pr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>dr.answer.includes(t))?"answer":e.every(t=>dr.code.includes(t))?"code":"full"}function fr(n,e){return ar.indexOf(n)<ar.indexOf(e)}function nn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function cr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var mr=!1;function hr(n,e){let t=pt(ft);if(t!=="off")return t==="active"&&!mr&&(mr=!0,e(`[decisions] seat "${ft}" is set to active, but only shadow is built: it records and changes nothing`)),ue(ft,ur(n),lr,{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=gr(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function yr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=pr(r);vs(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}`+(fr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function aa(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function wr(n,e){let t=aa(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 sn(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)`}Xt();gt();var br="session-continuity",xr={continues:Ue("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:Ue("Does the new request refer to something stated earlier in the conversation?")};function Sr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:rn(n.message,1200),previousRequest:n.previousMessage?rn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>rn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Ir(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 rn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Tt}from"execa";import{spawn as da}from"node:child_process";import{createHash as ca}from"node:crypto";import{createInterface as ua}from"node:readline";var le=class extends Error{},la=n=>da("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),on=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(),ua({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()}},an=class{constructor(e=la,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=ca("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[R])=>b.localeCompare(R))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new le("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 b=[...this.entries].find(([,R])=>!R.connection.busy);if(!b)throw new le("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:s,connection:new on(e,this.launchProcess)}}catch{throw new le("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,f,h=!1,p=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",p,{once:!0});let I=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),A=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(A),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let E=new Promise((O,P)=>{i.failTurn=P,i.notify=(D,L)=>{if(L?.threadId!==u)return;let F=L.item,j={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...L,type:D.replace("/","."),...F?{item:{...F,type:j[F.type]||F.type}}:{}}),D==="item/completed"&&F?.type==="agentMessage"&&F.phase==="final_answer"&&(d=F.text),D==="item/agentMessage/delta"&&(h||(h=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=L.delta,e.onDelta?.(L.delta,c)),D==="thread/tokenUsage/updated"){let H=L.tokenUsage.last;f=H.inputTokens;let q=H.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}D==="turn/completed"&&(L.turn.status==="completed"?O():P(new Error(L.turn.error?.message||`Codex turn ${L.turn.status}`)))}});return E.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await E,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:f,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new le(b.message);return{content:c,codexSessionId:u,usage:l,contextTokens:f,error:b.message,duration:Date.now()-t}}finally{clearTimeout(A),clearTimeout(I),e.signal?.removeEventListener("abort",p),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Tr=new an;import{execFile as Ra}from"child_process";import{StringDecoder as Ge}from"string_decoder";import{mkdtempSync as Br,readFileSync as jr,rmSync as Wr}from"fs";import{join as St}from"path";import{tmpdir as qr}from"os";function mt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function ht(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function yt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var vr=null;function wt(){return vr}function Ku(n){vr=n}function Be(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function ga(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 Ae=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},kr=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=Be(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=ga(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 Ae(`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 Ae(`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=Be(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=Be(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Be(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=Be(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(s.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as pa}from"child_process";import{randomUUID as fa}from"crypto";import{existsSync as ma,readFileSync as ha}from"fs";import{resolve as ya}from"path";function wa(n){let e=ya(n,"CLAUDE.md");if(!ma(e))return null;try{let t=ha(e,"utf8");return Es(t)}catch{return null}}var ba=20*60*1e3,xa=5e3,je=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},We=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Sa(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 Ar=class{constructor(e={}){this.opts=e}spawn(e,t){return new dn(e,t,this.opts)}},dn=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=pa(r,o,{cwd:t.workspace,env:ye(Sa({...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:wa(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(h=>{t=h}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=fa(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
3
  `);let c=e.deadlineMs??ba,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new je(c)),l=!1,f=null;try{for(;;){let h=d-Date.now();if(h<=0)throw u();let p=await this.nextEvent(h);if(p===null&&this.killReason)throw new We(this.killReason);if(p===null&&!this.exited)throw u();if(p===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(p.type==="user"&&p.uuid===i)l=!0,f&&(yield{type:f.type,raw:f});else if(p.type==="system"&&p.subtype==="init")f=p;else if(p.type==="result"){f=null;let I=typeof p.result=="string"?p.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${I.length} chars): ${I.slice(0,120)}`)}continue}if(yield{type:p.type,raw:p},p.type==="result"){this.onResultEvent(p);return}}}finally{let h=this.snap.state==="busy";this.snap={...this.snap,...h?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},xa);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"}}};Kt();na();Gt();import{resolve as $r,join as Cr}from"path";var Ia=4e3;function bt(n){try{let e=Cr($r(n.root),".agentx","db.sqlite"),t=Jt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Te(),r=n.input.command?n.input.command.slice(0,Ia):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -27,7 +27,7 @@ ${n}`}function Da(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
27
27
  `,l)}};O.stdout?.on("data",T=>{F+=H.write(T);let w=F.split(`
28
28
  `);F=w.pop()||"";for(let _ of w)G(_)}),O.stderr?.on("data",T=>{j+=q.write(T)});let $=await O;if(i&&i.removeEventListener("abort",L),F+=H.end(),F.trim()&&G(F),j+=q.end(),P)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if($.exitCode!==0||p){let T=$,w;return T.timedOut?w=`OpenCode timed out after ${Math.round(R/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?w=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+j)?w=Fr():w=j.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...X(w),duration:Date.now()-c,usage:f,opencodeSessionId:h}}return A=!1,{content:l.trim(),duration:Date.now()-c,usage:f,billedModel:e.model||n.model,opencodeSessionId:h}}catch(R){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let E=/ENOENT|spawn opencode/i.test(R?.message||"")?Fr():R?.message;return{content:l,...X(E||"OpenCode failed"),duration:Date.now()-c,usage:f,opencodeSessionId:h}}finally{b?.(),I?.release(A)}}async function Ga(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=pe(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...X(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Ka(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,f=!1,h=()=>{let A=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(A))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{f=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let I=()=>({content:"",...X(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let A=n.provider||"claude-code",b=s?`${s}
29
29
 
30
- ${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=Rs(n),D=Object.keys(P).length>0,L={task:b,cwd:n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-LJ4SUQCC.js"),$="",T,w,_,S;for await(let v of G(L)){if(c)try{c(v)}catch{}if(v.type==="text_delta")$+=v.text,r(v.text,$);else if(v.type==="thinking_delta")v.text&&i&&i(v.text);else if(v.type==="generate_result"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}T=v.result.tokensUsed,v.result.inputTokens!=null&&(w=v.result.inputTokens),v.result.outputTokens!=null&&(_=v.result.outputTokens)}else if(v.type==="done"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}v.result.tokensUsed!=null&&(T=v.result.tokensUsed)}else v.type==="error"&&(S=v.error)}return S&&!$?f?I():S==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${S}`),duration:Date.now()-d}:((w===void 0||_===void 0)&&T&&(w=Math.round(T*.7),_=T-w),{content:$||"Done.",tokensUsed:T,usage:w!==void 0||_!==void 0?{inputTokens:w||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:F}=await import("./agent-LJ4SUQCC.js"),j=await F(L),H=j.inputTokens,q=j.outputTokens;if((H===void 0||q===void 0)&&j.tokensUsed){let G=j.tokensUsed;H=Math.round(G*.7),q=G-H}return{content:j.content||"Done.",tokensUsed:j.tokensUsed,usage:H!==void 0||q!==void 0?{inputTokens:H||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return f?I():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var Ja=1e3;async function Qa(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"}),Ja),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 za(n,e,t,s,r,o,i){let a=wt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=kt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let f,h=!1;try{let $=a.list().length;f=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>$}catch($){return $ instanceof Ae,null}h&&pn(e.agentId,n,e.model,s,"persistent");let p=pe(n,e,t),I="",A,b,R,E,O,P,D,L="",F="",j=$=>{if(!i||!$)return;let T;if(F&&$.startsWith(F)?T=$.slice(F.length):T=L&&!L.endsWith(`
30
+ ${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=Rs(n),D=Object.keys(P).length>0,L={task:b,cwd:n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-4AQOFPRD.js"),$="",T,w,_,S;for await(let v of G(L)){if(c)try{c(v)}catch{}if(v.type==="text_delta")$+=v.text,r(v.text,$);else if(v.type==="thinking_delta")v.text&&i&&i(v.text);else if(v.type==="generate_result"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}T=v.result.tokensUsed,v.result.inputTokens!=null&&(w=v.result.inputTokens),v.result.outputTokens!=null&&(_=v.result.outputTokens)}else if(v.type==="done"){if(v.result.content&&v.result.content!==$){let J=v.result.content.slice($.length);J?($=v.result.content,r(J,$)):$=v.result.content}v.result.tokensUsed!=null&&(T=v.result.tokensUsed)}else v.type==="error"&&(S=v.error)}return S&&!$?f?I():S==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${S}`),duration:Date.now()-d}:((w===void 0||_===void 0)&&T&&(w=Math.round(T*.7),_=T-w),{content:$||"Done.",tokensUsed:T,usage:w!==void 0||_!==void 0?{inputTokens:w||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:F}=await import("./agent-4AQOFPRD.js"),j=await F(L),H=j.inputTokens,q=j.outputTokens;if((H===void 0||q===void 0)&&j.tokensUsed){let G=j.tokensUsed;H=Math.round(G*.7),q=G-H}return{content:j.content||"Done.",tokensUsed:j.tokensUsed,usage:H!==void 0||q!==void 0?{inputTokens:H||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return f?I():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var Ja=1e3;async function Qa(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"}),Ja),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 za(n,e,t,s,r,o,i){let a=wt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=kt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let f,h=!1;try{let $=a.list().length;f=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>$}catch($){return $ instanceof Ae,null}h&&pn(e.agentId,n,e.model,s,"persistent");let p=pe(n,e,t),I="",A,b,R,E,O,P,D,L="",F="",j=$=>{if(!i||!$)return;let T;if(F&&$.startsWith(F)?T=$.slice(F.length):T=L&&!L.endsWith(`
31
31
  `)?`
32
32
 
33
33
  ${$}`:$,F=$,!!T){L+=T;try{i(T,L)}catch{}}},H=!1,q=()=>{H=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let G=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of f.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:$})){if(G=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let w=T.raw.message?.content??[];for(let S of w)S.type==="text"&&typeof S.text=="string"?(I=S.text,j(S.text)):S.type==="tool_use"&&(F="");let _=T.raw.message?.usage;if(_){let S=(_.input_tokens||0)+(_.cache_read_input_tokens||0)+(_.cache_creation_input_tokens||0);S>0&&(E=S)}}if(T.type==="result"){let w=T.raw;if(w.is_error){let _=X(typeof w.result=="string"?w.result:"claude error");A=_.error,b=_.errorKind}else typeof w.result=="string"&&w.result.length>0&&(I=w.result,L||j(w.result));typeof w.session_id=="string"&&(D=w.session_id),w.usage&&(R={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(O=w.num_turns),typeof w.message?.model=="string"?P=w.message.model:typeof w.model=="string"?P=w.model:P=yt(w.modelUsage)||P}}}catch($){if(H)A="task cancelled by operator",b="cancelled";else if(G)if($ instanceof We)A=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,b="interrupted";else if($ instanceof je){let T=X(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);A=T.error,b=T.errorKind}else{let T=X(`persistent claude process error: ${$?.message||String($)}`);A=T.error,b=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); 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 H&&!A&&(A="task cancelled by operator",b="cancelled"),{content:H?"":I,error:A,errorKind:b,duration:Date.now()-c,usage:R,contextTokens:E,numTurns:O,billedModel:P,claudeSessionId:D}}function Zr(n){let e=ie(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?_r(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Nr(t.args,n.taskId,n.agentId)}function Xa(n){return ie(n.autonomy)||!!n.personLimits}async function Ya(n,e,t,s,r,o,i){let a=ie(e.autonomy)?e.autonomy:void 0,c=a&&Rr(a,n.tier)||e.personLimits&&Lr(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${ms(a)}
@@ -134,7 +134,7 @@ ${wu}`:n==="codex-cli"?Ti:""}function vi(n,e){return e!=="claude-code"&&e!=="cod
134
134
  `)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new Dt(K(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...Ot,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=Rn(t.context?.chatId),a=this.cloudSessionStore();return bi({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...Ot,...e.cloudSessions??{}},i=Date.now(),a=ye(Ke(ke(e.workspace),t),e.billing),c=await Ii({route:s,agentId:t.agentId,message:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d=>Si({...d,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),log:d=>this.log(d),trace:d=>{try{Y().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:d.action,status:d.status,outputSummary:d.status==="ok"?d.summary:void 0,error:d.status==="error"?d.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});return c?{content:c.content,error:c.error,cloudSession:c.cloudSession,duration:Date.now()-i}:null}callerGone(e,t){let s=Ee(e.callerSignal).message;return this.log(`[${e.agentId}] caller gone during ${t} \u2014 not starting (${s})`),{content:"",error:`Caller gone before agent "${e.agentId}" was free \u2014 not started`}}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(d){i={content:"",error:d?.message??String(d)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let c=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(c&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,s,r);if(c){let d=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${d}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let d=i.error?He(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Js().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:d,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(d){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${d?.message??d}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=ie(e.autonomy),a=xs(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:xo().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(c){let g=await c;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let d=this.agents.get(e.agentId);if(!d){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(x=>x.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let m=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(g.peer,e.message,e.agentId,{timeoutMs:m}),viaMesh:g.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:l}=kt(e.context),f;if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||i){let g=Date.now(),m=25*6e4,x=500;for(;d.activeTasks>=d.def.maxConcurrent;){if(e.callerSignal?.aborted)return this.callerGone(e,"slot wait");if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(M=>setTimeout(M,x))}}else if(u==="voice"){let g=Date.now(),m=25*6e4,x=`${e.agentId}\0${l}`;for(;this.messageQueue.isBusy(e.agentId,u,l)||this.voiceClaims.has(x);){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(m/6e4)}m`};await new Promise(M=>setTimeout(M,500))}f=x,this.voiceClaims.add(x)}else{let g=d.def.queueMode||"collect",m=this.messageQueue.enqueue(e.agentId,u,l,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:l,originalContext:e.context,queuedAt:e.queuedAt});if(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let x=this.messageQueue.pendingCount(e.agentId,u,l);return Y().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:Qt(e.context),humanRoot:lt(e.context),person:zt(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${x}) behind=${d.runningTasks.map(M=>M.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:Gs(m,x)}}}let h=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(g,m)=>{this.log(`[${e.agentId}] ${g} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/1e3))}s`)}});if(f&&this.voiceClaims.delete(f),!h.ok)return this.log(`[${e.agentId}] ${h.reason}`),{content:"",error:h.reason};if(e.callerSignal?.aborted)return this.callerGone(e,"rate-limit wait");if(e.queuedAt!==void 0){let g=lo(e.queuedAt);g&&(e.message=`${g}
135
135
  ${e.message}`),e.queuedAt=void 0}d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let p={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{}};d.runningTasks.push(p),e.runningTaskId=p.id;let I=zt(this.config.people,e.context);if(e.context&&(I?e.context.person=I.id:delete e.context.person),this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let A=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:A});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,b);let R=g=>{if(g){b.buffer+=g,b.buffer.length>ki&&(b.buffer=b.buffer.slice(b.buffer.length-ki));for(let m of b.subscribers)try{m(g)}catch{}}},E=Te();e.taskId=E;let O=new Map,P=(g,m,x)=>{try{Y().emit("task:step",{taskId:E,agentId:e.agentId,name:"pipeline",action:g,status:x,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},D=0,L=!1,F=()=>{L||(L=!0,D&&P("first-event",D,"ok"))},j;if(t){let g=Pu();j=m=>{F();let x=g(m);if(x&&R(x),Ci(E,e.agentId,m),$i(O,m),In(m,void 0,e.model||d.def.model),r)try{r(m)}catch{}}}else j=g=>{if(F(),Ci(E,e.agentId,g),$i(O,g),In(g,void 0,e.model||d.def.model),r)try{r(g)}catch{}};let H=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,q=H?setTimeout(()=>A.abort(new Error(`timed out after ${Math.round(H/1e3)}s`)),H):void 0;q?.unref?.();let G=(d.def.preSpawnTimeoutSec??Iu)*1e3,$=setTimeout(()=>{A.abort(new Error(`timed out before spawn after ${Math.round(G/1e3)}s in step "${p.step??"start"}"`))},G);$.unref?.();let T=()=>{$&&clearTimeout($),$=void 0},w=()=>`task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`,_;A.signal.addEventListener("abort",()=>{let g=Ee(A.signal).message;/^timed out/.test(g)&&(_=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${g} ${w()}`)},{once:!0});let S=g=>{p.step=g,this.log(`[${e.agentId}] step ${g} ${w()}`)},v=(g,m,x=0)=>{if(A.signal.aborted)return Promise.reject(Ee(A.signal));S(g),(g==="agent"||g==="workflow-auto-run")&&(T(),D=Date.now());let M=Date.now(),W=wi(m(),yu[g]??0,g);return yi(W,A.signal,x).then(B=>(P(g,M,"ok"),B),B=>{throw P(g,M,"error"),B instanceof Re&&this.log(`[${e.agentId}] ${B.message}; continuing without it ${w()}`),B})},J=async(g,m,x,M=0)=>{try{return await v(g,m,M)}catch(W){if(W instanceof Re)return x();throw W}},Dn=!1,On=g=>{if(Dn)return;Dn=!0,this.runReleases.delete(p.id),q&&clearTimeout(q),T(),d.activeTasks--;let m=d.runningTasks.findIndex(x=>x.id===p.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id),b.done=!0,b.endedAt=new Date;for(let x of b.subscribers)try{x(`
136
136
  [task finished]
137
- `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),xu).unref?.();try{let x=b.endedAt,M={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:x.toISOString(),durationMs:x.getTime()-p.startedAt.getTime(),ok:!g?.error,error:g?.error,..._?{status:"timeout",step:_}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(M);let W=(M.responseText||M.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:x,ok:M.ok})}}catch(x){this.log(`[${e.agentId}] task history persist failed: ${x?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(x=>{if(x.length===0)return;this.log(`[${e.agentId}] flushing ${x.length} queued message(s) after task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`);let M=Date.now();Y().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,count:x.length,at:new Date().toISOString()});let W=()=>Y().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,at:new Date().toISOString()});for(let B of x){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then(te=>(He(te.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,te)),te=>{throw W(),te}).catch(te=>{this.log(`[${e.agentId}] queued message failed: ${te.message}`)})}}).catch(x=>{Y().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: ${x.message}`)})};this.runReleases.set(p.id,On),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${w()}`);let y=e.context?.channel||"api",{evaluateRequest:_i,selectRequestContext:Ri}=await import("./request-planner-SEXYQN7D.js"),Nn=J("request-gate",()=>_i(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Nt=!1;Nn.then(()=>{Nt=!0},()=>{Nt=!0});let k=l,Lt=e.context?.sender||"User",se=d.def.tier==="codex-cli",Oe=qo(this.config.session,y,d.def.tier),Ze=Go(this.config.session),Ne=Oe==="lean"&&Ze.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,k),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${k}`),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"stale",at:new Date().toISOString()}));let et=this.sessions.sessionIdleMs(e.agentId,y,k);e.freshSession||await J("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,k,e.seedHistory),()=>{});let Ei=[...this.sessions.getSession(e.agentId,y,k).messages].reverse().find(g=>g.role==="agent")?.content;hi({agent:e.agentId,channel:y,chatId:k,message:e.message,previousReply:Ei,taskId:E}),this.sessions.addUserMessage(e.agentId,y,k,Lt,e.message);let Ln=Date.now();Y().emit("task:started",{agentId:e.agentId,channel:y,chatId:k,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ln).toISOString(),taskId:E,resumeOrigin:co(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Qt(e.context),...I?{person:I}:{},humanRoot:lt(e.context),pickup:hs(e.context),operator:ys(e.context)});let V,Ft,Fn=this.classifier;if(Fn&&y!=="a2a"&&!se){S("classify");let g=Date.now();Ft=Fn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:k,agentId:e.agentId}).then(m=>{V=m||void 0,V?.path?.length&&(p.intentPath=V.path.slice()),P("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),P("classify",g,"error")})}let Un=async g=>{if(!Ft)return;let m;await Promise.race([Ft,new Promise(x=>{m=setTimeout(x,g),m.unref?.()})]),m&&clearTimeout(m)};await Un(gu);let Se=this.config.workflows?.matching,Ie,Hn,Bn=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Bn?.enabled&&(Bn.agents[e.agentId]??!0)&&!i&&lt(e.context))try{let g=new en({baseDir:K(process.cwd(),this.config.workflows.dir)}),m=tn({agentId:e.agentId,channel:y,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=(Se?.suggestThreshold??.65)&&(Hn=sr(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Se?.enabled&&!i)try{let g=new en({baseDir:K(process.cwd(),this.config.workflows.dir)}),m=tn({agentId:e.agentId,channel:y,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=Se.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Se.mode} reasons=${m.reasons.join(",")||"n/a"}`),Se.mode==="auto"&&m.confidence>=Se.autoRunThreshold&&(this.workflowAutoRunner?Ie={workflowId:m.workflow.id,confidence:m.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 Di=this.wikiHub.getAgentWiki(e.agentId),jn=this.memoryStore.findRelevant(e.message,e.agentId,se?3:8),Wn=this.memoryStore.buildContext(jn),qn=this.memoryStore.contextFacts(jn),Oi=this.patternStore.findRelevant(e.message,e.agentId,5),Ni=this.patternStore.buildContext(Oi),Gn="";if(!se)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),x=await v("skills",()=>g(d.def.workspace)),M=e.personLimits?.skills??[],W=M.length?x.filter(B=>!M.some(ee=>Fe(ee,B.frontmatter.name))):x;Gn=m(W,e.message)}catch{}let N=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,k):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,k):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,k):void 0;if(N&&this.sessions.isSessionStale(e.agentId,y,k,et)&&(this.log(`[${e.agentId}] session stale for ${y}:${k}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"stale",at:new Date().toISOString()}),N=void 0),N&&this.sessions.shouldRotateByTierTwo(e.agentId,y,k)){let g=this.sessions.getLastTurnContextTokens(e.agentId,y,k);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${k} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),N=void 0}if(N&&this.sessions.shouldRotateByTurns(e.agentId,y,k)){let g=this.sessions.getTurnCount(e.agentId,y,k);this.log(`[${e.agentId}] max-turns rotation for ${y}:${k} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"max-turns",at:new Date().toISOString()}),N=void 0}if(N&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=wr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,k),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,k),idleMs:et??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${k}: ${sn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"cost");let x=this.sessions.getLastTurnInputTokens(e.agentId,y,k);this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"cost",lastTurnInputTokens:x,at:new Date().toISOString()}),N=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${k}: would ${sn(m)}`)}}if(N&&d.def.tier==="claude-code"){let g=N;await J("rotate",()=>this.maybeRotateForContinuity(e,d,y,k,g),()=>!1)&&(N=void 0)}try{let g=await v("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,k,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",x=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${k} (quality: ${m}%, ${x} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let M=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${M.overallScore} (lexicon=${M.lexiconDecay}, tools=${M.toolShift}, semantic=${M.semanticDrift})`),M.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${M.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Li=process.env.AGENTX_CONTEXT_SURGERY==="1",Fi=se?{maxMessages:8,maxChars:2400}:Li&&vi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ui=!N&&!se?$u(Di,e.agentId,{notesInbox:Au(this.config)}):void 0,tt=!N&&!Ne?this.sessions.buildHistoryContext(e.agentId,y,k,Fi):void 0,Hi=N?void 0:this.sessions.getRotationMemo(e.agentId,y,k)??void 0,Kn,Jn=[];if(this.config.procedures?.injection?.enabled&&!N&&!se)try{let g=new Xe({baseDir:K(process.cwd(),this.config.procedures.dir)}),m=An(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Kn=$n(m),Jn=m.map(x=>({id:x.procedure.meta.id,title:x.procedure.meta.title}));for(let x of m)this.log(`[${e.agentId}] procedure match ${x.procedure.meta.id} score=${x.score.toFixed(2)} (${x.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(he&&he.cat)try{let m=this.sessions.getSession(e.agentId,y,k).messages,x=m[0],M=m[m.length-1],W=tt===void 0?`resume=${N?N.slice(0,8):"?"} (no rebuild)`:`fresh history=${tt.length}c/${tt.split(`
137
+ `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),xu).unref?.();try{let x=b.endedAt,M={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:x.toISOString(),durationMs:x.getTime()-p.startedAt.getTime(),ok:!g?.error,error:g?.error,..._?{status:"timeout",step:_}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(M);let W=(M.responseText||M.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:x,ok:M.ok})}}catch(x){this.log(`[${e.agentId}] task history persist failed: ${x?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(x=>{if(x.length===0)return;this.log(`[${e.agentId}] flushing ${x.length} queued message(s) after task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`);let M=Date.now();Y().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,count:x.length,at:new Date().toISOString()});let W=()=>Y().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,at:new Date().toISOString()});for(let B of x){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then(te=>(He(te.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,te)),te=>{throw W(),te}).catch(te=>{this.log(`[${e.agentId}] queued message failed: ${te.message}`)})}}).catch(x=>{Y().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: ${x.message}`)})};this.runReleases.set(p.id,On),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${w()}`);let y=e.context?.channel||"api",{evaluateRequest:_i,selectRequestContext:Ri}=await import("./request-planner-LEUMSI2K.js"),Nn=J("request-gate",()=>_i(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Nt=!1;Nn.then(()=>{Nt=!0},()=>{Nt=!0});let k=l,Lt=e.context?.sender||"User",se=d.def.tier==="codex-cli",Oe=qo(this.config.session,y,d.def.tier),Ze=Go(this.config.session),Ne=Oe==="lean"&&Ze.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,k),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${k}`),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"stale",at:new Date().toISOString()}));let et=this.sessions.sessionIdleMs(e.agentId,y,k);e.freshSession||await J("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,k,e.seedHistory),()=>{});let Ei=[...this.sessions.getSession(e.agentId,y,k).messages].reverse().find(g=>g.role==="agent")?.content;hi({agent:e.agentId,channel:y,chatId:k,message:e.message,previousReply:Ei,taskId:E}),this.sessions.addUserMessage(e.agentId,y,k,Lt,e.message);let Ln=Date.now();Y().emit("task:started",{agentId:e.agentId,channel:y,chatId:k,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ln).toISOString(),taskId:E,resumeOrigin:co(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Qt(e.context),...I?{person:I}:{},humanRoot:lt(e.context),pickup:hs(e.context),operator:ys(e.context)});let V,Ft,Fn=this.classifier;if(Fn&&y!=="a2a"&&!se){S("classify");let g=Date.now();Ft=Fn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:k,agentId:e.agentId}).then(m=>{V=m||void 0,V?.path?.length&&(p.intentPath=V.path.slice()),P("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),P("classify",g,"error")})}let Un=async g=>{if(!Ft)return;let m;await Promise.race([Ft,new Promise(x=>{m=setTimeout(x,g),m.unref?.()})]),m&&clearTimeout(m)};await Un(gu);let Se=this.config.workflows?.matching,Ie,Hn,Bn=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Bn?.enabled&&(Bn.agents[e.agentId]??!0)&&!i&&lt(e.context))try{let g=new en({baseDir:K(process.cwd(),this.config.workflows.dir)}),m=tn({agentId:e.agentId,channel:y,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=(Se?.suggestThreshold??.65)&&(Hn=sr(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Se?.enabled&&!i)try{let g=new en({baseDir:K(process.cwd(),this.config.workflows.dir)}),m=tn({agentId:e.agentId,channel:y,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=Se.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Se.mode} reasons=${m.reasons.join(",")||"n/a"}`),Se.mode==="auto"&&m.confidence>=Se.autoRunThreshold&&(this.workflowAutoRunner?Ie={workflowId:m.workflow.id,confidence:m.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 Di=this.wikiHub.getAgentWiki(e.agentId),jn=this.memoryStore.findRelevant(e.message,e.agentId,se?3:8),Wn=this.memoryStore.buildContext(jn),qn=this.memoryStore.contextFacts(jn),Oi=this.patternStore.findRelevant(e.message,e.agentId,5),Ni=this.patternStore.buildContext(Oi),Gn="";if(!se)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),x=await v("skills",()=>g(d.def.workspace)),M=e.personLimits?.skills??[],W=M.length?x.filter(B=>!M.some(ee=>Fe(ee,B.frontmatter.name))):x;Gn=m(W,e.message)}catch{}let N=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,k):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,k):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,k):void 0;if(N&&this.sessions.isSessionStale(e.agentId,y,k,et)&&(this.log(`[${e.agentId}] session stale for ${y}:${k}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"stale",at:new Date().toISOString()}),N=void 0),N&&this.sessions.shouldRotateByTierTwo(e.agentId,y,k)){let g=this.sessions.getLastTurnContextTokens(e.agentId,y,k);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${k} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),N=void 0}if(N&&this.sessions.shouldRotateByTurns(e.agentId,y,k)){let g=this.sessions.getTurnCount(e.agentId,y,k);this.log(`[${e.agentId}] max-turns rotation for ${y}:${k} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"max-turns",at:new Date().toISOString()}),N=void 0}if(N&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=wr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,k),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,k),idleMs:et??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${k}: ${sn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,N,y,k,"cost");let x=this.sessions.getLastTurnInputTokens(e.agentId,y,k);this.sessions.clearClaudeSessionId(e.agentId,y,k),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:k,reason:"cost",lastTurnInputTokens:x,at:new Date().toISOString()}),N=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${k}: would ${sn(m)}`)}}if(N&&d.def.tier==="claude-code"){let g=N;await J("rotate",()=>this.maybeRotateForContinuity(e,d,y,k,g),()=>!1)&&(N=void 0)}try{let g=await v("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,k,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",x=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${k} (quality: ${m}%, ${x} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let M=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${M.overallScore} (lexicon=${M.lexiconDecay}, tools=${M.toolShift}, semantic=${M.semanticDrift})`),M.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${M.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Li=process.env.AGENTX_CONTEXT_SURGERY==="1",Fi=se?{maxMessages:8,maxChars:2400}:Li&&vi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ui=!N&&!se?$u(Di,e.agentId,{notesInbox:Au(this.config)}):void 0,tt=!N&&!Ne?this.sessions.buildHistoryContext(e.agentId,y,k,Fi):void 0,Hi=N?void 0:this.sessions.getRotationMemo(e.agentId,y,k)??void 0,Kn,Jn=[];if(this.config.procedures?.injection?.enabled&&!N&&!se)try{let g=new Xe({baseDir:K(process.cwd(),this.config.procedures.dir)}),m=An(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Kn=$n(m),Jn=m.map(x=>({id:x.procedure.meta.id,title:x.procedure.meta.title}));for(let x of m)this.log(`[${e.agentId}] procedure match ${x.procedure.meta.id} score=${x.score.toFixed(2)} (${x.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(he&&he.cat)try{let m=this.sessions.getSession(e.agentId,y,k).messages,x=m[0],M=m[m.length-1],W=tt===void 0?`resume=${N?N.slice(0,8):"?"} (no rebuild)`:`fresh history=${tt.length}c/${tt.split(`
138
138
  `).length}L`,B=`[${e.agentId}] ${y}:${k} ${W} | session.messages=${m.length}`+(m.length>0?` first=${x.timestamp.slice(11,19)}(${x.role}:${(x.content||"").slice(0,40).replace(/\n/g," ")}) last=${M.timestamp.slice(11,19)}(${M.role}:${(M.content||"").slice(0,40).replace(/\n/g," ")})`:"");he.cat("context",B)}catch(g){he.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Qn;if(d.def.contextReferences&&!N)try{let g=d.def.workspace,m=this.referencesCache.get(g);if(!m){let[M,W]=await v("references",()=>Promise.all([Yt(d.def.workspace),Vt(d.def.workspace)]));if(M.byId.size===0&&W.recipes.length===0){let[B,ee]=await v("references",()=>Promise.all([Yt(process.cwd()),Vt(process.cwd())]));m={refs:B,recipes:ee}}else m={refs:M,recipes:W};this.referencesCache.set(g,m)}let x=Qs({agentId:e.agentId,intentTags:V?.path,message:e.message},m.recipes,m.refs);x.cards.length>0&&(Qn=Ks(x.cards,500*4)),x.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${x.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let zn=Ne?"":this.sessions.getCrossSessionSummary(e.agentId,y,k,e.message),Xn,nt=so(e.message);if(nt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:y,chatId:k,lookbackDays:nt.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${nt.lookbackDays}d on this chat (cue-triggered)]`],x=[...g.turns].sort((M,W)=>M.ts.localeCompare(W.ts));for(let M of x){let W=M.ts.slice(11,16)+" "+M.day,B=M.role==="user"?M.senderName||"User":M.senderName||"Agent";m.push(`${W} ${B}: ${M.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),Xn=m.join(`
139
139
  `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${nt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Bi=se?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",Yn,Vn,Zn=!1;Nt||S("request-gate");let me=await Nn;if(me.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Bi==="planner"&&!me.active&&!Ne&&y!=="voice"&&y!=="desktop"){try{let{planContext:g}=await import("./context-planner-3JDA7FNR.js"),m=await v("plan-context",()=>g({agentId:e.agentId,channel:y,chatId:k,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(Zn=!0,Yn=m.sessionHistory,Wn=m.memoryContext,qn=m.memoryFacts,zn=m.crossChatContext,Vn=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.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)`)}Zn&&N&&(this.sessions.clearClaudeSessionId(e.agentId,y,k),N=void 0)}let Ut=`${e.agentId}:${y}:${k}`,st=_s(e.message);st&&(st==="default"?(this.activeSouls.delete(Ut),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Ut,st),this.log(`[${e.agentId}] Soul switched to: ${st}`)));let ji=this.activeSouls.get(Ut),Wi=Ms(d.def.workspace,ji),qi=Ps(Wi),Gi=this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Ki=bu(d.def.tier),Ji=_u(d.def.richMessages,y),Qi=d.def.tier==="claude-code"&&(Oe!=="lean"||Ko(Ze)),es="";if(d.def.workspace&&!Qi){let g=K(d.def.workspace,"CLAUDE.md");if(ne(g))try{let m=Ye(g,"utf-8");es=`[Project CLAUDE.md]
140
140
  ${m.length>4e3?m.slice(0,4e3)+`
@@ -148,9 +148,9 @@ ${te}`),m+=te.length}catch{}}}let zi=Ht.length>0?Ht.join(`
148
148
 
149
149
  `)||void 0,jt={channel:y,chatId:k,channelScope:e.context?.group?"group":y==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,y),systemPrompt:d.def.systemPrompt,sender:Lt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:se||Ne||vi(y,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:se?void 0:Ni||void 0,procedureContext:[Kn,Hn].filter(Boolean).join(`
150
150
 
151
- `)||void 0,references:Qn,skillInjection:Gn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Yn??tt,memoryContext:Wn||void 0,crossChatContext:zn||void 0,longMemoryRecall:Xn||void 0,contextOnDemand:Ne&&!N?Yo(y,k):void 0,wikiContext:Ui,handoverNote:this.buildHandoverNote(e.agentId,y,k),rotationMemo:Hi,eventDigest:N?void 0:ku(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=or(y,!N,d.def.richMessages);return g?Cu(d.def.workspace,g):void 0})(),intent:V?{path:V.path,pathLabel:V.pathLabel,pathId:V.pathId,axes:V.axes,leaf:V.leaf,status:V.status}:void 0,message:e.message},ot=e.model?void 0:As({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!N,sessionIdleMs:N?et:null});ot?.downgraded&&this.log(`[${e.agentId}] ${ot.reason}`);let ts=ks(d.def.tier,this.config.decisions.routing),ns=ot?.downgraded?Promise.resolve(ot.model):!e.model&&ts&&(!me.active||me.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-2V3Y6ZR5.js"),m=await v("route-model",()=>g({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!N,sessionIdleMs:N?et:null,cheapModel:ts}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),ss=!1;ns.then(()=>{ss=!0});let it=me.active&&me.preprocess?await J("select-context",()=>Ri(jt),()=>({input:jt,excluded:[]})):{input:jt,excluded:[]};it.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${it.excluded.join(", ")}`);let at=ao(it.input,se?{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),Xi=Bs(at,{memory:qn,procedures:Jn,wikiContext:it.input.wikiContext}),Wt=(at?.length??0)+(Bt?.length??0)+(e.message?.length??0),dt={history:at?.length??0,sysPrompt:Bt?.length??0,message:e.message?.length??0},rs=No(e.agentId,y,k);Lo(rs,Wt,dt);let os=Fo(rs);os&&this.log(`[${e.agentId}] ${os}`),Wt>16e3&&this.log(`[${e.agentId}] large context for ${y}:${k}: ${Wt} bytes (history=${dt.history}, sysPrompt=${dt.sysPrompt}, message=${dt.message})`),ss||S("route-model");let is=await ns,as=d.def.tier!=="claude-code"?void 0:Oe==="lean"?Qo(d.def.workspace,Ze,void 0,y):Xo(d.def.workspace);Oe==="lean"&&!N&&this.log(`[${e.agentId}] session profile for ${y}: ${Vo(Oe,Ze,y)}`);let ds=d.def.tier==="claude-code"&&!N?hr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:E},g=>this.log(g)):void 0,Yi={...e,systemPromptAppend:Bt,...as?{claudeArgs:as}:{},...is?{model:is}:{}},re,cs=!1,us=pi({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:d.def.maxExecutionMinutes??20}),Vi=j;j=g=>{us.observe(g),Vi?.(g)};try{let g=this.workflowAutoRunner;if(Ie&&g){let U=Ie;try{let Q=await v("workflow-auto-run",()=>g({workflowId:U.workflowId,agentId:e.agentId,channel:y,chatId:k,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:y,chatId:k,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:V?.path,matchedWorkflowId:U.workflowId,matchConfidence:U.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${Ie.workflowId} run=${Q.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:"",duration:0,metadata:{handledByWorkflow:Ie.workflowId,workflowRunId:Q.runId,workflowMatchConfidence:Ie.confidence}},re}catch(Q){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${Q?.message||Q}`)}}let m=()=>{if(d.def.tier!=="claude-code")return null;S("dispatch-gate");let U=d.def.persistentProcess?wt():null,Q=U!=null&&U.hasLive({agentId:e.agentId,channel:y,chatId:k}),ce=!!N||Q,oe=[So(ce),Do(ce,void 0,e.model||d.def.model)].find(ut=>ut&&ut.abort);if(oe){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${oe.reason}`);let ut={content:"",error:oe.message,duration:0};if(!t){b.buffer=`[error] ${oe.message}`;for(let ea of b.subscribers)try{ea(b.buffer)}catch{}}return ut}Ao();let Le=Oo();return Le&&this.log(`[${e.agentId}] ${Le}`),null},x=this.planCloudSession(d.def,e);if(x.route==="local"){let U=m();if(U)return d.errors++,re=U,U}let M=d.def.tier==="claude-code",W=M?t:(U,Q)=>{U&&R(U),t&&t(U,Q)},B=!1,ee=M?s:U=>{U&&(B?R(U):(R(`\u{1F4AD} ${U}`),B=!0)),s&&s(U)},te=()=>{B&&(R(`
151
+ `)||void 0,references:Qn,skillInjection:Gn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Yn??tt,memoryContext:Wn||void 0,crossChatContext:zn||void 0,longMemoryRecall:Xn||void 0,contextOnDemand:Ne&&!N?Yo(y,k):void 0,wikiContext:Ui,handoverNote:this.buildHandoverNote(e.agentId,y,k),rotationMemo:Hi,eventDigest:N?void 0:ku(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=or(y,!N,d.def.richMessages);return g?Cu(d.def.workspace,g):void 0})(),intent:V?{path:V.path,pathLabel:V.pathLabel,pathId:V.pathId,axes:V.axes,leaf:V.leaf,status:V.status}:void 0,message:e.message},ot=e.model?void 0:As({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!N,sessionIdleMs:N?et:null});ot?.downgraded&&this.log(`[${e.agentId}] ${ot.reason}`);let ts=ks(d.def.tier,this.config.decisions.routing),ns=ot?.downgraded?Promise.resolve(ot.model):!e.model&&ts&&(!me.active||me.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-FSJ42RZH.js"),m=await v("route-model",()=>g({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!N,sessionIdleMs:N?et:null,cheapModel:ts}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),ss=!1;ns.then(()=>{ss=!0});let it=me.active&&me.preprocess?await J("select-context",()=>Ri(jt),()=>({input:jt,excluded:[]})):{input:jt,excluded:[]};it.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${it.excluded.join(", ")}`);let at=ao(it.input,se?{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),Xi=Bs(at,{memory:qn,procedures:Jn,wikiContext:it.input.wikiContext}),Wt=(at?.length??0)+(Bt?.length??0)+(e.message?.length??0),dt={history:at?.length??0,sysPrompt:Bt?.length??0,message:e.message?.length??0},rs=No(e.agentId,y,k);Lo(rs,Wt,dt);let os=Fo(rs);os&&this.log(`[${e.agentId}] ${os}`),Wt>16e3&&this.log(`[${e.agentId}] large context for ${y}:${k}: ${Wt} bytes (history=${dt.history}, sysPrompt=${dt.sysPrompt}, message=${dt.message})`),ss||S("route-model");let is=await ns,as=d.def.tier!=="claude-code"?void 0:Oe==="lean"?Qo(d.def.workspace,Ze,void 0,y):Xo(d.def.workspace);Oe==="lean"&&!N&&this.log(`[${e.agentId}] session profile for ${y}: ${Vo(Oe,Ze,y)}`);let ds=d.def.tier==="claude-code"&&!N?hr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:E},g=>this.log(g)):void 0,Yi={...e,systemPromptAppend:Bt,...as?{claudeArgs:as}:{},...is?{model:is}:{}},re,cs=!1,us=pi({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:d.def.maxExecutionMinutes??20}),Vi=j;j=g=>{us.observe(g),Vi?.(g)};try{let g=this.workflowAutoRunner;if(Ie&&g){let U=Ie;try{let Q=await v("workflow-auto-run",()=>g({workflowId:U.workflowId,agentId:e.agentId,channel:y,chatId:k,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:y,chatId:k,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:V?.path,matchedWorkflowId:U.workflowId,matchConfidence:U.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${Ie.workflowId} run=${Q.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:"",duration:0,metadata:{handledByWorkflow:Ie.workflowId,workflowRunId:Q.runId,workflowMatchConfidence:Ie.confidence}},re}catch(Q){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${Q?.message||Q}`)}}let m=()=>{if(d.def.tier!=="claude-code")return null;S("dispatch-gate");let U=d.def.persistentProcess?wt():null,Q=U!=null&&U.hasLive({agentId:e.agentId,channel:y,chatId:k}),ce=!!N||Q,oe=[So(ce),Do(ce,void 0,e.model||d.def.model)].find(ut=>ut&&ut.abort);if(oe){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${oe.reason}`);let ut={content:"",error:oe.message,duration:0};if(!t){b.buffer=`[error] ${oe.message}`;for(let ea of b.subscribers)try{ea(b.buffer)}catch{}}return ut}Ao();let Le=Oo();return Le&&this.log(`[${e.agentId}] ${Le}`),null},x=this.planCloudSession(d.def,e);if(x.route==="local"){let U=m();if(U)return d.errors++,re=U,U}let M=d.def.tier==="claude-code",W=M?t:(U,Q)=>{U&&R(U),t&&t(U,Q)},B=!1,ee=M?s:U=>{U&&(B?R(U):(R(`\u{1F4AD} ${U}`),B=!0)),s&&s(U)},te=()=>{B&&(R(`
152
152
  `),B=!1)},Zi=M?W:W?(U,Q)=>{te(),W(U,Q)}:void 0,C=await v("agent",async()=>{if(x.route!=="local"){let U=await this.runCloudSession(d.def,e,x,E);if(U)return U;let Q=m();if(Q)return Q}return eo(d.def,Yi,this.providers,Zi,at,N,j,A.signal,ee)},Su);if(!C.error){let U=Mu(d.def.toolUseRequired,O);if(U){let Q=Array.from(O.entries()).map(([ce,ct])=>`${ce}=${ct}`).join(", ")||"none";C.error=`tool_required_not_called: ${U} (invoked: ${Q})`,C.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${U}, observed ${Q}`)}}ds&&yr(ds,{toolUses:O,eventsSeen:L,error:C.error,agentId:e.agentId},U=>this.log(U));let qt=this.interruptedRuns.get(p.id);qt&&(C.content="",C.error=qt,C.errorKind="interrupted"),re=C;let de=C.usage?Us(C.usage):void 0;if(cs=!0,Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:y,chatId:k,durationMs:Date.now()-Ln,error:C.error||void 0,errorKind:C.error?C.errorKind:void 0,interrupted:qt?!0:void 0,inputTokens:de?.inputTokens,outputTokens:de?.outputTokens,cacheReadTokens:de?.cacheReadTokens,cacheCreateTokens:de?.cacheCreateTokens,tier2InputTokens:de?.tier2InputTokens,tier2OutputTokens:de?.tier2OutputTokens,tier2CacheReadTokens:de?.tier2CacheReadTokens,tier2CacheCreateTokens:de?.tier2CacheCreateTokens,resumed:!!N,resumeSessionId:N||void 0,jevArm:me.arm,numTurns:C.numTurns,injectedContext:Xi,finalResponse:C.content||void 0,billedModel:C.billedModel||d.def.model||void 0,at:new Date().toISOString()}),!t&&(C.content||C.error)){let U=C.error?`[error] ${C.error}`:C.content;b.buffer=U;for(let Q of b.subscribers)try{Q(U)}catch{}}if(C.error)d.errors++,this.log(`[${e.agentId}] error: ${C.error}`);else{if(this.sessions.addAgentMessage(e.agentId,y,k,C.content),mi({agent:e.agentId,channel:y,chatId:k,request:e.message,reply:C.content,taskId:E}),C.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,y,k,C.claudeSessionId),C.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,y,k,C.codexSessionId),C.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,y,k,C.opencodeSessionId),(C.claudeSessionId||C.codexSessionId||C.opencodeSessionId)&&C.usage&&this.sessions.recordTurnUsage(e.agentId,y,k,C.usage,C.contextTokens),C.usage){let oe=C.contextTokens,Le=(C.usage.inputTokens||0)+(C.usage.cacheReadTokens||0)+(C.usage.cacheCreateTokens||0);(oe??Le)>=this.sessions.getTierTwoThresholdTokens(y)&&this.log(`[${e.agentId}] TIER-2 HIT on ${y}:${k}: context=${oe??"n/a"} tokens (cumulative turn total=${Le}) \u2014 next turn will rotate`)}if(Ds({channel:y,content:`User: ${e.message}`,responseLength:C.content.length}).capture){await Un(pu);try{let oe=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:oe,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:y,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
153
153
 
154
154
  Agent: ${C.content}`,meta:vu(V,e.context)})}catch{}Os(e.agentId,e.message,C.content,{channel:y,chatId:k,sender:Lt},this.memoryStore).catch(()=>{}),mo(e.agentId,e.message,C.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let Q=C.billedModel||e.model||d.def.model,ce=e.context?.channel,ct=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,Q,ce,ct),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${w()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=mt(g.message);return re={content:"",error:ht(m),errorKind:m.kind},re}finally{if(us.stop(),!cs)try{Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-p.startedAt.getTime(),error:re?.error||(A.signal.aborted?Ee(A.signal).message:"run ended before completion"),errorKind:re?.errorKind,interrupted:this.interruptedRuns.has(p.id)?!0:void 0,at:new Date().toISOString()})}catch{}On(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:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),De,this.safe(e.agentId),t);ne(s)||fu(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);hu(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(),De,this.safe(e));if(!ne(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let f=K(a,l);if(ne(f))try{for(let h of ae(f)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],I=parseInt(p,10);if(!Number.isFinite(I)||I<i||I>s)continue;let A=Math.floor((s-I)/36e5),b=t-1-A;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),De);if(!ne(e))return 0;let t=0;for(let s of ae(e)){let r=K(e,s),o;try{o=ae(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),c;try{c=ae(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(Ye(K(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let f=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:f,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Tu){let t=K(process.cwd(),De);if(!ne(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ae(t)){let i=K(t,o),a;try{a=ae(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{mu(K(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),De,this.safe(e));if(!ne(s))return[];let r=ae(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),c;try{c=ae(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(Ye(K(a,d),"utf-8")),{transcript:l,responseText:f,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),De,this.safe(e));if(!ne(s))return null;let r=this.safe(t),o=ae(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(ne(a))try{return JSON.parse(Ye(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=nr();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||He(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=kt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{}}: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}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let f=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:f,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);Y().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(f).toISOString(),sender:{name:s},humanRoot:!1,person:ws(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:f});let p=!1;if(r.replace){let I=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(I))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${I}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:l,pending:h}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=f=>{u||(u=!0,d(f))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:f=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:f,queued:!1})}).then(f=>{He(f.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):f.error?l({ok:!1,status:500,error:f.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:f.viaAttachedSession?"attached":"other"})}).catch(f=>l({ok:!1,status:500,error:f?.message??String(f)}))})}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 _u(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(`
155
155
  `)}export{Tr as a,Ku as b,kr as c,wa as d,Ar as e,bt as f,ol as g,cl as h,ul as i,ml as j,kt as k,Ua as l,Yr as m,qa as n,Ga as o,Ka as p,eo as q,At as r,$t as s,pd as t,Wl as u,ql as v,bn as w,Y as x,ho as y,Td as z,$d as A,bo as B,ag as C,xo as D,vo as E,Po as F,Sg as G,_o as H,Pt as I,Ag as J,$g as K,Xe as L,Rc as M,Ec as N,Dc as O,Oc as P,Nc as Q,An as R,wu as S,bu as T,pf as U,ff as V,vu as W,ku as X,$u as Y,En as Z,Ai as _,$i as $,Mu as aa,Ci as ba,Mi as ca,_u as da};
156
- //# sourceMappingURL=chunk-CDLJOGVZ.js.map
156
+ //# sourceMappingURL=chunk-W2HEJKJR.js.map
@@ -1,2 +1,2 @@
1
- import{y as l,z as T}from"./chunk-R6UCPHUD.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
2
- //# sourceMappingURL=chunk-XZN7QBRH.js.map
1
+ import{y as l,z as T}from"./chunk-I4GT27UO.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
2
+ //# sourceMappingURL=chunk-WX67I2KN.js.map
@@ -1,4 +1,4 @@
1
- import{b as S,c as O}from"./chunk-BWSB7NOX.js";import{g as B,i as J}from"./chunk-A347YHEW.js";import{a as I,b as P}from"./chunk-FCPTN6NF.js";import{a as X,b as ue}from"./chunk-7I7IEX4S.js";import{d as F}from"./chunk-QIJLFPWE.js";import{execFile as Ae}from"child_process";import{writeFileSync as ie,mkdirSync as x,existsSync as b,readFileSync as ke}from"fs";import{resolve as v}from"path";var le=["off","shadow","authoritative"],ge={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},me="INTENT_LEDGER_MODE";function G(i,e=process.env){let t=U(e[ge[i]]);if(t)return t;let n=U(e[me]);return n||"off"}function U(i){if(typeof i!="string")return null;let e=i.trim().toLowerCase();return le.includes(e)?e:null}P();import he from"better-sqlite3";import{existsSync as Ue,mkdirSync as fe}from"fs";import{dirname as pe,resolve as Ee}from"path";var T=class{db;path;constructor(e={}){this.path=Ee(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),fe(pe(this.path),{recursive:!0}),this.db=new he(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),ye(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let n=this.findEventBySourceId(e.source,e.sourceEventId);if(n)return n}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
1
+ import{b as S,c as O}from"./chunk-J4I5ZJ2V.js";import{g as B,i as J}from"./chunk-JE5EJGGD.js";import{a as I,b as P}from"./chunk-FCPTN6NF.js";import{a as X,b as ue}from"./chunk-7I7IEX4S.js";import{d as F}from"./chunk-QIJLFPWE.js";import{execFile as Ae}from"child_process";import{writeFileSync as ie,mkdirSync as x,existsSync as b,readFileSync as ke}from"fs";import{resolve as v}from"path";var le=["off","shadow","authoritative"],ge={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},me="INTENT_LEDGER_MODE";function G(i,e=process.env){let t=U(e[ge[i]]);if(t)return t;let n=U(e[me]);return n||"off"}function U(i){if(typeof i!="string")return null;let e=i.trim().toLowerCase();return le.includes(e)?e:null}P();import he from"better-sqlite3";import{existsSync as Ue,mkdirSync as fe}from"fs";import{dirname as pe,resolve as Ee}from"path";var T=class{db;path;constructor(e={}){this.path=Ee(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),fe(pe(this.path),{recursive:!0}),this.db=new he(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),ye(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let n=this.findEventBySourceId(e.source,e.sourceEventId);if(n)return n}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
2
2
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let n=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
3
3
  FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return n?Y(n):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
4
4
  FROM intent_events WHERE id = ?`).get(e);return t?Y(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
@@ -125,4 +125,4 @@ ${se(o.block,r.prompt)}`,r.maxOutputTokens),agentId:r.agent,autonomy:r.autonomy,
125
125
  `);return t.length<=e?t.join(`
126
126
  `):t.slice(-e).join(`
127
127
  `)}function Xe(i,e,t){return new Promise((n,r)=>{Ae("/bin/sh",["-c",i],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(s,a,o)=>{if(s&&s.killed){r(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}n({stdout:String(a??""),stderr:String(o??""),code:s?typeof s.code=="number"?s.code:1:0})})})}export{T as a,V as b,ot as c,we as d,at as e,ct as f,$ as g,ee as h,G as i,We as j,z as k,Q as l,lt as m,Ce as n,oe as o,ae as p,ce as q,C as r,M as s};
128
- //# sourceMappingURL=chunk-CPMQZ6Z7.js.map
128
+ //# sourceMappingURL=chunk-YHCPBMRH.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-UTSXNAHM.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
2
+ import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-FESSM5TY.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
3
3
  //# sourceMappingURL=cli.js.map
@@ -1,2 +1,2 @@
1
- import{a,b,c,d,e,f,g}from"./chunk-XOQNDWVW.js";import"./chunk-EOLEKSN6.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
2
- //# sourceMappingURL=client-A5OK3IFO.js.map
1
+ import{a,b,c,d,e,f,g}from"./chunk-QPYN2UTV.js";import"./chunk-UUFJQMHE.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
2
+ //# sourceMappingURL=client-KGWYROLX.js.map
@@ -1,2 +1,2 @@
1
- import{ca as a,da as b,ea as c,fa as d,ga as e,ha as f,ia as g,ja as h,ka as i,la as j,ma as k,na as l,oa as m,pa as n,qa as o,ra as p,sa as q,ua as r}from"./chunk-EOLEKSN6.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";r();export{a as INTEGRATION_KINDS,o as WIKI_CONTRIBUTE_JOB,p as WIKI_CONTRIBUTE_MERGE_JOB,j as approvalsConfigSchema,d as callsSchema,c as cameraBotSchema,k as daemonConfigSchema,b as eventSubscriptionSchema,l as expandEnvVars,m as loadDaemonConfig,h as membersConfigSchema,g as peopleConfigSchema,f as personSchema,i as requestStatusConfigSchema,e as requestsConfigSchema,n as validateWorkspaces,q as withContributionJobs};
2
- //# sourceMappingURL=config-DQ5SILHX.js.map
1
+ import{ca as a,da as b,ea as c,fa as d,ga as e,ha as f,ia as g,ja as h,ka as i,la as j,ma as k,na as l,oa as m,pa as n,qa as o,ra as p,sa as q,ua as r}from"./chunk-UUFJQMHE.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";r();export{a as INTEGRATION_KINDS,o as WIKI_CONTRIBUTE_JOB,p as WIKI_CONTRIBUTE_MERGE_JOB,j as approvalsConfigSchema,d as callsSchema,c as cameraBotSchema,k as daemonConfigSchema,b as eventSubscriptionSchema,l as expandEnvVars,m as loadDaemonConfig,h as membersConfigSchema,g as peopleConfigSchema,f as personSchema,i as requestStatusConfigSchema,e as requestsConfigSchema,n as validateWorkspaces,q as withContributionJobs};
2
+ //# sourceMappingURL=config-FNTLKUGA.js.map
@@ -1,2 +1,2 @@
1
- import{a,b}from"./chunk-ARSVKSC4.js";import"./chunk-EOLEKSN6.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
2
- //# sourceMappingURL=config-mutate-62FCJ3S6.js.map
1
+ import{a,b}from"./chunk-MZJY26FW.js";import"./chunk-UUFJQMHE.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
2
+ //# sourceMappingURL=config-mutate-7BLOYRZF.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e}from"./chunk-J4I5ZJ2V.js";import"./chunk-UUFJQMHE.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
2
+ //# sourceMappingURL=config-mutator-NCLHYPJ3.js.map
@@ -1,4 +1,4 @@
1
- import{a as ee}from"./chunk-X5JTG52Q.js";import"./chunk-PVUNDNT3.js";import{f as Q,k as V}from"./chunk-GLQLCBJS.js";import"./chunk-M7IJVOJA.js";import"./chunk-VD7IO653.js";import"./chunk-XIA2ACKX.js";import"./chunk-WPNRDEHW.js";import{c as O}from"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-R6UCPHUD.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import{b as X}from"./chunk-4VVHGR7H.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-EOLEKSN6.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
1
+ import{a as ee}from"./chunk-LLLBH2HH.js";import"./chunk-TN5A7PLU.js";import{f as Q,k as V}from"./chunk-GLQLCBJS.js";import"./chunk-I4OQQRY2.js";import"./chunk-VD7IO653.js";import"./chunk-N2YSVZML.js";import"./chunk-WPNRDEHW.js";import{c as O}from"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-I4GT27UO.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import{b as X}from"./chunk-4VVHGR7H.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-UUFJQMHE.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
2
2
  `),se(t,n)}function ie(n){return{agents:E(w(S(n),"state.json"),{agents:{}}).agents??{}}}function ye(n){let r=w(S(n),"pending");return z(r)?re(r).filter(t=>t.endsWith(".json")).sort().map(t=>E(w(r,t),null)).filter(t=>!!t):[]}function G(n){return w(S(n),"held.json")}function K(n,r={}){let t=E(G(n),[]);return r.all?t:t.filter(a=>a.status==="held")}function _e(n){let r=w(S(n),"reports");if(!z(r))return null;let t=re(r).filter(a=>a.endsWith(".json")).sort().pop();return t?E(w(r,t),null):null}function ke(n,r,t,a={}){let o=ie(r).agents[t],c=a.now??Date.now(),e=a.since??o?.lastRunAt??new Date(c-864e5).toISOString(),d=e.slice(0,10),u=new Set(o?.processed??[]),s=[];for(let g of n.getAgentEntries(t))g.date<d||u.has(g.id)||s.push({id:g.id,at:g.date,kind:"chat",title:[g.source,g.sourceContext].filter(Boolean).join(" \xB7 "),text:g.content});if(a.db){let g=Date.parse(e);for(let l of V(a.db,{agentId:t,since:Number.isFinite(g)?g:void 0,limit:500})){if(l.status==="in-flight"||u.has(l.taskId))continue;let k=(Q(a.db,l.taskId)?.steps??[]).filter(b=>b.name==="tool_use"||b.action).slice(0,be).map(b=>`- ${b.action??b.name}${b.inputSummary?` ${x(b.inputSummary,160)}`:""}${b.outputSummary?` \u2192 ${x(b.outputSummary,240)}`:""}${b.error?` \u2717 ${x(b.error,120)}`:""}`),y=[`Request: ${x(l.originalMessage??l.messagePreview??"",600)}`,k.length?`Tool calls:
3
3
  ${k.join(`
4
4
  `)}`:"",l.finalResponse?`Reply: ${x(l.finalResponse,800)}`:""].filter(Boolean).join(`
@@ -54,4 +54,4 @@ _Sources: ${t.sources.join("; ")}._`,a);return n.writeArticle(r,{title:t.title,.
54
54
  `).replace(/\n{3,}/g,`
55
55
 
56
56
  `).trim(),superseded:d}}function Ce(n){let r=n.previous?` (previously: ${n.previous})`:"";return`- **${n.attribute}:** ${n.value} \u2014 ${n.source}; checked ${n.checkedAt.slice(0,10)} by ${n.by}${r}`}function Re(n){let r=n.match(/^- \*\*.+?:\*\* (.*?) — .*?; checked (\S+) by \S+(?: \(previously: (.*)\))?$/);return r?{value:r[1],checkedAt:r[2],...r[3]?{previous:r[3]}:{}}:void 0}function J(n,r){return`contribution:${n}@${r.slice(0,10)}`}var Te={person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"};function de(n,r,t){let a=r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"page",o=t?Te[t]:"contributions",c=`${o}/${a}.md`;for(let e=2;n.readArticle(c);e++)c=`${o}/${a}-${e}.md`;return c}export{_ as DEFAULT_CONTRIBUTION_LIMITS,B as FACTS_HEADING,ue as applyFactLines,De as approveHeld,xe as buildContributionPrompt,S as contributionsDir,_e as latestReport,K as listHeld,ye as listPendingBatches,Be as mergeContributions,W as pageKey,Ae as parseContributionPatches,ke as pendingWork,Se as possibleDuplicate,Fe as rejectHeld,ce as replaceOnce,Me as runContribution};
57
- //# sourceMappingURL=contributions-L2YS4AH2.js.map
57
+ //# sourceMappingURL=contributions-DLUQEAGL.js.map
@@ -1,2 +1,2 @@
1
- import{b as a,c as b,d as c,e as d,f as e}from"./chunk-SCC7HBFZ.js";import"./chunk-S2GAEH2F.js";import"./chunk-JXF54PT7.js";import"./chunk-EOLEKSN6.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{e as daemonVoiceCheck,b as doctor,a as runDoctorChecks,c as runNotificationChecks,d as runReminderChecks};
2
- //# sourceMappingURL=doctor-7TPSMMFA.js.map
1
+ import{b as a,c as b,d as c,e as d,f as e}from"./chunk-RKB7FQJF.js";import"./chunk-S2GAEH2F.js";import"./chunk-JXF54PT7.js";import"./chunk-UUFJQMHE.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{e as daemonVoiceCheck,b as doctor,a as runDoctorChecks,c as runNotificationChecks,d as runReminderChecks};
2
+ //# sourceMappingURL=doctor-32YP26SJ.js.map
@@ -1,6 +1,6 @@
1
- import{b as h}from"./chunk-4ZFLYY5P.js";import"./chunk-RKPAVWXF.js";import{b as m}from"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-VJRITDSQ.js";import"./chunk-CPMQZ6Z7.js";import"./chunk-BWSB7NOX.js";import"./chunk-A347YHEW.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-EOLEKSN6.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function k(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(r=>`- ${String(r.at).slice(0,16).replace("T"," ")} ${r.step} ${r.status}${r.note?`: ${r.note}`:""}`)].filter(Boolean).join(`
1
+ import{b as h}from"./chunk-U2EHJZAZ.js";import"./chunk-RKPAVWXF.js";import{b as m}from"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-242MPMJX.js";import"./chunk-YHCPBMRH.js";import"./chunk-J4I5ZJ2V.js";import"./chunk-JE5EJGGD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-UUFJQMHE.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function k(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(r=>`- ${String(r.at).slice(0,16).replace("T"," ")} ${r.step} ${r.status}${r.note?`: ${r.note}`:""}`)].filter(Boolean).join(`
2
2
  `)}async function T(t,u){let r=u.fetch??fetch,$=u.daemonUrl.replace(/\/$/,""),a=(p(t.action)||"list").toLowerCase(),f=u.env??process.env,w=async i=>{let l=await r(`${$}${i}`,{signal:AbortSignal.timeout(1e4)}),n=await l.json().catch(()=>({}));return{ok:l.ok,status:l.status,data:n}};try{if(a==="list"){let e=await w("/follow-up");if(!e.ok)return`Error: ${e.data?.error||`HTTP ${e.status}`}`;let o=e.data.groups??[];return o.length?o.map(c=>[`${c.tag}:`,...c.rows.map(s=>`- ${s.runId} "${s.title}" on ${s.step}: waiting on ${s.waitingOn} (since ${String(s.since).slice(0,16).replace("T"," ")} UTC)`)].join(`
3
3
  `)).join(`
4
4
  `):"No follow-up workflows are running."}if(a==="match"){let e=p(t.request)||p(t.title);if(!e)return"Error: match needs `request`: the owner's request in their words.";let o=h(t,f),c=await w(`/follow-up/match?q=${encodeURIComponent(e)}${o?`&agentId=${encodeURIComponent(o.agentId)}`:""}`);if(!c.ok)return`Error: ${c.data?.error||`HTTP ${c.status}`}`;let s=c.data.matches??[];return s.length?["Saved workflows, best fit first (confidence 0-1):",...s.map(d=>`- ${d.workflowId} "${d.title}" (${d.confidence}${d.autoStart?", starts without asking":""}): ${d.steps.map(I=>I.id).join(" \u2192 ")}`),'Start one with {action:"start", workflowId:"<id>", title:"\u2026", tags:["client:<name>"]}. Run its steps through the workflow, not by hand.'].join(`
5
5
  `):"No saved workflow fits. If the request has several steps, build one: start with title and steps."}if(a==="status"){let e=p(t.runId);if(!e)return"Error: status needs runId.";let o=await w(`/follow-up/${encodeURIComponent(e)}`);return o.ok?k(o.data.run):`Error: ${o.data?.error||`HTTP ${o.status}`}`}let i=h(t,f);if(!i)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let l=await r(`${$}/follow-up`,{method:"POST",headers:{"Content-Type":"application/json",...m(f)},body:JSON.stringify({action:a,agentId:i.agentId,workflowId:t.workflowId,title:t.title,description:t.description,tags:t.tags,inputs:t.inputs,steps:t.steps,edges:t.edges,approval:t.approval,autoStart:t.autoStart,requestId:t.requestId,runId:t.runId,step:t.step,evidence:t.evidence,note:t.note,reason:t.reason,fromRun:t.fromRun}),signal:AbortSignal.timeout(2e4)}),n=await l.json().catch(()=>({}));if(!l.ok)return`Error: ${n?.error||`HTTP ${l.status}`}`;if(a==="start"){let e=n.run;return[`Started run ${e.runId} "${e.title}"${n.built?" (built from the steps you gave; propose it with fromRun to keep it)":""}.`,n.awaitingApproval?"It waits for the owner's approval before the first step.":`It is on step ${e.step}: ${e.waitingOn}.`,"AgentX follows it from here: it starts each step, reminds whoever is slow, and tells the owner when it ends. Do not run its steps by hand.",...n.warning?[`Note: ${n.warning}`]:[]].join(" ")}return a==="done"?`Step recorded as done. ${n.run?k(n.run):""}`.trim():a==="blocked"?"The step is marked blocked and the owner is told. Nothing more happens on it until it is sorted.":`Saved ${n.workflowId} switched off, and asked the owner (card ${n.cardId}) whether to keep it as a reusable workflow.`}catch(i){return`Error: couldn't reach the daemon (${i?.message??i}).`}}export{T as runWorkflowTool};
6
- //# sourceMappingURL=follow-up-tool-FKWIRFPW.js.map
6
+ //# sourceMappingURL=follow-up-tool-AQ7NYZZR.js.map
@@ -1,2 +1,2 @@
1
- import{a}from"./chunk-4O4GZBKZ.js";import"./chunk-BCUR2TJ7.js";import"./chunk-3PGPN323.js";import"./chunk-XIA2ACKX.js";import"./chunk-WPNRDEHW.js";import"./chunk-R6UCPHUD.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-4VVHGR7H.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-EOLEKSN6.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as WikiHub};
2
- //# sourceMappingURL=hub-EU5ECAJB.js.map
1
+ import{a}from"./chunk-TJDNS5G6.js";import"./chunk-NR7WLMNI.js";import"./chunk-3PGPN323.js";import"./chunk-N2YSVZML.js";import"./chunk-WPNRDEHW.js";import"./chunk-I4GT27UO.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-4VVHGR7H.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-UUFJQMHE.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as WikiHub};
2
+ //# sourceMappingURL=hub-Q3I4ALQ2.js.map
package/dist/index.d.ts CHANGED
@@ -4458,6 +4458,12 @@ declare const daemonConfigSchema: z.ZodObject<{
4458
4458
  * Each must run as the inbox agent. Empty: notes are kept but no run
4459
4459
  * reads them. */
4460
4460
  crons: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
4461
+ /** Agent whose `agentx wiki absorb` pass reads the inbox (#831). Absorb
4462
+ * is one model call with no tools: it gets the notes in its prompt,
4463
+ * answers each, and absorb applies the patches and records the
4464
+ * outcome. Unset: absorb reads no notes. Must run on this node, the
4465
+ * node that keeps the inbox. */
4466
+ absorbAgent: z.ZodOptional<z.ZodString>;
4461
4467
  /** Most notes one run is given. The rest wait for the next run. */
4462
4468
  maxNotesPerRun: z.ZodDefault<z.ZodNumber>;
4463
4469
  /** A note deferred this many times stops being offered (status
@@ -4469,10 +4475,12 @@ declare const daemonConfigSchema: z.ZodObject<{
4469
4475
  maxNotesPerRun: number;
4470
4476
  maxDeferrals: number;
4471
4477
  inbox?: string | undefined;
4478
+ absorbAgent?: string | undefined;
4472
4479
  }, {
4473
4480
  enabled?: boolean | undefined;
4474
4481
  inbox?: string | undefined;
4475
4482
  crons?: string[] | undefined;
4483
+ absorbAgent?: string | undefined;
4476
4484
  maxNotesPerRun?: number | undefined;
4477
4485
  maxDeferrals?: number | undefined;
4478
4486
  }>, {
@@ -4481,10 +4489,12 @@ declare const daemonConfigSchema: z.ZodObject<{
4481
4489
  maxNotesPerRun: number;
4482
4490
  maxDeferrals: number;
4483
4491
  inbox?: string | undefined;
4492
+ absorbAgent?: string | undefined;
4484
4493
  }, {
4485
4494
  enabled?: boolean | undefined;
4486
4495
  inbox?: string | undefined;
4487
4496
  crons?: string[] | undefined;
4497
+ absorbAgent?: string | undefined;
4488
4498
  maxNotesPerRun?: number | undefined;
4489
4499
  maxDeferrals?: number | undefined;
4490
4500
  }>>;
@@ -7957,6 +7967,7 @@ declare const daemonConfigSchema: z.ZodObject<{
7957
7967
  maxNotesPerRun: number;
7958
7968
  maxDeferrals: number;
7959
7969
  inbox?: string | undefined;
7970
+ absorbAgent?: string | undefined;
7960
7971
  };
7961
7972
  services: Record<string, {
7962
7973
  agent: string;
@@ -8911,6 +8922,7 @@ declare const daemonConfigSchema: z.ZodObject<{
8911
8922
  enabled?: boolean | undefined;
8912
8923
  inbox?: string | undefined;
8913
8924
  crons?: string[] | undefined;
8925
+ absorbAgent?: string | undefined;
8914
8926
  maxNotesPerRun?: number | undefined;
8915
8927
  maxDeferrals?: number | undefined;
8916
8928
  } | undefined;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,la as Tt,ma as Mt}from"./chunk-YHD4PHFX.js";import"./chunk-4FMZTM3W.js";import"./chunk-GTJIKXDB.js";import"./chunk-Z5CBUZIW.js";import"./chunk-BGG3ZSMW.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-EMGB23H5.js";import"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-JWDJMFU6.js";import"./chunk-GRMCAO3Q.js";import"./chunk-KZKDVIOE.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-WEPON4FP.js";import"./chunk-AKLZ4YO2.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-DVR6PFCJ.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-VJRITDSQ.js";import"./chunk-I3RAUJCD.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-CDLJOGVZ.js";import"./chunk-AOFTTIZZ.js";import"./chunk-GLQLCBJS.js";import"./chunk-MEFPXHQJ.js";import{s as ut}from"./chunk-CPMQZ6Z7.js";import{a as L}from"./chunk-UG2OF2EI.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-BWSB7NOX.js";import"./chunk-A347YHEW.js";import"./chunk-VWTBHLMX.js";import"./chunk-4O4GZBKZ.js";import{a as ht}from"./chunk-BCUR2TJ7.js";import"./chunk-3PGPN323.js";import"./chunk-M7IJVOJA.js";import"./chunk-VD7IO653.js";import{f as gt,g as ft}from"./chunk-XIA2ACKX.js";import"./chunk-WPNRDEHW.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-XZN7QBRH.js";import{j as it,k as rt,l as at}from"./chunk-R6UCPHUD.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-4VVHGR7H.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-2PJKGZWP.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{ma as tt,oa as st,pa as ot,ua as nt}from"./chunk-EOLEKSN6.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,la as Tt,ma as Mt}from"./chunk-UBA2QJCY.js";import"./chunk-QXZLYCEZ.js";import"./chunk-GTJIKXDB.js";import"./chunk-5KKXJZZ4.js";import"./chunk-BGG3ZSMW.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-EMGB23H5.js";import"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-JWDJMFU6.js";import"./chunk-GRMCAO3Q.js";import"./chunk-KZKDVIOE.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-WEPON4FP.js";import"./chunk-AKLZ4YO2.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-Q5FEWCS5.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-242MPMJX.js";import"./chunk-LJWEJ6UZ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-W2HEJKJR.js";import"./chunk-HF4OXA5L.js";import"./chunk-GLQLCBJS.js";import"./chunk-MEFPXHQJ.js";import{s as ut}from"./chunk-YHCPBMRH.js";import{a as L}from"./chunk-UG2OF2EI.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-J4I5ZJ2V.js";import"./chunk-JE5EJGGD.js";import"./chunk-VWTBHLMX.js";import"./chunk-TJDNS5G6.js";import{a as ht}from"./chunk-NR7WLMNI.js";import"./chunk-3PGPN323.js";import"./chunk-I4OQQRY2.js";import"./chunk-VD7IO653.js";import{f as gt,g as ft}from"./chunk-N2YSVZML.js";import"./chunk-WPNRDEHW.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-WX67I2KN.js";import{j as it,k as rt,l as at}from"./chunk-I4GT27UO.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-4VVHGR7H.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-2PJKGZWP.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{ma as tt,oa as st,pa as ot,ua as nt}from"./chunk-UUFJQMHE.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
4
  ${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
@@ -1,2 +1,2 @@
1
- import{a,b,c,d,e,f,g,h,i}from"./chunk-A347YHEW.js";import"./chunk-QIJLFPWE.js";export{c as DEFAULT_MAX_DEFERRALS,b as NOTE_LIMITS,a as NOTE_OUTCOMES,g as NoteStore,h as isWaiting,d as noteId,i as renderNotesInbox,e as today,f as validateNote};
2
- //# sourceMappingURL=notes-2VC47RCK.js.map
1
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-JE5EJGGD.js";import"./chunk-QIJLFPWE.js";export{c as DEFAULT_MAX_DEFERRALS,b as NOTE_LIMITS,a as NOTE_OUTCOMES,g as NoteStore,h as isWaiting,d as noteId,i as renderNotesInbox,e as today,f as validateNote};
2
+ //# sourceMappingURL=notes-TMAGEDUS.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b}from"./chunk-KBJNJGBP.js";import"./chunk-QIJLFPWE.js";export{b as patchWikiNotes,a as wikiNotesSettings};
2
+ //# sourceMappingURL=notes-settings-WMOH2V75.js.map