agentix-cli 0.138.1 → 0.139.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/dist/{App-F42CYCKX.js → App-VINKWTYN.js} +2 -2
  2. package/dist/{ChatApp-RPMQBKHV.js → ChatApp-RGHQCRBX.js} +2 -2
  3. package/dist/{absorb-eval-HRPEHJSO.js → absorb-eval-AERHBOQA.js} +2 -2
  4. package/dist/{agent-BLRZVUG4.js → agent-PRHZGF6J.js} +2 -2
  5. package/dist/{board-dashboard-42C7GGD7.js → board-dashboard-GBEBQUFJ.js} +4 -4
  6. package/dist/{chunk-7V73QTQ7.js → chunk-2BEZU5OF.js} +2 -2
  7. package/dist/chunk-3W2BHUGM.js +11 -0
  8. package/dist/chunk-3W2BHUGM.js.map +1 -0
  9. package/dist/{chunk-VVX4RXMV.js → chunk-7KAQHNLT.js} +2 -2
  10. package/dist/{chunk-6AUWEL6V.js → chunk-ANDEMOYE.js} +2 -2
  11. package/dist/{chunk-TFH6S7IT.js → chunk-AXHP6TMT.js} +2 -2
  12. package/dist/{chunk-375MXG3H.js → chunk-B65EC44C.js} +2 -2
  13. package/dist/{chunk-AGQYUOZY.js → chunk-EJIY45FZ.js} +2 -2
  14. package/dist/{chunk-J5FNCTG2.js → chunk-FUJ4KEWS.js} +198 -198
  15. package/dist/chunk-FUJ4KEWS.js.map +1 -0
  16. package/dist/{chunk-AP4DADXG.js → chunk-HGU5B7IY.js} +2 -2
  17. package/dist/{chunk-SK47VJMQ.js → chunk-HXLB2XCT.js} +3 -3
  18. package/dist/{chunk-XBARUCG5.js → chunk-IMUTN7PT.js} +2 -2
  19. package/dist/{chunk-LA6P3TUK.js → chunk-J7U3BASX.js} +2 -2
  20. package/dist/{chunk-ADYTED3R.js → chunk-JBYLG3CQ.js} +2 -2
  21. package/dist/{chunk-QGSUENRK.js → chunk-JJZVFDG6.js} +2 -2
  22. package/dist/{chunk-DBJUGKX2.js → chunk-JS2LEURJ.js} +2 -2
  23. package/dist/{chunk-BKSWOMAM.js → chunk-KO6BU3B3.js} +2 -2
  24. package/dist/{chunk-MTDVAO5C.js → chunk-LMZCB7TT.js} +2 -2
  25. package/dist/{chunk-HJCFLGVT.js → chunk-MGM33GOW.js} +6 -6
  26. package/dist/{chunk-HJCFLGVT.js.map → chunk-MGM33GOW.js.map} +1 -1
  27. package/dist/{chunk-AOV5RMFH.js → chunk-MUC7MMTT.js} +2 -2
  28. package/dist/{chunk-JIJDBCV7.js → chunk-NMYPZR4W.js} +2 -2
  29. package/dist/{chunk-EGPCEQJN.js → chunk-NQGLKWDO.js} +2 -2
  30. package/dist/{chunk-Y7IHOQC7.js → chunk-O6WW7ATO.js} +2 -2
  31. package/dist/{chunk-UPQTTOVQ.js → chunk-QN2OTBVC.js} +2 -2
  32. package/dist/{chunk-6XMISPQD.js → chunk-RIYQNADV.js} +5 -5
  33. package/dist/{chunk-XVYIPVSC.js → chunk-STIZFWDJ.js} +2 -2
  34. package/dist/{chunk-HQH44RGL.js → chunk-XQVL2RYG.js} +2 -2
  35. package/dist/{chunk-6VP2KMUM.js → chunk-Z5IHT6RK.js} +2 -2
  36. package/dist/cli.js +1 -1
  37. package/dist/{client-EB55Y6EJ.js → client-2KZWK6YT.js} +2 -2
  38. package/dist/{config-7DRUA5R3.js → config-THFRJMZD.js} +2 -2
  39. package/dist/{config-mutate-GGA7VXXH.js → config-mutate-HXWAXWHC.js} +2 -2
  40. package/dist/config-mutator-JZOAWRBH.js +2 -0
  41. package/dist/{contributions-TZ26MTML.js → contributions-OSIKL25B.js} +2 -2
  42. package/dist/{doctor-GTRZ7GWF.js → doctor-TOSA3RWP.js} +2 -2
  43. package/dist/{follow-up-tool-PNB7KMCY.js → follow-up-tool-M2KCLRQQ.js} +2 -2
  44. package/dist/{hub-QWJR4E6V.js → hub-XGWCWKMT.js} +2 -2
  45. package/dist/index.d.ts +46 -0
  46. package/dist/index.js +1 -1
  47. package/dist/{program-5RLTC6CR.js → program-X6EKIO24.js} +188 -188
  48. package/dist/program-X6EKIO24.js.map +1 -0
  49. package/dist/{promote-HAPXWGYH.js → promote-YVWRKIAU.js} +2 -2
  50. package/dist/{query-ICLOVLZ3.js → query-X4AFOKZ7.js} +2 -2
  51. package/dist/{query-settings-7AXUOHDL.js → query-settings-HV2RFQK7.js} +2 -2
  52. package/dist/{registry-RH5NFDL7.js → registry-B276QJ75.js} +2 -2
  53. package/dist/{request-planner-TDCLF2CH.js → request-planner-MY6VKTVC.js} +2 -2
  54. package/dist/{review-candidates-QCBXLWG6.js → review-candidates-BRTBB5XV.js} +2 -2
  55. package/dist/{routing-YUP3HHL5.js → routing-CSVLOGNS.js} +2 -2
  56. package/dist/schedule-tool-GUKYTQTY.js +2 -0
  57. package/dist/{scheduler-7NK2FH5V.js → scheduler-OUAVAU4O.js} +2 -2
  58. package/dist/{seat-PTPPQOTP.js → seat-H2QR3CRX.js} +2 -2
  59. package/dist/{select-2XSTWMBR.js → select-EEL5AZ2I.js} +2 -2
  60. package/dist/{set-enabled-SS5Q3OX7.js → set-enabled-IBGEH6U6.js} +2 -2
  61. package/dist/{tool-QCMSXEDB.js → tool-DFPOFXGA.js} +2 -2
  62. package/dist/{tool-RK4LDFFH.js → tool-GJ75MWV5.js} +2 -2
  63. package/dist/{wiki-Q2E44YAE.js → wiki-ISKHNG3P.js} +2 -2
  64. package/dist/wiki-enrich-7SBCPK2E.js +2 -0
  65. package/package.json +1 -1
  66. package/dist/chunk-J5FNCTG2.js.map +0 -1
  67. package/dist/chunk-LLNPKE7H.js +0 -11
  68. package/dist/chunk-LLNPKE7H.js.map +0 -1
  69. package/dist/config-mutator-POFVILXH.js +0 -2
  70. package/dist/program-5RLTC6CR.js.map +0 -1
  71. package/dist/schedule-tool-3C22NBMN.js +0 -2
  72. package/dist/wiki-enrich-6ULCDOTX.js +0 -2
  73. /package/dist/{App-F42CYCKX.js.map → App-VINKWTYN.js.map} +0 -0
  74. /package/dist/{ChatApp-RPMQBKHV.js.map → ChatApp-RGHQCRBX.js.map} +0 -0
  75. /package/dist/{absorb-eval-HRPEHJSO.js.map → absorb-eval-AERHBOQA.js.map} +0 -0
  76. /package/dist/{agent-BLRZVUG4.js.map → agent-PRHZGF6J.js.map} +0 -0
  77. /package/dist/{board-dashboard-42C7GGD7.js.map → board-dashboard-GBEBQUFJ.js.map} +0 -0
  78. /package/dist/{chunk-7V73QTQ7.js.map → chunk-2BEZU5OF.js.map} +0 -0
  79. /package/dist/{chunk-VVX4RXMV.js.map → chunk-7KAQHNLT.js.map} +0 -0
  80. /package/dist/{chunk-6AUWEL6V.js.map → chunk-ANDEMOYE.js.map} +0 -0
  81. /package/dist/{chunk-TFH6S7IT.js.map → chunk-AXHP6TMT.js.map} +0 -0
  82. /package/dist/{chunk-375MXG3H.js.map → chunk-B65EC44C.js.map} +0 -0
  83. /package/dist/{chunk-AGQYUOZY.js.map → chunk-EJIY45FZ.js.map} +0 -0
  84. /package/dist/{chunk-AP4DADXG.js.map → chunk-HGU5B7IY.js.map} +0 -0
  85. /package/dist/{chunk-SK47VJMQ.js.map → chunk-HXLB2XCT.js.map} +0 -0
  86. /package/dist/{chunk-XBARUCG5.js.map → chunk-IMUTN7PT.js.map} +0 -0
  87. /package/dist/{chunk-LA6P3TUK.js.map → chunk-J7U3BASX.js.map} +0 -0
  88. /package/dist/{chunk-ADYTED3R.js.map → chunk-JBYLG3CQ.js.map} +0 -0
  89. /package/dist/{chunk-QGSUENRK.js.map → chunk-JJZVFDG6.js.map} +0 -0
  90. /package/dist/{chunk-DBJUGKX2.js.map → chunk-JS2LEURJ.js.map} +0 -0
  91. /package/dist/{chunk-BKSWOMAM.js.map → chunk-KO6BU3B3.js.map} +0 -0
  92. /package/dist/{chunk-MTDVAO5C.js.map → chunk-LMZCB7TT.js.map} +0 -0
  93. /package/dist/{chunk-AOV5RMFH.js.map → chunk-MUC7MMTT.js.map} +0 -0
  94. /package/dist/{chunk-JIJDBCV7.js.map → chunk-NMYPZR4W.js.map} +0 -0
  95. /package/dist/{chunk-EGPCEQJN.js.map → chunk-NQGLKWDO.js.map} +0 -0
  96. /package/dist/{chunk-Y7IHOQC7.js.map → chunk-O6WW7ATO.js.map} +0 -0
  97. /package/dist/{chunk-UPQTTOVQ.js.map → chunk-QN2OTBVC.js.map} +0 -0
  98. /package/dist/{chunk-6XMISPQD.js.map → chunk-RIYQNADV.js.map} +0 -0
  99. /package/dist/{chunk-XVYIPVSC.js.map → chunk-STIZFWDJ.js.map} +0 -0
  100. /package/dist/{chunk-HQH44RGL.js.map → chunk-XQVL2RYG.js.map} +0 -0
  101. /package/dist/{chunk-6VP2KMUM.js.map → chunk-Z5IHT6RK.js.map} +0 -0
  102. /package/dist/{client-EB55Y6EJ.js.map → client-2KZWK6YT.js.map} +0 -0
  103. /package/dist/{config-7DRUA5R3.js.map → config-THFRJMZD.js.map} +0 -0
  104. /package/dist/{config-mutate-GGA7VXXH.js.map → config-mutate-HXWAXWHC.js.map} +0 -0
  105. /package/dist/{config-mutator-POFVILXH.js.map → config-mutator-JZOAWRBH.js.map} +0 -0
  106. /package/dist/{contributions-TZ26MTML.js.map → contributions-OSIKL25B.js.map} +0 -0
  107. /package/dist/{doctor-GTRZ7GWF.js.map → doctor-TOSA3RWP.js.map} +0 -0
  108. /package/dist/{follow-up-tool-PNB7KMCY.js.map → follow-up-tool-M2KCLRQQ.js.map} +0 -0
  109. /package/dist/{hub-QWJR4E6V.js.map → hub-XGWCWKMT.js.map} +0 -0
  110. /package/dist/{promote-HAPXWGYH.js.map → promote-YVWRKIAU.js.map} +0 -0
  111. /package/dist/{query-ICLOVLZ3.js.map → query-X4AFOKZ7.js.map} +0 -0
  112. /package/dist/{query-settings-7AXUOHDL.js.map → query-settings-HV2RFQK7.js.map} +0 -0
  113. /package/dist/{registry-RH5NFDL7.js.map → registry-B276QJ75.js.map} +0 -0
  114. /package/dist/{request-planner-TDCLF2CH.js.map → request-planner-MY6VKTVC.js.map} +0 -0
  115. /package/dist/{review-candidates-QCBXLWG6.js.map → review-candidates-BRTBB5XV.js.map} +0 -0
  116. /package/dist/{routing-YUP3HHL5.js.map → routing-CSVLOGNS.js.map} +0 -0
  117. /package/dist/{schedule-tool-3C22NBMN.js.map → schedule-tool-GUKYTQTY.js.map} +0 -0
  118. /package/dist/{scheduler-7NK2FH5V.js.map → scheduler-OUAVAU4O.js.map} +0 -0
  119. /package/dist/{seat-PTPPQOTP.js.map → seat-H2QR3CRX.js.map} +0 -0
  120. /package/dist/{select-2XSTWMBR.js.map → select-EEL5AZ2I.js.map} +0 -0
  121. /package/dist/{set-enabled-SS5Q3OX7.js.map → set-enabled-IBGEH6U6.js.map} +0 -0
  122. /package/dist/{tool-QCMSXEDB.js.map → tool-DFPOFXGA.js.map} +0 -0
  123. /package/dist/{tool-RK4LDFFH.js.map → tool-GJ75MWV5.js.map} +0 -0
  124. /package/dist/{wiki-Q2E44YAE.js.map → wiki-ISKHNG3P.js.map} +0 -0
  125. /package/dist/{wiki-enrich-6ULCDOTX.js.map → wiki-enrich-7SBCPK2E.js.map} +0 -0
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-RH5NFDL7.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-B276QJ75.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-AOV5RMFH.js.map
126
+ //# sourceMappingURL=chunk-MUC7MMTT.js.map
@@ -1,5 +1,5 @@
1
- import{Aa as x,qa as m,ra as $}from"./chunk-HJCFLGVT.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
1
+ import{Aa as x,qa as m,ra as $}from"./chunk-MGM33GOW.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
4
4
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{w as a,J as b,N as c,j as d,A as e};
5
- //# sourceMappingURL=chunk-JIJDBCV7.js.map
5
+ //# sourceMappingURL=chunk-NMYPZR4W.js.map
@@ -1,4 +1,4 @@
1
- import{c as w}from"./chunk-375MXG3H.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
1
+ import{c as w}from"./chunk-B65EC44C.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
2
2
  ${a.content}`),t.previous??""].join(`
