agentix-cli 0.143.0 → 0.144.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 (156) hide show
  1. package/dist/{App-UTDCBFZI.js → App-N2U77ED7.js} +2 -2
  2. package/dist/{ChatApp-7P22XAL2.js → ChatApp-GYVTECF6.js} +2 -2
  3. package/dist/{absorb-eval-EGO6JJOV.js → absorb-eval-WSAVWCZV.js} +2 -2
  4. package/dist/{agent-AI6LNZV2.js → agent-SLRGXBMK.js} +2 -2
  5. package/dist/{board-dashboard-ZKN5Y3GJ.js → board-dashboard-B3T7VCRQ.js} +4 -4
  6. package/dist/{chunk-SDSSRNSU.js → chunk-2GJFLPS7.js} +3 -3
  7. package/dist/{chunk-NYWIN4BW.js → chunk-3LAQ74H7.js} +2 -2
  8. package/dist/{chunk-THWDSPX4.js → chunk-45TKVOJX.js} +2 -2
  9. package/dist/{chunk-RB5W3FVO.js → chunk-4JHMV3D3.js} +2 -2
  10. package/dist/{chunk-QSKG754X.js → chunk-5TTHN7DP.js} +12 -8
  11. package/dist/chunk-5TTHN7DP.js.map +1 -0
  12. package/dist/{chunk-PYI7ZAU3.js → chunk-BAO77R4L.js} +2 -2
  13. package/dist/{chunk-YYPTXXCJ.js → chunk-CZWEXRIE.js} +2 -2
  14. package/dist/{chunk-OMO7UTWW.js → chunk-DFWPTNZ5.js} +2 -2
  15. package/dist/chunk-DG2DC43E.js +11 -0
  16. package/dist/chunk-DG2DC43E.js.map +1 -0
  17. package/dist/chunk-DPIQCHXB.js +62 -0
  18. package/dist/chunk-DPIQCHXB.js.map +1 -0
  19. package/dist/{chunk-3WBOWXAN.js → chunk-EX4AREN5.js} +2 -2
  20. package/dist/{chunk-MFUN3ZS3.js → chunk-GOAMSJ2D.js} +2 -2
  21. package/dist/{chunk-YVNGPYXN.js → chunk-GWBBWYGM.js} +58 -55
  22. package/dist/chunk-GWBBWYGM.js.map +1 -0
  23. package/dist/{chunk-WY5ZOEOE.js → chunk-JGX5IWNX.js} +2 -2
  24. package/dist/chunk-KV4ZA7FS.js +4 -0
  25. package/dist/chunk-KV4ZA7FS.js.map +1 -0
  26. package/dist/{chunk-YXFTUOZR.js → chunk-LLJZMS23.js} +2 -2
  27. package/dist/{chunk-L4RCA3OC.js → chunk-LVQHNTXV.js} +2 -2
  28. package/dist/{chunk-UNIXYV3U.js → chunk-M7527M7D.js} +2 -2
  29. package/dist/{chunk-IABJLTZN.js → chunk-MXWAREAQ.js} +2 -2
  30. package/dist/{chunk-GB4YT5IG.js → chunk-PJGLIAEP.js} +247 -240
  31. package/dist/chunk-PJGLIAEP.js.map +1 -0
  32. package/dist/{chunk-ERG5OUKH.js → chunk-Q73QQPDB.js} +2 -2
  33. package/dist/{chunk-O2CYERSX.js → chunk-QI4FYJGJ.js} +2 -2
  34. package/dist/{chunk-HPQ3AAG3.js → chunk-R5VGRKUW.js} +2 -2
  35. package/dist/{chunk-N2HLL25P.js → chunk-RGBQULXX.js} +2 -2
  36. package/dist/{chunk-6CTQPGBR.js → chunk-RV4WJZW5.js} +2 -2
  37. package/dist/{chunk-QVPBSV5Z.js → chunk-SFUNL7RV.js} +2 -2
  38. package/dist/{chunk-7H6HDN3K.js → chunk-SVNYI6GR.js} +2 -2
  39. package/dist/{chunk-DKLVB5L6.js → chunk-TTBCXVPJ.js} +6 -6
  40. package/dist/chunk-TTBCXVPJ.js.map +1 -0
  41. package/dist/{chunk-XWHD2Z3Z.js → chunk-UII54DAP.js} +2 -2
  42. package/dist/{chunk-5BXAKMYK.js → chunk-UNZRZOED.js} +2 -2
  43. package/dist/{chunk-Y4CYQV7G.js → chunk-VY7TBMJU.js} +2 -2
  44. package/dist/chunk-VY7TBMJU.js.map +1 -0
  45. package/dist/{chunk-AJUWIBLV.js → chunk-VYLMC5DO.js} +2 -2
  46. package/dist/{chunk-SHEUCITK.js → chunk-WBG6NA7R.js} +2 -2
  47. package/dist/{chunk-SHEUCITK.js.map → chunk-WBG6NA7R.js.map} +1 -1
  48. package/dist/cli.js +1 -1
  49. package/dist/{client-E66ELJK7.js → client-B7FXDTYK.js} +2 -2
  50. package/dist/config-MLP33NWR.js +2 -0
  51. package/dist/{config-mutate-QBDKJNHA.js → config-mutate-XQRUAVEH.js} +2 -2
  52. package/dist/config-mutator-5JFTMQ43.js +2 -0
  53. package/dist/{contributions-L5XZJ3DP.js → contributions-ESUSYUQG.js} +2 -2
  54. package/dist/{doctor-3ZUFSE6R.js → doctor-DIYZGSIS.js} +2 -2
  55. package/dist/{failure-candidates-XZSZP4HT.js → failure-candidates-NQX2JMMS.js} +2 -2
  56. package/dist/{follow-up-tool-6OCQUSC3.js → follow-up-tool-QXEYEWX7.js} +2 -2
  57. package/dist/{grants-CEUGZBQ4.js → grants-MM7U6GCK.js} +2 -2
  58. package/dist/{hub-MOQRSVCQ.js → hub-OC7PH2AR.js} +2 -2
  59. package/dist/index.d.ts +213 -76
  60. package/dist/index.js +1 -1
  61. package/dist/{program-AR6F763U.js → program-LZPM6I2Q.js} +289 -254
  62. package/dist/program-LZPM6I2Q.js.map +1 -0
  63. package/dist/{promote-ZGJEPCBE.js → promote-SIC6RWCX.js} +2 -2
  64. package/dist/{query-JLTHESIZ.js → query-OP2MSR2G.js} +2 -2
  65. package/dist/{query-settings-GMEL3EKR.js → query-settings-67332F5V.js} +2 -2
  66. package/dist/{registry-MFD3XJBR.js → registry-G2ZG5TIN.js} +2 -2
  67. package/dist/{request-planner-4ORFYSAT.js → request-planner-THTPE3FP.js} +2 -2
  68. package/dist/{review-candidates-77NDFTGM.js → review-candidates-7PS7CHXF.js} +2 -2
  69. package/dist/{routing-3FL3KYPJ.js → routing-PE7DB7WA.js} +2 -2
  70. package/dist/schedule-tool-3FXRKJGN.js +2 -0
  71. package/dist/{scheduler-QLL7ZHYW.js → scheduler-YTXCIQTZ.js} +2 -2
  72. package/dist/{seat-RBKONP63.js → seat-6DMK4274.js} +2 -2
  73. package/dist/{select-MOUDR6PQ.js → select-CLDYPAOS.js} +2 -2
  74. package/dist/{set-enabled-JKYF3QIA.js → set-enabled-ZH2DH4GU.js} +2 -2
  75. package/dist/tool-4AO3ZMAY.js +6 -0
  76. package/dist/tool-4AO3ZMAY.js.map +1 -0
  77. package/dist/{tool-Y3ZTSZGE.js → tool-MKDTKBJ4.js} +3 -3
  78. package/dist/{tool-Y3ZTSZGE.js.map → tool-MKDTKBJ4.js.map} +1 -1
  79. package/dist/traces-GVEQZX24.js +2 -0
  80. package/dist/{wiki-3FSSLQAE.js → wiki-CH2HYJVI.js} +2 -2
  81. package/dist/wiki-enrich-VEAYFVR2.js +2 -0
  82. package/dist/wiki-enrich-VEAYFVR2.js.map +1 -0
  83. package/dist/workflow-pilot-HCPSMGIC.js +2 -0
  84. package/dist/workflow-pilot-HCPSMGIC.js.map +1 -0
  85. package/package.json +1 -1
  86. package/dist/chunk-3W2BHUGM.js +0 -11
  87. package/dist/chunk-3W2BHUGM.js.map +0 -1
  88. package/dist/chunk-AKWBDCMU.js +0 -4
  89. package/dist/chunk-AKWBDCMU.js.map +0 -1
  90. package/dist/chunk-DKLVB5L6.js.map +0 -1
  91. package/dist/chunk-GB4YT5IG.js.map +0 -1
  92. package/dist/chunk-K22XMF6M.js +0 -62
  93. package/dist/chunk-K22XMF6M.js.map +0 -1
  94. package/dist/chunk-QSKG754X.js.map +0 -1
  95. package/dist/chunk-Y4CYQV7G.js.map +0 -1
  96. package/dist/chunk-YVNGPYXN.js.map +0 -1
  97. package/dist/config-3C3Z7VKG.js +0 -2
  98. package/dist/config-mutator-ZI3SQIUN.js +0 -2
  99. package/dist/program-AR6F763U.js.map +0 -1
  100. package/dist/schedule-tool-5KJMXBRZ.js +0 -2
  101. package/dist/tool-C4JNMTEF.js +0 -6
  102. package/dist/tool-C4JNMTEF.js.map +0 -1
  103. package/dist/wiki-enrich-HQWXZRID.js +0 -2
  104. /package/dist/{App-UTDCBFZI.js.map → App-N2U77ED7.js.map} +0 -0
  105. /package/dist/{ChatApp-7P22XAL2.js.map → ChatApp-GYVTECF6.js.map} +0 -0
  106. /package/dist/{absorb-eval-EGO6JJOV.js.map → absorb-eval-WSAVWCZV.js.map} +0 -0
  107. /package/dist/{agent-AI6LNZV2.js.map → agent-SLRGXBMK.js.map} +0 -0
  108. /package/dist/{board-dashboard-ZKN5Y3GJ.js.map → board-dashboard-B3T7VCRQ.js.map} +0 -0
  109. /package/dist/{chunk-SDSSRNSU.js.map → chunk-2GJFLPS7.js.map} +0 -0
  110. /package/dist/{chunk-NYWIN4BW.js.map → chunk-3LAQ74H7.js.map} +0 -0
  111. /package/dist/{chunk-THWDSPX4.js.map → chunk-45TKVOJX.js.map} +0 -0
  112. /package/dist/{chunk-RB5W3FVO.js.map → chunk-4JHMV3D3.js.map} +0 -0
  113. /package/dist/{chunk-PYI7ZAU3.js.map → chunk-BAO77R4L.js.map} +0 -0
  114. /package/dist/{chunk-YYPTXXCJ.js.map → chunk-CZWEXRIE.js.map} +0 -0
  115. /package/dist/{chunk-OMO7UTWW.js.map → chunk-DFWPTNZ5.js.map} +0 -0
  116. /package/dist/{chunk-3WBOWXAN.js.map → chunk-EX4AREN5.js.map} +0 -0
  117. /package/dist/{chunk-MFUN3ZS3.js.map → chunk-GOAMSJ2D.js.map} +0 -0
  118. /package/dist/{chunk-WY5ZOEOE.js.map → chunk-JGX5IWNX.js.map} +0 -0
  119. /package/dist/{chunk-YXFTUOZR.js.map → chunk-LLJZMS23.js.map} +0 -0
  120. /package/dist/{chunk-L4RCA3OC.js.map → chunk-LVQHNTXV.js.map} +0 -0
  121. /package/dist/{chunk-UNIXYV3U.js.map → chunk-M7527M7D.js.map} +0 -0
  122. /package/dist/{chunk-IABJLTZN.js.map → chunk-MXWAREAQ.js.map} +0 -0
  123. /package/dist/{chunk-ERG5OUKH.js.map → chunk-Q73QQPDB.js.map} +0 -0
  124. /package/dist/{chunk-O2CYERSX.js.map → chunk-QI4FYJGJ.js.map} +0 -0
  125. /package/dist/{chunk-HPQ3AAG3.js.map → chunk-R5VGRKUW.js.map} +0 -0
  126. /package/dist/{chunk-N2HLL25P.js.map → chunk-RGBQULXX.js.map} +0 -0
  127. /package/dist/{chunk-6CTQPGBR.js.map → chunk-RV4WJZW5.js.map} +0 -0
  128. /package/dist/{chunk-QVPBSV5Z.js.map → chunk-SFUNL7RV.js.map} +0 -0
  129. /package/dist/{chunk-7H6HDN3K.js.map → chunk-SVNYI6GR.js.map} +0 -0
  130. /package/dist/{chunk-XWHD2Z3Z.js.map → chunk-UII54DAP.js.map} +0 -0
  131. /package/dist/{chunk-5BXAKMYK.js.map → chunk-UNZRZOED.js.map} +0 -0
  132. /package/dist/{chunk-AJUWIBLV.js.map → chunk-VYLMC5DO.js.map} +0 -0
  133. /package/dist/{client-E66ELJK7.js.map → client-B7FXDTYK.js.map} +0 -0
  134. /package/dist/{config-3C3Z7VKG.js.map → config-MLP33NWR.js.map} +0 -0
  135. /package/dist/{config-mutate-QBDKJNHA.js.map → config-mutate-XQRUAVEH.js.map} +0 -0
  136. /package/dist/{config-mutator-ZI3SQIUN.js.map → config-mutator-5JFTMQ43.js.map} +0 -0
  137. /package/dist/{contributions-L5XZJ3DP.js.map → contributions-ESUSYUQG.js.map} +0 -0
  138. /package/dist/{doctor-3ZUFSE6R.js.map → doctor-DIYZGSIS.js.map} +0 -0
  139. /package/dist/{failure-candidates-XZSZP4HT.js.map → failure-candidates-NQX2JMMS.js.map} +0 -0
  140. /package/dist/{follow-up-tool-6OCQUSC3.js.map → follow-up-tool-QXEYEWX7.js.map} +0 -0
  141. /package/dist/{grants-CEUGZBQ4.js.map → grants-MM7U6GCK.js.map} +0 -0
  142. /package/dist/{hub-MOQRSVCQ.js.map → hub-OC7PH2AR.js.map} +0 -0
  143. /package/dist/{promote-ZGJEPCBE.js.map → promote-SIC6RWCX.js.map} +0 -0
  144. /package/dist/{query-JLTHESIZ.js.map → query-OP2MSR2G.js.map} +0 -0
  145. /package/dist/{query-settings-GMEL3EKR.js.map → query-settings-67332F5V.js.map} +0 -0
  146. /package/dist/{registry-MFD3XJBR.js.map → registry-G2ZG5TIN.js.map} +0 -0
  147. /package/dist/{request-planner-4ORFYSAT.js.map → request-planner-THTPE3FP.js.map} +0 -0
  148. /package/dist/{review-candidates-77NDFTGM.js.map → review-candidates-7PS7CHXF.js.map} +0 -0
  149. /package/dist/{routing-3FL3KYPJ.js.map → routing-PE7DB7WA.js.map} +0 -0
  150. /package/dist/{schedule-tool-5KJMXBRZ.js.map → schedule-tool-3FXRKJGN.js.map} +0 -0
  151. /package/dist/{scheduler-QLL7ZHYW.js.map → scheduler-YTXCIQTZ.js.map} +0 -0
  152. /package/dist/{seat-RBKONP63.js.map → seat-6DMK4274.js.map} +0 -0
  153. /package/dist/{select-MOUDR6PQ.js.map → select-CLDYPAOS.js.map} +0 -0
  154. /package/dist/{set-enabled-JKYF3QIA.js.map → set-enabled-ZH2DH4GU.js.map} +0 -0
  155. /package/dist/{wiki-3FSSLQAE.js.map → traces-GVEQZX24.js.map} +0 -0
  156. /package/dist/{wiki-enrich-HQWXZRID.js.map → wiki-CH2HYJVI.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{b as St,c as At}from"./chunk-QSKG754X.js";import{c as bt}from"./chunk-SZDACK6O.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-NYWIN4BW.js";import{b as ft,d as gt,e as mt}from"./chunk-PE5V2LI7.js";import{e as ut,g as ct,h as pt,i as Re}from"./chunk-GQ76J72O.js";import{a as kt}from"./chunk-GV7S5BAX.js";import{y as at,z as Bn}from"./chunk-HPQ3AAG3.js";import{b as st,f as Kn}from"./chunk-72SZI2UW.js";import{a as dt,b as $e,c as Se,d as lt,e as Ae}from"./chunk-QD6IICK7.js";import{c as ot,d as it}from"./chunk-QOYAX2FT.js";import{f as ve,n as Hn}from"./chunk-UIBUZ2N3.js";import{existsSync as qn,mkdirSync as xt,readFileSync as zn,writeFileSync as Jn,renameSync as Yn}from"fs";import{resolve as Pt,dirname as Gn}from"path";var Tt=class{filePath;log;constructor(e={}){let t=e.baseDir??Pt(process.cwd(),".agentx");this.filePath=Pt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),xt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!qn(this.filePath))return{version:1,overrides:{}};try{let e=zn(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){xt(Gn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Jn(t,JSON.stringify(e,null,2)),Yn(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Et,writeFileSync as Pe,appendFileSync as Xn,mkdirSync as er,existsSync as Mt,statSync as tr}from"fs";import{resolve as ne}from"path";var Wt="[Agent Memory \u2014 persistent facts from past conversations]",Vn=2400;function Nt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Qn(n,e=Date.now()){let t=gt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Nt(t,ut(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Zn(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=pt(n,e);return{line:`- [${n.category}] ${Nt(o,ct(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Dt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Wt.length,a=!1;for(let i of n){let d=e.length>0?mt(i.content,e):null,l,p,c=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!c){if(o.has(d.id))continue;o.add(d.id),l=Qn(d,t),p=d.id}else l=Zn(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?Re.length:0;if(s+f+l.line.length>Vn)break;r.push({fact:i,...l,...p?{wikiRef:p}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Ot(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Re]:[];return[Wt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
1
+ import{c as bt}from"./chunk-SZDACK6O.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as St,c as At}from"./chunk-5TTHN7DP.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-3LAQ74H7.js";import{b as ft,d as gt,e as mt}from"./chunk-PE5V2LI7.js";import{e as ut,g as ct,h as pt,i as Re}from"./chunk-GQ76J72O.js";import{a as kt}from"./chunk-GV7S5BAX.js";import{y as at,z as Bn}from"./chunk-R5VGRKUW.js";import{b as st,f as Kn}from"./chunk-72SZI2UW.js";import{a as dt,b as $e,c as Se,d as lt,e as Ae}from"./chunk-QD6IICK7.js";import{c as ot,d as it}from"./chunk-QOYAX2FT.js";import{f as ve,n as Hn}from"./chunk-UIBUZ2N3.js";import{existsSync as qn,mkdirSync as xt,readFileSync as zn,writeFileSync as Jn,renameSync as Yn}from"fs";import{resolve as Pt,dirname as Gn}from"path";var Tt=class{filePath;log;constructor(e={}){let t=e.baseDir??Pt(process.cwd(),".agentx");this.filePath=Pt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),xt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!qn(this.filePath))return{version:1,overrides:{}};try{let e=zn(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){xt(Gn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Jn(t,JSON.stringify(e,null,2)),Yn(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Et,writeFileSync as Pe,appendFileSync as Xn,mkdirSync as er,existsSync as Mt,statSync as tr}from"fs";import{resolve as ne}from"path";var Wt="[Agent Memory \u2014 persistent facts from past conversations]",Vn=2400;function Nt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Qn(n,e=Date.now()){let t=gt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Nt(t,ut(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Zn(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=pt(n,e);return{line:`- [${n.category}] ${Nt(o,ct(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Dt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Wt.length,a=!1;for(let i of n){let d=e.length>0?mt(i.content,e):null,l,p,c=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!c){if(o.has(d.id))continue;o.add(d.id),l=Qn(d,t),p=d.id}else l=Zn(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?Re.length:0;if(s+f+l.line.length>Vn)break;r.push({fact:i,...l,...p?{wikiRef:p}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Ot(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Re]:[];return[Wt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
2
2
  `)}var Ft=200,nr=7,jt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ne(e,".agentx/memory"),this.ledger=new ft(ne(e,".agentx/wiki")),Mt(this.memoryDir)||er(this.memoryDir,{recursive:!0})}filePath(e){return ne(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||$e(t.content))return!1;let r=t.source.trust??dt(t.source.channel),o=t.review??lt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Xn(this.filePath(e),JSON.stringify(s)+`
3
3
  `),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!Mt(t))return[];try{let{mtimeMs:r,size:o}=tr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Et(t,"utf-8").split(`
4
4
  `).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(Ae);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=ne(this.memoryDir,`${t}_bm25_cache.json`),i=it(s,a),d=ot(e,i),l=new Map(d.map(g=>[g.docIndex,g.score])),c=o.map((g,m)=>{let y=l.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(c.length===0)return o.slice(-r);let f=c.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Ot(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Dt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&Pe(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
@@ -38,4 +38,4 @@ ${n.text}`}async function me(n,e){let t=n.channels[e.channel],r={channel:e.chann
38
38
  `).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(Xe(this.file))try{let e=JSON.parse(et(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Sn(xn(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${Tn(4).toString("hex")}.tmp`;Rn(t,JSON.stringify(e,null,2)+`
39
39
  `,{encoding:"utf-8",mode:384}),An(t,this.file)}};import{extname as li}from"path";var Nn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,Dn=/<agentx-artifact>[\s\S]*$/i;function ld(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(Nn,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let l=d.mime,p=l.startsWith("image/")?"image":l==="application/pdf"?"pdf":l.startsWith("text/")?"text":"file";r.push({type:p,filename:d.filename,mime:l})}}catch{}return""});return{text:(t?s.replace(Dn,""):s).trim(),artifacts:r}}function ud(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(Nn,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(Dn,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ui={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},cd={bytes:20*1024*1024,perMessage:20,pathChars:512};function pd(n){return ui[li(n).toLowerCase()]??null}var ci=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ![what it shows](https://...)."].join(`
40
40
  `);function fd(n,e,t){return n==="app"&&e&&t!==!1?ci:void 0}import{lstatSync as nt,mkdirSync as pi,readdirSync as fi,realpathSync as tt,unlinkSync as gi}from"fs";import{join as be,resolve as On}from"path";var En=".agentx/outbox",mi=7*24*60*60*1e3;function hi(n,e){try{let t=tt(On(e,n)),r=be(t,En);return tt(r)===r&&nt(r).isDirectory()?r:null}catch{return null}}function wd(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=tt(On(t,n));nt(be(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||pi(be(o,En),{recursive:!0})}catch{return 0}let r=hi(n,t);return r?Mn(r,(e.now??Date.now())-(e.maxAgeMs??mi)):0}function Mn(n,e){let t=0;for(let r of fi(n)){let o=be(n,r);try{let s=nt(o);s.isDirectory()?t+=Mn(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(gi(o),t++)}catch{}}return t}export{Tt as a,jt as b,Ct as c,Di as d,ir as e,Oi as f,T as g,z as h,S as i,oe as j,Ir as k,Oe as l,F as m,Fe as n,Ce as o,Ge as p,To as q,Mo as r,Qe as s,_r as t,Go as u,Na as v,Da as w,Oa as x,Ea as y,Ma as z,Vo as A,Qo as B,Fa as C,ja as D,Ca as E,_a as F,Ha as G,Ka as H,Ba as I,qa as J,za as K,Ja as L,Ya as M,Ga as N,Va as O,Qa as P,Za as Q,ri as R,Xa as S,ed as T,td as U,nd as V,Wn as W,ld as X,ud as Y,cd as Z,pd as _,fd as $,En as aa,wd as ba};
41
- //# sourceMappingURL=chunk-THWDSPX4.js.map
41
+ //# sourceMappingURL=chunk-45TKVOJX.js.map
@@ -1,2 +1,2 @@
1
- import{y as l,z as T}from"./chunk-HPQ3AAG3.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
2
- //# sourceMappingURL=chunk-RB5W3FVO.js.map
1
+ import{y as l,z as T}from"./chunk-R5VGRKUW.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
2
+ //# sourceMappingURL=chunk-4JHMV3D3.js.map
@@ -1,11 +1,11 @@
1
- import{a as i,b as c}from"./chunk-FCPTN6NF.js";var m="[Institutional Wiki";function u(e){return[...new Set(e)].slice(0,20).map(n=>n.slice(0,80))}function p(e,n){let t=e??"";return{memory:u((n.memory??[]).filter(r=>r.content&&t.includes(r.content)).map(r=>r.id)),procedures:u((n.procedures??[]).filter(r=>t.includes(`[Known procedure: ${r.title}]`)).map(r=>r.id)),wiki:!!n.wikiContext&&t.includes(m)}}function o(e){return{memory:u(e.memory),procedures:u(e.procedures),wiki:e.wiki===!0}}c();function h(e,n,t=i()){return e.prepare(`
1
+ import{a as o,b as d}from"./chunk-FCPTN6NF.js";d();var m="[Institutional Wiki";function u(e){return[...new Set(e)].slice(0,20).map(n=>n.slice(0,80))}function p(e,n){let t=e??"";return{memory:u((n.memory??[]).filter(r=>r.content&&t.includes(r.content)).map(r=>r.id)),procedures:u((n.procedures??[]).filter(r=>t.includes(`[Known procedure: ${r.title}]`)).map(r=>r.id)),wiki:!!n.wikiContext&&t.includes(m)}}function c(e){return{memory:u(e.memory),procedures:u(e.procedures),wiki:e.wiki===!0}}function h(e,n,t=o()){return e.prepare(`
2
2
  INSERT INTO task_traces (
3
3
  task_id, agent_id, channel, chat_id, workflow_run_id, workflow_id,
4
4
  workflow_node_id, intent_event_id, intent_decided_by, resume_session_id,
5
5
  model, status, started_at, message_preview, original_message,
6
6
  resume_origin, resume_attempt, resumed_from, person
7
7
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'in-flight', ?, ?, ?, ?, ?, ?, ?)
8
- `).run(t,n.agentId,n.channel??null,n.chatId??null,n.workflowRunId??null,n.workflowId??null,n.workflowNodeId??null,n.intentEventId??null,n.intentDecidedBy??null,n.resumeSessionId??null,n.model??null,Date.now(),n.messagePreview??null,n.originalMessage??null,n.resumeOrigin??null,n.resumeAttempt??0,n.resumedFrom??null,n.person??null),t}function T(e,n,t){let r=Date.now();e.prepare(`
8
+ `).run(t,n.agentId,n.channel??null,n.chatId??null,n.workflowRunId??null,n.workflowId??null,n.workflowNodeId??null,n.intentEventId??null,n.intentDecidedBy??null,n.resumeSessionId??null,n.model??null,Date.now(),n.messagePreview??null,n.originalMessage??null,n.resumeOrigin??null,n.resumeAttempt??0,n.resumedFrom??null,n.person??null),t}function E(e,n,t){let r=Date.now();e.prepare(`
9
9
  UPDATE task_traces SET
10
10
  status = ?,
11
11
  final_session_id = ?,
@@ -24,14 +24,15 @@ import{a as i,b as c}from"./chunk-FCPTN6NF.js";var m="[Institutional Wiki";funct
24
24
  injected_context = COALESCE(?, injected_context),
25
25
  error = ?,
26
26
  final_response = COALESCE(?, final_response),
27
+ model = COALESCE(?, model),
27
28
  finished_at = ?,
28
29
  duration_ms = ? - started_at
29
30
  WHERE task_id = ?
30
- `).run(t.status,t.finalSessionId??null,t.inputTokens??null,t.outputTokens??null,t.cacheReadTokens??null,t.cacheCreateTokens??null,t.tier2InputTokens??null,t.tier2OutputTokens??null,t.tier2CacheReadTokens??null,t.tier2CacheCreateTokens??null,t.resumed==null?null:t.resumed?1:0,t.resumeSessionId??null,t.jevArm??null,t.numTurns??null,t.injectedContext?JSON.stringify(o(t.injectedContext)):null,t.error??null,t.finalResponse??null,r,r,n)}function E(e,n,t){let r=Date.now();return e.transaction(()=>{let l=(e.prepare("SELECT MAX(seq) AS max_seq FROM task_trace_steps WHERE task_id = ?").get(n)?.max_seq??-1)+1;return e.prepare(`
31
+ `).run(t.status,t.finalSessionId??null,t.inputTokens??null,t.outputTokens??null,t.cacheReadTokens??null,t.cacheCreateTokens??null,t.tier2InputTokens??null,t.tier2OutputTokens??null,t.tier2CacheReadTokens??null,t.tier2CacheCreateTokens??null,t.resumed==null?null:t.resumed?1:0,t.resumeSessionId??null,t.jevArm??null,t.numTurns??null,t.injectedContext?JSON.stringify(c(t.injectedContext)):null,t.error??null,t.finalResponse??null,t.model??null,r,r,n)}function T(e,n,t){let r=Date.now();return e.transaction(()=>{let i=(e.prepare("SELECT MAX(seq) AS max_seq FROM task_trace_steps WHERE task_id = ?").get(n)?.max_seq??-1)+1;return e.prepare(`
31
32
  INSERT INTO task_trace_steps (
32
33
  task_id, seq, name, action, status, input_summary, output_summary, error, ms, started_at
33
34
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
34
- `).run(n,l,t.name,t.action??null,t.status??null,t.inputSummary??null,t.outputSummary??null,t.error??null,t.ms??null,r),l})()}function g(e){if(typeof e!="string")return null;try{let n=JSON.parse(e);if(!n||typeof n!="object")return null;let t=r=>Array.isArray(r)?r.filter(s=>typeof s=="string"):[];return{memory:t(n.memory),procedures:t(n.procedures),wiki:n.wiki===!0}}catch{return null}}function d(e){return{taskId:e.task_id,agentId:e.agent_id,channel:e.channel??null,chatId:e.chat_id??null,workflowRunId:e.workflow_run_id??null,workflowId:e.workflow_id??null,workflowNodeId:e.workflow_node_id??null,intentEventId:e.intent_event_id??null,intentDecidedBy:e.intent_decided_by??null,resumeSessionId:e.resume_session_id??null,finalSessionId:e.final_session_id??null,model:e.model??null,status:e.status,startedAt:e.started_at,finishedAt:e.finished_at??null,durationMs:e.duration_ms??null,inputTokens:e.input_tokens??null,outputTokens:e.output_tokens??null,cacheReadTokens:e.cache_read_tokens??null,cacheCreateTokens:e.cache_create_tokens??null,tier2InputTokens:e.tier2_input_tokens??null,tier2OutputTokens:e.tier2_output_tokens??null,tier2CacheReadTokens:e.tier2_cache_read_tokens??null,tier2CacheCreateTokens:e.tier2_cache_create_tokens??null,resumed:e.resumed==null?null:e.resumed===1,jevArm:e.jev_arm??null,numTurns:e.num_turns??null,injectedContext:g(e.injected_context),error:e.error??null,messagePreview:e.message_preview??null,originalMessage:e.original_message??null,finalResponse:e.final_response??null}}function _(e){return{taskId:e.task_id,seq:e.seq,name:e.name,action:e.action??null,status:e.status??null,inputSummary:e.input_summary??null,outputSummary:e.output_summary??null,error:e.error??null,ms:e.ms??null,startedAt:e.started_at}}function b(e,n){let t=e.prepare("SELECT * FROM task_traces WHERE task_id = ?").get(n);if(!t)return null;let r=e.prepare("SELECT * FROM task_trace_steps WHERE task_id = ? ORDER BY seq").all(n);return{task:d(t),steps:r.map(_)}}function R(e){let n=Date.now();return e.prepare(`
35
+ `).run(n,i,t.name,t.action??null,t.status??null,t.inputSummary??null,t.outputSummary??null,t.error??null,t.ms??null,r),i})()}function g(e){if(typeof e!="string")return null;try{let n=JSON.parse(e);if(!n||typeof n!="object")return null;let t=r=>Array.isArray(r)?r.filter(s=>typeof s=="string"):[];return{memory:t(n.memory),procedures:t(n.procedures),wiki:n.wiki===!0}}catch{return null}}function l(e){return{taskId:e.task_id,agentId:e.agent_id,channel:e.channel??null,chatId:e.chat_id??null,workflowRunId:e.workflow_run_id??null,workflowId:e.workflow_id??null,workflowNodeId:e.workflow_node_id??null,intentEventId:e.intent_event_id??null,intentDecidedBy:e.intent_decided_by??null,resumeSessionId:e.resume_session_id??null,finalSessionId:e.final_session_id??null,model:e.model??null,status:e.status,startedAt:e.started_at,finishedAt:e.finished_at??null,durationMs:e.duration_ms??null,inputTokens:e.input_tokens??null,outputTokens:e.output_tokens??null,cacheReadTokens:e.cache_read_tokens??null,cacheCreateTokens:e.cache_create_tokens??null,tier2InputTokens:e.tier2_input_tokens??null,tier2OutputTokens:e.tier2_output_tokens??null,tier2CacheReadTokens:e.tier2_cache_read_tokens??null,tier2CacheCreateTokens:e.tier2_cache_create_tokens??null,resumed:e.resumed==null?null:e.resumed===1,jevArm:e.jev_arm??null,numTurns:e.num_turns??null,injectedContext:g(e.injected_context),error:e.error??null,messagePreview:e.message_preview??null,originalMessage:e.original_message??null,finalResponse:e.final_response??null}}function _(e){return{taskId:e.task_id,seq:e.seq,name:e.name,action:e.action??null,status:e.status??null,inputSummary:e.input_summary??null,outputSummary:e.output_summary??null,error:e.error??null,ms:e.ms??null,startedAt:e.started_at}}function R(e,n){let t=e.prepare("SELECT * FROM task_traces WHERE task_id = ?").get(n);if(!t)return null;let r=e.prepare("SELECT * FROM task_trace_steps WHERE task_id = ? ORDER BY seq").all(n);return{task:l(t),steps:r.map(_)}}function b(e){let n=Date.now();return e.prepare(`
35
36
  UPDATE task_traces
36
37
  SET status = 'canceled',
37
38
  error = 'daemon-restart (orphaned in-flight)',
@@ -52,13 +53,16 @@ import{a as i,b as c}from"./chunk-FCPTN6NF.js";var m="[Institutional Wiki";funct
52
53
  `);return t().map(s=>({taskId:s.task_id,agentId:s.agent_id,channel:s.channel??null,chatId:s.chat_id??null,workflowRunId:s.workflow_run_id??null,startedAt:s.started_at,originalMessage:s.original_message??null,resumeOrigin:s.resume_origin??null,resumeAttempt:s.resume_attempt??0,toolCalls:r.all(s.task_id).map(a=>({action:a.action??null,inputSummary:a.input_summary??null}))}))}function S(e,n){return(e.prepare(`
53
54
  UPDATE task_traces SET resume_decision = 'deciding'
54
55
  WHERE task_id = ? AND resume_decision = 'interrupted'
55
- `).run(n).changes??0)===1}function y(e,n,t,r){e.prepare("UPDATE task_traces SET resume_decision = ?, resume_reason = ? WHERE task_id = ?").run(t,r.slice(0,500),n)}function D(e,n={}){let t=[],r=[];n.agentId&&(t.push("agent_id = ?"),r.push(n.agentId)),n.channel&&(t.push("channel = ?"),r.push(n.channel)),n.chatId&&(t.push("chat_id = ?"),r.push(n.chatId)),n.workflowRunId&&(t.push("workflow_run_id = ?"),r.push(n.workflowRunId)),n.status&&(t.push("status = ?"),r.push(n.status)),n.since!==void 0&&(t.push("started_at >= ?"),r.push(n.since)),n.until!==void 0&&(t.push("started_at <= ?"),r.push(n.until));let s=Math.max(1,Math.min(n.limit??100,1e3)),a=`
56
+ `).run(n).changes??0)===1}function D(e,n,t,r){e.prepare("UPDATE task_traces SET resume_decision = ?, resume_reason = ? WHERE task_id = ?").run(t,r.slice(0,500),n)}function w(e,n={}){let t=[],r=[];n.agentId&&(t.push("agent_id = ?"),r.push(n.agentId)),n.channel&&(t.push("channel = ?"),r.push(n.channel)),n.chatId&&(t.push("chat_id = ?"),r.push(n.chatId)),n.workflowRunId&&(t.push("workflow_run_id = ?"),r.push(n.workflowRunId)),n.status&&(t.push("status = ?"),r.push(n.status)),n.since!==void 0&&(t.push("started_at >= ?"),r.push(n.since)),n.until!==void 0&&(t.push("started_at <= ?"),r.push(n.until));let s=Math.max(1,Math.min(n.limit??100,1e3)),a=`
56
57
  SELECT * FROM task_traces
57
58
  ${t.length>0?"WHERE "+t.join(" AND "):""}
58
59
  ORDER BY started_at DESC
59
60
  LIMIT ?
60
- `;return r.push(s),e.prepare(a).all(...r).map(d)}function A(e,n,t=200){return e.prepare(`
61
+ `;return r.push(s),e.prepare(a).all(...r).map(l)}function y(e,n){let t=[];for(let r=0;r<n.length;r+=500){let s=n.slice(r,r+500);if(!s.length)continue;let a=e.prepare(`
62
+ SELECT * FROM task_traces WHERE workflow_run_id IN (${s.map(()=>"?").join(",")})
63
+ ORDER BY started_at
64
+ `).all(...s);t.push(...a.map(l))}return t}function A(e,n,t=200){return e.prepare(`
61
65
  SELECT action, input_summary FROM task_trace_steps
62
66
  WHERE task_id = ? AND name = 'tool_use' ORDER BY seq LIMIT ?
63
- `).all(n,t).map(s=>({action:s.action??null,inputSummary:s.input_summary??null}))}export{p as a,h as b,T as c,E as d,g as e,b as f,R as g,C as h,S as i,y as j,D as k,A as l};
64
- //# sourceMappingURL=chunk-QSKG754X.js.map
67
+ `).all(n,t).map(s=>({action:s.action??null,inputSummary:s.input_summary??null}))}export{p as a,h as b,E as c,T as d,g as e,R as f,b as g,C as h,S as i,D as j,w as k,y as l,A as m};
68
+ //# sourceMappingURL=chunk-5TTHN7DP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/traces.ts","../src/agents/injected-context.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { newEventId } from \"@/intent/ulid\"\nimport { boundInjectedContext } from \"@/agents/injected-context\"\n\n// --- Task trace store ---\n//\n// Improvement plan #2 — per-task observability backed by SQLite. One\n// task_traces row per executeTask invocation, an append-only stream of\n// task_trace_steps inside it. The store is intentionally dumb: it stores\n// what callers give it. Callers (capture sites in src/agents/runtime.ts)\n// are responsible for byte-capping large step payloads so the daemon\n// memory stays bounded under tool-heavy turns.\n//\n// Why a separate store layer (vs writing inline in runtime.ts)?\n// - Tests can exercise the trace lifecycle against a temp SQLite without\n// spinning up the agent runtime.\n// - The HTTP endpoints (GET /task/:id/trace) read through the same\n// functions producers write through, so there's a single source of\n// truth on field names + semantics.\n// - Future capture sites (sdk tier, orchestrator tier) reuse this API\n// without copying SQL.\n//\n// Why ULID for task_id?\n// - URL-safe in HTTP routes (GET /task/:id/trace).\n// - Time-sortable, so listTraces ORDER BY started_at and ORDER BY\n// task_id agree without an explicit timestamp column index.\n// - Already in-tree (src/intent/ulid.ts); no new dep.\n//\n// Cross-DB FK note:\n// intent_event_id and intent_decided_by are logical foreign keys into\n// the intent ledger at .agentx/intent/ledger.sqlite. better-sqlite3\n// doesn't enforce cross-database FKs and we don't ATTACH the ledger\n// here on purpose — the rescue plan's append-only contract on the\n// ledger is honoured by routing all writes through src/intent/ledger.ts.\n// Joins happen at the HTTP / CLI layer when needed.\n\nexport interface TraceStartInput {\n agentId: string\n channel?: string | null\n chatId?: string | null\n messagePreview?: string | null\n /** Full untruncated user message — used by `agentx trace replay <taskId>`\n * to re-fire a recorded task against the current agent config. NULL on\n * rows from before migration v8, in which case replay falls back to\n * messagePreview (which is capped at 200 chars). */\n originalMessage?: string | null\n workflowRunId?: string | null\n workflowId?: string | null\n workflowNodeId?: string | null\n intentEventId?: string | null\n intentDecidedBy?: string | null\n resumeSessionId?: string | null\n model?: string | null\n /** How to re-enter this run after a restart (JSON, see agents/resume). */\n resumeOrigin?: string | null\n /** 0 for a fresh run; n for the n-th resume of a cut-off run. */\n resumeAttempt?: number | null\n /** The cut-off run this one continues. */\n resumedFrom?: string | null\n /** The known person who started the chain (people, #384). */\n person?: string | null\n}\n\nexport interface TraceEndInput {\n status: \"ok\" | \"error\" | \"timeout\" | \"stopped\"\n finalSessionId?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n cacheReadTokens?: number | null\n cacheCreateTokens?: number | null\n tier2InputTokens?: number | null\n tier2OutputTokens?: number | null\n tier2CacheReadTokens?: number | null\n tier2CacheCreateTokens?: number | null\n /** Whether the turn continued a provider session. The resume decision\n * is made after task:started, so it is recorded at the end. Omitted\n * leaves both resumed and resume_session_id untouched. */\n resumed?: boolean | null\n resumeSessionId?: string | null\n /** Request-gate experiment arm: \"treatment\" | \"holdout\". */\n jevArm?: string | null\n /** Runtime-reported turn count (Claude `num_turns`). */\n numTurns?: number | null\n /** Lessons injected into the prompt. See InjectedContext. */\n injectedContext?: InjectedContext | null\n error?: string | null\n /** The agent's final reply text. Stored verbatim so `replay --diff`\n * can compare original output vs the new run's output without\n * reconstructing it from the step ledger. NULL when the response\n * wasn't captured (older rows or non-text outputs). */\n finalResponse?: string | null\n /** Model the turn was billed on. Known only once the turn ends, so the\n * start row usually has none. Omitted leaves the column untouched. */\n model?: string | null\n}\n\n/** Ids of the lessons injected into one task's prompt. Memory facts and\n * procedures are matched per message, so their ids are recorded; the wiki\n * is injected as a whole catalog, so only its presence is. */\nexport interface InjectedContext {\n memory: string[]\n procedures: string[]\n wiki: boolean\n}\n\nexport interface TraceStepInput {\n /** Coarse step kind. Conventional values: \"tool_use\" | \"tool_result\" |\n * \"llm_message\" | \"session_rotation\" | \"error\" | \"preflight\". Free-form\n * strings allowed so future capture sites don't need a schema bump. */\n name: string\n /** Fine-grained name within the kind. For \"tool_use\", this is the tool\n * name (e.g. \"Bash\", \"Edit\"). Optional. */\n action?: string | null\n status?: \"ok\" | \"error\" | \"in-flight\" | null\n /** JSON-stringified input or human-readable summary. Caller-byte-capped. */\n inputSummary?: string | null\n outputSummary?: string | null\n error?: string | null\n /** Step duration when known. Optional — many step kinds are point-in-time. */\n ms?: number | null\n}\n\nexport interface TraceRecord {\n taskId: string\n agentId: string\n channel: string | null\n chatId: string | null\n workflowRunId: string | null\n workflowId: string | null\n workflowNodeId: string | null\n intentEventId: string | null\n intentDecidedBy: string | null\n resumeSessionId: string | null\n finalSessionId: string | null\n model: string | null\n status: string\n startedAt: number\n finishedAt: number | null\n durationMs: number | null\n inputTokens: number | null\n outputTokens: number | null\n cacheReadTokens: number | null\n cacheCreateTokens: number | null\n tier2InputTokens: number | null\n tier2OutputTokens: number | null\n tier2CacheReadTokens: number | null\n tier2CacheCreateTokens: number | null\n /** NULL on rows recorded before migration v12. */\n resumed: boolean | null\n /** NULL when the request gate was not active (or before migration v13). */\n jevArm: string | null\n /** NULL on rows recorded before lesson-impact capture (#98) or when the\n * runtime does not report a turn count. */\n numTurns: number | null\n /** NULL on rows recorded before lesson-impact capture (#98). */\n injectedContext: InjectedContext | null\n error: string | null\n messagePreview: string | null\n /** Full untruncated user message — populated for traces from migration v8\n * onward. NULL on older rows; consumers should fall back to messagePreview. */\n originalMessage: string | null\n /** Agent's final reply text — populated for traces from migration v8\n * onward when the executor records it on end. */\n finalResponse: string | null\n}\n\nexport interface TraceStepRecord {\n taskId: string\n seq: number\n name: string\n action: string | null\n status: string | null\n inputSummary: string | null\n outputSummary: string | null\n error: string | null\n ms: number | null\n startedAt: number\n}\n\nexport interface ListTracesFilters {\n agentId?: string\n channel?: string\n chatId?: string\n workflowRunId?: string\n status?: string\n /** ms epoch */\n since?: number\n /** ms epoch */\n until?: number\n /** Default 100, capped at 1000. */\n limit?: number\n}\n\n/**\n * Insert an in-flight trace row and return its ULID. Callers thread the\n * returned id through the executor and call recordTraceEnd at finish time.\n *\n * `taskId` is optional — when supplied, the caller has already allocated\n * a ULID upstream (e.g. registry.execute generating it before the bus\n * event so the runtime can capture per-step rows under the same id).\n * When omitted, a fresh ULID is allocated here.\n */\nexport function recordTraceStart(\n db: Database.Database,\n input: TraceStartInput,\n taskId: string = newEventId(),\n): string {\n db.prepare(`\n INSERT INTO task_traces (\n task_id, agent_id, channel, chat_id, workflow_run_id, workflow_id,\n workflow_node_id, intent_event_id, intent_decided_by, resume_session_id,\n model, status, started_at, message_preview, original_message,\n resume_origin, resume_attempt, resumed_from, person\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'in-flight', ?, ?, ?, ?, ?, ?, ?)\n `).run(\n taskId,\n input.agentId,\n input.channel ?? null,\n input.chatId ?? null,\n input.workflowRunId ?? null,\n input.workflowId ?? null,\n input.workflowNodeId ?? null,\n input.intentEventId ?? null,\n input.intentDecidedBy ?? null,\n input.resumeSessionId ?? null,\n input.model ?? null,\n Date.now(),\n input.messagePreview ?? null,\n input.originalMessage ?? null,\n input.resumeOrigin ?? null,\n input.resumeAttempt ?? 0,\n input.resumedFrom ?? null,\n input.person ?? null,\n )\n return taskId\n}\n\n/**\n * Finalize a trace. duration_ms is computed from finished_at - started_at\n * inside the UPDATE so the two columns can never disagree. Idempotent —\n * calling twice on the same task_id overwrites the prior end values; the\n * second call's status wins. (Soft-overwrite is intentional: timeout\n * handlers may write before a late stream-completion arrives.)\n */\nexport function recordTraceEnd(db: Database.Database, taskId: string, input: TraceEndInput): void {\n const finishedAt = Date.now()\n db.prepare(`\n UPDATE task_traces SET\n status = ?,\n final_session_id = ?,\n input_tokens = ?,\n output_tokens = ?,\n cache_read_tokens = ?,\n cache_create_tokens = ?,\n tier2_input_tokens = ?,\n tier2_output_tokens = ?,\n tier2_cache_read_tokens = ?,\n tier2_cache_create_tokens = ?,\n resumed = COALESCE(?, resumed),\n resume_session_id = COALESCE(?, resume_session_id),\n jev_arm = COALESCE(?, jev_arm),\n num_turns = COALESCE(?, num_turns),\n injected_context = COALESCE(?, injected_context),\n error = ?,\n final_response = COALESCE(?, final_response),\n model = COALESCE(?, model),\n finished_at = ?,\n duration_ms = ? - started_at\n WHERE task_id = ?\n `).run(\n input.status,\n input.finalSessionId ?? null,\n input.inputTokens ?? null,\n input.outputTokens ?? null,\n input.cacheReadTokens ?? null,\n input.cacheCreateTokens ?? null,\n input.tier2InputTokens ?? null,\n input.tier2OutputTokens ?? null,\n input.tier2CacheReadTokens ?? null,\n input.tier2CacheCreateTokens ?? null,\n input.resumed == null ? null : input.resumed ? 1 : 0,\n input.resumeSessionId ?? null,\n input.jevArm ?? null,\n input.numTurns ?? null,\n input.injectedContext ? JSON.stringify(boundInjectedContext(input.injectedContext)) : null,\n input.error ?? null,\n input.finalResponse ?? null,\n input.model ?? null,\n finishedAt,\n finishedAt,\n taskId,\n )\n}\n\n/**\n * Append a step. seq is auto-allocated as MAX(seq)+1 within a transaction\n * so concurrent step writes for the same task_id can't collide. Returns\n * the assigned seq, useful for downstream correlation.\n */\nexport function recordTraceStep(db: Database.Database, taskId: string, input: TraceStepInput): number {\n const startedAt = Date.now()\n const allocateAndInsert = db.transaction((): number => {\n const row = db\n .prepare(\"SELECT MAX(seq) AS max_seq FROM task_trace_steps WHERE task_id = ?\")\n .get(taskId) as { max_seq: number | null } | undefined\n const seq = ((row?.max_seq ?? -1) as number) + 1\n db.prepare(`\n INSERT INTO task_trace_steps (\n task_id, seq, name, action, status, input_summary, output_summary, error, ms, started_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n taskId,\n seq,\n input.name,\n input.action ?? null,\n input.status ?? null,\n input.inputSummary ?? null,\n input.outputSummary ?? null,\n input.error ?? null,\n input.ms ?? null,\n startedAt,\n )\n return seq\n })\n return allocateAndInsert()\n}\n\nexport function parseInjectedContext(raw: unknown): InjectedContext | null {\n if (typeof raw !== \"string\") return null\n try {\n const v = JSON.parse(raw)\n if (!v || typeof v !== \"object\") return null\n const ids = (x: unknown) => (Array.isArray(x) ? x.filter((i): i is string => typeof i === \"string\") : [])\n return { memory: ids(v.memory), procedures: ids(v.procedures), wiki: v.wiki === true }\n } catch {\n return null\n }\n}\n\nfunction rowToTrace(row: Record<string, unknown>): TraceRecord {\n return {\n taskId: row.task_id as string,\n agentId: row.agent_id as string,\n channel: (row.channel as string) ?? null,\n chatId: (row.chat_id as string) ?? null,\n workflowRunId: (row.workflow_run_id as string) ?? null,\n workflowId: (row.workflow_id as string) ?? null,\n workflowNodeId: (row.workflow_node_id as string) ?? null,\n intentEventId: (row.intent_event_id as string) ?? null,\n intentDecidedBy: (row.intent_decided_by as string) ?? null,\n resumeSessionId: (row.resume_session_id as string) ?? null,\n finalSessionId: (row.final_session_id as string) ?? null,\n model: (row.model as string) ?? null,\n status: row.status as string,\n startedAt: row.started_at as number,\n finishedAt: (row.finished_at as number) ?? null,\n durationMs: (row.duration_ms as number) ?? null,\n inputTokens: (row.input_tokens as number) ?? null,\n outputTokens: (row.output_tokens as number) ?? null,\n cacheReadTokens: (row.cache_read_tokens as number) ?? null,\n cacheCreateTokens: (row.cache_create_tokens as number) ?? null,\n tier2InputTokens: (row.tier2_input_tokens as number) ?? null,\n tier2OutputTokens: (row.tier2_output_tokens as number) ?? null,\n tier2CacheReadTokens: (row.tier2_cache_read_tokens as number) ?? null,\n tier2CacheCreateTokens: (row.tier2_cache_create_tokens as number) ?? null,\n resumed: row.resumed == null ? null : row.resumed === 1,\n jevArm: (row.jev_arm as string) ?? null,\n numTurns: (row.num_turns as number) ?? null,\n injectedContext: parseInjectedContext(row.injected_context),\n error: (row.error as string) ?? null,\n messagePreview: (row.message_preview as string) ?? null,\n originalMessage: (row.original_message as string) ?? null,\n finalResponse: (row.final_response as string) ?? null,\n }\n}\n\nfunction rowToStep(row: Record<string, unknown>): TraceStepRecord {\n return {\n taskId: row.task_id as string,\n seq: row.seq as number,\n name: row.name as string,\n action: (row.action as string) ?? null,\n status: (row.status as string) ?? null,\n inputSummary: (row.input_summary as string) ?? null,\n outputSummary: (row.output_summary as string) ?? null,\n error: (row.error as string) ?? null,\n ms: (row.ms as number) ?? null,\n startedAt: row.started_at as number,\n }\n}\n\n/** Fetch a trace + its ordered steps. Returns null if no such task_id. */\nexport function getTrace(\n db: Database.Database,\n taskId: string,\n): { task: TraceRecord; steps: TraceStepRecord[] } | null {\n const row = db.prepare(\"SELECT * FROM task_traces WHERE task_id = ?\").get(taskId) as\n | Record<string, unknown>\n | undefined\n if (!row) return null\n const stepRows = db\n .prepare(\"SELECT * FROM task_trace_steps WHERE task_id = ? ORDER BY seq\")\n .all(taskId) as Record<string, unknown>[]\n return { task: rowToTrace(row), steps: stepRows.map(rowToStep) }\n}\n\n/**\n * Cancel any in-flight trace rows left over from a previous daemon\n * lifetime. Mirrors the intent ledger's startup cleanup (rescue plan\n * Phase 1 commit a8514d9): a hard-killed daemon never gets to fire\n * task:completed, so the row sits \"in-flight\" forever and contaminates\n * triage queries (`agentx trace list --status in-flight`) with stale\n * orphans. Run once at daemon boot before subscribers attach.\n *\n * Returns the number of rows updated. duration_ms is intentionally NOT\n * computed — we don't know when the task actually ended; preserving\n * NULL there is more honest than backdating to \"now\".\n */\nexport function cleanupOrphanedTraces(db: Database.Database): number {\n const now = Date.now()\n const r = db.prepare(`\n UPDATE task_traces\n SET status = 'canceled',\n error = 'daemon-restart (orphaned in-flight)',\n finished_at = ?\n WHERE status = 'in-flight'\n `).run(now)\n return (r.changes ?? 0) as number\n}\n\n// --- Resume after restart (#103) -------------------------------------------\n\n/** A run that was still going when the previous daemon stopped. */\nexport interface InterruptedRun {\n taskId: string\n agentId: string\n channel: string | null\n chatId: string | null\n workflowRunId: string | null\n startedAt: number\n originalMessage: string | null\n resumeOrigin: string | null\n resumeAttempt: number\n /** Tool calls it had made, in order, for the resume note. */\n toolCalls: Array<{ action: string | null; inputSummary: string | null }>\n}\n\n/** Close every run left in flight by the previous daemon, marking it\n * `interrupted` for the resume planner, and return them. One transaction,\n * so a second process booting on the same database gets nothing. */\nexport function takeInterruptedRuns(db: Database.Database, now = Date.now()): InterruptedRun[] {\n const take = db.transaction(() => {\n const rows = db.prepare(`\n SELECT task_id, agent_id, channel, chat_id, workflow_run_id, started_at,\n original_message, resume_origin, resume_attempt\n FROM task_traces WHERE status = 'in-flight' ORDER BY started_at\n `).all() as Array<Record<string, any>>\n db.prepare(`\n UPDATE task_traces\n SET status = 'canceled', error = 'daemon-restart (interrupted)',\n finished_at = ?, resume_decision = 'interrupted'\n WHERE status = 'in-flight'\n `).run(now)\n return rows\n })\n const steps = db.prepare(`\n SELECT action, input_summary FROM task_trace_steps\n WHERE task_id = ? AND name = 'tool_use' ORDER BY seq\n `)\n return take().map((r) => ({\n taskId: r.task_id,\n agentId: r.agent_id,\n channel: r.channel ?? null,\n chatId: r.chat_id ?? null,\n workflowRunId: r.workflow_run_id ?? null,\n startedAt: r.started_at,\n originalMessage: r.original_message ?? null,\n resumeOrigin: r.resume_origin ?? null,\n resumeAttempt: r.resume_attempt ?? 0,\n toolCalls: (steps.all(r.task_id) as Array<Record<string, any>>).map((s) => ({\n action: s.action ?? null, inputSummary: s.input_summary ?? null,\n })),\n }))\n}\n\n/** Claim an interrupted run before deciding what to do with it. Returns\n * false when another process already claimed or decided it, so a run is\n * never resumed — or its chat told — twice. */\nexport function claimResume(db: Database.Database, taskId: string): boolean {\n const r = db.prepare(`\n UPDATE task_traces SET resume_decision = 'deciding'\n WHERE task_id = ? AND resume_decision = 'interrupted'\n `).run(taskId)\n return (r.changes ?? 0) === 1\n}\n\nexport type ResumeDecision = \"resumed\" | \"reported\" | \"skipped\" | \"resume-failed\"\n\nexport function recordResumeDecision(\n db: Database.Database, taskId: string, decision: ResumeDecision, reason: string,\n): void {\n db.prepare(\"UPDATE task_traces SET resume_decision = ?, resume_reason = ? WHERE task_id = ?\")\n .run(decision, reason.slice(0, 500), taskId)\n}\n\n/** Triage / dashboard surface — list traces newest-first, filtered. */\nexport function listTraces(db: Database.Database, filters: ListTracesFilters = {}): TraceRecord[] {\n const where: string[] = []\n const params: unknown[] = []\n if (filters.agentId) { where.push(\"agent_id = ?\"); params.push(filters.agentId) }\n if (filters.channel) { where.push(\"channel = ?\"); params.push(filters.channel) }\n if (filters.chatId) { where.push(\"chat_id = ?\"); params.push(filters.chatId) }\n if (filters.workflowRunId) { where.push(\"workflow_run_id = ?\"); params.push(filters.workflowRunId) }\n if (filters.status) { where.push(\"status = ?\"); params.push(filters.status) }\n if (filters.since !== undefined) { where.push(\"started_at >= ?\"); params.push(filters.since) }\n if (filters.until !== undefined) { where.push(\"started_at <= ?\"); params.push(filters.until) }\n\n const limit = Math.max(1, Math.min(filters.limit ?? 100, 1000))\n const sql = `\n SELECT * FROM task_traces\n ${where.length > 0 ? \"WHERE \" + where.join(\" AND \") : \"\"}\n ORDER BY started_at DESC\n LIMIT ?\n `\n params.push(limit)\n return (db.prepare(sql).all(...params) as Record<string, unknown>[]).map(rowToTrace)\n}\n\n/** Every trace row of these workflow runs, oldest first. Unbounded by\n * design: a report over a few hundred runs needs all of their rows. */\nexport function listTracesForRuns(db: Database.Database, runIds: string[]): TraceRecord[] {\n const out: TraceRecord[] = []\n // SQLite caps bound parameters; stay well under it.\n for (let i = 0; i < runIds.length; i += 500) {\n const chunk = runIds.slice(i, i + 500)\n if (!chunk.length) continue\n const rows = db.prepare(`\n SELECT * FROM task_traces WHERE workflow_run_id IN (${chunk.map(() => \"?\").join(\",\")})\n ORDER BY started_at\n `).all(...chunk) as Record<string, unknown>[]\n out.push(...rows.map(rowToTrace))\n }\n return out\n}\n\n/** The tool calls one run made, in order: what a stop signal's resume plan\n * lists when the agent wrote none (#857). Bounded. */\nexport function traceToolCalls(\n db: Database.Database, taskId: string, limit = 200,\n): Array<{ action: string | null; inputSummary: string | null }> {\n const rows = db.prepare(`\n SELECT action, input_summary FROM task_trace_steps\n WHERE task_id = ? AND name = 'tool_use' ORDER BY seq LIMIT ?\n `).all(taskId, limit) as Array<Record<string, any>>\n return rows.map((s) => ({ action: s.action ?? null, inputSummary: s.input_summary ?? null }))\n}\n","import type { InjectedContext } from \"@/storage/traces\"\n\n// --- Injected lessons per task (#98) ---\n//\n// Which memory facts, procedures and wiki catalog actually reached the\n// prompt. Candidates are not enough: the request-context selector can drop\n// a whole layer, and the layer budgets in buildAgentContext can cut a layer\n// short. So a lesson counts as injected only when its text is in the\n// assembled context. Only ids are recorded, never content, and the lists\n// are capped, so the trace row stays small.\n\nexport const MAX_INJECTED_IDS = 20\nconst MAX_ID_LENGTH = 80\n\nexport interface InjectionCandidates {\n memory?: Array<{ id: string; content: string }>\n procedures?: Array<{ id: string; title: string }>\n /** The wiki catalog block offered to the prompt, if any. */\n wikiContext?: string\n}\n\n/** The first line of the wiki catalog block; see buildWikiContext. */\nconst WIKI_MARKER = \"[Institutional Wiki\"\n\nfunction capIds(ids: string[]): string[] {\n return [...new Set(ids)].slice(0, MAX_INJECTED_IDS).map((id) => id.slice(0, MAX_ID_LENGTH))\n}\n\nexport function injectedContextOf(assembled: string, candidates: InjectionCandidates): InjectedContext {\n const text = assembled ?? \"\"\n return {\n memory: capIds((candidates.memory ?? []).filter((m) => m.content && text.includes(m.content)).map((m) => m.id)),\n procedures: capIds(\n (candidates.procedures ?? []).filter((p) => text.includes(`[Known procedure: ${p.title}]`)).map((p) => p.id),\n ),\n wiki: Boolean(candidates.wikiContext) && text.includes(WIKI_MARKER),\n }\n}\n\n/** Clamp an InjectedContext from any source to the recorded bounds. */\nexport function boundInjectedContext(ctx: InjectedContext): InjectedContext {\n return { memory: capIds(ctx.memory), procedures: capIds(ctx.procedures), wiki: ctx.wiki === true }\n}\n"],"mappings":"+CACAA,ICqBA,IAAMC,EAAc,sBAEpB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,GAAI,CAAC,EACxDI,EAAM;AAAA;AAAA,MAERH,EAAM,OAAS,EAAI,SAAWA,EAAM,KAAK,OAAO,EAAI;AAAA;AAAA;AAAA,IAIxD,OAAAC,EAAO,KAAKC,CAAK,EACTrC,EAAG,QAAQsC,CAAG,EAAE,IAAI,GAAGF,CAAM,EAAgC,IAAIpB,CAAU,CACrF,CAIO,SAASuB,EAAkBvC,EAAuBwC,EAAiC,CACxF,IAAMC,EAAqB,CAAC,EAE5B,QAAS1B,EAAI,EAAGA,EAAIyB,EAAO,OAAQzB,GAAK,IAAK,CAC3C,IAAM2B,EAAQF,EAAO,MAAMzB,EAAGA,EAAI,GAAG,EACrC,GAAI,CAAC2B,EAAM,OAAQ,SACnB,IAAMjB,EAAOzB,EAAG,QAAQ;AAAA,4DACgC0C,EAAM,IAAI,IAAM,GAAG,EAAE,KAAK,GAAG;AAAA;AAAA,KAEpF,EAAE,IAAI,GAAGA,CAAK,EACfD,EAAI,KAAK,GAAGhB,EAAK,IAAIT,CAAU,CAAC,EAElC,OAAOyB,CACT,CAIO,SAASE,EACd3C,EAAuBE,EAAgBmC,EAAQ,IACgB,CAK/D,OAJarC,EAAG,QAAQ;AAAA;AAAA;AAAA,GAGvB,EAAE,IAAIE,EAAQmC,CAAK,EACR,IAAK,IAAO,CAAE,OAAQ,EAAE,QAAU,KAAM,aAAc,EAAE,eAAiB,IAAK,EAAE,CAC9F","names":["init_ulid","WIKI_MARKER","capIds","ids","id","injectedContextOf","assembled","candidates","text","m","p","boundInjectedContext","ctx","recordTraceStart","db","input","taskId","newEventId","recordTraceEnd","finishedAt","boundInjectedContext","recordTraceStep","startedAt","seq","parseInjectedContext","raw","v","ids","x","i","rowToTrace","row","rowToStep","getTrace","stepRows","cleanupOrphanedTraces","now","takeInterruptedRuns","take","rows","steps","r","s","claimResume","recordResumeDecision","decision","reason","listTraces","filters","where","params","limit","sql","listTracesForRuns","runIds","out","chunk","traceToolCalls"]}
@@ -1,4 +1,4 @@
1
- import{a as Re,b as w,c as z,d as Pe,e as ie,f as se,g as M,h as le,i as N,j as O,n as De,o as ze,p as _e,q as We}from"./chunk-XVTD6I34.js";import{e as Ee,i as Te}from"./chunk-QAWKN2N4.js";import{b as oe}from"./chunk-MTX4UPNB.js";import{c as Ie,d as ae,e as T,f as re,g as B}from"./chunk-B2QYMUTD.js";import{a as G,b as Ce}from"./chunk-YYPTXXCJ.js";import{a as Se}from"./chunk-7LN4VKDU.js";import{a as Ae}from"./chunk-IMLAPB7G.js";import{b as $e}from"./chunk-MRIVENBY.js";import{i as ne,k as ke}from"./chunk-AKWBDCMU.js";import{b as xe}from"./chunk-YMX3QCV7.js";import{c as ye,e as we}from"./chunk-LQE73AZR.js";import{G as K}from"./chunk-THWDSPX4.js";import{a as L,b as F}from"./chunk-QVPBSV5Z.js";import{a as ve}from"./chunk-ERG5OUKH.js";import{a as be}from"./chunk-ROLSSYXE.js";import{Ga as ee,Ia as H,Ja as he,L as Z,M as me,Ra as te,T as dt,ia as fe,pa as ct}from"./chunk-K22XMF6M.js";import{existsSync as j,readFileSync as Oe,writeFileSync as Ue,appendFileSync as ut,mkdirSync as mt}from"fs";import{dirname as ft,resolve as _}from"path";import{fileURLToPath as ht}from"url";import{hostname as bt}from"os";import{spawn as vt}from"child_process";function Me(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",a=`<header class="ax-topbar">
1
+ import{a as Re,b as w,c as z,d as Pe,e as ie,f as se,g as M,h as le,i as N,j as O,n as De,o as ze,p as _e,q as We}from"./chunk-XVTD6I34.js";import{e as Ee,i as Te}from"./chunk-QAWKN2N4.js";import{b as oe}from"./chunk-MTX4UPNB.js";import{a as G,b as Ce}from"./chunk-CZWEXRIE.js";import{c as Ie,d as ae,e as T,f as re,g as B}from"./chunk-B2QYMUTD.js";import{a as Se}from"./chunk-7LN4VKDU.js";import{a as Ae}from"./chunk-IMLAPB7G.js";import{b as $e}from"./chunk-MRIVENBY.js";import{l as ne,n as ke}from"./chunk-KV4ZA7FS.js";import{b as xe}from"./chunk-YMX3QCV7.js";import{c as ye,e as we}from"./chunk-LQE73AZR.js";import{G as K}from"./chunk-45TKVOJX.js";import{a as L,b as F}from"./chunk-SFUNL7RV.js";import{a as ve}from"./chunk-Q73QQPDB.js";import{a as be}from"./chunk-ROLSSYXE.js";import{Ha as ee,Ja as H,Ka as he,L as Z,M as me,Sa as te,T as dt,ia as fe,pa as ct}from"./chunk-DPIQCHXB.js";import{existsSync as j,readFileSync as Oe,writeFileSync as Ue,appendFileSync as ut,mkdirSync as mt}from"fs";import{dirname as ft,resolve as _}from"path";import{fileURLToPath as ht}from"url";import{hostname as bt}from"os";import{spawn as vt}from"child_process";function Me(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",a=`<header class="ax-topbar">
2
2
  <div class="ax-topbar__left">
3
3
  <div class="ax-brand">
4
4
  <span class="ax-brand__mark">AX</span>
@@ -858,4 +858,4 @@ tr:hover td { background: var(--bg-hover); }
858
858
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
859
859
  ${a}`).all(t,...n,...o).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function ga(e,t){return et(e,t,Z,"ORDER BY created_at")}function ua(e,t,n=50){return et(e,t,[...Z,...me],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}ct();var ue="member:",Yt=90,Vt="members",Xt="tailscale-user-login",Qt=400,Zt=60*60*1e3;function en(e){let t=e.scopes.find(n=>n.startsWith(ue));return t?t.slice(ue.length):null}function nt(e,t){if(!e)return null;let n=t.verify(e),a=n?en(n):null;return n&&a?{rec:n,personId:a}:null}function ya(e,t){let n=e.people().find(s=>s.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:a,record:o}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${ue}${n.id}`],expiresInDays:Yt}),{code:r,expiresAt:i}=e.codes.create({token:a,tokenId:o.id,name:n.id});return e.members.log({person:n.id,device:o.id,event:"invited"}),{ok:!0,code:r,expiresAt:i,tokenId:o.id,person:n}}var tn=Math.round(ye/6e4);function nn(e){return e==="client"?"Your project":"My work"}function wa(e){let t=nn(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${we(e.code)}`,` The code works once, for ${tn} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
860
860
  `)}var an="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",rn="Too many machines are waiting for the owner's answer. Try again later.",tt="That code didn't work. Check it, or ask the person who invited you for a new one.",at=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function rt(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function on(e){if(!rt(e))return null;let t=at(e,Xt).toLowerCase();return t?t.slice(0,80):null}function sn(e){let t=e.socket?.remoteAddress||"unknown";if(!rt(e))return t;let n=at(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function ln(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function dn(e){return e.identities.map(fe).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function ka(e,t){let n=Date.now(),a=t.now??Date.now,o=t.log??(b=>console.log(b)),r=sn(e),i=t.limiter.retryAfter(r);if(i>0)return o(`[member] pair-code refused from ${r}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,l="";try{let b=await xe(e,2048);s=b.code,l=ln(b.machine)}catch{}let c=t.codes.redeem(s),d=c?nt(c.token,t.tokens):null;if(await pn(n,t.minMs??Qt),!c||!d)return t.limiter.fail(r),o(`[member] pair-code failed from ${r}`),{status:401,body:{error:tt}};t.limiter.succeed(r);let{rec:m,personId:p}=d,k=t.people().find(b=>b.id===p);if(!k)return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:r,detail:"person no longer listed"}),o(`[member] pair-code for ${p} refused from ${r}: person no longer listed`),{status:403,body:{error:tt}};let u=on(e),f=dn(k);if(f.length&&(!u||!f.includes(u)))return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:r,detail:`network login ${u??"missing"}; expected ${f.join(" or ")}`}),o(`[member] ${p}: pairing from ${r} refused: the network says "${u??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:an}};let I=l||"Unnamed machine",x=k.name.slice(0,40),v=ke(t.root,{title:`New machine for ${x}`,ask:`From ${r}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${I}". Let it see ${x}'s own work?`,recommend:`Yes if ${x} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:Vt},{now:a()});return v.ok?(t.members.add({tokenId:m.id,personId:p,name:I,state:"pending",cardId:v.card.id,address:r,...u?{network:u}:{},createdAt:new Date(a()).toISOString()}),t.members.log({person:p,device:m.id,event:"paired",address:r,detail:I}),o(`[member] ${p} paired "${I}" from ${r}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:p,name:I,state:"pending"},token:c.token}):(t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:r,detail:v.error}),o(`[member] ${p}: pairing from ${r} refused: ${v.error}`),{status:503,body:{error:rn}})}var Q="this machine is not paired",cn="waiting for the owner to approve this machine";function ot(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function $a(e,t){return t.state==="pending"&&t.cardId?ot(ne(e,t.cardId)):null}function Aa(e,t,n){let a=t.now??Date.now,o=t.log??(d=>console.log(d)),r=nt(e,t.tokens);if(!r)return{ok:!1,status:401,error:Q};let{rec:i,personId:s}=r,l=t.members.byToken(i.id);if(!l||l.state==="removed"||l.personId!==s)return{ok:!1,status:401,error:Q};if(t.people&&!t.people().some(d=>d.id===s))return it(t,i.id,"person no longer listed"),o(`[member] ${s}: "${l.name}" ended: person no longer listed`),{ok:!1,status:401,error:Q};if(l.state==="pending"){let d=l.cardId?ne(t.root,l.cardId):null,m=ot(d);if(m==="yes")l=t.members.update(i.id,{state:"active",approvedAt:new Date(a()).toISOString()})??l,t.members.log({person:s,device:i.id,event:"approved",detail:d?.decided_by}),o(`[member] ${s}: "${l.name}" approved`);else if(m==="no"){let p=d?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(i.id),t.members.update(i.id,{state:"removed",removedAt:new Date(a()).toISOString(),removedReason:p}),t.members.log({person:s,device:i.id,event:"refused",detail:p}),o(`[member] ${s}: "${l.name}" refused: ${p}`),{ok:!1,status:401,error:Q}}else return{ok:!1,status:403,error:cn,waiting:!0}}let c=l.lastSeenAt?Date.parse(l.lastSeenAt):0;return n&&(a()-c>=Zt||l.lastAddress!==n)&&(l=t.members.update(i.id,{lastSeenAt:new Date(a()).toISOString(),lastAddress:n})??l,t.members.log({person:s,device:i.id,event:"signed-in",address:n})),{ok:!0,device:l,personId:s,rec:i}}function it(e,t,n="removed by the owner"){let a=e.members.byToken(t);if(!a)return null;e.tokens.revoke(t);let o=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:a.personId,device:t,event:"removed",detail:n}),o}function Sa(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>it(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function pn(e,t){let n=e+t-Date.now();n>0&&await new Promise(a=>setTimeout(a,n))}var st=["gitlab","github"];function gn(e,t,n){let a=String(t||"").trim().toLowerCase();if(!st.includes(a))throw new Error(`Request status works on ${st.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let o=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(r=>String(r).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...o,a])]:o.filter(r=>r!==a),`request status on ${a} is ${n?"on":"off"}`}function Ea(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function Ta(e){let{summary:t}=G(n=>gn(n,e?.channel,!!e?.enabled));return{summary:t}}function Pa(e){return new Set(Object.entries(e).filter(([,t])=>t?.wiki?.absorb?.enabled===!1).map(([t])=>t))}function Da(e,t){return t.only?{agents:[t.only],skipped:[]}:{agents:e.filter(n=>!t.off.has(n)),skipped:e.filter(n=>t.off.has(n))}}function za(e,t){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===t?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function _a(e,t){if(t){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var un="https://ntfy.sh";function Ma(e){return{enabled:!!e?.enabled,server:e?.server||un,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Na(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let a=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(a))throw new Error("ntfy server must be an http(s) URL");n.server=a}if("topic"in t){let a=String(t.topic).trim();if(!a)throw new Error("ntfy topic cannot be empty");n.topic=a}if("token"in t){let a=String(t.token??"").trim();a?n.token=a:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{Be as a,An as b,Sn as c,In as d,Pn as e,Dn as f,zn as g,pa as h,ga as i,ua as j,Yt as k,ya as l,tn as m,nn as n,wa as o,sn as p,ka as q,$a as r,Aa as s,it as t,Sa as u,st as v,gn as w,Ea as x,Ta as y,Pa as z,Da as A,za as B,_a as C,Ma as D,Na as E,Ht as F,ta as G,sa as H,la as I};
861
- //# sourceMappingURL=chunk-PYI7ZAU3.js.map
861
+ //# sourceMappingURL=chunk-BAO77R4L.js.map
@@ -1,4 +1,4 @@
1
- import{Ja as l,Ra as m}from"./chunk-K22XMF6M.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
1
+ import{Ka as l,Sa as m}from"./chunk-DPIQCHXB.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
2
2
  `,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
4
- //# sourceMappingURL=chunk-YYPTXXCJ.js.map
4
+ //# sourceMappingURL=chunk-CZWEXRIE.js.map
@@ -1,4 +1,4 @@
1
- import{e as g}from"./chunk-SDSSRNSU.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
1
+ import{e as g}from"./chunk-2GJFLPS7.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
2
2
  `)}).join(`
3
3
 
4
4
  ---
@@ -14,4 +14,4 @@ These ${e.length} articles were found by searching the wiki for each entry below
14
14
 
15
15
  ${i}
16
16
  `}var d=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,y=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,w=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,k=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,C=/^\s*\d+[.)]\s/gm;function A(e){let i=[...e.matchAll(d)].map(s=>s[0].replace(/[.,;:!?'"]+$/,"")),r=[...e.matchAll(y)].map(s=>s[1].trim()),n=e.replace(d," ").replace(y," ").replace(C," "),o=[...n.matchAll(w)].map(s=>s[0].toLowerCase()),c=[...n.replace(w," ").matchAll(k)].map(s=>v(s[0]));return{commits:m(o),urls:m(i),wikilinks:m(r),numbers:m(c)}}function R(e,i){let r=A(e),n=A(i),o=i.toLowerCase(),a=[];for(let t of r.commits)!o.includes(t)&&!n.commits.some(l=>l.startsWith(t)||t.startsWith(l))&&a.push(`commit ${t}`);let c=t=>t.toLowerCase().replace(/\/+$/,""),s=new Set(n.urls.map(c));for(let t of r.urls)s.has(c(t))||a.push(`link ${t}`);let f=new Set(n.wikilinks.map(t=>t.toLowerCase()));for(let t of r.wikilinks)f.has(t.toLowerCase())||a.push(`link [[${t}]]`);let h=new Set(n.numbers);for(let t of r.numbers)h.has(t)||a.push(`number ${t}`);return a}function v(e){return/^\d{1,3}(,\d{3})+$/.test(e)?e.replace(/,/g,""):e}function m(e){return[...new Set(e)]}function L(e,i){if(i.some(n=>n.path===e.path))return e.path;let r=b(e.title);return r?i.find(n=>b(n.title)===r)?.path??e.path:e.path}function b(e){return(e||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}export{$ as a,x as b,A as c,R as d,L as e};
17
- //# sourceMappingURL=chunk-OMO7UTWW.js.map
17
+ //# sourceMappingURL=chunk-DFWPTNZ5.js.map
@@ -0,0 +1,11 @@
1
+ import{a as w,b as f}from"./chunk-WBG6NA7R.js";import{randomUUID as _}from"crypto";function p(r){return r.status&&r.status!=="ringing"?", waiting_since=NULL, told_at=NULL":""}var E=["ringing","answered","later"],A=`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`,y=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 e=new Set(t.prepare("PRAGMA table_info(calls)").all().map(n=>n.name));e.has("kind")||t.exec("ALTER TABLE calls ADD COLUMN kind TEXT NOT NULL DEFAULT 'voice'"),e.has("channel")||t.exec("ALTER TABLE calls ADD COLUMN channel TEXT"),e.has("chat_id")||t.exec("ALTER TABLE calls ADD COLUMN chat_id TEXT"),e.has("waiting_since")||t.exec("ALTER TABLE calls ADD COLUMN waiting_since INTEGER"),e.has("told_at")||t.exec("ALTER TABLE calls ADD COLUMN told_at INTEGER")}waiting(){let t=this.db.prepare("SELECT id, waiting_since AS since, told_at AS toldAt FROM calls WHERE waiting_since IS NOT NULL AND status='ringing'").all();return new Map(t.map(({id:e,since:n,toldAt:i})=>[e,{since:n,toldAt:i??n}]))}setWaiting(t,e){this.db.prepare("UPDATE calls SET waiting_since=?, told_at=? WHERE id=?").run(e?.since??null,e?.toldAt??null,t)}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 ${A} FROM calls WHERE id=?`).get(t)}update(t,e){let n={reason:"reason",urgency:"urgency",status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},i=Object.keys(e).filter(a=>a in n);if(i.length){let a=i.map(s=>`${n[s]}=?`).join(", ")+p(e);this.db.prepare(`UPDATE calls SET ${a} WHERE id=?`).run(...i.map(s=>e[s]??null),t)}return this.get(t)}transition(t,e,n){let i=Array.isArray(e)?e:[e],a={status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},s=Object.keys(n).filter(l=>l in a),o=s.map(l=>`${a[l]}=?`).join(", ")+p(n),u=i.map(()=>"?").join(",");return this.db.prepare(`UPDATE calls SET ${o} WHERE id=? AND status IN (${u})`).run(...s.map(l=>n[l]??null),t,...i).changes?this.get(t):void 0}list(t={}){let e=Math.min(Math.max(t.limit??50,1),200),n=[],i=[];t.status?.length&&(n.push(`status IN (${t.status.map(()=>"?").join(",")})`),i.push(...t.status)),t.kind&&(n.push("kind=?"),i.push(t.kind));let a=n.length?`WHERE ${n.join(" AND ")}`:"";return this.db.prepare(`SELECT ${A} FROM calls ${a} ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(...i,e)}countSince(t,e){return this.db.prepare("SELECT COUNT(*) AS n FROM calls WHERE agent_id=? AND created_at>?").get(t,e).n}};var C=200,k=1e4,I=2*36e5,$=10,T=240;function D(r=process.env){return r.AGENTX_TASK_ID?{"X-AgentX-Task":r.AGENTX_TASK_ID}:r.AGENTX_CHANNEL&&r.AGENTX_CHAT_ID?{"X-AgentX-Channel":r.AGENTX_CHANNEL,"X-AgentX-Chat":r.AGENTX_CHAT_ID}:{}}function N(r){return`[Call answered] The owner just picked up the voice call you asked for. You called because: "${r.reason}". Speak first: greet them in a few words and say why you called, then let them answer.`}var M="[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.",S=class{constructor(t){this.deps=t;this.waiting=t.store.waiting()}widgetSeenAt=0;widget={};waiting;setWaiting(t,e){if(e)this.waiting.set(t,e);else if(!this.waiting.delete(t))return;this.deps.store.setWaiting(t,e)}now(){return this.deps.now?.()??Date.now()}name(t){return this.deps.agentName(t)??t}async request(t,e={}){let n=String(t.agentId??"").trim(),i=String(t.reason??"").replace(/\s+/g," ").trim(),a=t.urgency==="urgent"?"urgent":"normal",s=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(!n||!i)return{ok:!1,status:400,error:"Required: agentId and reason"};if(i.length>C)return{ok:!1,status:413,error:`reason is over ${C} characters; keep it to one line`};if(this.deps.agentName(n)===null)return{ok:!1,status:404,error:`Unknown agent: ${n}`};if(!this.deps.isRunningTurn(n,e))return{ok:!1,status:403,error:`No running turn of ${n} placed this call. An agent calls from inside its own run.`};let o=this.deps.config();if(!o.allow.includes("*")&&!o.allow.includes(n))return{ok:!1,status:403,error:`${n} ${s==="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 ${n}).`};if(await this.sweep(),this.deps.store.list({status:E,limit:200}).some(m=>m.agentId===n))return{ok:!1,status:409,error:`${n} already has a call in progress`};let u=this.now();if(this.deps.store.countSince(n,u-36e5)>=o.maxPerHour)return{ok:!1,status:429,error:`${n} has placed ${o.maxPerHour} calls in the last hour (calls.maxPerHour)`};let g=s==="camera"?this.deps.turnSession?.(n,e)??e:{},l={id:`call-${_().slice(0,8)}`,agentId:n,kind:s,reason:i,urgency:a,status:"ringing",createdAt:u,ringingSince:u,answeredAt:null,endedAt:null,ringAgainAt:null,note:null,summary:null,channel:g.channel&&g.chatId?g.channel:null,chatId:g.channel&&g.chatId?g.chatId:null};this.deps.store.insert(l),this.deps.log?.(`[calls] ${n} asks ${s==="camera"?"to see":"for a call"} (${a}): ${i}`);let d=await this.ring(l),h=this.deps.store.get(l.id);return d!=="waiting"?{ok:!0,call:h,rang:d}:this.waiting.has(l.id)?{ok:!0,call:h,rang:d,busy:this.busyInfo(l)}:{ok:!0,call:h,rang:"widget"}}async cancel(t,e={}){let n=String(t.agentId??"").trim();if(!n)return{ok:!1,status:400,error:"Required: agentId"};if(!this.deps.isRunningTurn(n,e))return{ok:!1,status:403,error:`No running turn of ${n} asked for this. An agent withdraws its own call from inside its run.`};let i=this.deps.store.list({status:["ringing","later"],kind:"voice",limit:200}).find(s=>s.agentId===n);if(!i)return{ok:!1,status:404,error:`${n} has no call waiting or ringing`};let a=this.deps.store.transition(i.id,["ringing","later"],{status:"ended",endedAt:this.now(),ringingSince:null,ringAgainAt:null,note:b});return a?(this.setWaiting(i.id,null),this.deps.log?.(`[calls] ${i.id} withdrawn by ${n}`),{ok:!0,call:a}):{ok:!1,status:409,error:`call is ${this.deps.store.get(i.id)?.status}`}}async ring(t){let e=(this.deps.focus??w)();return e.active&&t.urgency!=="urgent"?(this.deps.store.transition(t.id,"ringing",{status:"missed",ringingSince:null,note:f(e)})&&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,e,n){try{await this.deps.alert({title:e,message:n?`${t.reason}
10
+ ${n}`:t.reason,urgent:t.urgency==="urgent",from:t.agentId})}catch(i){this.deps.log?.(`[calls] notice for ${t.id} failed: ${i?.message??i}`)}}startWaiting(t){let e=this.now();this.setWaiting(t.id,{since:e,toldAt:e}),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(e=>e.id!==t.id).reverse()}async callWaiting(t){let e=this.deps.config().busy;await this.notice(t,e.title.replaceAll("{agent}",this.name(t.agentId)),e.notice)}busyInfo(t){let e=this.deps.config().busy,{since:n,toldAt:i}=this.waiting.get(t.id)??{since:this.now(),toldAt:this.now()},a=this.otherCalls(t),s=a.find(d=>d.status==="answered"),o=a.find(d=>d.id===this.widget.showing)??a.find(d=>!this.waiting.has(d.id)),u=n+e.maxWaitMinutes*6e4+this.deps.config().ringSeconds*1e3,g=i+e.retryMinutes*6e4,l=n+e.maxWaitMinutes*6e4;return{why:s?"call":o?"ringing":"voice",with:s?this.name(s.agentId):o?this.name(o.agentId):null,remindAt:g<l?g: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)}`}inCall(){if(this.widgetAlive()&&this.widget.busy)return"the widget is busy";let t=this.now()-I,e=this.deps.store.list({status:["answered"],limit:5}).find(n=>(n.answeredAt??0)>=t);return e?`on a call with ${this.name(e.agentId)}`:null}widgetAlive(){return this.now()-this.widgetSeenAt<k}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 e=this.now(),n=this.deps.config().busy,i=[],a=this.deps.store.list({status:["ringing"],kind:"voice",limit:20});for(let s of[...this.waiting.keys()])a.some(o=>o.id===s)||this.setWaiting(s,null);for(let s of a){if(s.id===t.showing){this.waiting.has(s.id)&&(this.setWaiting(s.id,null),this.deps.store.transition(s.id,"ringing",{ringingSince:e}));continue}if(!t.busy)continue;let o=this.waiting.get(s.id);if(!(o&&e-o.since>=n.maxWaitMinutes*6e4)&&this.deps.store.transition(s.id,"ringing",{ringingSince:e})){if(!o)this.startWaiting(s);else if(e-o.toldAt>=n.retryMinutes*6e4)this.setWaiting(s.id,{since:o.since,toldAt:e});else continue;i.push(s)}}for(let s of i)await this.callWaiting(s)}async asking(){return await this.sweep(),this.deps.store.list({status:["ringing"],kind:"camera",limit:20}).reverse()}async sweep(){let t=this.now(),e=this.deps.config().ringSeconds*1e3,n=this.deps.config().maxCallMinutes*6e4;for(let i of this.deps.store.list({status:["ringing","later","answered"],limit:200}))if(i.status==="ringing"&&i.ringingSince!==null&&t-i.ringingSince>=e){if(!this.deps.store.transition(i.id,"ringing",{status:"missed",ringingSince:null,note:this.waiting.has(i.id)?"widget busy":"not answered"}))continue;this.deps.log?.(`[calls] ${i.id} from ${i.agentId} missed`),await this.notice(i,this.missedTitle(i))}else if(i.status==="answered"&&i.answeredAt!==null&&t-i.answeredAt>=n){if(!this.deps.store.transition(i.id,"answered",{status:"ended",endedAt:t,note:"no hang-up"}))continue;this.deps.log?.(`[calls] ${i.id} from ${i.agentId} ended: no hang-up in ${this.deps.config().maxCallMinutes} min`)}else if(i.status==="later"&&i.ringAgainAt!==null&&t>=i.ringAgainAt){let a=this.deps.store.transition(i.id,"later",{status:"ringing",ringingSince:t,ringAgainAt:null});if(!a)continue;this.setWaiting(i.id,null),await this.ring(a)}}answer(t){let e=this.deps.store.get(t);if(!e)return c(t);let n=this.deps.store.transition(t,"ringing",{status:"answered",answeredAt:this.now(),ringingSince:null});return n?(this.deps.log?.(`[calls] ${t} answered (${e.agentId})`),n.kind==="camera"?{ok:!0,call:n}:{ok:!0,call:n,opener:N(n)}):{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 n=this.deps.store.transition(t,["ringing","later"],{status:"declined",endedAt:this.now(),ringingSince:null,ringAgainAt:null});return n?{ok:!0,call:n}:{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}`}}later(t,e){if(!this.deps.store.get(t))return c(t);let i=e===void 0?$:Number(e);if(!Number.isInteger(i)||i<1||i>T)return{ok:!1,status:400,error:`minutes must be a whole number from 1 to ${T}`};let a=this.deps.store.transition(t,"ringing",{status:"later",ringingSince:null,ringAgainAt:this.now()+i*6e4});return a?{ok:!0,call:a}:{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}, not ringing`}}hangup(t){let e=this.deps.store.get(t);if(!e)return c(t);let n=this.deps.store.transition(t,"answered",{status:"ended",endedAt:this.now()});if(!n)return{ok:!1,status:409,error:`call is ${e.status}, not answered`};this.deps.log?.(`[calls] ${t} ended (${e.agentId})`);let i=this.deps.summarize;if(n.kind==="camera"||!this.deps.config().summary||!i)return{ok:!0,call:n};let a=(async()=>{try{let s=(await i(n))?.trim();if(!s)return;let o=this.deps.store.update(t,{summary:s});this.deps.file?.(o,s)}catch(s){this.deps.log?.(`[calls] summary for ${t} failed: ${s?.message??s}`)}})();return{ok:!0,call:n,summarized:a}}endCamera(t,e){let n=this.deps.store.get(t);if(!n||n.kind!=="camera")return!1;let i=this.deps.store.transition(t,"answered",{status:"ended",endedAt:this.now(),note:e??null});return i&&this.deps.log?.(`[calls] ${t} ended (${n.agentId}): ${e??"share over"}`),!!i}get(t){return this.deps.store.get(t)}list(t={}){return this.deps.store.list(t)}},b="withdrawn by the caller";function W(r,t=Date.now(),e){let n=a=>`${new Date(a).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short",timeZone:e})} (in ${Math.max(1,Math.round((a-t)/6e4))} min)`;return`${r.why==="call"?`The owner is busy in another call${r.with?` (with ${r.with})`:""}.`:r.why==="ringing"?`The owner is busy: another call${r.with?` (from ${r.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. `+(r.remindAt!==null?`Still busy at ${n(r.remindAt)}, they are told again that you are waiting. `:"")+`It waits until ${n(r.waitsUntil)} at most, then counts as a missed call.`}var c=r=>({ok:!1,status:404,error:`No such call: ${r}`});export{y as a,D as b,M as c,S as d,W as e};
11
+ //# sourceMappingURL=chunk-DG2DC43E.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, type Waiting } 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\n/** An answered call older than this holds nothing: one never marked ended\n * must not hold the owner's notices forever. */\nexport const CALL_HOLD_MAX_MS = 2 * 3_600_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. Written through to the store, so a restart keeps them. */\n private waiting: Map<string, Waiting>\n\n constructor(private deps: CallDeps) {\n this.waiting = deps.store.waiting()\n }\n\n private setWaiting(id: string, w: Waiting | null): void {\n if (w) this.waiting.set(id, w)\n else if (!this.waiting.delete(id)) return\n this.deps.store.setWaiting(id, w)\n }\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.setWaiting(mine.id, null)\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.setWaiting(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 /** Why the owner is in a call now, or null (#394, the call check): a\n * voice call answered in the last two hours and not ended, or a live\n * widget that says it is busy (a call, the microphone, a turn). */\n inCall(): string | null {\n if (this.widgetAlive() && this.widget.busy) return \"the widget is busy\"\n const since = this.now() - CALL_HOLD_MAX_MS\n const live = this.deps.store.list({ status: [\"answered\"], limit: 5 }).find((c) => (c.answeredAt ?? 0) >= since)\n return live ? `on a call with ${this.name(live.agentId)}` : null\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.setWaiting(id, null)\n for (const call of live) {\n if (call.id === widget.showing) {\n if (this.waiting.has(call.id)) {\n this.setWaiting(call.id, null)\n this.deps.store.transition(call.id, \"ringing\", { ringingSince: now })\n }\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) this.setWaiting(call.id, { since: held.since, 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) continue\n // A wait from before the snooze does not carry over.\n this.setWaiting(call.id, null)\n 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. Times are\n * in the host's time zone (or `timeZone`), and say which one. */\nexport function busyText(busy: BusyInfo, now: number = Date.now(), timeZone?: string): string {\n const at = (ms: number) => `${new Date(ms).toLocaleTimeString(\"en-GB\", { hour: \"2-digit\", minute: \"2-digit\", hour12: false, timeZoneName: \"short\", timeZone })} (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/** A call waiting for a busy owner: since when, and when the owner was\n * last told. Ms since the epoch. */\nexport interface Waiting {\n since: number\n toldAt: number\n}\n\n/** A call that stops ringing (answered, snoozed, missed...) is no longer\n * waiting: the mark goes in the same write, so a call that rings again\n * later starts a fresh wait, even across a restart. */\nfunction leaving(patch: { status?: CallStatus }): string {\n return patch.status && patch.status !== \"ringing\" ? \", waiting_since=NULL, told_at=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 // A call waiting for a busy owner (#969), kept so a restart does not\n // forget it: since when it waits, and when the owner was last told.\n if (!have.has(\"waiting_since\")) db.exec(\"ALTER TABLE calls ADD COLUMN waiting_since INTEGER\")\n if (!have.has(\"told_at\")) db.exec(\"ALTER TABLE calls ADD COLUMN told_at INTEGER\")\n }\n\n /** Ringing calls marked as waiting for a busy owner, by id. */\n waiting(): Map<string, Waiting> {\n const rows = this.db.prepare(\"SELECT id, waiting_since AS since, told_at AS toldAt FROM calls WHERE waiting_since IS NOT NULL AND status='ringing'\")\n .all() as Array<{ id: string } & Waiting>\n return new Map(rows.map(({ id, since, toldAt }) => [id, { since, toldAt: toldAt ?? since }]))\n }\n\n /** Mark a call as waiting, or clear the mark with null. */\n setWaiting(id: string, w: Waiting | null): void {\n this.db.prepare(\"UPDATE calls SET waiting_since=?, told_at=? WHERE id=?\").run(w?.since ?? null, w?.toldAt ?? null, id)\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(\", \") + leaving(patch)\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(\", \") + leaving(patch)\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,SCqB3B,SAASC,EAAQC,EAAw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AAC,SAAS,KAAK,IAAI,EAAG,KAAK,OAAOE,EAAK7C,GAAO,GAAM,CAAC,SAIjN,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,iBAAiB8B,EAAG9B,EAAK,QAAQ,gDAAkD,IAC7G,kBAAkB8B,EAAG9B,EAAK,UAAU,0CACxC,CAEA,IAAMgB,EAAWzC,IAA4B,CAAE,GAAI,GAAO,OAAQ,IAAK,MAAO,iBAAiBA,GAAK","names":["randomUUID","leaving","patch","LIVE","COLUMNS","CallStore","db","have","c","rows","id","since","toldAt","w","call","cols","keys","k","set","from","statuses","marks","opts","limit","where","args","filter","agentId","REASON_MAX","WIDGET_FRESH_MS","CALL_HOLD_MAX_MS","LATER_DEFAULT_MINUTES","LATER_MAX_MINUTES","callerHeaders","env","openerPrompt","call","SUMMARY_PROMPT","CallService","deps","id","w","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","live","widget","tell","held","ringFor","talkFor","again","unknown","answered","declined","minutes","n","later","summarize","summarized","text","done","note","opts","busyText","timeZone","at","ms"]}