agentix-cli 0.138.0 → 0.139.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) 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-L5CJF3GH.js → agent-PRHZGF6J.js} +2 -2
  5. package/dist/{board-dashboard-33NGOGWC.js → board-dashboard-GBEBQUFJ.js} +119 -119
  6. package/dist/board-dashboard-GBEBQUFJ.js.map +1 -0
  7. package/dist/{chunk-7V73QTQ7.js → chunk-2BEZU5OF.js} +2 -2
  8. package/dist/{chunk-UPNKRCFX.js → chunk-34XYHSL6.js} +198 -198
  9. package/dist/chunk-34XYHSL6.js.map +1 -0
  10. package/dist/{chunk-VVX4RXMV.js → chunk-7KAQHNLT.js} +2 -2
  11. package/dist/{chunk-6AUWEL6V.js → chunk-ANDEMOYE.js} +2 -2
  12. package/dist/{chunk-TFH6S7IT.js → chunk-AXHP6TMT.js} +2 -2
  13. package/dist/{chunk-375MXG3H.js → chunk-B65EC44C.js} +2 -2
  14. package/dist/{chunk-AGQYUOZY.js → chunk-EJIY45FZ.js} +2 -2
  15. package/dist/{chunk-AP4DADXG.js → chunk-HGU5B7IY.js} +2 -2
  16. package/dist/{chunk-SK47VJMQ.js → chunk-HXLB2XCT.js} +3 -3
  17. package/dist/{chunk-XBARUCG5.js → chunk-IMUTN7PT.js} +2 -2
  18. package/dist/{chunk-LA6P3TUK.js → chunk-J7U3BASX.js} +2 -2
  19. package/dist/{chunk-CZZJEFUM.js → chunk-JAML6222.js} +2 -2
  20. package/dist/{chunk-TVW5ZKJY.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-7YZL5MUL.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-GAIXI26T.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-Q4XP5TBI.js +11 -0
  32. package/dist/chunk-Q4XP5TBI.js.map +1 -0
  33. package/dist/{chunk-UPQTTOVQ.js → chunk-QN2OTBVC.js} +2 -2
  34. package/dist/{chunk-4HHHVWDB.js → chunk-RIYQNADV.js} +17 -17
  35. package/dist/chunk-RIYQNADV.js.map +1 -0
  36. package/dist/{chunk-XVYIPVSC.js → chunk-STIZFWDJ.js} +2 -2
  37. package/dist/{chunk-HQH44RGL.js → chunk-XQVL2RYG.js} +2 -2
  38. package/dist/{chunk-7DYVNET6.js → chunk-YMX3QCV7.js} +1 -1
  39. package/dist/chunk-YMX3QCV7.js.map +1 -0
  40. package/dist/{chunk-6VP2KMUM.js → chunk-Z5IHT6RK.js} +2 -2
  41. package/dist/cli.js +1 -1
  42. package/dist/{client-EB55Y6EJ.js → client-2KZWK6YT.js} +2 -2
  43. package/dist/{config-7DRUA5R3.js → config-THFRJMZD.js} +2 -2
  44. package/dist/{config-mutate-GGA7VXXH.js → config-mutate-HXWAXWHC.js} +2 -2
  45. package/dist/config-mutator-JZOAWRBH.js +2 -0
  46. package/dist/{contributions-TZ26MTML.js → contributions-OSIKL25B.js} +2 -2
  47. package/dist/{doctor-GTRZ7GWF.js → doctor-TOSA3RWP.js} +2 -2
  48. package/dist/{follow-up-tool-PNB7KMCY.js → follow-up-tool-QRECR3AH.js} +2 -2
  49. package/dist/{hub-QWJR4E6V.js → hub-XGWCWKMT.js} +2 -2
  50. package/dist/index.d.ts +50 -0
  51. package/dist/index.js +1 -1
  52. package/dist/{program-KMUCHLDU.js → program-7VHY5RVZ.js} +188 -188
  53. package/dist/program-7VHY5RVZ.js.map +1 -0
  54. package/dist/{promote-HAPXWGYH.js → promote-YVWRKIAU.js} +2 -2
  55. package/dist/{push-bridge-276ZLSUT.js → push-bridge-P7HH25VN.js} +2 -2
  56. package/dist/{query-ICLOVLZ3.js → query-X4AFOKZ7.js} +2 -2
  57. package/dist/{query-settings-7AXUOHDL.js → query-settings-HV2RFQK7.js} +2 -2
  58. package/dist/{registry-IUNSHCOL.js → registry-B276QJ75.js} +2 -2
  59. package/dist/{request-planner-TDCLF2CH.js → request-planner-MY6VKTVC.js} +2 -2
  60. package/dist/{review-candidates-QCBXLWG6.js → review-candidates-BRTBB5XV.js} +2 -2
  61. package/dist/{routing-YUP3HHL5.js → routing-CSVLOGNS.js} +2 -2
  62. package/dist/schedule-tool-GUKYTQTY.js +2 -0
  63. package/dist/{scheduler-7NK2FH5V.js → scheduler-OUAVAU4O.js} +2 -2
  64. package/dist/{seat-PTPPQOTP.js → seat-H2QR3CRX.js} +2 -2
  65. package/dist/{select-2XSTWMBR.js → select-EEL5AZ2I.js} +2 -2
  66. package/dist/{set-enabled-SS5Q3OX7.js → set-enabled-IBGEH6U6.js} +2 -2
  67. package/dist/{tool-RK4LDFFH.js → tool-5WCC7SKQ.js} +2 -2
  68. package/dist/{tool-QCMSXEDB.js → tool-UPXUWIMM.js} +2 -2
  69. package/dist/{wiki-Q2E44YAE.js → wiki-ISKHNG3P.js} +2 -2
  70. package/dist/wiki-enrich-7SBCPK2E.js +2 -0
  71. package/package.json +1 -1
  72. package/dist/board-dashboard-33NGOGWC.js.map +0 -1
  73. package/dist/chunk-4HHHVWDB.js.map +0 -1
  74. package/dist/chunk-7DYVNET6.js.map +0 -1
  75. package/dist/chunk-LLNPKE7H.js +0 -11
  76. package/dist/chunk-LLNPKE7H.js.map +0 -1
  77. package/dist/chunk-UPNKRCFX.js.map +0 -1
  78. package/dist/config-mutator-POFVILXH.js +0 -2
  79. package/dist/program-KMUCHLDU.js.map +0 -1
  80. package/dist/schedule-tool-3C22NBMN.js +0 -2
  81. package/dist/wiki-enrich-6ULCDOTX.js +0 -2
  82. /package/dist/{App-F42CYCKX.js.map → App-VINKWTYN.js.map} +0 -0
  83. /package/dist/{ChatApp-RPMQBKHV.js.map → ChatApp-RGHQCRBX.js.map} +0 -0
  84. /package/dist/{absorb-eval-HRPEHJSO.js.map → absorb-eval-AERHBOQA.js.map} +0 -0
  85. /package/dist/{agent-L5CJF3GH.js.map → agent-PRHZGF6J.js.map} +0 -0
  86. /package/dist/{chunk-7V73QTQ7.js.map → chunk-2BEZU5OF.js.map} +0 -0
  87. /package/dist/{chunk-VVX4RXMV.js.map → chunk-7KAQHNLT.js.map} +0 -0
  88. /package/dist/{chunk-6AUWEL6V.js.map → chunk-ANDEMOYE.js.map} +0 -0
  89. /package/dist/{chunk-TFH6S7IT.js.map → chunk-AXHP6TMT.js.map} +0 -0
  90. /package/dist/{chunk-375MXG3H.js.map → chunk-B65EC44C.js.map} +0 -0
  91. /package/dist/{chunk-AGQYUOZY.js.map → chunk-EJIY45FZ.js.map} +0 -0
  92. /package/dist/{chunk-AP4DADXG.js.map → chunk-HGU5B7IY.js.map} +0 -0
  93. /package/dist/{chunk-SK47VJMQ.js.map → chunk-HXLB2XCT.js.map} +0 -0
  94. /package/dist/{chunk-XBARUCG5.js.map → chunk-IMUTN7PT.js.map} +0 -0
  95. /package/dist/{chunk-LA6P3TUK.js.map → chunk-J7U3BASX.js.map} +0 -0
  96. /package/dist/{chunk-CZZJEFUM.js.map → chunk-JAML6222.js.map} +0 -0
  97. /package/dist/{chunk-TVW5ZKJY.js.map → chunk-JBYLG3CQ.js.map} +0 -0
  98. /package/dist/{chunk-QGSUENRK.js.map → chunk-JJZVFDG6.js.map} +0 -0
  99. /package/dist/{chunk-DBJUGKX2.js.map → chunk-JS2LEURJ.js.map} +0 -0
  100. /package/dist/{chunk-7YZL5MUL.js.map → chunk-KO6BU3B3.js.map} +0 -0
  101. /package/dist/{chunk-MTDVAO5C.js.map → chunk-LMZCB7TT.js.map} +0 -0
  102. /package/dist/{chunk-GAIXI26T.js.map → chunk-MUC7MMTT.js.map} +0 -0
  103. /package/dist/{chunk-JIJDBCV7.js.map → chunk-NMYPZR4W.js.map} +0 -0
  104. /package/dist/{chunk-EGPCEQJN.js.map → chunk-NQGLKWDO.js.map} +0 -0
  105. /package/dist/{chunk-Y7IHOQC7.js.map → chunk-O6WW7ATO.js.map} +0 -0
  106. /package/dist/{chunk-UPQTTOVQ.js.map → chunk-QN2OTBVC.js.map} +0 -0
  107. /package/dist/{chunk-XVYIPVSC.js.map → chunk-STIZFWDJ.js.map} +0 -0
  108. /package/dist/{chunk-HQH44RGL.js.map → chunk-XQVL2RYG.js.map} +0 -0
  109. /package/dist/{chunk-6VP2KMUM.js.map → chunk-Z5IHT6RK.js.map} +0 -0
  110. /package/dist/{client-EB55Y6EJ.js.map → client-2KZWK6YT.js.map} +0 -0
  111. /package/dist/{config-7DRUA5R3.js.map → config-THFRJMZD.js.map} +0 -0
  112. /package/dist/{config-mutate-GGA7VXXH.js.map → config-mutate-HXWAXWHC.js.map} +0 -0
  113. /package/dist/{config-mutator-POFVILXH.js.map → config-mutator-JZOAWRBH.js.map} +0 -0
  114. /package/dist/{contributions-TZ26MTML.js.map → contributions-OSIKL25B.js.map} +0 -0
  115. /package/dist/{doctor-GTRZ7GWF.js.map → doctor-TOSA3RWP.js.map} +0 -0
  116. /package/dist/{follow-up-tool-PNB7KMCY.js.map → follow-up-tool-QRECR3AH.js.map} +0 -0
  117. /package/dist/{hub-QWJR4E6V.js.map → hub-XGWCWKMT.js.map} +0 -0
  118. /package/dist/{promote-HAPXWGYH.js.map → promote-YVWRKIAU.js.map} +0 -0
  119. /package/dist/{push-bridge-276ZLSUT.js.map → push-bridge-P7HH25VN.js.map} +0 -0
  120. /package/dist/{query-ICLOVLZ3.js.map → query-X4AFOKZ7.js.map} +0 -0
  121. /package/dist/{query-settings-7AXUOHDL.js.map → query-settings-HV2RFQK7.js.map} +0 -0
  122. /package/dist/{registry-IUNSHCOL.js.map → registry-B276QJ75.js.map} +0 -0
  123. /package/dist/{request-planner-TDCLF2CH.js.map → request-planner-MY6VKTVC.js.map} +0 -0
  124. /package/dist/{review-candidates-QCBXLWG6.js.map → review-candidates-BRTBB5XV.js.map} +0 -0
  125. /package/dist/{routing-YUP3HHL5.js.map → routing-CSVLOGNS.js.map} +0 -0
  126. /package/dist/{schedule-tool-3C22NBMN.js.map → schedule-tool-GUKYTQTY.js.map} +0 -0
  127. /package/dist/{scheduler-7NK2FH5V.js.map → scheduler-OUAVAU4O.js.map} +0 -0
  128. /package/dist/{seat-PTPPQOTP.js.map → seat-H2QR3CRX.js.map} +0 -0
  129. /package/dist/{select-2XSTWMBR.js.map → select-EEL5AZ2I.js.map} +0 -0
  130. /package/dist/{set-enabled-SS5Q3OX7.js.map → set-enabled-IBGEH6U6.js.map} +0 -0
  131. /package/dist/{tool-RK4LDFFH.js.map → tool-5WCC7SKQ.js.map} +0 -0
  132. /package/dist/{tool-QCMSXEDB.js.map → tool-UPXUWIMM.js.map} +0 -0
  133. /package/dist/{wiki-Q2E44YAE.js.map → wiki-ISKHNG3P.js.map} +0 -0
  134. /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-IUNSHCOL.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-GAIXI26T.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
@@ -0,0 +1,11 @@
1
+ import{a as w,b as f}from"./chunk-SHEUCITK.js";import{randomUUID as E}from"crypto";var y=["ringing","answered","later"],p=`id, agent_id AS agentId, kind, reason, urgency, status, created_at AS createdAt,
2
+ ringing_since AS ringingSince, answered_at AS answeredAt, ended_at AS endedAt,
3
+ ring_again_at AS ringAgainAt, note, summary, channel, chat_id AS chatId`,A=class{constructor(t){this.db=t;t.exec(`CREATE TABLE IF NOT EXISTS calls (
4
+ id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, reason TEXT NOT NULL,
5
+ urgency TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL,
6
+ ringing_since INTEGER, answered_at INTEGER, ended_at INTEGER,
7
+ ring_again_at INTEGER, note TEXT, summary TEXT);
8
+ CREATE INDEX IF NOT EXISTS calls_recent ON calls(created_at DESC);`);let s=new Set(t.prepare("PRAGMA table_info(calls)").all().map(e=>e.name));s.has("kind")||t.exec("ALTER TABLE calls ADD COLUMN kind TEXT NOT NULL DEFAULT 'voice'"),s.has("channel")||t.exec("ALTER TABLE calls ADD COLUMN channel TEXT"),s.has("chat_id")||t.exec("ALTER TABLE calls ADD COLUMN chat_id TEXT")}insert(t){this.db.prepare(`INSERT INTO calls (id, agent_id, kind, reason, urgency, status, created_at, ringing_since,
9
+ answered_at, ended_at, ring_again_at, note, summary, channel, chat_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(t.id,t.agentId,t.kind,t.reason,t.urgency,t.status,t.createdAt,t.ringingSince,t.answeredAt,t.endedAt,t.ringAgainAt,t.note,t.summary,t.channel,t.chatId)}get(t){return this.db.prepare(`SELECT ${p} FROM calls WHERE id=?`).get(t)}update(t,s){let e={reason:"reason",urgency:"urgency",status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},n=Object.keys(s).filter(r=>r in e);if(n.length){let r=n.map(i=>`${e[i]}=?`).join(", ");this.db.prepare(`UPDATE calls SET ${r} WHERE id=?`).run(...n.map(i=>s[i]??null),t)}return this.get(t)}transition(t,s,e){let n=Array.isArray(s)?s:[s],r={status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},i=Object.keys(e).filter(l=>l in r),o=i.map(l=>`${r[l]}=?`).join(", "),u=n.map(()=>"?").join(",");return this.db.prepare(`UPDATE calls SET ${o} WHERE id=? AND status IN (${u})`).run(...i.map(l=>e[l]??null),t,...n).changes?this.get(t):void 0}list(t={}){let s=Math.min(Math.max(t.limit??50,1),200),e=[],n=[];t.status?.length&&(e.push(`status IN (${t.status.map(()=>"?").join(",")})`),n.push(...t.status)),t.kind&&(e.push("kind=?"),n.push(t.kind));let r=e.length?`WHERE ${e.join(" AND ")}`:"";return this.db.prepare(`SELECT ${p} FROM calls ${r} ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(...n,s)}countSince(t,s){return this.db.prepare("SELECT COUNT(*) AS n FROM calls WHERE agent_id=? AND created_at>?").get(t,s).n}};var C=200,S=1e4,I=10,T=240;function L(a=process.env){return a.AGENTX_TASK_ID?{"X-AgentX-Task":a.AGENTX_TASK_ID}:a.AGENTX_CHANNEL&&a.AGENTX_CHAT_ID?{"X-AgentX-Channel":a.AGENTX_CHANNEL,"X-AgentX-Chat":a.AGENTX_CHAT_ID}:{}}function _(a){return`[Call answered] The owner just picked up the voice call you asked for. You called because: "${a.reason}". Speak first: greet them in a few words and say why you called, then let them answer.`}var x="[Call ended] The owner hung up. In two or three plain sentences, summarise what was said and decided on this call, for your records. Reply with the summary only.",k=class{constructor(t){this.deps=t}widgetSeenAt=0;widget={};waiting=new Map;now(){return this.deps.now?.()??Date.now()}name(t){return this.deps.agentName(t)??t}async request(t,s={}){let e=String(t.agentId??"").trim(),n=String(t.reason??"").replace(/\s+/g," ").trim(),r=t.urgency==="urgent"?"urgent":"normal",i=t.kind==="camera"?"camera":"voice";if(t.kind!==void 0&&t.kind!=="voice"&&t.kind!=="camera")return{ok:!1,status:400,error:"kind must be voice or camera"};if(!e||!n)return{ok:!1,status:400,error:"Required: agentId and reason"};if(n.length>C)return{ok:!1,status:413,error:`reason is over ${C} characters; keep it to one line`};if(this.deps.agentName(e)===null)return{ok:!1,status:404,error:`Unknown agent: ${e}`};if(!this.deps.isRunningTurn(e,s))return{ok:!1,status:403,error:`No running turn of ${e} placed this call. An agent calls from inside its own run.`};let o=this.deps.config();if(!o.allow.includes("*")&&!o.allow.includes(e))return{ok:!1,status:403,error:`${e} ${i==="camera"?"may not ask to see through the owner's camera":"may not call the owner"}. Add it to calls.allow in agentx.json (or: agentx call allow ${e}).`};if(await this.sweep(),this.deps.store.list({status:y,limit:200}).some(m=>m.agentId===e))return{ok:!1,status:409,error:`${e} already has a call in progress`};let u=this.now();if(this.deps.store.countSince(e,u-36e5)>=o.maxPerHour)return{ok:!1,status:429,error:`${e} has placed ${o.maxPerHour} calls in the last hour (calls.maxPerHour)`};let d=i==="camera"?this.deps.turnSession?.(e,s)??s:{},l={id:`call-${E().slice(0,8)}`,agentId:e,kind:i,reason:n,urgency:r,status:"ringing",createdAt:u,ringingSince:u,answeredAt:null,endedAt:null,ringAgainAt:null,note:null,summary:null,channel:d.channel&&d.chatId?d.channel:null,chatId:d.channel&&d.chatId?d.chatId:null};this.deps.store.insert(l),this.deps.log?.(`[calls] ${e} asks ${i==="camera"?"to see":"for a call"} (${r}): ${n}`);let g=await this.ring(l),h=this.deps.store.get(l.id);return g!=="waiting"?{ok:!0,call:h,rang:g}:this.waiting.has(l.id)?{ok:!0,call:h,rang:g,busy:this.busyInfo(l)}:{ok:!0,call:h,rang:"widget"}}async cancel(t,s={}){let e=String(t.agentId??"").trim();if(!e)return{ok:!1,status:400,error:"Required: agentId"};if(!this.deps.isRunningTurn(e,s))return{ok:!1,status:403,error:`No running turn of ${e} asked for this. An agent withdraws its own call from inside its run.`};let n=this.deps.store.list({status:["ringing","later"],kind:"voice",limit:200}).find(i=>i.agentId===e);if(!n)return{ok:!1,status:404,error:`${e} has no call waiting or ringing`};let r=this.deps.store.transition(n.id,["ringing","later"],{status:"ended",endedAt:this.now(),ringingSince:null,ringAgainAt:null,note:$});return r?(this.waiting.delete(n.id),this.deps.log?.(`[calls] ${n.id} withdrawn by ${e}`),{ok:!0,call:r}):{ok:!1,status:409,error:`call is ${this.deps.store.get(n.id)?.status}`}}async ring(t){let s=(this.deps.focus??w)();return s.active&&t.urgency!=="urgent"?(this.deps.store.transition(t.id,"ringing",{status:"missed",ringingSince:null,note:f(s)})&&await this.notice(t,this.missedTitle(t)),!1):t.kind==="camera"?(await this.notice(t,`${this.name(t.agentId)} wants to see through your camera`,`Open the phone app and tap Show within ${this.deps.config().ringSeconds} s.`),"notify"):this.widgetAlive()?!this.widget.busy&&!this.otherCalls(t).length?"widget":(this.startWaiting(t),await this.callWaiting(t),"waiting"):(await this.notice(t,`${this.name(t.agentId)} is calling`,`Open AgentX Voice to answer within ${this.deps.config().ringSeconds} s.`),"notify")}async notice(t,s,e){try{await this.deps.alert({title:s,message:e?`${t.reason}
10
+ ${e}`:t.reason,urgent:t.urgency==="urgent",from:t.agentId})}catch(n){this.deps.log?.(`[calls] notice for ${t.id} failed: ${n?.message??n}`)}}startWaiting(t){let s=this.now();this.waiting.set(t.id,{since:s,toldAt:s}),this.deps.log?.(`[calls] ${t.id} from ${t.agentId} waits: the widget is busy`)}otherCalls(t){return this.deps.store.list({status:["ringing","answered"],kind:"voice",limit:200}).filter(s=>s.id!==t.id).reverse()}async callWaiting(t){let s=this.deps.config().busy;await this.notice(t,s.title.replaceAll("{agent}",this.name(t.agentId)),s.notice)}busyInfo(t){let s=this.deps.config().busy,{since:e,toldAt:n}=this.waiting.get(t.id)??{since:this.now(),toldAt:this.now()},r=this.otherCalls(t),i=r.find(g=>g.status==="answered"),o=r.find(g=>g.id===this.widget.showing)??r.find(g=>!this.waiting.has(g.id)),u=e+s.maxWaitMinutes*6e4+this.deps.config().ringSeconds*1e3,d=n+s.retryMinutes*6e4,l=e+s.maxWaitMinutes*6e4;return{why:i?"call":o?"ringing":"voice",with:i?this.name(i.agentId):o?this.name(o.agentId):null,remindAt:d<l?d:null,waitsUntil:u}}missedTitle(t){return t.kind==="camera"?`${this.name(t.agentId)} asked to see through your camera`:`Missed call from ${this.name(t.agentId)}`}widgetAlive(){return this.now()-this.widgetSeenAt<S}async ringing(t={}){return this.widgetSeenAt=this.now(),this.widget=t,await this.hold(t),await this.sweep(),this.deps.store.list({status:["ringing"],kind:"voice",limit:20}).reverse()}async hold(t){let s=this.now(),e=this.deps.config().busy,n=[],r=this.deps.store.list({status:["ringing"],kind:"voice",limit:20});for(let i of this.waiting.keys())r.some(o=>o.id===i)||this.waiting.delete(i);for(let i of r){if(i.id===t.showing){this.waiting.delete(i.id)&&this.deps.store.transition(i.id,"ringing",{ringingSince:s});continue}if(!t.busy)continue;let o=this.waiting.get(i.id);if(!(o&&s-o.since>=e.maxWaitMinutes*6e4)&&this.deps.store.transition(i.id,"ringing",{ringingSince:s})){if(!o)this.startWaiting(i);else if(s-o.toldAt>=e.retryMinutes*6e4)o.toldAt=s;else continue;n.push(i)}}for(let i of n)await this.callWaiting(i)}async asking(){return await this.sweep(),this.deps.store.list({status:["ringing"],kind:"camera",limit:20}).reverse()}async sweep(){let t=this.now(),s=this.deps.config().ringSeconds*1e3,e=this.deps.config().maxCallMinutes*6e4;for(let n of this.deps.store.list({status:["ringing","later","answered"],limit:200}))if(n.status==="ringing"&&n.ringingSince!==null&&t-n.ringingSince>=s){if(!this.deps.store.transition(n.id,"ringing",{status:"missed",ringingSince:null,note:this.waiting.has(n.id)?"widget busy":"not answered"}))continue;this.deps.log?.(`[calls] ${n.id} from ${n.agentId} missed`),await this.notice(n,this.missedTitle(n))}else if(n.status==="answered"&&n.answeredAt!==null&&t-n.answeredAt>=e){if(!this.deps.store.transition(n.id,"answered",{status:"ended",endedAt:t,note:"no hang-up"}))continue;this.deps.log?.(`[calls] ${n.id} from ${n.agentId} ended: no hang-up in ${this.deps.config().maxCallMinutes} min`)}else if(n.status==="later"&&n.ringAgainAt!==null&&t>=n.ringAgainAt){let r=this.deps.store.transition(n.id,"later",{status:"ringing",ringingSince:t,ringAgainAt:null});r&&await this.ring(r)}}answer(t){let s=this.deps.store.get(t);if(!s)return c(t);let e=this.deps.store.transition(t,"ringing",{status:"answered",answeredAt:this.now(),ringingSince:null});return e?(this.deps.log?.(`[calls] ${t} answered (${s.agentId})`),e.kind==="camera"?{ok:!0,call:e}:{ok:!0,call:e,opener:_(e)}):{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}, not ringing`}}decline(t){if(!this.deps.store.get(t))return c(t);let e=this.deps.store.transition(t,["ringing","later"],{status:"declined",endedAt:this.now(),ringingSince:null,ringAgainAt:null});return e?{ok:!0,call:e}:{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}`}}later(t,s){if(!this.deps.store.get(t))return c(t);let n=s===void 0?I:Number(s);if(!Number.isInteger(n)||n<1||n>T)return{ok:!1,status:400,error:`minutes must be a whole number from 1 to ${T}`};let r=this.deps.store.transition(t,"ringing",{status:"later",ringingSince:null,ringAgainAt:this.now()+n*6e4});return r?{ok:!0,call:r}:{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}, not ringing`}}hangup(t){let s=this.deps.store.get(t);if(!s)return c(t);let e=this.deps.store.transition(t,"answered",{status:"ended",endedAt:this.now()});if(!e)return{ok:!1,status:409,error:`call is ${s.status}, not answered`};this.deps.log?.(`[calls] ${t} ended (${s.agentId})`);let n=this.deps.summarize;if(e.kind==="camera"||!this.deps.config().summary||!n)return{ok:!0,call:e};let r=(async()=>{try{let i=(await n(e))?.trim();if(!i)return;let o=this.deps.store.update(t,{summary:i});this.deps.file?.(o,i)}catch(i){this.deps.log?.(`[calls] summary for ${t} failed: ${i?.message??i}`)}})();return{ok:!0,call:e,summarized:r}}endCamera(t,s){let e=this.deps.store.get(t);if(!e||e.kind!=="camera")return!1;let n=this.deps.store.transition(t,"answered",{status:"ended",endedAt:this.now(),note:s??null});return n&&this.deps.log?.(`[calls] ${t} ended (${e.agentId}): ${s??"share over"}`),!!n}get(t){return this.deps.store.get(t)}list(t={}){return this.deps.store.list(t)}},$="withdrawn by the caller";function D(a,t=Date.now()){let s=n=>`${new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})} (in ${Math.max(1,Math.round((n-t)/6e4))} min)`;return`${a.why==="call"?`The owner is busy in another call${a.with?` (with ${a.with})`:""}.`:a.why==="ringing"?`The owner is busy: another call${a.with?` (from ${a.with})`:""} is ringing.`:"The owner is busy on the voice widget."} They were told you are calling, and why. Your call waits and rings by itself as soon as they are free: do not call again. `+(a.remindAt!==null?`Still busy at ${s(a.remindAt)}, they are told again that you are waiting. `:"")+`It waits until ${s(a.waitsUntil)} at most, then counts as a missed call.`}var c=a=>({ok:!1,status:404,error:`No such call: ${a}`});export{A as a,L as b,x as c,k as d,D as e};
11
+ //# sourceMappingURL=chunk-Q4XP5TBI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/calls/service.ts","../src/calls/store.ts"],"sourcesContent":["// --- An agent rings the owner (#321) ---\n//\n// An agent that needs the owner directly asks for a call. It rings on the\n// desktop widget (AgentX Voice), which polls `ringing()`. Answering starts\n// the widget's hands-free conversation with that agent, which opens with\n// its reason. When the widget is not running, `notify` stands in. While\n// the widget is busy (a turn, the microphone, another call) the call waits\n// for it: its ring time does not run, and the owner gets a call-waiting\n// notice (#408), again every calls.busy.retryMinutes. The caller is told\n// the owner is busy, with whom, and until when its call waits (#969). It\n// rings by itself once the widget is free, oldest first; the caller may\n// withdraw it meanwhile (`cancel`).\n//\n// Checked before anything rings, in this order:\n// 0. the caller is that agent: a turn of it is running now, named by its\n// task id or by its channel and chat (see CallerProof),\n// 1. the owner allows this agent (calls.allow; empty allows nobody),\n// 2. the agent has no other call in progress,\n// 3. it is under calls.maxPerHour,\n// 4. Focus: a non-urgent call does not ring. It becomes a missed call,\n// and its notice goes through notify, which holds it until Focus\n// ends. Urgent calls ring through, as `notify --urgent` does.\n//\n// A camera ask (#325 phase 3, kind \"camera\") goes through the same checks\n// and the same table. It never rings the widget: the notice goes to the\n// phone through notify, and the phone app polls `asking()` to show a\n// Show / Decline bar. Answering it is the owner tapping Show; the camera\n// opens only then, and the share ends the ask (see camera-api.ts).\n\nimport { randomUUID } from \"crypto\"\nimport { focusLabel, readFocus, type FocusState } from \"@/notify/focus\"\nimport type { CallsConfig } from \"@/daemon/config\"\nimport { LIVE, type Call, type CallKind, type CallStore, type CallUrgency } from \"./store\"\n\nexport const REASON_MAX = 200\n/** The widget polls every 2 s; missing this long means it is not running. */\nexport const WIDGET_FRESH_MS = 10_000\nexport const LATER_DEFAULT_MINUTES = 10\nexport const LATER_MAX_MINUTES = 240\n\n/** What a caller is told when the owner cannot take its call now (#969). */\nexport interface BusyInfo {\n /** \"call\": the owner is in a call; \"ringing\": another call is ringing;\n * \"voice\": AgentX Voice is in a turn of the owner's, or recording. */\n why: \"call\" | \"ringing\" | \"voice\"\n /** The agent the owner is in a call with, or whose call is ringing. */\n with: string | null\n /** When the owner is told again that this call waits, if still busy\n * then; null when the wait ends first. Ms since the epoch. */\n remindAt: number | null\n /** The call stops waiting then: still busy, it counts as missed. */\n waitsUntil: number\n}\n\nexport type CallResult =\n | { ok: true; call: Call }\n | { ok: false; status: number; error: string }\n\n/** What the request says about the turn placing it: the run's\n * AGENTX_TASK_ID, or, for a warm process that has none, its\n * AGENTX_CHANNEL and AGENTX_CHAT_ID. Loopback is not an identity. */\nexport interface CallerProof {\n taskId?: string\n channel?: string\n chatId?: string\n}\n\n/** The proof headers for a call placed from inside an agent's run. */\nexport function callerHeaders(env: NodeJS.ProcessEnv = process.env): Record<string, string> {\n if (env.AGENTX_TASK_ID) return { \"X-AgentX-Task\": env.AGENTX_TASK_ID }\n if (env.AGENTX_CHANNEL && env.AGENTX_CHAT_ID) {\n return { \"X-AgentX-Channel\": env.AGENTX_CHANNEL, \"X-AgentX-Chat\": env.AGENTX_CHAT_ID }\n }\n return {}\n}\n\n/** What the widget says with its poll. A widget from before #408 says nothing. */\nexport interface WidgetState {\n /** It cannot ring a new call now. */\n busy?: boolean\n /** The call ringing on it. */\n showing?: string\n}\n\nexport interface CallDeps {\n store: CallStore\n config: () => CallsConfig\n /** The agent's display name, or null when there is no such agent here. */\n agentName: (agentId: string) => string | null\n /** True when `proof` names a running turn of `agentId`. */\n isRunningTurn: (agentId: string, proof: CallerProof) => boolean\n /** The channel and chat of that running turn, when it has one, so a\n * camera ask is answered where it was asked. Unset: only a proof that\n * names them itself is kept. */\n turnSession?: (agentId: string, proof: CallerProof) => { channel?: string; chatId?: string } | null\n /** Tell the owner through notify. `urgent` passes Focus, like notify --urgent. */\n alert: (notice: { title: string; message: string; urgent: boolean; from: string }) => Promise<void>\n /** Ask the agent, in its voice session, to summarise the call. */\n summarize?: (call: Call) => Promise<string | null>\n /** File a finished summary where the dashboard shows it. */\n file?: (call: Call, summary: string) => void\n focus?: () => FocusState\n now?: () => number\n log?: (m: string) => void\n}\n\n/** What the widget sends through /ask when the owner answers, so the\n * agent speaks first and says why it called. */\nexport function openerPrompt(call: Pick<Call, \"reason\">): string {\n return \"[Call answered] The owner just picked up the voice call you asked for. \" +\n `You called because: \"${call.reason}\". Speak first: greet them in a few words ` +\n \"and say why you called, then let them answer.\"\n}\n\nexport const SUMMARY_PROMPT =\n \"[Call ended] The owner hung up. In two or three plain sentences, summarise what \" +\n \"was said and decided on this call, for your records. Reply with the summary only.\"\n\nexport class CallService {\n private widgetSeenAt = 0\n /** What the widget said with its last poll. */\n private widget: WidgetState = {}\n /** Calls waiting for a busy widget: since when, and when the owner was\n * last told. */\n private waiting = new Map<string, { since: number; toldAt: number }>()\n\n constructor(private deps: CallDeps) {}\n\n private now(): number { return this.deps.now?.() ?? Date.now() }\n private name(agentId: string): string { return this.deps.agentName(agentId) ?? agentId }\n\n /** An agent asks for a call, or to see (kind \"camera\"). 201 ringing, or\n * waiting for a busy owner (`rang: \"waiting\"`, with `busy`); 202 held\n * as missed (Focus). */\n async request(input: { agentId?: unknown; reason?: unknown; urgency?: unknown; kind?: unknown }, proof: CallerProof = {}): Promise<CallResult & { rang?: Rang; busy?: BusyInfo }> {\n const agentId = String(input.agentId ?? \"\").trim()\n const reason = String(input.reason ?? \"\").replace(/\\s+/g, \" \").trim()\n const urgency: CallUrgency = input.urgency === \"urgent\" ? \"urgent\" : \"normal\"\n const kind: CallKind = input.kind === \"camera\" ? \"camera\" : \"voice\"\n if (input.kind !== undefined && input.kind !== \"voice\" && input.kind !== \"camera\") return { ok: false, status: 400, error: \"kind must be voice or camera\" }\n if (!agentId || !reason) return { ok: false, status: 400, error: \"Required: agentId and reason\" }\n if (reason.length > REASON_MAX) return { ok: false, status: 413, error: `reason is over ${REASON_MAX} characters; keep it to one line` }\n if (this.deps.agentName(agentId) === null) return { ok: false, status: 404, error: `Unknown agent: ${agentId}` }\n if (!this.deps.isRunningTurn(agentId, proof)) {\n return { ok: false, status: 403, error: `No running turn of ${agentId} placed this call. An agent calls from inside its own run.` }\n }\n\n const cfg = this.deps.config()\n if (!cfg.allow.includes(\"*\") && !cfg.allow.includes(agentId)) {\n const verb = kind === \"camera\" ? \"may not ask to see through the owner's camera\" : \"may not call the owner\"\n return { ok: false, status: 403, error: `${agentId} ${verb}. Add it to calls.allow in agentx.json (or: agentx call allow ${agentId}).` }\n }\n await this.sweep()\n if (this.deps.store.list({ status: LIVE, limit: 200 }).some((c) => c.agentId === agentId)) {\n return { ok: false, status: 409, error: `${agentId} already has a call in progress` }\n }\n const now = this.now()\n if (this.deps.store.countSince(agentId, now - 3_600_000) >= cfg.maxPerHour) {\n return { ok: false, status: 429, error: `${agentId} has placed ${cfg.maxPerHour} calls in the last hour (calls.maxPerHour)` }\n }\n\n // Where the ask came from, for kind \"camera\": the turn's own chat, or\n // the one the proof names. A task run has neither.\n const session: { channel?: string; chatId?: string } = kind === \"camera\" ? (this.deps.turnSession?.(agentId, proof) ?? proof) : {}\n const call: Call = {\n id: `call-${randomUUID().slice(0, 8)}`, agentId, kind, reason, urgency, status: \"ringing\", createdAt: now,\n ringingSince: now, answeredAt: null, endedAt: null, ringAgainAt: null, note: null, summary: null,\n channel: session.channel && session.chatId ? session.channel : null,\n chatId: session.channel && session.chatId ? session.chatId : null,\n }\n this.deps.store.insert(call)\n this.deps.log?.(`[calls] ${agentId} asks ${kind === \"camera\" ? \"to see\" : \"for a call\"} (${urgency}): ${reason}`)\n const rang = await this.ring(call)\n const saved = this.deps.store.get(call.id)!\n if (rang !== \"waiting\") return { ok: true, call: saved, rang }\n // The widget may have come free while the owner was being told.\n return this.waiting.has(call.id) ? { ok: true, call: saved, rang, busy: this.busyInfo(call) } : { ok: true, call: saved, rang: \"widget\" }\n }\n\n /** The caller withdraws its own voice call while it waits or rings, for\n * example to send a message instead (#969). */\n async cancel(input: { agentId?: unknown }, proof: CallerProof = {}): Promise<CallResult> {\n const agentId = String(input.agentId ?? \"\").trim()\n if (!agentId) return { ok: false, status: 400, error: \"Required: agentId\" }\n if (!this.deps.isRunningTurn(agentId, proof)) {\n return { ok: false, status: 403, error: `No running turn of ${agentId} asked for this. An agent withdraws its own call from inside its run.` }\n }\n // No sweep first: a call back that is due must not ring just to be withdrawn.\n const mine = this.deps.store.list({ status: [\"ringing\", \"later\"], kind: \"voice\", limit: 200 }).find((c) => c.agentId === agentId)\n if (!mine) return { ok: false, status: 404, error: `${agentId} has no call waiting or ringing` }\n const ended = this.deps.store.transition(mine.id, [\"ringing\", \"later\"], { status: \"ended\", endedAt: this.now(), ringingSince: null, ringAgainAt: null, note: CANCELLED_NOTE })\n if (!ended) return { ok: false, status: 409, error: `call is ${this.deps.store.get(mine.id)?.status}` }\n this.waiting.delete(mine.id)\n this.deps.log?.(`[calls] ${mine.id} withdrawn by ${agentId}`)\n return { ok: true, call: ended }\n }\n\n /** Ring now, wait for a busy widget, or hold as missed in Focus.\n * Returns how it rang. */\n private async ring(call: Call): Promise<Rang> {\n const focus = (this.deps.focus ?? readFocus)()\n if (focus.active && call.urgency !== \"urgent\") {\n if (!this.deps.store.transition(call.id, \"ringing\", { status: \"missed\", ringingSince: null, note: focusLabel(focus) })) return false\n await this.notice(call, this.missedTitle(call))\n return false\n }\n // A camera ask is answered on the phone, never on the widget.\n if (call.kind === \"camera\") {\n await this.notice(call, `${this.name(call.agentId)} wants to see through your camera`,\n `Open the phone app and tap Show within ${this.deps.config().ringSeconds} s.`)\n return \"notify\"\n }\n if (this.widgetAlive()) {\n // Busy by its last poll, or by a call placed since that it will show first.\n if (!this.widget.busy && !this.otherCalls(call).length) return \"widget\"\n this.startWaiting(call)\n await this.callWaiting(call)\n return \"waiting\"\n }\n await this.notice(call, `${this.name(call.agentId)} is calling`,\n `Open AgentX Voice to answer within ${this.deps.config().ringSeconds} s.`)\n return \"notify\"\n }\n\n private async notice(call: Call, title: string, extra?: string): Promise<void> {\n try {\n await this.deps.alert({\n title, message: extra ? `${call.reason}\\n${extra}` : call.reason,\n urgent: call.urgency === \"urgent\", from: call.agentId,\n })\n } catch (e: any) {\n this.deps.log?.(`[calls] notice for ${call.id} failed: ${e?.message ?? e}`)\n }\n }\n\n /** The call starts waiting for the busy widget. */\n private startWaiting(call: Call): void {\n const now = this.now()\n this.waiting.set(call.id, { since: now, toldAt: now })\n this.deps.log?.(`[calls] ${call.id} from ${call.agentId} waits: the widget is busy`)\n }\n\n /** Voice calls ringing or answered other than `call`, oldest first. */\n private otherCalls(call: Call): Call[] {\n return this.deps.store.list({ status: [\"ringing\", \"answered\"], kind: \"voice\", limit: 200 }).filter((c) => c.id !== call.id).reverse()\n }\n\n private async callWaiting(call: Call): Promise<void> {\n const busy = this.deps.config().busy\n await this.notice(call, busy.title.replaceAll(\"{agent}\", this.name(call.agentId)), busy.notice)\n }\n\n /** Why the owner cannot take `call` now, and how long it waits. */\n private busyInfo(call: Call): BusyInfo {\n const cfg = this.deps.config().busy\n const { since, toldAt } = this.waiting.get(call.id) ?? { since: this.now(), toldAt: this.now() }\n const others = this.otherCalls(call)\n const talking = others.find((c) => c.status === \"answered\")\n // The call on the pill, or the oldest one it has yet to show.\n const showing = others.find((c) => c.id === this.widget.showing) ?? others.find((c) => !this.waiting.has(c.id))\n // After the wait the ring time runs once more before it is missed.\n const waitsUntil = since + cfg.maxWaitMinutes * 60_000 + this.deps.config().ringSeconds * 1000\n const remindAt = toldAt + cfg.retryMinutes * 60_000\n const stopsWaiting = since + cfg.maxWaitMinutes * 60_000\n return {\n why: talking ? \"call\" : showing ? \"ringing\" : \"voice\",\n with: talking ? this.name(talking.agentId) : showing ? this.name(showing.agentId) : null,\n remindAt: remindAt < stopsWaiting ? remindAt : null,\n waitsUntil,\n }\n }\n\n private missedTitle(call: Call): string {\n return call.kind === \"camera\" ? `${this.name(call.agentId)} asked to see through your camera` : `Missed call from ${this.name(call.agentId)}`\n }\n\n /** True when the widget polled recently. */\n widgetAlive(): boolean {\n return this.now() - this.widgetSeenAt < WIDGET_FRESH_MS\n }\n\n /** The widget's poll: voice calls ringing now, oldest first. Marks it alive. */\n async ringing(widget: WidgetState = {}): Promise<Call[]> {\n this.widgetSeenAt = this.now()\n this.widget = widget\n await this.hold(widget)\n await this.sweep()\n return this.deps.store.list({ status: [\"ringing\"], kind: \"voice\", limit: 20 }).reverse()\n }\n\n /** A busy widget cannot ring: the ring time of each call it is not\n * showing starts over at every poll, for calls.busy.maxWaitMinutes at\n * most. The owner is told that the call waits, and again every\n * calls.busy.retryMinutes. The ring time starts over once more when the\n * widget first shows a call that waited. */\n private async hold(widget: WidgetState): Promise<void> {\n const now = this.now()\n const busy = this.deps.config().busy\n // Told after the loop: a poll that overlaps a slow notice must not\n // carry on from a list and a widget state that are out of date.\n const tell: Call[] = []\n const live = this.deps.store.list({ status: [\"ringing\"], kind: \"voice\", limit: 20 })\n for (const id of this.waiting.keys()) if (!live.some((c) => c.id === id)) this.waiting.delete(id)\n for (const call of live) {\n if (call.id === widget.showing) {\n if (this.waiting.delete(call.id)) this.deps.store.transition(call.id, \"ringing\", { ringingSince: now })\n continue\n }\n if (!widget.busy) continue\n const held = this.waiting.get(call.id)\n if (held && now - held.since >= busy.maxWaitMinutes * 60_000) continue\n if (!this.deps.store.transition(call.id, \"ringing\", { ringingSince: now })) continue\n if (!held) this.startWaiting(call)\n else if (now - held.toldAt >= busy.retryMinutes * 60_000) held.toldAt = now\n else continue\n tell.push(call)\n }\n for (const call of tell) await this.callWaiting(call)\n }\n\n /** The phone app's poll: camera asks waiting for the owner, oldest first.\n * Does not count as the widget being up. */\n async asking(): Promise<Call[]> {\n await this.sweep()\n return this.deps.store.list({ status: [\"ringing\"], kind: \"camera\", limit: 20 }).reverse()\n }\n\n /** Unanswered calls become missed; \"later\" calls that came due ring\n * again; answered calls nobody hung up end after calls.maxCallMinutes. */\n async sweep(): Promise<void> {\n const now = this.now()\n const ringFor = this.deps.config().ringSeconds * 1000\n const talkFor = this.deps.config().maxCallMinutes * 60_000\n for (const call of this.deps.store.list({ status: [\"ringing\", \"later\", \"answered\"], limit: 200 })) {\n // The list was read before any await below: each move re-checks the\n // status in the store, so a call answered meanwhile is left alone.\n if (call.status === \"ringing\" && call.ringingSince !== null && now - call.ringingSince >= ringFor) {\n if (!this.deps.store.transition(call.id, \"ringing\", { status: \"missed\", ringingSince: null, note: this.waiting.has(call.id) ? \"widget busy\" : \"not answered\" })) continue\n this.deps.log?.(`[calls] ${call.id} from ${call.agentId} missed`)\n await this.notice(call, this.missedTitle(call))\n } else if (call.status === \"answered\" && call.answeredAt !== null && now - call.answeredAt >= talkFor) {\n if (!this.deps.store.transition(call.id, \"answered\", { status: \"ended\", endedAt: now, note: \"no hang-up\" })) continue\n this.deps.log?.(`[calls] ${call.id} from ${call.agentId} ended: no hang-up in ${this.deps.config().maxCallMinutes} min`)\n } else if (call.status === \"later\" && call.ringAgainAt !== null && now >= call.ringAgainAt) {\n const again = this.deps.store.transition(call.id, \"later\", { status: \"ringing\", ringingSince: now, ringAgainAt: null })\n if (again) await this.ring(again)\n }\n }\n }\n\n /** The owner picked up, or tapped Show. Returns the call and, for a\n * voice call, the opener for /ask. */\n answer(id: string): CallResult & { opener?: string } {\n const call = this.deps.store.get(id)\n if (!call) return unknown(id)\n const answered = this.deps.store.transition(id, \"ringing\", { status: \"answered\", answeredAt: this.now(), ringingSince: null })\n if (!answered) return { ok: false, status: 409, error: `call is ${this.deps.store.get(id)?.status}, not ringing` }\n this.deps.log?.(`[calls] ${id} answered (${call.agentId})`)\n return answered.kind === \"camera\" ? { ok: true, call: answered } : { ok: true, call: answered, opener: openerPrompt(answered) }\n }\n\n decline(id: string): CallResult {\n const call = this.deps.store.get(id)\n if (!call) return unknown(id)\n const declined = this.deps.store.transition(id, [\"ringing\", \"later\"], { status: \"declined\", endedAt: this.now(), ringingSince: null, ringAgainAt: null })\n return declined ? { ok: true, call: declined } : { ok: false, status: 409, error: `call is ${this.deps.store.get(id)?.status}` }\n }\n\n /** \"Call back in N min\": it rings again then. */\n later(id: string, minutes?: unknown): CallResult {\n const call = this.deps.store.get(id)\n if (!call) return unknown(id)\n const n = minutes === undefined ? LATER_DEFAULT_MINUTES : Number(minutes)\n if (!Number.isInteger(n) || n < 1 || n > LATER_MAX_MINUTES) {\n return { ok: false, status: 400, error: `minutes must be a whole number from 1 to ${LATER_MAX_MINUTES}` }\n }\n const later = this.deps.store.transition(id, \"ringing\", { status: \"later\", ringingSince: null, ringAgainAt: this.now() + n * 60_000 })\n return later ? { ok: true, call: later } : { ok: false, status: 409, error: `call is ${this.deps.store.get(id)?.status}, not ringing` }\n }\n\n /** End an answered call. The summary is written in the background;\n * `summarized` settles when it is filed (tests wait on it). */\n hangup(id: string): CallResult & { summarized?: Promise<void> } {\n const call = this.deps.store.get(id)\n if (!call) return unknown(id)\n const ended = this.deps.store.transition(id, \"answered\", { status: \"ended\", endedAt: this.now() })\n if (!ended) return { ok: false, status: 409, error: `call is ${call.status}, not answered` }\n this.deps.log?.(`[calls] ${id} ended (${call.agentId})`)\n const summarize = this.deps.summarize\n // What the agent saw is already its answer; only a voice call is summarised.\n if (ended.kind === \"camera\" || !this.deps.config().summary || !summarize) return { ok: true, call: ended }\n const summarized = (async () => {\n try {\n const text = (await summarize(ended))?.trim()\n if (!text) return\n const done = this.deps.store.update(id, { summary: text })!\n this.deps.file?.(done, text)\n } catch (e: any) {\n this.deps.log?.(`[calls] summary for ${id} failed: ${e?.message ?? e}`)\n }\n })()\n return { ok: true, call: ended, summarized }\n }\n\n /** A camera ask ends when the share ends; no summary. Only an answered\n * ask ends this way, so a stop before Show leaves it ringing. */\n endCamera(id: string, note?: string): boolean {\n const call = this.deps.store.get(id)\n if (!call || call.kind !== \"camera\") return false\n const ended = this.deps.store.transition(id, \"answered\", { status: \"ended\", endedAt: this.now(), note: note ?? null })\n if (ended) this.deps.log?.(`[calls] ${id} ended (${call.agentId}): ${note ?? \"share over\"}`)\n return !!ended\n }\n\n get(id: string): Call | undefined { return this.deps.store.get(id) }\n\n list(opts: Parameters<CallStore[\"list\"]>[0] = {}): Call[] { return this.deps.store.list(opts) }\n}\n\n/** How a call reached the owner: on the widget, through notify, waiting\n * for a busy widget, or not at all (held as missed). */\nexport type Rang = \"widget\" | \"notify\" | \"waiting\" | false\n\n/** The note on a call its caller withdrew. */\nexport const CANCELLED_NOTE = \"withdrawn by the caller\"\n\n/** What the caller reads when its call waits for a busy owner. */\nexport function busyText(busy: BusyInfo, now: number = Date.now()): string {\n const at = (ms: number) => `${new Date(ms).toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\", hour12: false })} (in ${Math.max(1, Math.round((ms - now) / 60_000))} min)`\n const why = busy.why === \"call\" ? `The owner is busy in another call${busy.with ? ` (with ${busy.with})` : \"\"}.`\n : busy.why === \"ringing\" ? `The owner is busy: another call${busy.with ? ` (from ${busy.with})` : \"\"} is ringing.`\n : \"The owner is busy on the voice widget.\"\n return `${why} They were told you are calling, and why. Your call waits and rings by itself as soon as they are free: do not call again. ` +\n (busy.remindAt !== null ? `Still busy at ${at(busy.remindAt)}, they are told again that you are waiting. ` : \"\") +\n `It waits until ${at(busy.waitsUntil)} at most, then counts as a missed call.`\n}\n\nconst unknown = (id: string): CallResult => ({ ok: false, status: 404, error: `No such call: ${id}` })\n","// --- Calls an agent placed to the owner, kept in SQLite ---\n//\n// One row per call, so a missed call is still there after a restart and\n// the dashboard can list them. Nothing else reads this table. A camera\n// ask (#325 phase 3: \"show me\") is a call of kind \"camera\": same\n// allowlist, same hourly limit, same lifecycle, answered on the phone\n// instead of the voice widget.\n\nimport type Database from \"better-sqlite3\"\n\nexport type CallStatus = \"ringing\" | \"answered\" | \"ended\" | \"declined\" | \"missed\" | \"later\"\nexport type CallUrgency = \"normal\" | \"urgent\"\n/** \"voice\": a live voice call on the widget. \"camera\": the agent asks to see through the phone camera. */\nexport type CallKind = \"voice\" | \"camera\"\n\nexport interface Call {\n id: string\n agentId: string\n kind: CallKind\n reason: string\n urgency: CallUrgency\n status: CallStatus\n /** The channel and chat the asking turn ran in, so what the agent sees\n * is answered there; null when the turn had none (a task run). */\n channel: string | null\n chatId: string | null\n /** When the agent asked, ms since the epoch. */\n createdAt: number\n /** When it last started ringing: at the request, or when \"later\" came due. */\n ringingSince: number | null\n answeredAt: number | null\n endedAt: number | null\n /** Status \"later\": when it rings again. */\n ringAgainAt: number | null\n /** Why it ended the way it did, in a few words (\"in Focus\", \"not answered\"). */\n note: string | null\n /** The agent's own summary, written after hang-up. */\n summary: string | null\n}\n\n/** Calls still in progress: an agent has at most one of these. */\nexport const LIVE: CallStatus[] = [\"ringing\", \"answered\", \"later\"]\n\nconst COLUMNS = `id, agent_id AS agentId, kind, reason, urgency, status, created_at AS createdAt,\n ringing_since AS ringingSince, answered_at AS answeredAt, ended_at AS endedAt,\n ring_again_at AS ringAgainAt, note, summary, channel, chat_id AS chatId`\n\nexport class CallStore {\n constructor(private db: Database.Database) {\n db.exec(`CREATE TABLE IF NOT EXISTS calls (\n id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, reason TEXT NOT NULL,\n urgency TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL,\n ringing_since INTEGER, answered_at INTEGER, ended_at INTEGER,\n ring_again_at INTEGER, note TEXT, summary TEXT);\n CREATE INDEX IF NOT EXISTS calls_recent ON calls(created_at DESC);`)\n // Columns added since the table first shipped (#325 phase 3). A row\n // from before is a voice call from a turn whose chat was not kept.\n const have = new Set((db.prepare(\"PRAGMA table_info(calls)\").all() as Array<{ name: string }>).map((c) => c.name))\n if (!have.has(\"kind\")) db.exec(\"ALTER TABLE calls ADD COLUMN kind TEXT NOT NULL DEFAULT 'voice'\")\n if (!have.has(\"channel\")) db.exec(\"ALTER TABLE calls ADD COLUMN channel TEXT\")\n if (!have.has(\"chat_id\")) db.exec(\"ALTER TABLE calls ADD COLUMN chat_id TEXT\")\n }\n\n insert(call: Call): void {\n this.db.prepare(`INSERT INTO calls (id, agent_id, kind, reason, urgency, status, created_at, ringing_since,\n answered_at, ended_at, ring_again_at, note, summary, channel, chat_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(\n call.id, call.agentId, call.kind, call.reason, call.urgency, call.status, call.createdAt,\n call.ringingSince, call.answeredAt, call.endedAt, call.ringAgainAt, call.note, call.summary, call.channel, call.chatId)\n }\n\n get(id: string): Call | undefined {\n return this.db.prepare(`SELECT ${COLUMNS} FROM calls WHERE id=?`).get(id) as Call | undefined\n }\n\n /** Write the changed fields of one call. */\n update(id: string, patch: Partial<Omit<Call, \"id\" | \"agentId\" | \"createdAt\">>): Call | undefined {\n const cols: Record<string, string> = {\n reason: \"reason\", urgency: \"urgency\", status: \"status\", ringingSince: \"ringing_since\",\n answeredAt: \"answered_at\", endedAt: \"ended_at\", ringAgainAt: \"ring_again_at\", note: \"note\", summary: \"summary\",\n }\n const keys = Object.keys(patch).filter((k) => k in cols)\n if (keys.length) {\n const set = keys.map((k) => `${cols[k]}=?`).join(\", \")\n this.db.prepare(`UPDATE calls SET ${set} WHERE id=?`).run(...keys.map((k) => (patch as any)[k] ?? null), id)\n }\n return this.get(id)\n }\n\n /** Change a call only if it is still `from`: the check and the write are\n * one statement, so two sweeps, or a sweep and the owner answering,\n * cannot both move the same call. Undefined when it had moved on. */\n transition(id: string, from: CallStatus | CallStatus[], patch: Partial<Omit<Call, \"id\" | \"agentId\" | \"createdAt\">>): Call | undefined {\n const statuses = Array.isArray(from) ? from : [from]\n const cols: Record<string, string> = {\n status: \"status\", ringingSince: \"ringing_since\", answeredAt: \"answered_at\", endedAt: \"ended_at\",\n ringAgainAt: \"ring_again_at\", note: \"note\", summary: \"summary\",\n }\n const keys = Object.keys(patch).filter((k) => k in cols)\n const set = keys.map((k) => `${cols[k]}=?`).join(\", \")\n const marks = statuses.map(() => \"?\").join(\",\")\n const changed = this.db.prepare(`UPDATE calls SET ${set} WHERE id=? AND status IN (${marks})`)\n .run(...keys.map((k) => (patch as any)[k] ?? null), id, ...statuses).changes\n return changed ? this.get(id) : undefined\n }\n\n /** Newest first; only these statuses, and only this kind, when given. */\n list(opts: { status?: CallStatus[]; kind?: CallKind; limit?: number } = {}): Call[] {\n const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200)\n const where: string[] = []\n const args: unknown[] = []\n if (opts.status?.length) {\n where.push(`status IN (${opts.status.map(() => \"?\").join(\",\")})`)\n args.push(...opts.status)\n }\n if (opts.kind) { where.push(\"kind=?\"); args.push(opts.kind) }\n const filter = where.length ? `WHERE ${where.join(\" AND \")}` : \"\"\n return this.db.prepare(`SELECT ${COLUMNS} FROM calls ${filter} ORDER BY created_at DESC, rowid DESC LIMIT ?`)\n .all(...args, limit) as Call[]\n }\n\n /** Calls this agent placed after `since` (ms), for the hourly limit. */\n countSince(agentId: string, since: number): number {\n return (this.db.prepare(\"SELECT COUNT(*) AS n FROM calls WHERE agent_id=? AND created_at>?\")\n .get(agentId, since) as { n: number }).n\n }\n}\n"],"mappings":"+CA6BA,OAAS,cAAAA,MAAkB,SCYpB,IAAMC,EAAqB,CAAC,UAAW,WAAY,OAAO,EAE3DC,EAAU;AAAA;AAAA,2EAIHC,EAAN,KAAgB,CACrB,YAAoBC,EAAuB,CAAvB,QAAAA,EAClBA,EAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA,yEAK6D,EAGrE,IAAMC,EAAO,IAAI,IAAKD,EAAG,QAAQ,0BAA0B,EAAE,IAAI,EAA8B,IAAKE,GAAMA,EAAE,IAAI,CAAC,EAC5GD,EAAK,IAAI,MAAM,GAAGD,EAAG,KAAK,iEAAiE,EAC3FC,EAAK,IAAI,SAAS,GAAGD,EAAG,KAAK,2CAA2C,EACxEC,EAAK,IAAI,SAAS,GAAGD,EAAG,KAAK,2CAA2C,CAC/E,CAEA,OAAOG,EAAkB,CACvB,KAAK,GAAG,QAAQ;AAAA,oHACgG,EAAE,IAChHA,EAAK,GAAIA,EAAK,QAASA,EAAK,KAAMA,EAAK,OAAQA,EAAK,QAASA,EAAK,OAAQA,EAAK,UAC/EA,EAAK,aAAcA,EAAK,WAAYA,EAAK,QAASA,EAAK,YAAaA,EAAK,KAAMA,EAAK,QAASA,EAAK,QAASA,EAAK,MAAM,CAC1H,CAEA,IAAIC,EAA8B,CAChC,OAAO,KAAK,GAAG,QAAQ,UAAUN,yBAA+B,EAAE,IAAIM,CAAE,C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E,KAAKe,EAAyC,CAAC,EAAW,CAAE,OAAO,KAAK,KAAK,MAAM,KAAKA,CAAI,CAAE,CAChG,EAOalC,EAAiB,0BAGvB,SAASmC,EAAS5B,EAAgBd,EAAc,KAAK,IAAI,EAAW,CACzE,IAAM2C,EAAMC,GAAe,GAAG,IAAI,KAAKA,CAAE,EAAE,mBAAmB,CAAC,EAAG,CAAE,KAAM,UAAW,OAAQ,UAAW,OAAQ,EAAM,CAAC,SAAS,KAAK,IAAI,EAAG,KAAK,OAAOA,EAAK5C,GAAO,GAAM,CAAC,SAI3K,MAAO,GAHKc,EAAK,MAAQ,OAAS,oCAAoCA,EAAK,KAAO,UAAUA,EAAK,QAAU,MACvGA,EAAK,MAAQ,UAAY,kCAAkCA,EAAK,KAAO,UAAUA,EAAK,QAAU,iBAChG,uKAEDA,EAAK,WAAa,KAAO,iBAAiB6B,EAAG7B,EAAK,QAAQ,gDAAkD,IAC7G,kBAAkB6B,EAAG7B,EAAK,UAAU,0CACxC,CAEA,IAAMiB,EAAWL,IAA4B,CAAE,GAAI,GAAO,OAAQ,IAAK,MAAO,iBAAiBA,GAAK","names":["randomUUID","LIVE","COLUMNS","CallStore","db","have","c","call","id","patch","cols","keys","k","set","from","statuses","marks","opts","limit","where","args","filter","agentId","since","REASON_MAX","WIDGET_FRESH_MS","LATER_DEFAULT_MINUTES","LATER_MAX_MINUTES","callerHeaders","env","openerPrompt","call","SUMMARY_PROMPT","CallService","deps","agentId","input","proof","reason","urgency","kind","cfg","LIVE","c","now","session","randomUUID","rang","saved","mine","ended","CANCELLED_NOTE","focus","readFocus","focusLabel","title","extra","e","busy","since","toldAt","others","talking","showing","waitsUntil","remindAt","stopsWaiting","widget","tell","live","id","held","ringFor","talkFor","again","unknown","answered","declined","minutes","later","summarize","summarized","text","done","note","opts","busyText","at","ms"]}
@@ -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