agentix-cli 0.196.0 → 0.197.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 (198) hide show
  1. package/dist/{App-HBM52GXI.js → App-GF6MCNH6.js} +2 -2
  2. package/dist/{App-HBM52GXI.js.map → App-GF6MCNH6.js.map} +1 -1
  3. package/dist/ChatApp-FO2JNLWI.js +7 -0
  4. package/dist/{ChatApp-N4P7M2TD.js.map → ChatApp-FO2JNLWI.js.map} +1 -1
  5. package/dist/absorb-eval-7KMQJ5BR.js +2 -0
  6. package/dist/{adapter-X6T3YBUB.js → adapter-V7DQXCII.js} +2 -2
  7. package/dist/{adapter-X6T3YBUB.js.map → adapter-V7DQXCII.js.map} +1 -1
  8. package/dist/{agent-3B4RMEDI.js → agent-PJBGUZMR.js} +2 -2
  9. package/dist/{board-dashboard-Y2X7GNAS.js → board-dashboard-M3RVQM7K.js} +717 -380
  10. package/dist/board-dashboard-M3RVQM7K.js.map +1 -0
  11. package/dist/{chunk-YWAJNF2A.js → chunk-27ICCQVL.js} +54 -54
  12. package/dist/chunk-27ICCQVL.js.map +1 -0
  13. package/dist/{chunk-PMSL4A5Y.js → chunk-35GSB7SK.js} +3 -3
  14. package/dist/{chunk-XH36J3Z2.js → chunk-3K3IBV5K.js} +2 -2
  15. package/dist/{chunk-ZALVAXQ4.js → chunk-3LMBT5LK.js} +2 -2
  16. package/dist/{chunk-MB5CBY2C.js → chunk-424CABZF.js} +7 -7
  17. package/dist/chunk-424CABZF.js.map +1 -0
  18. package/dist/{chunk-F2FJXKDG.js → chunk-425HPUKF.js} +2 -2
  19. package/dist/{chunk-PX7PWXBI.js → chunk-4O6ZFYWT.js} +2 -2
  20. package/dist/chunk-7AB3QUGH.js +2 -0
  21. package/dist/{chunk-3FZ6WHKX.js.map → chunk-7AB3QUGH.js.map} +1 -1
  22. package/dist/chunk-7MW44Y5O.js +145 -0
  23. package/dist/chunk-7MW44Y5O.js.map +1 -0
  24. package/dist/chunk-B3JQ5J47.js +2 -0
  25. package/dist/chunk-B3JQ5J47.js.map +1 -0
  26. package/dist/chunk-BMNDAEF4.js +2 -0
  27. package/dist/chunk-BMNDAEF4.js.map +1 -0
  28. package/dist/{chunk-2GCPSAXQ.js → chunk-BN5JVELZ.js} +2 -2
  29. package/dist/{chunk-LQIF2OHS.js → chunk-BY5CN7C7.js} +2 -2
  30. package/dist/{chunk-HOZZUN47.js → chunk-DHD4KUTW.js} +2 -2
  31. package/dist/{chunk-KE6BF4ZJ.js → chunk-GMP2IB4E.js} +2 -2
  32. package/dist/{chunk-K2BEV3BD.js → chunk-HIHROVHC.js} +2 -2
  33. package/dist/{chunk-KXJRXRSD.js → chunk-HOL645BZ.js} +2 -2
  34. package/dist/{chunk-7L54Z4EH.js → chunk-HUOR3FGJ.js} +2 -2
  35. package/dist/chunk-I22ZKW7Q.js +4 -0
  36. package/dist/chunk-I22ZKW7Q.js.map +1 -0
  37. package/dist/chunk-IFUAP7UD.js +11 -0
  38. package/dist/chunk-IFUAP7UD.js.map +1 -0
  39. package/dist/{chunk-V7FZBETJ.js → chunk-IOCULCCJ.js} +2 -2
  40. package/dist/{chunk-NT3DGEBE.js → chunk-IQQ3I6R7.js} +312 -311
  41. package/dist/chunk-IQQ3I6R7.js.map +1 -0
  42. package/dist/{chunk-6V5JBHUN.js → chunk-J7PZJRYO.js} +2 -2
  43. package/dist/{chunk-F3CMNSON.js → chunk-K3623S4U.js} +2 -2
  44. package/dist/{chunk-2KYGPVTX.js → chunk-KB5JMDGS.js} +2 -2
  45. package/dist/{chunk-HNZEXUNM.js → chunk-OVB3LW6L.js} +2 -2
  46. package/dist/{chunk-6NQ7KYJH.js → chunk-OXTFAV2A.js} +2 -2
  47. package/dist/{chunk-VX4PSOKU.js → chunk-QABY3WEM.js} +2 -2
  48. package/dist/{chunk-M2E3CNFS.js → chunk-R3TH2OG7.js} +2 -2
  49. package/dist/chunk-RC3QYH2J.js +20 -0
  50. package/dist/chunk-RC3QYH2J.js.map +1 -0
  51. package/dist/{chunk-UOIWIVU3.js → chunk-RLI32DLG.js} +2 -2
  52. package/dist/{chunk-RW5FKJRE.js → chunk-SK7M6PS6.js} +2 -2
  53. package/dist/chunk-SNYAM7YB.js +116 -0
  54. package/dist/chunk-SNYAM7YB.js.map +1 -0
  55. package/dist/{chunk-BOCLWYWL.js → chunk-TBS7OVMI.js} +2 -2
  56. package/dist/{chunk-FO762MEC.js → chunk-TKXZHRV3.js} +2 -2
  57. package/dist/{chunk-PO2SORKY.js → chunk-WFPLZLCF.js} +2 -2
  58. package/dist/cli.js +1 -1
  59. package/dist/client-ZHE4B2DD.js +2 -0
  60. package/dist/config-THBWCNN7.js +2 -0
  61. package/dist/config-mutate-FBX6TFCY.js +2 -0
  62. package/dist/config-mutator-33RBNPV4.js +2 -0
  63. package/dist/{contributions-6VZ4OXJ5.js → contributions-2HR5ZGMK.js} +2 -2
  64. package/dist/{contributions-6VZ4OXJ5.js.map → contributions-2HR5ZGMK.js.map} +1 -1
  65. package/dist/doctor-VMWX6GKN.js +2 -0
  66. package/dist/{follow-up-tool-NVP56W7E.js → follow-up-tool-BCSCBKVL.js} +2 -2
  67. package/dist/{follow-up-tool-NVP56W7E.js.map → follow-up-tool-BCSCBKVL.js.map} +1 -1
  68. package/dist/hub-WPC6MTZY.js +2 -0
  69. package/dist/index.d.ts +131 -6
  70. package/dist/index.js +1 -1
  71. package/dist/index.js.map +1 -1
  72. package/dist/{note-tool-ANQWBBZE.js → note-tool-KVH3YBTX.js} +2 -2
  73. package/dist/ntfy-73UW6GHN.js +2 -0
  74. package/dist/{program-W7ZO7UDB.js → program-MOVUJBAA.js} +246 -246
  75. package/dist/program-MOVUJBAA.js.map +1 -0
  76. package/dist/promote-WWPXP5Z4.js +2 -0
  77. package/dist/push-E5YKRFAW.js +2 -0
  78. package/dist/push-bridge-RV3CBTYO.js +2 -0
  79. package/dist/query-F7HRTCWI.js +2 -0
  80. package/dist/{query-settings-C5UBKJMN.js → query-settings-Z32LXLJI.js} +2 -2
  81. package/dist/registry-D5HHCFCC.js +2 -0
  82. package/dist/request-planner-4FSNZJVQ.js +6 -0
  83. package/dist/{request-planner-G6IAUMSE.js.map → request-planner-4FSNZJVQ.js.map} +1 -1
  84. package/dist/review-candidates-U2DOD5Z3.js +4 -0
  85. package/dist/{review-candidates-ZL2SJXWC.js.map → review-candidates-U2DOD5Z3.js.map} +1 -1
  86. package/dist/routing-USMMBJYT.js +2 -0
  87. package/dist/schedule-tool-IRTB23XL.js +2 -0
  88. package/dist/scheduler-L4ERAOMG.js +2 -0
  89. package/dist/seat-3LW672DM.js +2 -0
  90. package/dist/select-MPMJSYKX.js +2 -0
  91. package/dist/{select-MU52ACKG.js.map → select-MPMJSYKX.js.map} +1 -1
  92. package/dist/self-HICJTWYO.js +2 -0
  93. package/dist/set-enabled-TQXG3MSQ.js +2 -0
  94. package/dist/{set-enabled-XRNSYEI3.js.map → set-enabled-TQXG3MSQ.js.map} +1 -1
  95. package/dist/{sprint-tool-E4MABD2N.js → sprint-tool-JQ5KCJDP.js} +2 -2
  96. package/dist/{sprint-tool-E4MABD2N.js.map → sprint-tool-JQ5KCJDP.js.map} +1 -1
  97. package/dist/{tool-ZYVT4VUU.js → tool-D4DHXF4Z.js} +2 -2
  98. package/dist/{tool-ZYVT4VUU.js.map → tool-D4DHXF4Z.js.map} +1 -1
  99. package/dist/tool-DHCKG3SK.js +10 -0
  100. package/dist/tool-DHCKG3SK.js.map +1 -0
  101. package/dist/{tool-V5Z4KWK7.js → tool-ZP3SZKYR.js} +2 -2
  102. package/dist/{tool-V5Z4KWK7.js.map → tool-ZP3SZKYR.js.map} +1 -1
  103. package/dist/wiki-CRH6XAXE.js +2 -0
  104. package/dist/wiki-enrich-YZEW6RZT.js +2 -0
  105. package/package.json +1 -1
  106. package/dist/ChatApp-N4P7M2TD.js +0 -7
  107. package/dist/absorb-eval-HRWWPKT3.js +0 -2
  108. package/dist/board-dashboard-Y2X7GNAS.js.map +0 -1
  109. package/dist/chunk-3FZ6WHKX.js +0 -2
  110. package/dist/chunk-5HLD66CW.js +0 -2
  111. package/dist/chunk-5HLD66CW.js.map +0 -1
  112. package/dist/chunk-AJ5HMDRW.js +0 -11
  113. package/dist/chunk-AJ5HMDRW.js.map +0 -1
  114. package/dist/chunk-IS2IWRP7.js +0 -4
  115. package/dist/chunk-IS2IWRP7.js.map +0 -1
  116. package/dist/chunk-MB5CBY2C.js.map +0 -1
  117. package/dist/chunk-MC3ZZA5G.js +0 -143
  118. package/dist/chunk-MC3ZZA5G.js.map +0 -1
  119. package/dist/chunk-NT3DGEBE.js.map +0 -1
  120. package/dist/chunk-P6WSD2UR.js +0 -116
  121. package/dist/chunk-P6WSD2UR.js.map +0 -1
  122. package/dist/chunk-UOYIC7XN.js +0 -3
  123. package/dist/chunk-UOYIC7XN.js.map +0 -1
  124. package/dist/chunk-YWAJNF2A.js.map +0 -1
  125. package/dist/client-YN3T56NM.js +0 -2
  126. package/dist/config-G7T3TMWE.js +0 -2
  127. package/dist/config-mutate-6CRKZQVQ.js +0 -2
  128. package/dist/config-mutator-7VS3J5BY.js +0 -2
  129. package/dist/doctor-GFZZTK7C.js +0 -2
  130. package/dist/hub-B434CABZ.js +0 -2
  131. package/dist/ntfy-Q4YHFKWW.js +0 -2
  132. package/dist/program-W7ZO7UDB.js.map +0 -1
  133. package/dist/promote-3P6PGJOW.js +0 -2
  134. package/dist/push-PRFZMCIK.js +0 -2
  135. package/dist/push-bridge-NR7SLHGX.js +0 -2
  136. package/dist/query-E4V7TS5S.js +0 -2
  137. package/dist/registry-IG324PR3.js +0 -2
  138. package/dist/request-planner-G6IAUMSE.js +0 -6
  139. package/dist/review-candidates-ZL2SJXWC.js +0 -4
  140. package/dist/routing-2IBIZYQU.js +0 -2
  141. package/dist/schedule-tool-QCTT2R3B.js +0 -2
  142. package/dist/scheduler-ZGB7IKZQ.js +0 -2
  143. package/dist/seat-CFY7LMPS.js +0 -2
  144. package/dist/select-MU52ACKG.js +0 -2
  145. package/dist/self-ELWZIMVY.js +0 -2
  146. package/dist/set-enabled-XRNSYEI3.js +0 -2
  147. package/dist/tool-W6M7GYRZ.js +0 -8
  148. package/dist/tool-W6M7GYRZ.js.map +0 -1
  149. package/dist/wiki-VP6XRWIS.js +0 -2
  150. package/dist/wiki-enrich-LUFXPUYY.js +0 -2
  151. /package/dist/{absorb-eval-HRWWPKT3.js.map → absorb-eval-7KMQJ5BR.js.map} +0 -0
  152. /package/dist/{agent-3B4RMEDI.js.map → agent-PJBGUZMR.js.map} +0 -0
  153. /package/dist/{chunk-PMSL4A5Y.js.map → chunk-35GSB7SK.js.map} +0 -0
  154. /package/dist/{chunk-XH36J3Z2.js.map → chunk-3K3IBV5K.js.map} +0 -0
  155. /package/dist/{chunk-ZALVAXQ4.js.map → chunk-3LMBT5LK.js.map} +0 -0
  156. /package/dist/{chunk-F2FJXKDG.js.map → chunk-425HPUKF.js.map} +0 -0
  157. /package/dist/{chunk-PX7PWXBI.js.map → chunk-4O6ZFYWT.js.map} +0 -0
  158. /package/dist/{chunk-2GCPSAXQ.js.map → chunk-BN5JVELZ.js.map} +0 -0
  159. /package/dist/{chunk-LQIF2OHS.js.map → chunk-BY5CN7C7.js.map} +0 -0
  160. /package/dist/{chunk-HOZZUN47.js.map → chunk-DHD4KUTW.js.map} +0 -0
  161. /package/dist/{chunk-KE6BF4ZJ.js.map → chunk-GMP2IB4E.js.map} +0 -0
  162. /package/dist/{chunk-K2BEV3BD.js.map → chunk-HIHROVHC.js.map} +0 -0
  163. /package/dist/{chunk-KXJRXRSD.js.map → chunk-HOL645BZ.js.map} +0 -0
  164. /package/dist/{chunk-7L54Z4EH.js.map → chunk-HUOR3FGJ.js.map} +0 -0
  165. /package/dist/{chunk-V7FZBETJ.js.map → chunk-IOCULCCJ.js.map} +0 -0
  166. /package/dist/{chunk-6V5JBHUN.js.map → chunk-J7PZJRYO.js.map} +0 -0
  167. /package/dist/{chunk-F3CMNSON.js.map → chunk-K3623S4U.js.map} +0 -0
  168. /package/dist/{chunk-2KYGPVTX.js.map → chunk-KB5JMDGS.js.map} +0 -0
  169. /package/dist/{chunk-HNZEXUNM.js.map → chunk-OVB3LW6L.js.map} +0 -0
  170. /package/dist/{chunk-6NQ7KYJH.js.map → chunk-OXTFAV2A.js.map} +0 -0
  171. /package/dist/{chunk-VX4PSOKU.js.map → chunk-QABY3WEM.js.map} +0 -0
  172. /package/dist/{chunk-M2E3CNFS.js.map → chunk-R3TH2OG7.js.map} +0 -0
  173. /package/dist/{chunk-UOIWIVU3.js.map → chunk-RLI32DLG.js.map} +0 -0
  174. /package/dist/{chunk-RW5FKJRE.js.map → chunk-SK7M6PS6.js.map} +0 -0
  175. /package/dist/{chunk-BOCLWYWL.js.map → chunk-TBS7OVMI.js.map} +0 -0
  176. /package/dist/{chunk-FO762MEC.js.map → chunk-TKXZHRV3.js.map} +0 -0
  177. /package/dist/{chunk-PO2SORKY.js.map → chunk-WFPLZLCF.js.map} +0 -0
  178. /package/dist/{client-YN3T56NM.js.map → client-ZHE4B2DD.js.map} +0 -0
  179. /package/dist/{config-G7T3TMWE.js.map → config-THBWCNN7.js.map} +0 -0
  180. /package/dist/{config-mutate-6CRKZQVQ.js.map → config-mutate-FBX6TFCY.js.map} +0 -0
  181. /package/dist/{config-mutator-7VS3J5BY.js.map → config-mutator-33RBNPV4.js.map} +0 -0
  182. /package/dist/{doctor-GFZZTK7C.js.map → doctor-VMWX6GKN.js.map} +0 -0
  183. /package/dist/{hub-B434CABZ.js.map → hub-WPC6MTZY.js.map} +0 -0
  184. /package/dist/{note-tool-ANQWBBZE.js.map → note-tool-KVH3YBTX.js.map} +0 -0
  185. /package/dist/{ntfy-Q4YHFKWW.js.map → ntfy-73UW6GHN.js.map} +0 -0
  186. /package/dist/{promote-3P6PGJOW.js.map → promote-WWPXP5Z4.js.map} +0 -0
  187. /package/dist/{push-PRFZMCIK.js.map → push-E5YKRFAW.js.map} +0 -0
  188. /package/dist/{push-bridge-NR7SLHGX.js.map → push-bridge-RV3CBTYO.js.map} +0 -0
  189. /package/dist/{query-E4V7TS5S.js.map → query-F7HRTCWI.js.map} +0 -0
  190. /package/dist/{query-settings-C5UBKJMN.js.map → query-settings-Z32LXLJI.js.map} +0 -0
  191. /package/dist/{registry-IG324PR3.js.map → registry-D5HHCFCC.js.map} +0 -0
  192. /package/dist/{routing-2IBIZYQU.js.map → routing-USMMBJYT.js.map} +0 -0
  193. /package/dist/{schedule-tool-QCTT2R3B.js.map → schedule-tool-IRTB23XL.js.map} +0 -0
  194. /package/dist/{scheduler-ZGB7IKZQ.js.map → scheduler-L4ERAOMG.js.map} +0 -0
  195. /package/dist/{seat-CFY7LMPS.js.map → seat-3LW672DM.js.map} +0 -0
  196. /package/dist/{self-ELWZIMVY.js.map → self-HICJTWYO.js.map} +0 -0
  197. /package/dist/{wiki-VP6XRWIS.js.map → wiki-CRH6XAXE.js.map} +0 -0
  198. /package/dist/{wiki-enrich-LUFXPUYY.js.map → wiki-enrich-YZEW6RZT.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{c as w}from"./chunk-F3CMNSON.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
1
+ import{c as w}from"./chunk-K3623S4U.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
2
2
  ${a.content}`),t.previous??""].join(`
3
3
  `),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
4
4
  `).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