3
3
  `),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
4
4
  `).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
33
33
  {"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
34
34
  `)+`
35
35
  `}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
36
- //# sourceMappingURL=chunk-EGPCEQJN.js.map
36
+ //# sourceMappingURL=chunk-NQGLKWDO.js.map
@@ -1,6 +1,6 @@
1
- import{d as h}from"./chunk-375MXG3H.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
1
+ import{d as h}from"./chunk-B65EC44C.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
2
2
  `),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
3
3
  `).filter(o=>o.trim()).length,a=c.split(`
4
4
  `).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
5
5
  `))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
6
- //# sourceMappingURL=chunk-Y7IHOQC7.js.map
6
+ //# sourceMappingURL=chunk-O6WW7ATO.js.map
@@ -1,5 +1,5 @@
1
- import{Aa as b,sa as m}from"./chunk-HJCFLGVT.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
1
+ import{Aa as b,sa as m}from"./chunk-MGM33GOW.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
2
2
 
3
3
  `))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
4
4
  `))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
5
- //# sourceMappingURL=chunk-UPQTTOVQ.js.map
5
+ //# sourceMappingURL=chunk-QN2OTBVC.js.map
@@ -1,4 +1,4 @@
1
- import{$ as $r,H as mr,I as hr,J as yr,L as wr,M as br,N as xr,O as Ir,R as Sr,S as Tr,V as kr,W as vr,a as Zs,b as er,ba as Ar,d as nr,f as ze,l as kt,m as pr,t as vt,v as fr}from"./chunk-7V73QTQ7.js";import{a as Vs}from"./chunk-QSKG754X.js";import{b as tr}from"./chunk-MEFPXHQJ.js";import{a as gr}from"./chunk-W4YR2RO2.js";import{b as rr,c as pn,d as ir,e as Tt,h as ar}from"./chunk-DBJUGKX2.js";import{e as Xs,f as Ys}from"./chunk-36AXN6ZB.js";import{a as ln,b as sr}from"./chunk-J3SOEFRE.js";import{a as gn,b as or}from"./chunk-SIU6STB2.js";import{e as dr,i as cr,j as ur,k as lr}from"./chunk-X5C5W3E4.js";import{a as zs}from"./chunk-TFH6S7IT.js";import{g as Js,h as Qs}from"./chunk-VVX4RXMV.js";import{c as Ns,f as Ls}from"./chunk-QGSUENRK.js";import{s as Ds,v as St,w as Os,y as ye,z as un}from"./chunk-MTDVAO5C.js";import{a as Qe,b as Ee,f as It}from"./chunk-72SZI2UW.js";import{a as _e,b as rn}from"./chunk-FCPTN6NF.js";import{a as Fs,c as Us}from"./chunk-MYVHVJWZ.js";import{d as De,h as Ae}from"./chunk-6TURWSMN.js";import{a as Hs,b as Bs,c as js,d as Ws,l as qs}from"./chunk-AV7T3SYT.js";import{a as Gs,b as Ks}from"./chunk-Y5MFVVTM.js";import{c as Ss,d as Ts}from"./chunk-QOYAX2FT.js";import{e as $e}from"./chunk-DSYKYZMT.js";import{$ as Rs,Aa as $a,G as As,I as dn,K as ka,N as Cs,R as va,X as Ms,Y as cn,Z as Ps,_ as Je,aa as _s,ga as Es}from"./chunk-HJCFLGVT.js";import{g as Ke,h as Sa}from"./chunk-BRK6M6LA.js";import{f as an,n as Ta}from"./chunk-UIBUZ2N3.js";import{a as ks,b as le,c as vs,d as $s,e as on}from"./chunk-2QNT5JDS.js";un();It();var $t="tool-set",Cr=["answer","code","full"],Mr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Aa=.1;function Rr(n){return{task:Pr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Pr(n.agentPrompt,600)}:{}}}var _r={bundle:Ee({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Er(n,e=Aa){let s=n?.bundle?.probabilities;if(!s)return"full";let r=fn(s.answer),o=fn(s.code),i=fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Dr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Mr.answer.includes(t))?"answer":e.every(t=>Mr.code.includes(t))?"code":"full"}function Or(n,e){return Cr.indexOf(n)<Cr.indexOf(e)}function fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Pr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Nr=!1;function Lr(n,e){let t=St($t);if(t!=="off")return t==="active"&&!Nr&&(Nr=!0,e(`[decisions] seat "${$t}" is set to active, but only shadow is built: it records and changes nothing`)),ye($t,Rr(n),_r,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Er(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Fr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Dr(r);Os(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Or(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Ca(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Ur(n,e){let t=Ca(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function mn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}un();It();var Hr="session-continuity",Br={continues:Qe("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Qe("Does the new request refer to something stated earlier in the conversation?")};function jr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:hn(n.message,1200),previousRequest:n.previousMessage?hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Wr(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ot}from"execa";import{spawn as Ma}from"node:child_process";import{createHash as Pa}from"node:crypto";import{createInterface as Ra}from"node:readline";var we=class extends Error{},_a=n=>Ma("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),yn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Ra({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
1
+ import{$ as $r,H as mr,I as hr,J as yr,L as wr,M as br,N as xr,O as Ir,R as Sr,S as Tr,V as kr,W as vr,a as Zs,b as er,ba as Ar,d as nr,f as ze,l as kt,m as pr,t as vt,v as fr}from"./chunk-2BEZU5OF.js";import{a as Vs}from"./chunk-QSKG754X.js";import{b as tr}from"./chunk-MEFPXHQJ.js";import{a as gr}from"./chunk-W4YR2RO2.js";import{b as rr,c as pn,d as ir,e as Tt,h as ar}from"./chunk-JS2LEURJ.js";import{e as Xs,f as Ys}from"./chunk-36AXN6ZB.js";import{a as ln,b as sr}from"./chunk-J3SOEFRE.js";import{a as gn,b as or}from"./chunk-SIU6STB2.js";import{e as dr,i as cr,j as ur,k as lr}from"./chunk-X5C5W3E4.js";import{a as zs}from"./chunk-AXHP6TMT.js";import{g as Js,h as Qs}from"./chunk-7KAQHNLT.js";import{c as Ns,f as Ls}from"./chunk-JJZVFDG6.js";import{s as Ds,v as St,w as Os,y as ye,z as un}from"./chunk-LMZCB7TT.js";import{a as Qe,b as Ee,f as It}from"./chunk-72SZI2UW.js";import{a as _e,b as rn}from"./chunk-FCPTN6NF.js";import{a as Fs,c as Us}from"./chunk-MYVHVJWZ.js";import{d as De,h as Ae}from"./chunk-6TURWSMN.js";import{a as Hs,b as Bs,c as js,d as Ws,l as qs}from"./chunk-AV7T3SYT.js";import{a as Gs,b as Ks}from"./chunk-Y5MFVVTM.js";import{c as Ss,d as Ts}from"./chunk-QOYAX2FT.js";import{e as $e}from"./chunk-DSYKYZMT.js";import{$ as Rs,Aa as $a,G as As,I as dn,K as ka,N as Cs,R as va,X as Ms,Y as cn,Z as Ps,_ as Je,aa as _s,ga as Es}from"./chunk-MGM33GOW.js";import{g as Ke,h as Sa}from"./chunk-BRK6M6LA.js";import{f as an,n as Ta}from"./chunk-UIBUZ2N3.js";import{a as ks,b as le,c as vs,d as $s,e as on}from"./chunk-2QNT5JDS.js";un();It();var $t="tool-set",Cr=["answer","code","full"],Mr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Aa=.1;function Rr(n){return{task:Pr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Pr(n.agentPrompt,600)}:{}}}var _r={bundle:Ee({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Er(n,e=Aa){let s=n?.bundle?.probabilities;if(!s)return"full";let r=fn(s.answer),o=fn(s.code),i=fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Dr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Mr.answer.includes(t))?"answer":e.every(t=>Mr.code.includes(t))?"code":"full"}function Or(n,e){return Cr.indexOf(n)<Cr.indexOf(e)}function fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Pr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Nr=!1;function Lr(n,e){let t=St($t);if(t!=="off")return t==="active"&&!Nr&&(Nr=!0,e(`[decisions] seat "${$t}" is set to active, but only shadow is built: it records and changes nothing`)),ye($t,Rr(n),_r,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Er(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Fr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Dr(r);Os(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Or(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Ca(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Ur(n,e){let t=Ca(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function mn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}un();It();var Hr="session-continuity",Br={continues:Qe("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Qe("Does the new request refer to something stated earlier in the conversation?")};function jr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:hn(n.message,1200),previousRequest:n.previousMessage?hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Wr(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ot}from"execa";import{spawn as Ma}from"node:child_process";import{createHash as Pa}from"node:crypto";import{createInterface as Ra}from"node:readline";var we=class extends Error{},_a=n=>Ma("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),yn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Ra({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
2
2
  `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},wn=class{constructor(e=_a,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=Pa("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[P])=>w.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new we("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let w=[...this.entries].find(([,P])=>!P.connection.busy);if(!w)throw new we("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:s,connection:new yn(e,this.launchProcess)}}catch{throw new we("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,g,m,h=!1,p=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",p,{once:!0});let x=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),S=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let w={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(S),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let R=new Promise((L,M)=>{i.failTurn=M,i.notify=(D,U)=>{if(U?.threadId!==u)return;let N=U.item,q={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...U,type:D.replace("/","."),...N?{item:{...N,type:q[N.type]||N.type}}:{}}),D==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),D==="item/agentMessage/delta"&&(h||(h=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=U.delta,e.onDelta?.(U.delta,c)),D==="thread/tokenUsage/updated"){let H=U.tokenUsage.last;m=H.inputTokens;let K=H.cachedInputTokens||0;g={inputTokens:(g?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-K),outputTokens:(g?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(g?.cacheReadTokens||0)+K,cacheCreateTokens:(g?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}D==="turn/completed"&&(U.turn.status==="completed"?L():M(new Error(U.turn.error?.message||`Codex turn ${U.turn.status}`)))}});return R.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await R,{content:d??c,codexSessionId:u,billedModel:e.model,usage:g,contextTokens:m,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new we(w.message);return{content:c,codexSessionId:u,usage:g,contextTokens:m,error:w.message,duration:Date.now()-t}}finally{clearTimeout(S),clearTimeout(x),e.signal?.removeEventListener("abort",p),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},qr=new wn;import{execFile as Za}from"child_process";import{StringDecoder as et}from"string_decoder";import{mkdtempSync as co,readFileSync as uo,rmSync as lo}from"fs";import{join as Et}from"path";import{tmpdir as go}from"os";function At(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Ct(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Mt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var Gr=null;function Pt(){return Gr}function fl(n){Gr=n}function Xe(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Ea(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Oe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},Kr=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=Xe(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Ea(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new Oe(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new Oe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Xe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Xe(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Xe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<s&&(s=i,t=o)}if(!t)return!1;let r=Xe(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(s.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Da}from"child_process";import{randomUUID as Oa}from"crypto";import{existsSync as Na,readFileSync as La}from"fs";import{resolve as Fa}from"path";function Ua(n){let e=Fa(n,"CLAUDE.md");if(!Na(e))return null;try{let t=La(e,"utf8");return qs(t)}catch{return null}}var Ha=20*60*1e3,Ba=5e3,Ye=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ve=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function ja(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var Jr=class{constructor(e={}){this.opts=e}spawn(e,t){return new bn(e,t,this.opts)}},bn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=Da(r,o,{cwd:t.workspace,env:Ae(ja({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:Ua(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(h=>{t=h}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=Oa(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
3
  `);let c=e.deadlineMs??Ha,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new Ye(c)),g=!1,m=null;try{for(;;){let h=d-Date.now();if(h<=0)throw u();let p=await this.nextEvent(h);if(p===null&&this.killReason)throw new Ve(this.killReason);if(p===null&&!this.exited)throw u();if(p===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!g){if(p.type==="user"&&p.uuid===i)g=!0,m&&(yield{type:m.type,raw:m});else if(p.type==="system"&&p.subtype==="init")m=p;else if(p.type==="result"){m=null;let x=typeof p.result=="string"?p.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${x.length} chars): ${x.slice(0,120)}`)}continue}if(yield{type:p.type,raw:p},p.type==="result"){this.onResultEvent(p);return}}}finally{let h=this.snap.state==="busy";this.snap={...this.snap,...h?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ba);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
4
  `))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};on();Ta();rn();import{resolve as Qr,join as zr}from"path";var Wa=4e3;function Rt(n){try{let e=zr(Qr(n.root),".agentx","db.sqlite"),t=an({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=_e(),r=n.input.command?n.input.command.slice(0,Wa):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -31,7 +31,7 @@ ${n}`}function td(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
31
31
  `,g)}};L.stdout?.on("data",T=>{N+=H.write(T);let b=N.split(`
32
32
  `);N=b.pop()||"";for(let O of b)X(O)}),L.stderr?.on("data",T=>{q+=K.write(T)});let A=await L;if(i&&i.removeEventListener("abort",U),N+=H.end(),N.trim()&&X(N),q+=K.end(),M)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(A.exitCode!==0||p){let T=A,b;return T.timedOut?b=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?b=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+q)?b=oo():b=q.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...V(b),duration:Date.now()-c,usage:m,opencodeSessionId:h}}return S=!1,{content:g.trim(),duration:Date.now()-c,usage:m,billedModel:e.model||n.model,opencodeSessionId:h}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let R=/ENOENT|spawn opencode/i.test(P?.message||"")?oo():P?.message;return{content:g,...V(R||"OpenCode failed"),duration:Date.now()-c,usage:m,opencodeSessionId:h}}finally{w?.(),x?.release(S)}}async function gd(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=xe(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function pd(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),g=new AbortController,m=!1,h=()=>{let S=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{g.abort(new Error(S))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{m=!0;try{g.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let x=()=>({content:"",...V(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let S=n.provider||"claude-code",w=s?`${s}
33
33
 
34
- ${e.message}`:e.message,P=e.context?.sender,R=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),L=e.context?.channel==="web-chat"&&R?{userId:P,agentId:e.agentId||"acme-public"}:void 0,M=Ws(n),D=Object.keys(M).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:L,providerOpts:o,abortSignal:g.signal,mcpServers:D?M:void 0};if(r){let{generateStream:X}=await import("./agent-BLRZVUG4.js"),A="",T,b,O,B;for await(let C of X(U)){if(c)try{c(C)}catch{}if(C.type==="text_delta")A+=C.text,r(C.text,A);else if(C.type==="thinking_delta")C.text&&i&&i(C.text);else if(C.type==="generate_result"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}T=C.result.tokensUsed,C.result.inputTokens!=null&&(b=C.result.inputTokens),C.result.outputTokens!=null&&(O=C.result.outputTokens)}else if(C.type==="done"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}C.result.tokensUsed!=null&&(T=C.result.tokensUsed)}else C.type==="error"&&(B=C.error)}return B&&!A?m?x():B==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${B}`),duration:Date.now()-d}:((b===void 0||O===void 0)&&T&&(b=Math.round(T*.7),O=T-b),{content:A||"Done.",tokensUsed:T,usage:b!==void 0||O!==void 0?{inputTokens:b||0,outputTokens:O||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:N}=await import("./agent-BLRZVUG4.js"),q=await N(U),H=q.inputTokens,K=q.outputTokens;if((H===void 0||K===void 0)&&q.tokensUsed){let X=q.tokensUsed;H=Math.round(X*.7),K=X-H}return{content:q.content||"Done.",tokensUsed:q.tokensUsed,usage:H!==void 0||K!==void 0?{inputTokens:H||0,outputTokens:K||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(S){return m?x():S?.message==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var In=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},fd=1e3;async function md(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),fd),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function hd(n,e,t,s,r,o,i){let a=Pt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Lt(e.context),g={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(g,"freshSession=true")}catch{}let m,h=!1;try{let A=a.list().length;m=a.acquire(g,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>A}catch(A){return A instanceof Oe,null}h&&vn(e.agentId,n,e.model,s,"persistent");let p=xe(n,e,t),x="",S,w,P,R,L,M,D,U="",N="",q=A=>{if(!i||!A)return;let T;if(N&&A.startsWith(N)?T=A.slice(N.length):T=U&&!U.endsWith(`
34
+ ${e.message}`:e.message,P=e.context?.sender,R=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),L=e.context?.channel==="web-chat"&&R?{userId:P,agentId:e.agentId||"acme-public"}:void 0,M=Ws(n),D=Object.keys(M).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:L,providerOpts:o,abortSignal:g.signal,mcpServers:D?M:void 0};if(r){let{generateStream:X}=await import("./agent-PRHZGF6J.js"),A="",T,b,O,B;for await(let C of X(U)){if(c)try{c(C)}catch{}if(C.type==="text_delta")A+=C.text,r(C.text,A);else if(C.type==="thinking_delta")C.text&&i&&i(C.text);else if(C.type==="generate_result"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}T=C.result.tokensUsed,C.result.inputTokens!=null&&(b=C.result.inputTokens),C.result.outputTokens!=null&&(O=C.result.outputTokens)}else if(C.type==="done"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}C.result.tokensUsed!=null&&(T=C.result.tokensUsed)}else C.type==="error"&&(B=C.error)}return B&&!A?m?x():B==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${B}`),duration:Date.now()-d}:((b===void 0||O===void 0)&&T&&(b=Math.round(T*.7),O=T-b),{content:A||"Done.",tokensUsed:T,usage:b!==void 0||O!==void 0?{inputTokens:b||0,outputTokens:O||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:N}=await import("./agent-PRHZGF6J.js"),q=await N(U),H=q.inputTokens,K=q.outputTokens;if((H===void 0||K===void 0)&&q.tokensUsed){let X=q.tokensUsed;H=Math.round(X*.7),K=X-H}return{content:q.content||"Done.",tokensUsed:q.tokensUsed,usage:H!==void 0||K!==void 0?{inputTokens:H||0,outputTokens:K||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(S){return m?x():S?.message==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var In=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},fd=1e3;async function md(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),fd),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function hd(n,e,t,s,r,o,i){let a=Pt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Lt(e.context),g={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(g,"freshSession=true")}catch{}let m,h=!1;try{let A=a.list().length;m=a.acquire(g,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>A}catch(A){return A instanceof Oe,null}h&&vn(e.agentId,n,e.model,s,"persistent");let p=xe(n,e,t),x="",S,w,P,R,L,M,D,U="",N="",q=A=>{if(!i||!A)return;let T;if(N&&A.startsWith(N)?T=A.slice(N.length):T=U&&!U.endsWith(`
35
35
  `)?`
36
36
 
37
37
  ${A}`:A,N=A,!!T){U+=T;try{i(T,U)}catch{}}},H=!1,K=()=>{H=!0,a.kill(g,"operator-cancel").catch(()=>{})};o&&(o.aborted?K():o.addEventListener("abort",K,{once:!0}));let X=!1;try{let A=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of m.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:A})){if(X=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let b=T.raw.message?.content??[];for(let B of b)B.type==="text"&&typeof B.text=="string"?(x=B.text,q(B.text)):B.type==="tool_use"&&(N="");let O=T.raw.message?.usage;if(O){let B=(O.input_tokens||0)+(O.cache_read_input_tokens||0)+(O.cache_creation_input_tokens||0);B>0&&(R=B)}}if(T.type==="result"){let b=T.raw;if(b.is_error){let O=V(typeof b.result=="string"?b.result:"claude error");S=O.error,w=O.errorKind}else typeof b.result=="string"&&b.result.length>0&&(x=b.result,U||q(b.result));typeof b.session_id=="string"&&(D=b.session_id),b.usage&&(P={inputTokens:b.usage.input_tokens||0,outputTokens:b.usage.output_tokens||0,cacheReadTokens:b.usage.cache_read_input_tokens||0,cacheCreateTokens:b.usage.cache_creation_input_tokens||0}),typeof b.num_turns=="number"&&(L=b.num_turns),typeof b.message?.model=="string"?M=b.message.model:typeof b.model=="string"?M=b.model:M=Mt(b.modelUsage)||M}}}catch(A){if(H)S="task cancelled by operator",w="cancelled";else if(X)if(A instanceof Ve)S=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,w="interrupted";else if(A instanceof Ye){let T=V(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);S=T.error,w=T.errorKind}else{let T=V(`persistent claude process error: ${A?.message||String(A)}`);S=T.error,w=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(g,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",K),null}finally{o&&o.removeEventListener("abort",K)}return H&&!S&&(S="task cancelled by operator",w="cancelled"),{content:H?"":x,error:S,errorKind:w,duration:Date.now()-c,usage:P,contextTokens:R,numTurns:L,billedModel:M,claudeSessionId:D}}function Io(n){let e=le(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?Vr(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:so(t.args,n.taskId,n.agentId)}function yd(n){return le(n.autonomy)||!!n.personLimits}async function wd(n,e,t,s,r,o,i){let a=le(e.autonomy)?e.autonomy:void 0,c=a&&Zr(a,n.tier)||e.personLimits&&ro(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${$s(a)}
@@ -138,7 +138,7 @@ ${Hu}`:n==="codex-cli"?qi:""}function Gi(n,e){return e!=="claude-code"&&e!=="cod
138
138
  `)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new Kt(Q(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...Jt,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=qn(t.context?.chatId),a=this.cloudSessionStore();return Hi({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...Jt,...e.cloudSessions??{}},i=Date.now(),a=Ae(tt(De(e.workspace),t),e.billing),c=await Wi({route:s,agentId:t.agentId,message:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d=>ji({...d,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),log:d=>this.log(d),trace:d=>{try{Z().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:d.action,status:d.status,outputSummary:d.status==="ok"?d.summary:void 0,error:d.status==="error"?d.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});return c?{content:c.content,error:c.error,cloudSession:c.cloudSession,duration:Date.now()-i}:null}callerGone(e,t){let s=Re(e.callerSignal).message;return this.log(`[${e.agentId}] caller gone during ${t} \u2014 not starting (${s})`),{content:"",error:`Caller gone before agent "${e.agentId}" was free \u2014 not started`}}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(u){i={content:"",error:u?.message??String(u)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"});let c=!a&&e.runningTaskId?this.stoppedRuns.get(e.runningTaskId):void 0;c&&(this.stoppedRuns.delete(e.runningTaskId),i={...i,content:"",error:c,errorKind:"stopped"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&!c&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,s,r);if(d){let u=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${u}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let u=i.error?ze(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";rr().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:u,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(u){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${u?.message??u}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=le(e.autonomy),a=Rs(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:Bo().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(c){let l=await c;if(l.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${l.sessionId}`),{content:l.text,viaAttachedSession:l.sessionId};this.log(`[${e.agentId}] attached session did not take it (${l.reason}) \u2014 spawning`)}let d=this.agents.get(e.agentId);if(!d){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let l=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(v=>v.id===e.agentId));if(l){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${l.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(l.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:l.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${l.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:g}=Lt(e.context),m;if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||i){let l=Date.now(),f=25*6e4,v=500;for(;d.activeTasks>=d.def.maxConcurrent;){if(e.callerSignal?.aborted)return this.callerGone(e,"slot wait");if(Date.now()-l>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(k=>setTimeout(k,v))}}else if(u==="voice"){let l=Date.now(),f=25*6e4,v=`${e.agentId}\0${g}`;for(;this.messageQueue.isBusy(e.agentId,u,g)||this.voiceClaims.has(v);){if(Date.now()-l>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(k=>setTimeout(k,500))}m=v,this.voiceClaims.add(v)}else{let l=d.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,u,g,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:g,originalContext:e.context,queuedAt:e.queuedAt});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let v=this.messageQueue.pendingCount(e.agentId,u,g);return Z().emit("task:queued",{agentId:e.agentId,channel:u,chatId:g,at:new Date().toISOString(),sender:dn(e.context),humanRoot:Ke(e.context),person:cn(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${v}) behind=${d.runningTasks.map(k=>k.id).join(",")||"-"} chat=${u}:${g} at=${new Date().toISOString()}`),{content:"",error:nr(f,v)}}}let h=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(l,f)=>{this.log(`[${e.agentId}] ${l} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(m&&this.voiceClaims.delete(m),!h.ok)return this.log(`[${e.agentId}] ${h.reason}`),{content:"",error:h.reason};if(e.callerSignal?.aborted)return this.callerGone(e,"rate-limit wait");if(e.queuedAt!==void 0){let l=_o(e.queuedAt);l&&(e.message=`${l}
139
139
  ${e.message}`),e.queuedAt=void 0}d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let p={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(p),e.runningTaskId=p.id;let x=cn(this.config.people,e.context);if(e.context&&(x?e.context.person=x.id:delete e.context.person),this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let S=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:S,sender:e.context?.sender,rootId:Tt()?.rootId,workflowRunId:e.workflowRunId??(typeof p.chatId=="string"&&p.chatId.startsWith("workflow:")&&p.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let w={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,w);let P=l=>{if(l){w.buffer+=l,w.buffer.length>Ki&&(w.buffer=w.buffer.slice(w.buffer.length-Ki));for(let f of w.subscribers)try{f(l)}catch{}}},R=_e();e.taskId=R,p.traceId=R;let L=this.taskAborts.get(p.id);L&&(L.traceId=R);let M=new Map,D=(l,f,v)=>{try{Z().emit("task:step",{taskId:R,agentId:e.agentId,name:"pipeline",action:l,status:v,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},U=0,N=!1,q=()=>{N||(N=!0,U&&D("first-event",U,"ok"))},H;if(t){let l=Vu();H=f=>{q();let v=l(f);if(v&&P(v),zi(R,e.agentId,f),Qi(M,f),Dn(f,void 0,e.model||d.def.model),r)try{r(f)}catch{}}}else H=l=>{if(q(),zi(R,e.agentId,l),Qi(M,l),Dn(l,void 0,e.model||d.def.model),r)try{r(l)}catch{}};let K=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,X=K?setTimeout(()=>S.abort(new Error(`timed out after ${Math.round(K/1e3)}s`)),K):void 0;X?.unref?.();let A=(d.def.preSpawnTimeoutSec??qu)*1e3,T=setTimeout(()=>{S.abort(new Error(`timed out before spawn after ${Math.round(A/1e3)}s in step "${p.step??"start"}"`))},A);T.unref?.();let b=()=>{T&&clearTimeout(T),T=void 0},O=()=>`task=${p.id} chat=${u}:${g} at=${new Date().toISOString()}`,B;S.signal.addEventListener("abort",()=>{let l=Re(S.signal).message;/^timed out/.test(l)&&(B=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${l} ${O()}`)},{once:!0});let C=l=>{p.step=l,this.log(`[${e.agentId}] step ${l} ${O()}`)},W=(l,f,v=0)=>{if(S.signal.aborted)return Promise.reject(Re(S.signal));C(l),(l==="agent"||l==="workflow-auto-run")&&(b(),U=Date.now());let k=Date.now(),j=Ui(f(),Uu[l]??0,l);return Fi(j,S.signal,v).then(G=>(D(l,k,"ok"),G),G=>{throw D(l,k,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${O()}`),G})},te=async(l,f,v,k=0)=>{try{return await W(l,f,k)}catch(j){if(j instanceof Be)return v();throw j}},ne=!1,_=!1,se=l=>{if(!(!ne||_)){_=!0;try{Z().emit("task:completed",{taskId:R,agentId:e.agentId,channel:u,chatId:g,durationMs:Date.now()-p.startedAt.getTime(),error:l?.error||(S.signal.aborted?Re(S.signal).message:"run ended before completion"),errorKind:l?.errorKind,interrupted:this.interruptedRuns.has(p.id)?!0:void 0,stopped:!this.interruptedRuns.has(p.id)&&(this.stoppedRuns.has(p.id)||l?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ie=!1,Kn=l=>{if(ie)return;ie=!0,se(l),this.runReleases.delete(p.id),X&&clearTimeout(X),b(),d.activeTasks--;let f=d.runningTasks.findIndex(k=>k.id===p.id);f!==-1&&d.runningTasks.splice(f,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id);let v=this.runEndWaiters.get(p.id);this.runEndWaiters.delete(p.id);for(let k of v??[])try{k()}catch{}w.done=!0,w.endedAt=new Date;for(let k of w.subscribers)try{k(`
140
140
  [task finished]
141
- `)}catch{}w.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),ju).unref?.();try{let k=w.endedAt,j={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-p.startedAt.getTime(),ok:!l?.error,error:l?.error,...this.stoppedRuns.has(p.id)||l?.errorKind==="stopped"?{status:"stopped"}:B?{status:"timeout",step:B}:{},responseText:l?.content||"",transcript:w.buffer};this.persistTaskRecord(j);let G=(j.responseText||j.error||"").trim();if(G){let Y=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Y,at:k,ok:j.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,g).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${p.id} chat=${u}:${g} at=${new Date().toISOString()}`);let j=Date.now();Z().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,count:k.length,at:new Date().toISOString()});let G=()=>Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,at:new Date().toISOString()});for(let Y of k){let ve=Y.originalContext||{channel:Y.channel,sender:Y.sender,chatId:Y.chatId};this.execute({message:Y.text,agentId:e.agentId,context:ve,queuedAt:Y.queuedAt??Y.timestamp}).then(fe=>(ze(fe.error)||G(),this.postQueuedResponseToChannel(e.agentId,ve,fe)),fe=>{throw G(),fe}).catch(fe=>{this.log(`[${e.agentId}] queued message failed: ${fe.message}`)})}}).catch(k=>{Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(p.id,Kn),this.messageQueue.markRunning(e.agentId,u,g),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${O()}`);let y=e.context?.channel||"api",{evaluateRequest:Vi,selectRequestContext:Zi}=await import("./request-planner-TDCLF2CH.js"),Jn=te("request-gate",()=>Vi(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Qt=!1;Jn.then(()=>{Qt=!0},()=>{Qt=!0});let I=g,zt=e.context?.sender||"User",ce=d.def.tier==="codex-cli",We=li(this.config.session,y,d.def.tier),dt=gi(this.config.session),qe=We==="lean"&&dt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${I}`),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}));let ct=this.sessions.sessionIdleMs(e.agentId,y,I);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,I,e.seedHistory),()=>{});let ea=[...this.sessions.getSession(e.agentId,y,I).messages].reverse().find(l=>l.role==="agent")?.content;Li({agent:e.agentId,channel:y,chatId:I,message:e.message,previousReply:ea,taskId:R}),this.sessions.addUserMessage(e.agentId,y,I,zt,e.message);let Qn=Date.now();Z().emit("task:started",{agentId:e.agentId,channel:y,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Qn).toISOString(),taskId:R,resumeOrigin:Po(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:dn(e.context),...x?{person:x}:{},humanRoot:Ke(e.context),pickup:As(e.context),operator:Cs(e.context)}),ne=!0;let ee,Xt,zn=this.classifier;if(zn&&y!=="a2a"&&!ce){C("classify");let l=Date.now();Xt=zn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{ee=f||void 0,ee?.path?.length&&(p.intentPath=ee.path.slice()),D("classify",l,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),D("classify",l,"error")})}let Xn=async l=>{if(!Xt)return;let f;await Promise.race([Xt,new Promise(v=>{f=setTimeout(v,l),f.unref?.()})]),f&&clearTimeout(f)};await Xn(Eu);let Se=this.config.workflows?.matching,pe,Yn,Vn=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Vn?.enabled&&(Vn.agents[e.agentId]??!0)&&!i&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=(Se?.suggestThreshold??.65)&&(Yn=fr(f.workflow))}catch(l){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${l?.message||l}`)}if(this.config.workflows?.enabled&&Se?.enabled&&!i)try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=Se.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Se.mode} reasons=${f.reasons.join(",")||"n/a"}`),Se.mode==="auto"&&f.confidence>=Se.autoRunThreshold&&(this.workflowAutoRunner?pe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(l){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${l?.message||l}`)}let Te=mr(this.config.workflows,e.agentId)&&hr(e)?this.workflowRuns:void 0;if(Te&&!pe&&!i&&this.workflowAutoRunner&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list()),v=Se?.autoRunThreshold??.85;f&&f.confidence>=v&&(pe={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(l){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${l?.message||l}`)}let ae=Te?Fu():void 0,ta=ae?yr(ae):void 0,na=this.wikiHub.getAgentWiki(e.agentId),Zn=this.memoryStore.findRelevant(e.message,e.agentId,ce?3:8),es=this.memoryStore.buildContext(Zn),ts=this.memoryStore.contextFacts(Zn),sa=this.patternStore.findRelevant(e.message,e.agentId,5),ra=this.patternStore.buildContext(sa),ns="";if(!ce)try{let{loadLocalSkills:l,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),v=await W("skills",()=>l(d.def.workspace)),k=e.personLimits?.skills??[],j=k.length?v.filter(G=>!k.some(Y=>Je(Y,G.frontmatter.name))):v;ns=f(j,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,I):void 0;if(F&&this.sessions.isSessionStale(e.agentId,y,I,ct)&&(this.log(`[${e.agentId}] session stale for ${y}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,y,I)){let l=this.sessions.getLastTurnContextTokens(e.agentId,y,I);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${I} (last turn context: ${l} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"tier-2",lastTurnInputTokens:l,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,y,I)){let l=this.sessions.getTurnCount(e.agentId,y,I);this.log(`[${e.agentId}] max-turns rotation for ${y}:${I} (${l} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let l=this.config.session?.resumeGate;if(l&&l.mode!=="off"){let f=Ur({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,I),idleMs:ct??0},l);if(f.rotate&&l.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${I}: ${mn(f)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"cost");let v=this.sessions.getLastTurnInputTokens(e.agentId,y,I);this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"cost",lastTurnInputTokens:v,at:new Date().toISOString()}),F=void 0}else l.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${I}: would ${mn(f)}`)}}if(F&&d.def.tier==="claude-code"){let l=F;await te("rotate",()=>this.maybeRotateForContinuity(e,d,y,I,l),()=>!1)&&(F=void 0)}try{let l=await W("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,I,this.memoryStore));if(l.compacted){let f=l.qualityScore??"?",v=l.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${I} (quality: ${f}%, ${v} entities lost)`),l.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${l.lostEntities.slice(0,5).join(", ")}`),l.drift){let k=l.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(l){this.log(`[${e.agentId}] compaction failed (non-fatal): ${l.message}`)}let oa=process.env.AGENTX_CONTEXT_SURGERY==="1",ia=ce?{maxMessages:8,maxChars:2400}:oa&&Gi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,aa=!F&&!ce?zu(na,e.agentId,{notesInbox:Qu(this.config)}):void 0,ut=!F&&!qe?this.sessions.buildHistoryContext(e.agentId,y,I,ia):void 0,da=F?void 0:this.sessions.getRotationMemo(e.agentId,y,I)??void 0,ss,rs=[];if(this.config.procedures?.injection?.enabled&&!F&&!ce)try{let l=new ot({baseDir:Q(process.cwd(),this.config.procedures.dir)}),f=Fn(e.message,l.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){ss=Un(f),rs=f.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of f)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(l){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${l?.message||l}`)}if($e&&$e.cat)try{let f=this.sessions.getSession(e.agentId,y,I).messages,v=f[0],k=f[f.length-1],j=ut===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${ut.length}c/${ut.split(`
141
+ `)}catch{}w.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),ju).unref?.();try{let k=w.endedAt,j={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-p.startedAt.getTime(),ok:!l?.error,error:l?.error,...this.stoppedRuns.has(p.id)||l?.errorKind==="stopped"?{status:"stopped"}:B?{status:"timeout",step:B}:{},responseText:l?.content||"",transcript:w.buffer};this.persistTaskRecord(j);let G=(j.responseText||j.error||"").trim();if(G){let Y=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Y,at:k,ok:j.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,g).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${p.id} chat=${u}:${g} at=${new Date().toISOString()}`);let j=Date.now();Z().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,count:k.length,at:new Date().toISOString()});let G=()=>Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,at:new Date().toISOString()});for(let Y of k){let ve=Y.originalContext||{channel:Y.channel,sender:Y.sender,chatId:Y.chatId};this.execute({message:Y.text,agentId:e.agentId,context:ve,queuedAt:Y.queuedAt??Y.timestamp}).then(fe=>(ze(fe.error)||G(),this.postQueuedResponseToChannel(e.agentId,ve,fe)),fe=>{throw G(),fe}).catch(fe=>{this.log(`[${e.agentId}] queued message failed: ${fe.message}`)})}}).catch(k=>{Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(p.id,Kn),this.messageQueue.markRunning(e.agentId,u,g),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${O()}`);let y=e.context?.channel||"api",{evaluateRequest:Vi,selectRequestContext:Zi}=await import("./request-planner-MY6VKTVC.js"),Jn=te("request-gate",()=>Vi(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Qt=!1;Jn.then(()=>{Qt=!0},()=>{Qt=!0});let I=g,zt=e.context?.sender||"User",ce=d.def.tier==="codex-cli",We=li(this.config.session,y,d.def.tier),dt=gi(this.config.session),qe=We==="lean"&&dt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${I}`),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}));let ct=this.sessions.sessionIdleMs(e.agentId,y,I);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,I,e.seedHistory),()=>{});let ea=[...this.sessions.getSession(e.agentId,y,I).messages].reverse().find(l=>l.role==="agent")?.content;Li({agent:e.agentId,channel:y,chatId:I,message:e.message,previousReply:ea,taskId:R}),this.sessions.addUserMessage(e.agentId,y,I,zt,e.message);let Qn=Date.now();Z().emit("task:started",{agentId:e.agentId,channel:y,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Qn).toISOString(),taskId:R,resumeOrigin:Po(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:dn(e.context),...x?{person:x}:{},humanRoot:Ke(e.context),pickup:As(e.context),operator:Cs(e.context)}),ne=!0;let ee,Xt,zn=this.classifier;if(zn&&y!=="a2a"&&!ce){C("classify");let l=Date.now();Xt=zn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{ee=f||void 0,ee?.path?.length&&(p.intentPath=ee.path.slice()),D("classify",l,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),D("classify",l,"error")})}let Xn=async l=>{if(!Xt)return;let f;await Promise.race([Xt,new Promise(v=>{f=setTimeout(v,l),f.unref?.()})]),f&&clearTimeout(f)};await Xn(Eu);let Se=this.config.workflows?.matching,pe,Yn,Vn=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Vn?.enabled&&(Vn.agents[e.agentId]??!0)&&!i&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=(Se?.suggestThreshold??.65)&&(Yn=fr(f.workflow))}catch(l){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${l?.message||l}`)}if(this.config.workflows?.enabled&&Se?.enabled&&!i)try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=Se.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Se.mode} reasons=${f.reasons.join(",")||"n/a"}`),Se.mode==="auto"&&f.confidence>=Se.autoRunThreshold&&(this.workflowAutoRunner?pe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(l){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${l?.message||l}`)}let Te=mr(this.config.workflows,e.agentId)&&hr(e)?this.workflowRuns:void 0;if(Te&&!pe&&!i&&this.workflowAutoRunner&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list()),v=Se?.autoRunThreshold??.85;f&&f.confidence>=v&&(pe={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(l){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${l?.message||l}`)}let ae=Te?Fu():void 0,ta=ae?yr(ae):void 0,na=this.wikiHub.getAgentWiki(e.agentId),Zn=this.memoryStore.findRelevant(e.message,e.agentId,ce?3:8),es=this.memoryStore.buildContext(Zn),ts=this.memoryStore.contextFacts(Zn),sa=this.patternStore.findRelevant(e.message,e.agentId,5),ra=this.patternStore.buildContext(sa),ns="";if(!ce)try{let{loadLocalSkills:l,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),v=await W("skills",()=>l(d.def.workspace)),k=e.personLimits?.skills??[],j=k.length?v.filter(G=>!k.some(Y=>Je(Y,G.frontmatter.name))):v;ns=f(j,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,I):void 0;if(F&&this.sessions.isSessionStale(e.agentId,y,I,ct)&&(this.log(`[${e.agentId}] session stale for ${y}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,y,I)){let l=this.sessions.getLastTurnContextTokens(e.agentId,y,I);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${I} (last turn context: ${l} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"tier-2",lastTurnInputTokens:l,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,y,I)){let l=this.sessions.getTurnCount(e.agentId,y,I);this.log(`[${e.agentId}] max-turns rotation for ${y}:${I} (${l} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let l=this.config.session?.resumeGate;if(l&&l.mode!=="off"){let f=Ur({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,I),idleMs:ct??0},l);if(f.rotate&&l.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${I}: ${mn(f)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"cost");let v=this.sessions.getLastTurnInputTokens(e.agentId,y,I);this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"cost",lastTurnInputTokens:v,at:new Date().toISOString()}),F=void 0}else l.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${I}: would ${mn(f)}`)}}if(F&&d.def.tier==="claude-code"){let l=F;await te("rotate",()=>this.maybeRotateForContinuity(e,d,y,I,l),()=>!1)&&(F=void 0)}try{let l=await W("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,I,this.memoryStore));if(l.compacted){let f=l.qualityScore??"?",v=l.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${I} (quality: ${f}%, ${v} entities lost)`),l.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${l.lostEntities.slice(0,5).join(", ")}`),l.drift){let k=l.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(l){this.log(`[${e.agentId}] compaction failed (non-fatal): ${l.message}`)}let oa=process.env.AGENTX_CONTEXT_SURGERY==="1",ia=ce?{maxMessages:8,maxChars:2400}:oa&&Gi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,aa=!F&&!ce?zu(na,e.agentId,{notesInbox:Qu(this.config)}):void 0,ut=!F&&!qe?this.sessions.buildHistoryContext(e.agentId,y,I,ia):void 0,da=F?void 0:this.sessions.getRotationMemo(e.agentId,y,I)??void 0,ss,rs=[];if(this.config.procedures?.injection?.enabled&&!F&&!ce)try{let l=new ot({baseDir:Q(process.cwd(),this.config.procedures.dir)}),f=Fn(e.message,l.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){ss=Un(f),rs=f.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of f)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(l){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${l?.message||l}`)}if($e&&$e.cat)try{let f=this.sessions.getSession(e.agentId,y,I).messages,v=f[0],k=f[f.length-1],j=ut===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${ut.length}c/${ut.split(`
142
142
  `).length}L`,G=`[${e.agentId}] ${y}:${I} ${j} | session.messages=${f.length}`+(f.length>0?` first=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")}) last=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")})`:"");$e.cat("context",G)}catch(l){$e.cat("context",`[${e.agentId}] context-diag error: ${l?.message??l}`)}let os;if(d.def.contextReferences&&!F)try{let l=d.def.workspace,f=this.referencesCache.get(l);if(!f){let[k,j]=await W("references",()=>Promise.all([ln(d.def.workspace),gn(d.def.workspace)]));if(k.byId.size===0&&j.recipes.length===0){let[G,Y]=await W("references",()=>Promise.all([ln(process.cwd()),gn(process.cwd())]));f={refs:G,recipes:Y}}else f={refs:k,recipes:j};this.referencesCache.set(l,f)}let v=or({agentId:e.agentId,intentTags:ee?.path,message:e.message},f.recipes,f.refs);v.cards.length>0&&(os=sr(v.cards,500*4)),v.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${v.unresolvedIds.join(", ")}`)}catch(l){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${l?.message||l}`)}let is=qe?"":this.sessions.getCrossSessionSummary(e.agentId,y,I,e.message),as,lt=vo(e.message);if(lt)try{let l=this.sessions.recallTurns({agentId:e.agentId,channel:y,chatId:I,lookbackDays:lt.lookbackDays,limit:12});if(l.turns.length>0){let f=[`[Long-memory recall \u2014 last ${lt.lookbackDays}d on this chat (cue-triggered)]`],v=[...l.turns].sort((k,j)=>k.ts.localeCompare(j.ts));for(let k of v){let j=k.ts.slice(11,16)+" "+k.day,G=k.role==="user"?k.senderName||"User":k.senderName||"Agent";f.push(`${j} ${G}: ${k.content}`)}l.hasMore&&f.push(`[\u2026${l.totalScanned-l.turns.length}+ older turns available \u2014 call /recall with before=${l.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),as=f.join(`
143
143
  `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${lt.lookbackDays}d, turns=${l.turns.length}, scanned=${l.totalScanned}`)}}catch(l){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${l.message}`)}let ca=ce?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",ds,cs,us=!1;Qt||C("request-gate");let ke=await Jn;if(ke.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),ca==="planner"&&!ke.active&&!qe&&y!=="voice"&&y!=="desktop"){try{let{planContext:l}=await import("./context-planner-3JDA7FNR.js"),f=await W("plan-context",()=>l({agentId:e.agentId,channel:y,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(us=!0,ds=f.sessionHistory,es=f.memoryContext,ts=f.memoryFacts,is=f.crossChatContext,cs=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(l){this.log(`[${e.agentId}] planner failed (non-fatal): ${l.message} \u2014 falling back to layered (keeping --resume for continuity)`)}us&&F&&(this.sessions.clearClaudeSessionId(e.agentId,y,I),F=void 0)}let Yt=`${e.agentId}:${y}:${I}`,gt=js(e.message);gt&&(gt==="default"?(this.activeSouls.delete(Yt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Yt,gt),this.log(`[${e.agentId}] Soul switched to: ${gt}`)));let ua=this.activeSouls.get(Yt),la=Hs(d.def.workspace,ua),ga=Bs(la),pa=this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),fa=Bu(d.def.tier),ma=Zu(d.def.richMessages,y),ha=d.def.tier==="claude-code"&&(We!=="lean"||pi(dt)),ls="";if(d.def.workspace&&!ha){let l=Q(d.def.workspace,"CLAUDE.md");if(de(l))try{let f=it(l,"utf-8");ls=`[Project CLAUDE.md]
144
144
  ${f.length>4e3?f.slice(0,4e3)+`
@@ -152,9 +152,9 @@ ${ve}`),f+=ve.length}catch{}}}let ya=Vt.length>0?Vt.join(`
152
152
 
153
153
  `)||void 0,en={channel:y,chatId:I,channelScope:e.context?.group?"group":y==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,y),systemPrompt:d.def.systemPrompt,sender:zt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ce||qe||Gi(y,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ce?void 0:ra||void 0,procedureContext:[ss,Yn].filter(Boolean).join(`
154
154
 
155
- `)||void 0,workflowRunContext:ta,references:os,skillInjection:ns||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ds??ut,memoryContext:es||void 0,crossChatContext:is||void 0,longMemoryRecall:as||void 0,contextOnDemand:qe&&!F?wi(y,I):void 0,wikiContext:aa,handoverNote:this.buildHandoverNote(e.agentId,y,I),rotationMemo:da,eventDigest:F?void 0:Ju(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let l=$r(y,!F,d.def.richMessages);return l?Xu(d.def.workspace,l):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message},ft=e.model?void 0:Ls({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?ct:null});ft?.downgraded&&this.log(`[${e.agentId}] ${ft.reason}`);let gs=Ns(d.def.tier,this.config.decisions.routing),ps=ft?.downgraded?Promise.resolve(ft.model):!e.model&&gs&&(!ke.active||ke.preprocess)?(async()=>{try{let{routeTaskModel:l}=await import("./routing-YUP3HHL5.js"),f=await W("route-model",()=>l({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!F,sessionIdleMs:F?ct:null,cheapModel:gs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),fs=!1;ps.then(()=>{fs=!0});let mt=ke.active&&ke.preprocess?await te("select-context",()=>Zi(en),()=>({input:en,excluded:[]})):{input:en,excluded:[]};mt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${mt.excluded.join(", ")}`);let ht=Mo(mt.input,ce?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),wa=Vs(ht,{memory:ts,procedures:rs,wikiContext:mt.input.wikiContext}),tn=(ht?.length??0)+(Zt?.length??0)+(e.message?.length??0),yt={history:ht?.length??0,sysPrompt:Zt?.length??0,message:e.message?.length??0},ms=si(e.agentId,y,I);ri(ms,tn,yt);let hs=oi(ms);hs&&this.log(`[${e.agentId}] ${hs}`),tn>16e3&&this.log(`[${e.agentId}] large context for ${y}:${I}: ${tn} bytes (history=${yt.history}, sysPrompt=${yt.sysPrompt}, message=${yt.message})`),fs||C("route-model");let ys=await ps,ws=d.def.tier!=="claude-code"?void 0:We==="lean"?mi(d.def.workspace,dt,void 0,y):yi(d.def.workspace);We==="lean"&&!F&&this.log(`[${e.agentId}] session profile for ${y}: ${bi(We,dt,y)}`);let bs=d.def.tier==="claude-code"&&!F?Lr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:R},l=>this.log(l)):void 0,ba={...e,systemPromptAppend:Zt,...ws?{claudeArgs:ws}:{},...ys?{model:ys}:{}},re,xs=Di({agent:e.agentId,request:e.message,taskId:R,budgetMinutes:d.def.maxExecutionMinutes??20}),xa=H,Is=!1,nn=!0;H=l=>{if(xs.observe(l),ae&&nn)for(let f of br(l))wr(f.name,f.input)||(nn=!1);xa?.(l)};try{let l=this.workflowAutoRunner;if(pe&&l){let E=pe;try{let J=await W("workflow-auto-run",()=>l({workflowId:E.workflowId,agentId:e.agentId,channel:y,chatId:I,message:e.message,...E.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:y,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:E.workflowId,matchConfidence:E.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${pe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:E.follow?`Started the workflow "${J.title??E.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:pe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:pe.confidence}},re}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&Te)try{let E=Ir(Te,e.resumedFrom);xr(Te,{runId:ae,agentId:e.agentId,channel:y,chatId:I,message:e.message,taskId:R,...E?{continues:E}:{}}),Is=!0,p.workflow={runId:ae,workflowId:pr}}catch(E){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${E?.message||E}`)}let f=()=>{if(d.def.tier!=="claude-code")return null;C("dispatch-gate");let E=d.def.persistentProcess?Pt():null,J=E!=null&&E.hasLive({agentId:e.agentId,channel:y,chatId:I}),he=!!F||J,ue=[jo(he),ti(he,void 0,e.model||d.def.model)].find(xt=>xt&&xt.abort);if(ue){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ue.reason}`);let xt={content:"",error:ue.message,duration:0};if(!t){w.buffer=`[error] ${ue.message}`;for(let Ia of w.subscribers)try{Ia(w.buffer)}catch{}}return xt}Jo();let Ge=ni();return Ge&&this.log(`[${e.agentId}] ${Ge}`),null},v=this.planCloudSession(d.def,e);if(v.route==="local"){let E=f();if(E)return d.errors++,re=E,E}let k=d.def.tier==="claude-code",j=k?t:(E,J)=>{E&&P(E),t&&t(E,J)},G=!1,Y=k?s:E=>{E&&(G?P(E):(P(`\u{1F4AD} ${E}`),G=!0)),s&&s(E)},ve=()=>{G&&(P(`
155
+ `)||void 0,workflowRunContext:ta,references:os,skillInjection:ns||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ds??ut,memoryContext:es||void 0,crossChatContext:is||void 0,longMemoryRecall:as||void 0,contextOnDemand:qe&&!F?wi(y,I):void 0,wikiContext:aa,handoverNote:this.buildHandoverNote(e.agentId,y,I),rotationMemo:da,eventDigest:F?void 0:Ju(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let l=$r(y,!F,d.def.richMessages);return l?Xu(d.def.workspace,l):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message},ft=e.model?void 0:Ls({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?ct:null});ft?.downgraded&&this.log(`[${e.agentId}] ${ft.reason}`);let gs=Ns(d.def.tier,this.config.decisions.routing),ps=ft?.downgraded?Promise.resolve(ft.model):!e.model&&gs&&(!ke.active||ke.preprocess)?(async()=>{try{let{routeTaskModel:l}=await import("./routing-CSVLOGNS.js"),f=await W("route-model",()=>l({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!F,sessionIdleMs:F?ct:null,cheapModel:gs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),fs=!1;ps.then(()=>{fs=!0});let mt=ke.active&&ke.preprocess?await te("select-context",()=>Zi(en),()=>({input:en,excluded:[]})):{input:en,excluded:[]};mt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${mt.excluded.join(", ")}`);let ht=Mo(mt.input,ce?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),wa=Vs(ht,{memory:ts,procedures:rs,wikiContext:mt.input.wikiContext}),tn=(ht?.length??0)+(Zt?.length??0)+(e.message?.length??0),yt={history:ht?.length??0,sysPrompt:Zt?.length??0,message:e.message?.length??0},ms=si(e.agentId,y,I);ri(ms,tn,yt);let hs=oi(ms);hs&&this.log(`[${e.agentId}] ${hs}`),tn>16e3&&this.log(`[${e.agentId}] large context for ${y}:${I}: ${tn} bytes (history=${yt.history}, sysPrompt=${yt.sysPrompt}, message=${yt.message})`),fs||C("route-model");let ys=await ps,ws=d.def.tier!=="claude-code"?void 0:We==="lean"?mi(d.def.workspace,dt,void 0,y):yi(d.def.workspace);We==="lean"&&!F&&this.log(`[${e.agentId}] session profile for ${y}: ${bi(We,dt,y)}`);let bs=d.def.tier==="claude-code"&&!F?Lr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:R},l=>this.log(l)):void 0,ba={...e,systemPromptAppend:Zt,...ws?{claudeArgs:ws}:{},...ys?{model:ys}:{}},re,xs=Di({agent:e.agentId,request:e.message,taskId:R,budgetMinutes:d.def.maxExecutionMinutes??20}),xa=H,Is=!1,nn=!0;H=l=>{if(xs.observe(l),ae&&nn)for(let f of br(l))wr(f.name,f.input)||(nn=!1);xa?.(l)};try{let l=this.workflowAutoRunner;if(pe&&l){let E=pe;try{let J=await W("workflow-auto-run",()=>l({workflowId:E.workflowId,agentId:e.agentId,channel:y,chatId:I,message:e.message,...E.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:y,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:E.workflowId,matchConfidence:E.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${pe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:E.follow?`Started the workflow "${J.title??E.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:pe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:pe.confidence}},re}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&Te)try{let E=Ir(Te,e.resumedFrom);xr(Te,{runId:ae,agentId:e.agentId,channel:y,chatId:I,message:e.message,taskId:R,...E?{continues:E}:{}}),Is=!0,p.workflow={runId:ae,workflowId:pr}}catch(E){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${E?.message||E}`)}let f=()=>{if(d.def.tier!=="claude-code")return null;C("dispatch-gate");let E=d.def.persistentProcess?Pt():null,J=E!=null&&E.hasLive({agentId:e.agentId,channel:y,chatId:I}),he=!!F||J,ue=[jo(he),ti(he,void 0,e.model||d.def.model)].find(xt=>xt&&xt.abort);if(ue){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ue.reason}`);let xt={content:"",error:ue.message,duration:0};if(!t){w.buffer=`[error] ${ue.message}`;for(let Ia of w.subscribers)try{Ia(w.buffer)}catch{}}return xt}Jo();let Ge=ni();return Ge&&this.log(`[${e.agentId}] ${Ge}`),null},v=this.planCloudSession(d.def,e);if(v.route==="local"){let E=f();if(E)return d.errors++,re=E,E}let k=d.def.tier==="claude-code",j=k?t:(E,J)=>{E&&P(E),t&&t(E,J)},G=!1,Y=k?s:E=>{E&&(G?P(E):(P(`\u{1F4AD} ${E}`),G=!0)),s&&s(E)},ve=()=>{G&&(P(`
156
156
  `),G=!1)},fe=k?j:j?(E,J)=>{ve(),j(E,J)}:void 0,$=await W("agent",async()=>{if(v.route!=="local"){let E=await this.runCloudSession(d.def,e,v,R);if(E)return E;let J=f();if(J)return J}return So(d.def,ba,this.providers,fe,ht,F,H,S.signal,Y)},Wu);if(!$.error){let E=Yu(d.def.toolUseRequired,M);if(E){let J=Array.from(M.entries()).map(([he,bt])=>`${he}=${bt}`).join(", ")||"none";$.error=`tool_required_not_called: ${E} (invoked: ${J})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${E}, observed ${J}`)}}bs&&Fr(bs,{toolUses:M,eventsSeen:N,error:$.error,agentId:e.agentId},E=>this.log(E));let wt=this.interruptedRuns.get(p.id);wt&&($.content="",$.error=wt,$.errorKind="interrupted");let sn=wt?void 0:this.stoppedRuns.get(p.id);sn&&($.content="",$.error=sn,$.errorKind="stopped"),re=$;let me=$.usage?Xs($.usage):void 0;if(_=!0,Z().emit("task:completed",{taskId:R,agentId:e.agentId,channel:y,chatId:I,durationMs:Date.now()-Qn,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:wt?!0:void 0,stopped:sn?!0:void 0,inputTokens:me?.inputTokens,outputTokens:me?.outputTokens,cacheReadTokens:me?.cacheReadTokens,cacheCreateTokens:me?.cacheCreateTokens,tier2InputTokens:me?.tier2InputTokens,tier2OutputTokens:me?.tier2OutputTokens,tier2CacheReadTokens:me?.tier2CacheReadTokens,tier2CacheCreateTokens:me?.tier2CacheCreateTokens,resumed:!!F,resumeSessionId:F||void 0,jevArm:ke.arm,numTurns:$.numTurns,injectedContext:wa,finalResponse:$.content||void 0,billedModel:$.billedModel||d.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let E=$.error?`[error] ${$.error}`:$.content;w.buffer=E;for(let J of w.subscribers)try{J(E)}catch{}}if($.error)d.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,y,I,$.content),Ni({agent:e.agentId,channel:y,chatId:I,request:e.message,reply:$.content,taskId:R}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,y,I,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,y,I,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,y,I,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,y,I,$.usage,$.contextTokens),$.usage){let ue=$.contextTokens,Ge=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ue??Ge)>=this.sessions.getTierTwoThresholdTokens(y)&&this.log(`[${e.agentId}] TIER-2 HIT on ${y}:${I}: context=${ue??"n/a"} tokens (cumulative turn total=${Ge}) \u2014 next turn will rotate`)}if(Gs({channel:y,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await Xn(Du);try{let ue=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ue,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:y,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
157
157
 
158
158
  Agent: ${$.content}`,meta:Ku(ee,e.context)})}catch{}Ks(e.agentId,e.message,$.content,{channel:y,chatId:I,sender:zt},this.memoryStore).catch(()=>{}),No(e.agentId,e.message,$.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=$.billedModel||e.model||d.def.model,he=e.context?.channel,bt=he&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${he}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,J,he,bt),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${O()}`)}return $}catch(l){d.errors++,this.log(`[${e.agentId}] unexpected error: ${l.message}`);let f=At(l.message);return re={content:"",error:Ct(f),errorKind:f.kind},re}finally{if(xs.stop(),Is&&ae&&Te)try{let l=re?.usage,f=Sr(Te,ae,{error:re?re.error||void 0:S.signal.aborted?Re(S.signal).message:"run ended before completion",canceled:Tr(re?.errorKind)||this.stoppedRuns.has(p.id)||this.interruptedRuns.has(p.id)||!re&&S.signal.aborted,durationMs:Date.now()-p.startedAt.getTime(),...l?{inputTokens:l.inputTokens,outputTokens:l.outputTokens}:{},readOnly:nn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(l){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${l?.message||l}`)}se(re),Kn(re)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withWorkflowSteps(e.runningTasks),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:kr(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=Q(process.cwd(),je,this.safe(e.agentId),t);de(s)||Ou(s,{recursive:!0});let r=Q(s,`${this.safe(e.id)}.json`);Lu(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=Q(process.cwd(),je,this.safe(e));if(!de(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let g of[d,c]){let m=Q(a,g);if(de(m))try{for(let h of ge(m)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],x=parseInt(p,10);if(!Number.isFinite(x)||x<i||x>s)continue;let S=Math.floor((s-x)/36e5),w=t-1-S;w>=0&&w<t&&o[w]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=Q(process.cwd(),je);if(!de(e))return 0;let t=0;for(let s of ge(e)){let r=Q(e,s),o;try{o=ge(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=Q(r,i),c;try{c=ge(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(it(Q(a,d),"utf-8")),g=(u.responseText||u.error||"").trim();if(!g)continue;let m=g.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:m,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Gu){let t=Q(process.cwd(),je);if(!de(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ge(t)){let i=Q(t,o),a;try{a=ge(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Nu(Q(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=Q(process.cwd(),je,this.safe(e));if(!de(s))return[];let r=ge(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=Q(s,i),c;try{c=ge(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(it(Q(a,d),"utf-8")),{transcript:g,responseText:m,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=Q(process.cwd(),je,this.safe(e));if(!de(s))return null;let r=this.safe(t),o=ge(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=Q(s,i,`${r}.json`);if(de(a))try{return JSON.parse(it(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=gr();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||ze(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Lt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let r=[...this.taskAborts].filter(([,o])=>o.agentId===e.agentId&&o.channel===e.channel&&o.chatId===e.chatId).map(([o])=>o);t=r.length===1?r[0]:void 0}let s=t?this.taskAborts.get(t):void 0;return!t||!s?null:{taskId:t,traceId:s.traceId,agentId:s.agentId,channel:s.channel,chatId:s.chatId,sender:s.sender,rootId:s.rootId,originalMessage:s.originalMessage,origin:s.origin??null,...s.workflowRunId?{workflowRunId:s.workflowRunId}:{}}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,g=!1;u&&d&&(g=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let m=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:m,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);Z().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(m).toISOString(),sender:{name:s},humanRoot:!1,person:Ms(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:m});let p=!1;if(r.replace){let x=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(x))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${x}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${g?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:g,pending:h}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,g=m=>{u||(u=!0,d(m))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:m=>g({ok:!0,agentId:e,channel:a,chatId:c,taskId:m,queued:!1})}).then(m=>{ze(m.error)?g({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):m.error?g({ok:!1,status:500,error:m.error||"run did not start"}):g({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:m.viaAttachedSession?"attached":"other"})}).catch(m=>g({ok:!1,status:500,error:m?.message??String(m)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Zu(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
159
159
  `)}export{qr as a,fl as b,Kr as c,Ua as d,Jr as e,Rt as f,Al as g,Rl as h,_l as i,Ll as j,Lt as k,id as l,bo as m,ld as n,gd as o,pd as p,So as q,Ft as r,Ut as s,Dd as t,lg as u,gg as v,Rn as w,Z as x,Lo as y,qd as z,Qd as A,Ho as B,Mg as C,Bo as D,Go as E,Yo as F,Wg as G,Vo as H,jt as I,Qg as J,zg as K,ot as L,Zc as M,eu as N,tu as O,nu as P,su as Q,Fn as R,Hu as S,Bu as T,Ff as U,Uf as V,Ku as W,Ju as X,zu as Y,Gn as Z,Ji as _,Qi as $,Yu as aa,zi as ba,Xi as ca,Zu as da};
160
- //# sourceMappingURL=chunk-6XMISPQD.js.map
160
+ //# sourceMappingURL=chunk-RIYQNADV.js.map
@@ -1,4 +1,4 @@
1
- import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-VVX4RXMV.js";import{y as C,z as K}from"./chunk-MTDVAO5C.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
1
+ import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-7KAQHNLT.js";import{y as C,z as K}from"./chunk-LMZCB7TT.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
2
2
  `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
3
3
  `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
4
4
  `));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
@@ -102,4 +102,4 @@ We use GitLab for version control.
102
102
  There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
103
 
104
104
  ${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
105
- //# sourceMappingURL=chunk-XVYIPVSC.js.map
105
+ //# sourceMappingURL=chunk-STIZFWDJ.js.map
@@ -1,4 +1,4 @@
1
- import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-ROH45HXN.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-QWJR4E6V.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-LQ2I2PQI.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-R2LIDLPZ.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-R2LIDLPZ.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
1
+ import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-ROH45HXN.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-XGWCWKMT.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-LQ2I2PQI.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-R2LIDLPZ.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-R2LIDLPZ.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
2
2
  `).slice(0,12).map(n=>` | ${n}`).join(`
3
3
  `)))}u.outcomes.length===0&&console.log(t.dim(" nothing to do: no entity of these types changed since the last run (--force redoes them)")),console.log(t.dim(` spent $${u.costUsd.toFixed(3)} of $${w}${u.capped?" \xB7 stopped at the cap":""}`))})}export{N as a,I as b};
4
- //# sourceMappingURL=chunk-HQH44RGL.js.map
4
+ //# sourceMappingURL=chunk-XQVL2RYG.js.map
@@ -1,4 +1,4 @@
1
- import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-XVYIPVSC.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
1
+ import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-STIZFWDJ.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
2
2
  ## Worldview
3
3
 
4
4
  ${r}
@@ -249,4 +249,4 @@ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
249
249
  Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let m=[{role:"user",content:n}];s&&(m.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),m.push({role:"user",content:`Your previous response failed validation: ${s}
250
250
  Re-emit the FULL corrected JSON object.`}));let u=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:m}),signal:i.signal});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`anthropic API ${u.status}: ${a.slice(0,500)}`)}let d=await u.json(),e=(Array.isArray(d.content)?d.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
251
251
  `).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...l)=>t(l.map(String).join(" "))),p=c.rebuildIndex(),m=z(r),u=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(u,p,m,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let d=p.articles.map(l=>({title:l.title,path:l.path,type:l.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,d,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,d,g);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(l=>l.candidates),w=new Set(y.map(l=>l.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(l=>[l.stamp,l]));for(let l of f.articles){let A=c.readArticle(l.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${l.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(l.promotedFrom,T),S={id:Y(o,l.path),createdAt:v,status:"pending",article:l,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:l.path,title:l.title,type:l.type,stamps:l.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of l.promotedFrom)k.push({stamp:X,decision:"proposed",article:l.path,proposal:S.id,at:v})}for(let l of f.skipped)k.push({stamp:l.stamp,decision:"skipped",reason:l.reason,at:v}),i.skipped.push(l);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let m=s.now??Date.now(),u=new Date(m).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??u,lastUpdated:u,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let g=new Date(m).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:g}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:g};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
252
- //# sourceMappingURL=chunk-6VP2KMUM.js.map
252
+ //# sourceMappingURL=chunk-Z5IHT6RK.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 e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-5RLTC6CR.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
2
+ import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-X6EKIO24.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
3
3
  //# sourceMappingURL=cli.js.map
@@ -1,2 +1,2 @@
1
- import{a,b,c,d,e,f,g}from"./chunk-UPQTTOVQ.js";import"./chunk-HJCFLGVT.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-EB55Y6EJ.js.map
1
+ import{a,b,c,d,e,f,g}from"./chunk-QN2OTBVC.js";import"./chunk-MGM33GOW.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-2KZWK6YT.js.map
@@ -1,2 +1,2 @@
1
- import{Aa as u,fa as a,ga as b,ha as c,ia as d,ja as e,ka as f,la as g,ma as h,na as i,oa as j,pa as k,qa as l,ra as m,sa as n,ta as o,ua as p,va as q,wa as r,xa as s,ya as t}from"./chunk-HJCFLGVT.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";u();export{a as INTEGRATION_KINDS,p as WIKI_CONTRIBUTE_JOB,q as WIKI_CONTRIBUTE_MERGE_JOB,s as WIKI_SUMMARIZE_JOB,k as approvalsConfigSchema,e as callsSchema,c as cameraBotSchema,l as daemonConfigSchema,b as eventSubscriptionSchema,m as expandEnvVars,d as isCronExpression,n as loadDaemonConfig,i as membersConfigSchema,h as peopleConfigSchema,g as personSchema,j as requestStatusConfigSchema,f as requestsConfigSchema,o as validateWorkspaces,r as withContributionJobs,t as withSummariesJob};
2
- //# sourceMappingURL=config-7DRUA5R3.js.map
1
+ import{Aa as u,fa as a,ga as b,ha as c,ia as d,ja as e,ka as f,la as g,ma as h,na as i,oa as j,pa as k,qa as l,ra as m,sa as n,ta as o,ua as p,va as q,wa as r,xa as s,ya as t}from"./chunk-MGM33GOW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";u();export{a as INTEGRATION_KINDS,p as WIKI_CONTRIBUTE_JOB,q as WIKI_CONTRIBUTE_MERGE_JOB,s as WIKI_SUMMARIZE_JOB,k as approvalsConfigSchema,e as callsSchema,c as cameraBotSchema,l as daemonConfigSchema,b as eventSubscriptionSchema,m as expandEnvVars,d as isCronExpression,n as loadDaemonConfig,i as membersConfigSchema,h as peopleConfigSchema,g as personSchema,j as requestStatusConfigSchema,f as requestsConfigSchema,o as validateWorkspaces,r as withContributionJobs,t as withSummariesJob};
2
+ //# sourceMappingURL=config-THFRJMZD.js.map
@@ -1,2 +1,2 @@
1
- import{a,b}from"./chunk-AGQYUOZY.js";import"./chunk-HJCFLGVT.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-GGA7VXXH.js.map
1
+ import{a,b}from"./chunk-EJIY45FZ.js";import"./chunk-MGM33GOW.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-HXWAXWHC.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e}from"./chunk-NMYPZR4W.js";import"./chunk-MGM33GOW.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-JZOAWRBH.js.map