33
33
  {"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
34
34
  `)+`
35
35
  `}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
36
- //# sourceMappingURL=chunk-7L54Z4EH.js.map
36
+ //# sourceMappingURL=chunk-HUOR3FGJ.js.map
@@ -0,0 +1,4 @@
1
+ import{b as T}from"./chunk-7AB3QUGH.js";import{a as l,b as A}from"./chunk-BMNDAEF4.js";A();var M=[1e3,3e3,8e3],R=2e4;function N(t){let e=t,n=e?.message??String(t),r=e?.cause;return r?.code?`${n} code=${r.code}`:r?.message&&r.message!==n?`${n} (${r.message})`:n}var D=new Set(["ECONNREFUSED","ETIMEDOUT","ENETUNREACH","EHOSTUNREACH","EADDRNOTAVAIL","ENOTFOUND","EAI_AGAIN","UND_ERR_CONNECT_TIMEOUT"]);function _(t){let e=t?.cause?.code;return!!e&&D.has(e)}function k(t){return t===429||t===503}function $(t){return/^[\x20-\x7E]*$/.test(t)?t:`=?UTF-8?B?${Buffer.from(t,"utf8").toString("base64")}?=`}function v(t){let e=t.split(`
2
+ `),n=(e[0]??"").trim(),r=e.slice(1).join(`
3
+ `).trim();return r?n.length===0||n.length>80?{body:t.trim()}:{title:n,body:r}:{body:t.trim()}}function O(t){if(!t||t.state!=="ringing")return{};let e={Priority:t.urgent?"5":"4",Tags:"telephone_receiver"};return t.url&&/^https?:\/\/\S+$/.test(t.url)&&(e.Click=t.url),e}function S(t,e,n){if(l(t))return t;if(!l(n))return;let r=e?.startsWith("/")?e:T;return n.replace(/\/+$/,"")+r}var b=class{name="ntfy";config;log;constructor(e,n=console.error.bind(console,"[ntfy]")){this.config=e,this.log=n}async start(){this.log(`ntfy: ready (${this.serverUrl()}/${this.config.topic})`)}async stop(){}onMessage(e){}serverUrl(){return(this.config.server||"https://ntfy.sh").replace(/\/+$/,"")}async send(e){let n=(e.chatId||"").trim(),r=n&&n!=="default"?n:this.config.topic;if(!r)throw new Error("ntfy: no topic (pass chatId, or set channels.ntfy.topic)");let d=v(e.text||""),w=d.title||this.config.defaultTitle||"AgentX",a={"Content-Type":"text/plain; charset=utf-8",Title:$(w),Priority:String(this.config.defaultPriority??3)};this.config.token&&(a.Authorization=`Bearer ${this.config.token}`),e.parseMode==="markdown"&&(a.Markdown="yes"),Object.assign(a,O(e.ring));let f=(e.buttons??[]).filter(o=>l(o.url)).slice(0,3);if(f.length){let o=f.map(s=>`view, ${s.label.replace(/[,;]/g," ")}, ${s.url}`).join("; ");a.Actions=$(o)}let m=S(f[0]?.url,e.open,this.config.publicUrl);m&&!a.Click&&(a.Click=m);let C=`${this.serverUrl()}/${encodeURIComponent(r)}`,U=d.body||e.text||"",h=this.config.retryDelaysMs??M,p=h.length+1,y=this.config.sendTimeoutMs??R,E=Date.now()+y;for(let o=1;;o++){let s,c,g=!1;try{let i=AbortSignal.timeout(Math.max(1,E-Date.now()));s=await fetch(C,{method:"POST",headers:a,body:U,signal:i})}catch(i){c=i?.name==="TimeoutError"?new Error(`ntfy: send time limit of ${y} ms reached`,{cause:i}):new Error(`ntfy: ${N(i)}`,{cause:i}),g=_(i)}if(s){if(s.ok)return(await s.json().catch(()=>null))?.id;let i=await s.text().catch(()=>"");c=new Error(`ntfy: ${s.status} ${i.slice(0,200)}`),g=k(s.status)}let u=h[o-1];if(!g||o>=p||Date.now()+u>=E)throw this.log(`ntfy: send failed after ${o} attempt(s): ${c.message}`),c;this.log(`ntfy: attempt ${o}/${p} failed (${c.message}); retrying in ${u} ms`),await new Promise(i=>setTimeout(i,u))}}};export{N as a,v as b,O as c,S as d,b as e};
4
+ //# sourceMappingURL=chunk-I22ZKW7Q.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/channels/ntfy.ts"],"sourcesContent":["import type { CallRing, ChannelAdapter, IncomingMessage, OutgoingMessage } from \"./types\"\nimport { HUB_PATH } from \"@/daemon/ui/hub-name\"\nimport { isPhoneLink } from \"@/notify/phone-link\"\n\n// --- ntfy channel — push notifications to the operator's phone ---\n//\n// Outbound only. ntfy has an inbound side (SSE subscribe), but nothing here\n// wants it: a push notification is a one-way tap on the shoulder, and replies\n// come back through the channels that already carry conversation (Telegram,\n// WhatsApp) or through POST /ask when Siri asks a follow-up.\n//\n// Registering it as a ChannelAdapter rather than a bespoke notifier is what\n// makes it free everywhere: notifications.destination, POST /send, cron\n// failure pings, and the agent-facing `channel` action all funnel through\n// router.sendOutbound() and already know how to address a channel + chatId.\n//\n// Addressing: `chatId` is the ntfy topic. The literal `\"default\"` (and an\n// empty string) resolve to the configured topic instead. That indirection\n// exists so agents never have to carry the topic in their prompts — on the\n// public ntfy.sh the topic IS the credential, and every caller that funnels\n// through the router (POST /send, channel.reply) requires a non-empty chatId.\n\nexport interface NtfyConfig {\n /** Base URL of the ntfy server. Default is the public ntfy.sh. */\n server?: string\n /** Default topic when an OutgoingMessage carries no chatId. */\n topic: string\n /** Access token for protected topics (ntfy `Authorization: Bearer`). */\n token?: string\n /** 1 (min) .. 5 (max). ntfy's default is 3. */\n defaultPriority?: number\n /** Notification title. Per-message titles override it. */\n defaultTitle?: string\n /** notifications.publicUrl: the origin a tap opens the Hub at (#1652). */\n publicUrl?: string\n /** Test hook, not in the config schema: waits between attempts when a\n * publish is safe to repeat. One attempt more than there are entries. */\n retryDelaysMs?: number[]\n /** Test hook, not in the config schema: time limit for one send, all\n * attempts and waits included. */\n sendTimeoutMs?: number\n}\n\nconst DEFAULT_RETRY_DELAYS_MS = [1000, 3000, 8000]\nconst DEFAULT_SEND_TIMEOUT_MS = 20_000\n\n/** `fetch failed` hides the reason in `cause`; surface its code so a log\n * line says ETIMEDOUT or ECONNREFUSED rather than nothing useful (#930). */\nexport function describeFetchError(e: unknown): string {\n const err = e as { message?: string; cause?: { code?: string; message?: string } }\n const message = err?.message ?? String(e)\n const cause = err?.cause\n if (cause?.code) return `${message} code=${cause.code}`\n if (cause?.message && cause.message !== message) return `${message} (${cause.message})`\n return message\n}\n\n// A publish is retried only when the server cannot have stored it: ntfy has\n// no key to drop a repeat, so re-posting after a 500 or a reset mid-response\n// could put the same notification on the phone twice.\n\n/** The connection never opened, so the request never reached the server.\n * ETIMEDOUT can also, rarely, mean an open connection went silent; then a\n * repeat is possible. Telling the two apart would need to know whether the\n * body was written, which fetch does not expose. */\nconst CONNECT_FAILURE_CODES = new Set([\n \"ECONNREFUSED\", \"ETIMEDOUT\", \"ENETUNREACH\", \"EHOSTUNREACH\", \"EADDRNOTAVAIL\",\n \"ENOTFOUND\", \"EAI_AGAIN\", \"UND_ERR_CONNECT_TIMEOUT\",\n])\n\nfunction isRetryableFetchError(e: unknown): boolean {\n const code = (e as { cause?: { code?: string } })?.cause?.code\n return !!code && CONNECT_FAILURE_CODES.has(code)\n}\n\n/** 429 and 503 say the server turned the request away without handling it. */\nfunction isRetryableStatus(status: number): boolean {\n return status === 429 || status === 503\n}\n\n/**\n * ntfy requires header values to be ASCII. Titles and tags routinely aren't\n * (French accents, Arabic), so non-ASCII values go out as RFC 2047 encoded\n * words, which ntfy decodes. Pure-ASCII values are passed through untouched\n * so the common case stays readable in logs.\n */\nfunction encodeHeader(value: string): string {\n // eslint-disable-next-line no-control-regex\n if (/^[\\x20-\\x7E]*$/.test(value)) return value\n return `=?UTF-8?B?${Buffer.from(value, \"utf8\").toString(\"base64\")}?=`\n}\n\n/** First line of the body, when it reads like a title (short, no trailing\n * punctuation that implies a sentence continues). Lets an agent write a\n * single blob and still get a well-formed notification. */\nexport function splitTitle(text: string): { title?: string; body: string } {\n const lines = text.split(\"\\n\")\n const first = (lines[0] ?? \"\").trim()\n const rest = lines.slice(1).join(\"\\n\").trim()\n if (!rest) return { body: text.trim() }\n if (first.length === 0 || first.length > 80) return { body: text.trim() }\n return { title: first, body: rest }\n}\n\n/** A ringing call (#1605) goes out as a call: priority 5 when urgent, so\n * the ntfy app's \"max priority\" channel (set to a ringtone that overrides\n * Do Not Disturb) rings through; 4 otherwise, which follows Do Not\n * Disturb. The phone tag shows a receiver, and a tap opens the call in\n * the phone app. A missed call is an ordinary notice. */\nexport function ringHeaders(ring: CallRing | undefined): Record<string, string> {\n if (!ring || ring.state !== \"ringing\") return {}\n const out: Record<string, string> = { \"Priority\": ring.urgent ? \"5\" : \"4\", \"Tags\": \"telephone_receiver\" }\n if (ring.url && /^https?:\\/\\/\\S+$/.test(ring.url)) out[\"Click\"] = ring.url\n return out\n}\n\n/** What a tap on the notification body opens (#1652): the message's own\n * first link, else its `open` path (a request on the Hub), else the Hub,\n * both on the public address. Nothing when there is no public address. */\nexport function clickUrl(link: string | undefined, open: string | undefined, publicUrl: string | undefined): string | undefined {\n if (isPhoneLink(link)) return link\n if (!isPhoneLink(publicUrl)) return undefined\n const path = open?.startsWith(\"/\") ? open : HUB_PATH\n return publicUrl.replace(/\\/+$/, \"\") + path\n}\n\nexport class NtfyAdapter implements ChannelAdapter {\n readonly name = \"ntfy\"\n private config: NtfyConfig\n private log: (...args: unknown[]) => void\n\n constructor(config: NtfyConfig, log: (...args: unknown[]) => void = console.error.bind(console, \"[ntfy]\")) {\n this.config = config\n this.log = log\n }\n\n async start(): Promise<void> {\n this.log(`ntfy: ready (${this.serverUrl()}/${this.config.topic})`)\n }\n\n async stop(): Promise<void> {}\n\n /** No inbound side — the handler is accepted and never invoked, which\n * satisfies router.addChannel() without pretending to poll. */\n onMessage(_handler: (msg: IncomingMessage) => Promise<void>): void {}\n\n private serverUrl(): string {\n return (this.config.server || \"https://ntfy.sh\").replace(/\\/+$/, \"\")\n }\n\n async send(msg: OutgoingMessage): Promise<string | void> {\n const requested = (msg.chatId || \"\").trim()\n const topic = requested && requested !== \"default\" ? requested : this.config.topic\n if (!topic) throw new Error(\"ntfy: no topic (pass chatId, or set channels.ntfy.topic)\")\n\n const split = splitTitle(msg.text || \"\")\n const title = split.title || this.config.defaultTitle || \"AgentX\"\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"text/plain; charset=utf-8\",\n \"Title\": encodeHeader(title),\n \"Priority\": String(this.config.defaultPriority ?? 3),\n }\n if (this.config.token) headers[\"Authorization\"] = `Bearer ${this.config.token}`\n if (msg.parseMode === \"markdown\") headers[\"Markdown\"] = \"yes\"\n Object.assign(headers, ringHeaders(msg.ring))\n\n // URL buttons map onto ntfy's view actions, so an alert can carry\n // \"open the MR\" without the operator hunting for it. A loopback link\n // would open the phone itself, so it is left out (#1652).\n const buttons = (msg.buttons ?? []).filter(b => isPhoneLink(b.url)).slice(0, 3) // ntfy caps at 3\n if (buttons.length) {\n const actions = buttons\n .map(b => `view, ${b.label.replace(/[,;]/g, \" \")}, ${b.url}`)\n .join(\"; \")\n headers[\"Actions\"] = encodeHeader(actions)\n }\n const click = clickUrl(buttons[0]?.url, msg.open, this.config.publicUrl)\n if (click && !headers[\"Click\"]) headers[\"Click\"] = click\n\n const url = `${this.serverUrl()}/${encodeURIComponent(topic)}`\n const body = split.body || msg.text || \"\"\n const delays = this.config.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS\n const attempts = delays.length + 1\n // Each try can spend several seconds per address on a dead link, so the\n // whole send gets one time limit and callers never wait much past it.\n const limitMs = this.config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS\n const deadline = Date.now() + limitMs\n\n // A slow or flapping link loses pushes that a few seconds later would\n // go through. Retry only what cannot have been stored (see above).\n for (let attempt = 1; ; attempt++) {\n let res: Response | undefined\n let failure!: Error\n let retryable = false\n try {\n const signal = AbortSignal.timeout(Math.max(1, deadline - Date.now()))\n res = await fetch(url, { method: \"POST\", headers, body, signal })\n } catch (e) {\n // The abort only says \"aborted due to timeout\"; name the send limit.\n failure = (e as { name?: string })?.name === \"TimeoutError\"\n ? new Error(`ntfy: send time limit of ${limitMs} ms reached`, { cause: e })\n : new Error(`ntfy: ${describeFetchError(e)}`, { cause: e })\n retryable = isRetryableFetchError(e)\n }\n if (res) {\n if (res.ok) {\n const json = await res.json().catch(() => null) as { id?: string } | null\n return json?.id\n }\n const detail = await res.text().catch(() => \"\")\n failure = new Error(`ntfy: ${res.status} ${detail.slice(0, 200)}`)\n retryable = isRetryableStatus(res.status)\n }\n const wait = delays[attempt - 1]\n if (!retryable || attempt >= attempts || Date.now() + wait >= deadline) {\n this.log(`ntfy: send failed after ${attempt} attempt(s): ${failure.message}`)\n throw failure\n }\n this.log(`ntfy: attempt ${attempt}/${attempts} failed (${failure.message}); retrying in ${wait} ms`)\n await new Promise(r => setTimeout(r, wait))\n }\n }\n}\n"],"mappings":"uFAEAA,IAyCA,IAAMC,EAA0B,CAAC,IAAM,IAAM,GAAI,EAC3CC,EAA0B,IAIzB,SAASC,EAAmBC,EAAoB,CACrD,IAAMC,EAAMD,EACNE,EAAUD,GAAK,SAAW,OAAOD,CAAC,EAClCG,EAAQF,GAAK,MACnB,OAAIE,GAAO,KAAa,GAAGD,UAAgBC,EAAM,OAC7CA,GAAO,SAAWA,EAAM,UAAYD,EAAgB,GAAGA,MAAYC,EAAM,WACtED,CACT,CAUA,IAAME,EAAwB,IAAI,IAAI,CACpC,eAAgB,YAAa,cAAe,eAAgB,gBAC5D,YAAa,YAAa,yBAC5B,CAAC,EAED,SAASC,EAAsBL,EAAqB,CAClD,IAAMM,EAAQN,GA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CAAC,EAE9C,CACF","names":["init_phone_link","DEFAULT_RETRY_DELAYS_MS","DEFAULT_SEND_TIMEOUT_MS","describeFetchError","e","err","message","cause","CONNECT_FAILURE_CODES","isRetryableFetchError","code","isRetryableStatus","status","encodeHeader","value","splitTitle","text","lines","first","rest","ringHeaders","ring","out","clickUrl","link","open","publicUrl","isPhoneLink","path","HUB_PATH","NtfyAdapter","config","log","_handler","msg","requested","topic","split","title","headers","buttons","b","actions","click","url","body","delays","attempts","limitMs","deadline","attempt","res","failure","retryable","signal","detail","wait","r"]}
@@ -0,0 +1,11 @@
1
+ import{a as p,c as A}from"./chunk-KP7KDLZ2.js";import{randomUUID as E}from"crypto";function y(o){return o.status&&o.status!=="ringing"?", waiting_since=NULL, told_at=NULL":""}var m=["ringing","answered","later"],C=`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, placed_by AS placedBy`,T=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"),e.has("placed_by")||t.exec("ALTER TABLE calls ADD COLUMN placed_by TEXT")}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, placed_by) 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,t.placedBy??null)}get(t){return this.db.prepare(`SELECT ${C} 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(s=>s in n);if(i.length){let s=i.map(r=>`${n[r]}=?`).join(", ")+y(e);this.db.prepare(`UPDATE calls SET ${s} WHERE id=?`).run(...i.map(r=>e[r]??null),t)}return this.get(t)}transition(t,e,n){let i=Array.isArray(e)?e:[e],s={status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary",channel:"channel",chatId:"chat_id"},r=Object.keys(n).filter(d=>d in s),a=r.map(d=>`${s[d]}=?`).join(", ")+y(n),l=i.map(()=>"?").join(",");return this.db.prepare(`UPDATE calls SET ${a} WHERE id=? AND status IN (${l})`).run(...r.map(d=>n[d]??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 s=n.length?`WHERE ${n.join(" AND ")}`:"";return this.db.prepare(`SELECT ${C} FROM calls ${s} 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 w=200,S=1e4,_=2*36e5,$=10,k=240;function P(o=process.env){return o.AGENTX_TASK_ID?{"X-AgentX-Task":o.AGENTX_TASK_ID}:o.AGENTX_CHANNEL&&o.AGENTX_CHAT_ID?{"X-AgentX-Channel":o.AGENTX_CHANNEL,"X-AgentX-Chat":o.AGENTX_CHAT_ID}:{}}function N(o){return o.placedBy==="owner"?`[Call answered] The owner called you to talk about this: "${o.reason}". Speak first: greet them in a few words, say in a sentence or two where that work stands, then let them answer.`:`[Call answered] The owner just picked up the voice call you asked for. You called because: "${o.reason}". Speak first: greet them in a few words and say why you called, then let them answer.`}var D="[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.",I=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(),s=t.urgency==="urgent"?"urgent":"normal",r=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>w)return{ok:!1,status:413,error:`reason is over ${w} 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 a=this.deps.config();if(!a.allow.includes("*")&&!a.allow.includes(n))return{ok:!1,status:403,error:`${n} ${r==="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:m,limit:200}).some(f=>f.agentId===n))return{ok:!1,status:409,error:`${n} already has a call in progress`};let l=this.now();if(this.deps.store.countSince(n,l-36e5)>=a.maxPerHour)return{ok:!1,status:429,error:`${n} has placed ${a.maxPerHour} calls in the last hour (calls.maxPerHour)`};let g=r==="camera"?this.deps.turnSession?.(n,e)??e:{},d={id:`call-${E().slice(0,8)}`,agentId:n,kind:r,reason:i,urgency:s,status:"ringing",createdAt:l,ringingSince:l,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(d),this.deps.log?.(`[calls] ${n} asks ${r==="camera"?"to see":"for a call"} (${s}): ${i}`);let c=await this.ring(d),h=this.deps.store.get(d.id);return c!=="waiting"?{ok:!0,call:h,rang:c}:this.waiting.has(d.id)?{ok:!0,call:h,rang:c,busy:this.busyInfo(d)}:{ok:!0,call:h,rang:"widget"}}async ownerCall(t){let e=String(t.agentId??"").trim(),n=String(t.reason??"").replace(/\s+/g," ").trim().slice(0,w);if(!e||!n)return{ok:!1,status:400,error:"Required: agentId and reason"};if(this.deps.agentName(e)===null)return{ok:!1,status:404,error:`${e} does not run on this computer`};if(await this.sweep(),this.deps.store.list({status:m,limit:200}).some(g=>g.agentId===e))return{ok:!1,status:409,error:`${e} already has a call in progress`};let i=this.now(),s=this.deps.config();if(this.deps.store.countSince(e,i-36e5)>=s.maxPerHour)return{ok:!1,status:429,error:`${e} has had ${s.maxPerHour} calls in the last hour (calls.maxPerHour)`};let r={id:`call-${E().slice(0,8)}`,agentId:e,kind:"voice",reason:n,urgency:"normal",status:"ringing",createdAt:i,ringingSince:i,answeredAt:null,endedAt:null,ringAgainAt:null,note:null,summary:null,channel:null,chatId:null,placedBy:"owner"};this.deps.store.insert(r),this.deps.log?.(`[calls] the owner calls ${e}: ${n}`);let a=await this.ring(r),l=this.deps.store.get(r.id);return a!=="waiting"?{ok:!0,call:l,rang:a}:this.waiting.has(r.id)?{ok:!0,call:l,rang:a,busy:this.busyInfo(r)}:{ok:!0,call:l,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(r=>r.agentId===n);if(!i)return{ok:!1,status:404,error:`${n} has no call waiting or ringing`};let s=this.deps.store.transition(i.id,["ringing","later"],{status:"ended",endedAt:this.now(),ringingSince:null,ringAgainAt:null,note:b});return s?(this.setWaiting(i.id,null),this.deps.log?.(`[calls] ${i.id} withdrawn by ${n}`),{ok:!0,call:s}):{ok:!1,status:409,error:`call is ${this.deps.store.get(i.id)?.status}`}}async ring(t){let e=(this.deps.focus??p)();return e.active&&t.urgency!=="urgent"&&t.placedBy!=="owner"?(this.deps.store.transition(t.id,"ringing",{status:"missed",ringingSince:null,note:A(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?(await this.ringPhone(t,!0),"widget"):(this.startWaiting(t),await this.callWaiting(t),"waiting"):(await this.ringPhone(t,!1),"notify")}async ringPhone(t,e){let n=this.deps.config();if(t.placedBy==="owner"){e||await this.notice(t,`${this.name(t.agentId)} is calling`,`Open AgentX Voice to answer within ${n.ringSeconds} s.`);return}e&&n.phone?.ring==="away"||await this.notice(t,`${this.name(t.agentId)} is calling`,`Answer on your phone${e?" or in AgentX Voice":""} within ${n.ringSeconds} s.`,{callId:t.id,state:"ringing",since:t.ringingSince??this.now(),...e?{widget:!0}:{}})}async notice(t,e,n,i){try{await this.deps.alert({title:e,message:n?`${t.reason}
10
+ ${n}`:t.reason,urgent:t.urgency==="urgent",from:t.agentId,...i?{ring:i}:{}})}catch(s){this.deps.log?.(`[calls] notice for ${t.id} failed: ${s?.message??s}`)}}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()},s=this.otherCalls(t),r=s.find(c=>c.status==="answered"),a=s.find(c=>c.id===this.widget.showing)??s.find(c=>!this.waiting.has(c.id)),l=n+e.maxWaitMinutes*6e4+this.deps.config().ringSeconds*1e3,g=i+e.retryMinutes*6e4,d=n+e.maxWaitMinutes*6e4;return{why:r?"call":a?"ringing":"voice",with:r?this.name(r.agentId):a?this.name(a.agentId):null,remindAt:g<d?g:null,waitsUntil:l}}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()-_,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<S}async ringing(t={}){return this.widgetSeenAt=this.now(),this.widget=t,await this.hold(t),await this.sweep(),this.deps.store.list({status:["ringing"],kind:"voice",limit:20}).reverse()}async hold(t){let e=this.now(),n=this.deps.config().busy,i=[],s=[],r=this.deps.store.list({status:["ringing"],kind:"voice",limit:20});for(let a of[...this.waiting.keys()])r.some(l=>l.id===a)||this.setWaiting(a,null);for(let a of r){if(a.id===t.showing){if(this.waiting.has(a.id)){this.setWaiting(a.id,null);let g=this.deps.store.transition(a.id,"ringing",{ringingSince:e});g&&s.push(g)}continue}if(!t.busy)continue;let l=this.waiting.get(a.id);if(!(l&&e-l.since>=n.maxWaitMinutes*6e4)&&this.deps.store.transition(a.id,"ringing",{ringingSince:e})){if(!l)this.startWaiting(a);else if(e-l.toldAt>=n.retryMinutes*6e4)this.setWaiting(a.id,{since:l.since,toldAt:e});else continue;i.push(a)}}for(let a of i)await this.callWaiting(a);for(let a of s)await this.ringPhone(a,!0)}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),void 0,i.kind==="voice"?{callId:i.id,state:"missed",since:t}:void 0)}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 s=this.deps.store.transition(i.id,"later",{status:"ringing",ringingSince:t,ringAgainAt:null});if(!s)continue;this.setWaiting(i.id,null),await this.ring(s)}}answer(t){let e=this.deps.store.get(t);if(!e)return u(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 u(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 u(t);let i=e===void 0?$:Number(e);if(!Number.isInteger(i)||i<1||i>k)return{ok:!1,status:400,error:`minutes must be a whole number from 1 to ${k}`};let s=this.deps.store.transition(t,"ringing",{status:"later",ringingSince:null,ringAgainAt:this.now()+i*6e4});return s?{ok:!0,call:s}:{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}, not ringing`}}hangup(t,e){let n=this.deps.store.get(t);if(!n)return u(t);let i=e&&n.kind==="voice"?{channel:e.channel,chatId:e.chatId}:{},s=this.deps.store.transition(t,"answered",{status:"ended",endedAt:this.now(),...i});if(!s)return{ok:!1,status:409,error:`call is ${n.status}, not answered`};this.deps.log?.(`[calls] ${t} ended (${n.agentId})`);let r=this.deps.summarize;if(s.kind==="camera"||!this.deps.config().summary||!r)return{ok:!0,call:s};let a=(async()=>{try{let l=(await r(s))?.trim();if(!l)return;let g=this.deps.store.update(t,{summary:l});this.deps.file?.(g,l)}catch(l){this.deps.log?.(`[calls] summary for ${t} failed: ${l?.message??l}`)}})();return{ok:!0,call:s,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 M(o,t=Date.now(),e){let n=s=>`${new Date(s).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short",timeZone:e})} (in ${Math.max(1,Math.round((s-t)/6e4))} min)`;return`${o.why==="call"?`The owner is busy in another call${o.with?` (with ${o.with})`:""}.`:o.why==="ringing"?`The owner is busy: another call${o.with?` (from ${o.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. `+(o.remindAt!==null?`Still busy at ${n(o.remindAt)}, they are told again that you are waiting. `:"")+`It waits until ${n(o.waitsUntil)} at most, then counts as a missed call.`}var u=o=>({ok:!1,status:404,error:`No such call: ${o}`});export{T as a,P as b,D as c,I as d,M as e};
11
+ //# sourceMappingURL=chunk-IFUAP7UD.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// The phone rings too (#1605): a voice call an agent places goes to the\n// phone as a call push (`ring` on the notice), with the widget or, with\n// calls.phone.ring \"away\", only when the widget is not running. The phone\n// app answers it through the same `answer`, so the first to pick up takes\n// the call and the other stops ringing. A missed call is marked, so the\n// phone can replace its ringing notification.\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\n * --urgent. `ring`: the notice is a call on the phone (#1605). */\n alert: (notice: { title: string; message: string; urgent: boolean; from: string; ring?: PhoneRing }) => 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\" | \"placedBy\">): string {\n if (call.placedBy === \"owner\") {\n return \"[Call answered] The owner called you to talk about this: \" +\n `\"${call.reason}\". Speak first: greet them in a few words, say in a sentence or two where that work stands, ` +\n \"then let them answer.\"\n }\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 owner asks an agent to talk (#1316, \"Call\" on a Wall post): a\n * voice call that rings the owner's own widget, so answering opens the\n * same hands-free conversation an agent's call does. The daemon checks\n * the operator key before this runs; there is no running turn to prove,\n * and calls.allow does not apply, since the owner chose to call. The\n * agent still has one call at a time, and its calls this hour count\n * toward calls.maxPerHour. Focus does not hold it: the owner asked. */\n async ownerCall(input: { agentId?: unknown; reason?: unknown }): Promise<CallResult & { rang?: Rang; busy?: BusyInfo }> {\n const agentId = String(input.agentId ?? \"\").trim()\n const reason = String(input.reason ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, REASON_MAX)\n if (!agentId || !reason) return { ok: false, status: 400, error: \"Required: agentId and reason\" }\n if (this.deps.agentName(agentId) === null) return { ok: false, status: 404, error: `${agentId} does not run on this computer` }\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 const cfg = this.deps.config()\n if (this.deps.store.countSince(agentId, now - 3_600_000) >= cfg.maxPerHour) {\n return { ok: false, status: 429, error: `${agentId} has had ${cfg.maxPerHour} calls in the last hour (calls.maxPerHour)` }\n }\n const call: Call = {\n id: `call-${randomUUID().slice(0, 8)}`, agentId, kind: \"voice\", reason, urgency: \"normal\", status: \"ringing\", createdAt: now,\n ringingSince: now, answeredAt: null, endedAt: null, ringAgainAt: null, note: null, summary: null, channel: null, chatId: null,\n placedBy: \"owner\",\n }\n this.deps.store.insert(call)\n this.deps.log?.(`[calls] the owner calls ${agentId}: ${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 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\" && call.placedBy !== \"owner\") {\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) {\n await this.ringPhone(call, true)\n return \"widget\"\n }\n this.startWaiting(call)\n await this.callWaiting(call)\n return \"waiting\"\n }\n await this.ringPhone(call, false)\n return \"notify\"\n }\n\n /** The phone rings for an agent's voice call (#1605): with the widget\n * (`withWidget`) unless calls.phone.ring is \"away\", and always when the\n * widget is not running. A call the owner placed rings the widget only;\n * without it, the owner is told to open AgentX Voice, as before. */\n private async ringPhone(call: Call, withWidget: boolean): Promise<void> {\n const cfg = this.deps.config()\n if (call.placedBy === \"owner\") {\n if (!withWidget) await this.notice(call, `${this.name(call.agentId)} is calling`, `Open AgentX Voice to answer within ${cfg.ringSeconds} s.`)\n return\n }\n if (withWidget && cfg.phone?.ring === \"away\") return\n await this.notice(call, `${this.name(call.agentId)} is calling`,\n `Answer on your phone${withWidget ? \" or in AgentX Voice\" : \"\"} within ${cfg.ringSeconds} s.`,\n { callId: call.id, state: \"ringing\", since: call.ringingSince ?? this.now(), ...(withWidget ? { widget: true } : {}) })\n }\n\n private async notice(call: Call, title: string, extra?: string, ring?: PhoneRing): 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 ...(ring ? { ring } : {}),\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 shown: 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 const again = this.deps.store.transition(call.id, \"ringing\", { ringingSince: now })\n // It rings now: on the phone too.\n if (again) shown.push(again)\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 for (const call of shown) await this.ringPhone(call, true)\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), undefined, call.kind === \"voice\" ? { callId: call.id, state: \"missed\", since: now } : undefined)\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, where?: { channel: string; chatId: string }): CallResult & { summarized?: Promise<void> } {\n const call = this.deps.store.get(id)\n if (!call) return unknown(id)\n // Answered on the phone (#1605): the conversation it had there is the\n // one the agent summarises.\n const session = where && call.kind === \"voice\" ? { channel: where.channel, chatId: where.chatId } : {}\n const ended = this.deps.store.transition(id, \"answered\", { status: \"ended\", endedAt: this.now(), ...session })\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/** A notice that is a call on the phone (#1605). `since`: when this ring\n * started, so each ring is its own item for the told-the-owner record. */\nexport interface PhoneRing {\n callId: string\n state: \"ringing\" | \"missed\"\n since: number\n /** It rings on the widget too: no banner or sound on this computer. */\n widget?: boolean\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 /** \"owner\": the owner placed it, asking the agent to talk (from a Wall\n * post, #1316). Unset or null: the agent placed it. */\n placedBy?: \"owner\" | 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, placed_by AS placedBy`\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 // Who placed it (#1316): \"owner\" for a call the owner asked for from\n // the Wall; null for the agent's own call, as every older row is.\n if (!have.has(\"placed_by\")) db.exec(\"ALTER TABLE calls ADD COLUMN placed_by TEXT\")\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, placed_by) 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, call.placedBy ?? null)\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\", channel: \"channel\", chatId: \"chat_id\",\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":"+CAoCA,OAAS,cAAAA,MAAkB,SCiB3B,SAASC,EAAQC,EAAwC,CACvD,OAAOA,EAAM,QAAUA,EAAM,SAAW,UAAY,qCAAuC,EAC7F,CAGO,IAAMC,EAAqB,CAAC,UAAW,WAAY,OAAO,EAE3DC,EAAU;AAAA;AAAA,kGAIHC,EAAN,KAAgB,CACrB,YAAoBC,EAAuB,CAAvB,QAAAA,EAClBA,EAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA,yEAK6D,EAGrE,IAAMC,EAAO,IAAI,IAAKD,EAAG,QAAQ,0BAA0B,EAAE,IAAI,EAA8B,IAAKE,GAAMA,EAAE,IAAI,CAAC,EAC5GD,EAAK,IAAI,MAAM,GAAGD,EAAG,KAAK,iEAAiE,EAC3FC,EAAK,IAAI,SAAS,GAAGD,EAAG,KAAK,2CAA2C,EACxEC,EAAK,IAAI,SAAS,GAAGD,EAAG,KAAK,2CAA2C,EAGxEC,EAAK,IAAI,eAAe,GAAGD,EAAG,KAAK,oDAAoD,EACvFC,EAAK,IAAI,SAAS,GAAGD,EAAG,KAAK,8CAA8C,EAG3EC,EAAK,IAAI,WAAW,GAAGD,EAAG,KAAK,6CAA6C,CACnF,CAGA,SAAgC,CAC9B,IAAMG,EAAO,KAAK,GAAG,QAAQ,sHAAsH,EAChJ,IAAI,EACP,OAAO,IAAI,IAAIA,EAAK,IAAI,CAAC,CAAE,G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,CAAC,EACrH,OAAItC,GAAO,KAAK,KAAK,MAAM,WAAWjB,YAAaJ,EAAK,aAAa2D,GAAQ,cAAc,EACpF,CAAC,CAACtC,CACX,CAEA,IAAIjB,EAA8B,CAAE,OAAO,KAAK,KAAK,MAAM,IAAIA,CAAE,CAAE,CAEnE,KAAKwD,EAAyC,CAAC,EAAW,CAAE,OAAO,KAAK,KAAK,MAAM,KAAKA,CAAI,CAAE,CAChG,EAiBatC,EAAiB,0BAIvB,SAASuC,EAAS9B,EAAgBhB,EAAc,KAAK,IAAI,EAAG+C,EAA2B,CAC5F,IAAMC,EAAMC,GAAe,GAAG,IAAI,KAAKA,CAAE,EAAE,mBAAmB,QAAS,CAAE,KAAM,UAAW,OAAQ,UAAW,OAAQ,GAAO,aAAc,QAAS,SAAAF,CAAS,CAAC,SAAS,KAAK,IAAI,EAAG,KAAK,OAAOE,EAAKjD,GAAO,GAAM,CAAC,SAIjN,MAAO,GAHKgB,EAAK,MAAQ,OAAS,oCAAoCA,EAAK,KAAO,UAAUA,EAAK,QAAU,MACvGA,EAAK,MAAQ,UAAY,kCAAkCA,EAAK,KAAO,UAAUA,EAAK,QAAU,iBAChG,uKAEDA,EAAK,WAAa,KAAO,iBAAiBgC,EAAGhC,EAAK,QAAQ,gDAAkD,IAC7G,kBAAkBgC,EAAGhC,EAAK,UAAU,0CACxC,CAEA,IAAMiB,EAAW5C,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","withWidget","title","extra","ring","e","busy","since","toldAt","others","talking","showing","waitsUntil","remindAt","stopsWaiting","live","widget","tell","shown","again","held","ringFor","talkFor","unknown","answered","declined","minutes","n","later","where","summarize","summarized","text","done","note","opts","busyText","timeZone","at","ms"]}
@@ -1,4 +1,4 @@
1
- import{a as Ge,b as k,c as D,d as Ve,e as ue,f as me,g as L,h as fe,i as N,j,n as Qe,o as Ze,p as ea,q as aa}from"./chunk-EFGAPAYZ.js";import{e as Je,i as Xe}from"./chunk-QAWKN2N4.js";import{b as ge}from"./chunk-DODL5POT.js";import{a as Q,b as Ye}from"./chunk-PX7PWXBI.js";import{Ia as Be,Ja as Ue,Ka as Fe,Ma as qe,ja as $,oa as We,wb as Ke}from"./chunk-YWAJNF2A.js";import{a as G}from"./chunk-IMLAPB7G.js";import{b as V}from"./chunk-2VDO2HEK.js";import{c as He,e as Le}from"./chunk-LQE73AZR.js";import{b as je}from"./chunk-MRIVENBY.js";import{q as xe,s as Ne}from"./chunk-XPZSEDE3.js";import{ga as X}from"./chunk-PO2SORKY.js";import{b as pe}from"./chunk-3FZ6WHKX.js";import{a as q,b as J}from"./chunk-KXJRXRSD.js";import{a as Me}from"./chunk-RW5FKJRE.js";import{c as Re,d as Oe}from"./chunk-OWNQ2FD4.js";import{a as De}from"./chunk-ROLSSYXE.js";import{a as Pe}from"./chunk-QUFIUXMQ.js";import{Ib as ce,Va as ze,ab as Qa,fa as de,ga as Ie,qa as Va,vb as le,yb as F,zb as Ee}from"./chunk-P6WSD2UR.js";import{existsSync as K,readFileSync as la,writeFileSync as ca,appendFileSync as it,mkdirSync as st}from"fs";import{dirname as dt,resolve as M}from"path";import{fileURLToPath as lt}from"url";import{hostname as ct}from"os";import{spawn as pt}from"child_process";var he=`:root {
1
+ import{a as Ge,b as k,c as D,d as Ve,e as ue,f as me,g as L,h as fe,i as N,j,n as Qe,o as Ze,p as ea,q as aa}from"./chunk-EFGAPAYZ.js";import{e as Je,i as Xe}from"./chunk-QAWKN2N4.js";import{b as ge}from"./chunk-DODL5POT.js";import{a as Q,b as Ye}from"./chunk-4O6ZFYWT.js";import{Ia as Be,Ja as Ue,Ka as Fe,Ma as qe,ja as $,oa as We,wb as Ke}from"./chunk-27ICCQVL.js";import{a as G}from"./chunk-IMLAPB7G.js";import{b as V}from"./chunk-2VDO2HEK.js";import{c as He,e as Le}from"./chunk-LQE73AZR.js";import{b as je}from"./chunk-MRIVENBY.js";import{q as xe,s as Ne}from"./chunk-XPZSEDE3.js";import{ga as X}from"./chunk-WFPLZLCF.js";import{b as pe}from"./chunk-7AB3QUGH.js";import{a as q,b as J}from"./chunk-HOL645BZ.js";import{a as Me}from"./chunk-SK7M6PS6.js";import{c as Re,d as Oe}from"./chunk-OWNQ2FD4.js";import{a as De}from"./chunk-ROLSSYXE.js";import{a as Pe}from"./chunk-QUFIUXMQ.js";import{Cb as F,Db as Ee,Mb as ce,Za as ze,eb as Qa,ja as de,ka as Ie,ua as Va,zb as le}from"./chunk-SNYAM7YB.js";import{existsSync as K,readFileSync as la,writeFileSync as ca,appendFileSync as it,mkdirSync as st}from"fs";import{dirname as dt,resolve as M}from"path";import{fileURLToPath as lt}from"url";import{hostname as ct}from"os";import{spawn as pt}from"child_process";var he=`:root {
2
2
  /* --- Brand (agentina) --------------------------------------------- */
3
3
  --ax-blue: #2979FF;
4
4
  --ax-blue-d: #1B5FD9;
@@ -2903,4 +2903,4 @@ ${a}=${t}
2903
2903
  WHERE person = ? AND state IN (${t.map(()=>"?").join(",")})
2904
2904
  ${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function ti(e,a){return Ba(e,a,de,"ORDER BY created_at")}function ri(e,a,t=50){return Ba(e,a,[...de,...Ie],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}Qa();var Te="member:",xr=90,gr="members",ur="tailscale-user-login",mr=400,fr=60*60*1e3;function hr(e){let a=e.scopes.find(t=>t.startsWith(Te));return a?a.slice(Te.length):null}function Fa(e,a){if(!e)return null;let t=a.verify(e),r=t?hr(t):null;return t&&r?{rec:t,personId:r}:null}function ci(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${Te}${t.id}`],expiresInDays:xr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var br=Math.round(He/6e4);function vr(e){return e==="client"?"Your project":"My work"}function pi(e){let a=vr(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": 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, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","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: ${Le(e.code)}`,` The code works once, for ${br} 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(`
2905
2905
  `)}var wr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",yr="Too many machines are waiting for the owner's answer. Try again later.",Ua="That code didn't work. Check it, or ask the person who invited you for a new one.",qa=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ka(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function kr(e){if(!Ka(e))return null;let a=qa(e,ur).toLowerCase();return a?a.slice(0,80):null}function _r(e){let a=e.socket?.remoteAddress||"unknown";if(!Ka(e))return a;let t=qa(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function $r(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function Sr(e){return e.identities.map(ze).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function xi(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=_r(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await V(e,2048);s=b.code,d=$r(b.machine)}catch{}let l=a.codes.redeem(s),c=l?Fa(l.token,a.tokens):null;if(await Cr(t,a.minMs??mr),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Ua}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Ua}};let x=kr(e),f=Sr(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:wr}};let C=d||"Unnamed machine",w=u.name.slice(0,40),v=Ne(a.root,{title:`New machine for ${w}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${w}'s own work?`,recommend:`Yes if ${w} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:gr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:C,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:C}),n(`[member] ${g} paired "${C}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:C,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:yr}})}var se="this machine is not paired",Ar="waiting for the owner to approve this machine";function Ya(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function gi(e,a){return a.state==="pending"&&a.cardId?Ya(xe(e,a.cardId)):null}function ui(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=Fa(e,a.tokens);if(!o)return{ok:!1,status:401,error:se};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:se};if(a.people&&!a.people().some(c=>c.id===s))return Ja(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:se};if(d.state==="pending"){let c=d.cardId?xe(a.root,d.cardId):null,m=Ya(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:se}}else return{ok:!1,status:403,error:Ar,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=fr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Ja(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function mi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Ja(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function Cr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Xa=["gitlab","github"];function Tr(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Xa.includes(r))throw new Error(`Request status works on ${Xa.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function bi(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function vi(e){let{summary:a}=Q(t=>Tr(t,e?.channel,!!e?.enabled));return{summary:a}}var yi="https://myaccount.google.com/apppasswords";function ki(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function _i(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function $i(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function Ai(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ci(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Ti(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Ii(e,a){if(a){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 Ir="https://ntfy.sh";function Ei(e){return{enabled:!!e?.enabled,server:e?.server||Ir,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Pi(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}export{he as a,oa as b,ve as c,at as d,tt as e,rt as f,pa as g,xt as h,$n as i,Sn as j,An as k,ko as l,or as m,Ao as n,zo as o,Wa as p,Vo as q,Qo as r,Rn as s,On as t,At as u,It as v,we as w,Dn as x,Mn as y,zt as z,Bn as A,Un as B,Fn as C,ai as D,ti as E,ri as F,xr as G,ci as H,br as I,vr as J,pi as K,_r as L,xi as M,gi as N,ui as O,Ja as P,mi as Q,Xa as R,Tr as S,bi as T,vi as U,yi as V,ki as W,_i as X,$i as Y,Ai as Z,Ci as _,Ti as $,Ii as aa,Ei as ba,Pi as ca,Xt as da,go as ea,vo as fa,wo as ga};
2906
- //# sourceMappingURL=chunk-V7FZBETJ.js.map
2906
+ //# sourceMappingURL=chunk-IOCULCCJ.js.map