agentix-cli 0.200.1 → 0.202.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 (207) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/Brand.swift +1 -0
  2. package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +67 -2
  3. package/dist/{App-AUKNCAVD.js → App-FQRHQT5J.js} +2 -2
  4. package/dist/{ChatApp-KYQIQZ6Q.js → ChatApp-WBCGSGJM.js} +2 -2
  5. package/dist/{absorb-eval-TJN5WUYZ.js → absorb-eval-3IU37HZQ.js} +2 -2
  6. package/dist/{adapter-VLNSNP6C.js → adapter-URFSOOFE.js} +2 -2
  7. package/dist/agent-P7XUCP3A.js +2 -0
  8. package/dist/{board-dashboard-QKOJEHXS.js → board-dashboard-CXFXO5XU.js} +1058 -468
  9. package/dist/board-dashboard-CXFXO5XU.js.map +1 -0
  10. package/dist/chunk-36X7D4JA.js +2 -0
  11. package/dist/chunk-36X7D4JA.js.map +1 -0
  12. package/dist/{chunk-25U5MNNF.js → chunk-5VD2J4JN.js} +2 -2
  13. package/dist/chunk-7NQQIDDI.js +2 -0
  14. package/dist/chunk-7NQQIDDI.js.map +1 -0
  15. package/dist/chunk-7QW4RECS.js +2 -0
  16. package/dist/chunk-7QW4RECS.js.map +1 -0
  17. package/dist/chunk-BYEL7KKR.js +13 -0
  18. package/dist/chunk-BYEL7KKR.js.map +1 -0
  19. package/dist/{chunk-S5A7QZVQ.js → chunk-C2VZHIIX.js} +2 -2
  20. package/dist/{chunk-EFGAPAYZ.js → chunk-CAYY2IEV.js} +2 -2
  21. package/dist/{chunk-7VHE7WLJ.js → chunk-CJI26AJC.js} +3 -3
  22. package/dist/{chunk-SXL6R3HH.js → chunk-EMWSFITR.js} +2 -2
  23. package/dist/{chunk-ORAQRC6A.js → chunk-EQPMQSJE.js} +2 -2
  24. package/dist/{chunk-AKDJGDLN.js → chunk-FCDMB2JA.js} +76 -74
  25. package/dist/chunk-FCDMB2JA.js.map +1 -0
  26. package/dist/chunk-FOWRNDMJ.js +2 -0
  27. package/dist/chunk-FOWRNDMJ.js.map +1 -0
  28. package/dist/chunk-GDHSJH3T.js +111 -0
  29. package/dist/chunk-GDHSJH3T.js.map +1 -0
  30. package/dist/{chunk-AHJ6FEHW.js → chunk-HX4R7RPR.js} +2 -2
  31. package/dist/{chunk-QMFNIUW7.js → chunk-IAR5F3T5.js} +2 -2
  32. package/dist/{chunk-TBSPEM7I.js → chunk-JKT5EFXT.js} +2 -2
  33. package/dist/{chunk-TBSPEM7I.js.map → chunk-JKT5EFXT.js.map} +1 -1
  34. package/dist/chunk-JLBRNYKY.js +2 -0
  35. package/dist/chunk-JLBRNYKY.js.map +1 -0
  36. package/dist/{chunk-QISI5WM2.js → chunk-JUSQMQ7L.js} +2 -2
  37. package/dist/{chunk-O672XL5L.js → chunk-M4VYHPDS.js} +2 -2
  38. package/dist/{chunk-6QVUXEVK.js → chunk-MAQFWGFT.js} +2 -2
  39. package/dist/{chunk-BNTN3LKN.js → chunk-N6NZBAWR.js} +2 -2
  40. package/dist/{chunk-RW2JLP5P.js → chunk-P65XGEB7.js} +2 -2
  41. package/dist/{chunk-64UGFZPX.js → chunk-PSOE356C.js} +25 -25
  42. package/dist/{chunk-64UGFZPX.js.map → chunk-PSOE356C.js.map} +1 -1
  43. package/dist/chunk-Q3A5P373.js +3 -0
  44. package/dist/chunk-Q3A5P373.js.map +1 -0
  45. package/dist/{chunk-M6EQBW2F.js → chunk-QOEO27LF.js} +2 -2
  46. package/dist/{chunk-KOZSBUXJ.js → chunk-RB7M2NPU.js} +2 -2
  47. package/dist/chunk-RIBANO2H.js +118 -0
  48. package/dist/chunk-RIBANO2H.js.map +1 -0
  49. package/dist/{chunk-K34LYNGN.js → chunk-RUNCUVAH.js} +2 -2
  50. package/dist/{chunk-4MJOSO7T.js → chunk-SLX3OHEW.js} +2 -2
  51. package/dist/chunk-SY7R5N7U.js +7 -0
  52. package/dist/chunk-SY7R5N7U.js.map +1 -0
  53. package/dist/{chunk-LBIU3OWW.js → chunk-T7WY5BSJ.js} +85 -85
  54. package/dist/chunk-T7WY5BSJ.js.map +1 -0
  55. package/dist/{chunk-R5TCPLWF.js → chunk-TV5BDCQA.js} +2 -2
  56. package/dist/chunk-U2WAIDSM.js +2 -0
  57. package/dist/chunk-U2WAIDSM.js.map +1 -0
  58. package/dist/{chunk-J4AMQF7D.js → chunk-V3FSKTDF.js} +2 -2
  59. package/dist/{chunk-W764F42W.js → chunk-VGYW3Q7F.js} +2 -2
  60. package/dist/{chunk-EM72LW2F.js → chunk-WIGH5WMP.js} +57 -64
  61. package/dist/chunk-WIGH5WMP.js.map +1 -0
  62. package/dist/{chunk-6RJ7ERGC.js → chunk-WKR2OSCH.js} +2 -2
  63. package/dist/{chunk-APULKE2J.js → chunk-Y2D6FQBL.js} +2 -2
  64. package/dist/{chunk-3I3TBJZV.js → chunk-Z6KAK22L.js} +312 -312
  65. package/dist/chunk-Z6KAK22L.js.map +1 -0
  66. package/dist/{chunk-UBLPD6DK.js → chunk-ZPCSPEGO.js} +2 -2
  67. package/dist/cli.js +1 -1
  68. package/dist/client-EOQLSAUW.js +2 -0
  69. package/dist/{config-IOQKEH47.js → config-SZZQFIJF.js} +2 -2
  70. package/dist/config-mutate-66VDWR46.js +2 -0
  71. package/dist/config-mutator-OILDQCAJ.js +2 -0
  72. package/dist/connect-JIWRIGVI.js +2 -0
  73. package/dist/connect-JIWRIGVI.js.map +1 -0
  74. package/dist/{contributions-3AE43OSI.js → contributions-LRQCDZCQ.js} +2 -2
  75. package/dist/daemon-api-JBXTSPB6.js +2 -0
  76. package/dist/daemon-api-JBXTSPB6.js.map +1 -0
  77. package/dist/doctor-QASDCIQ5.js +2 -0
  78. package/dist/dotenv-DGZD3EDY.js +2 -0
  79. package/dist/{enrich-MZMIQ3SV.js → enrich-NIUEEGPA.js} +2 -2
  80. package/dist/{event-levels-PCFARGKL.js → event-levels-D6QSANGF.js} +2 -2
  81. package/dist/{follow-up-tool-WLDWTZRW.js → follow-up-tool-QOO2TIQS.js} +2 -2
  82. package/dist/hub-6TKU6CHO.js +2 -0
  83. package/dist/index.d.ts +375 -48
  84. package/dist/index.js +1 -1
  85. package/dist/index.js.map +1 -1
  86. package/dist/keyring-EKFUNQAO.js +2 -0
  87. package/dist/oauth-7J7DJMKN.js +2 -0
  88. package/dist/open-browser-BTEYT7G4.js +2 -0
  89. package/dist/{program-QHE7PH65.js → program-L2ZLEJAO.js} +296 -290
  90. package/dist/program-L2ZLEJAO.js.map +1 -0
  91. package/dist/{promote-DLM7N6V2.js → promote-D3KYLUBD.js} +2 -2
  92. package/dist/providers-P76CWTGQ.js +2 -0
  93. package/dist/push-bridge-T5HZZRA2.js +1 -1
  94. package/dist/{query-TBQGAIZG.js → query-D2TQ2PUO.js} +2 -2
  95. package/dist/{query-settings-U6XNO5V4.js → query-settings-ILDX3HDF.js} +2 -2
  96. package/dist/registry-N3BY3HSI.js +2 -0
  97. package/dist/{request-planner-YQ4RTZNU.js → request-planner-CVCG5XQR.js} +2 -2
  98. package/dist/resolve-JKXYBZ6R.js +2 -0
  99. package/dist/{review-candidates-OE5HDVWI.js → review-candidates-CKUN4PSY.js} +2 -2
  100. package/dist/routing-OCIRGUKK.js +2 -0
  101. package/dist/{rules-FBOLGE2S.js → rules-A5ES57QT.js} +2 -2
  102. package/dist/schedule-tool-YFMRYTEO.js +2 -0
  103. package/dist/schedule-tool-YFMRYTEO.js.map +1 -0
  104. package/dist/scheduler-D2Z7RSEE.js +2 -0
  105. package/dist/scheduler-D2Z7RSEE.js.map +1 -0
  106. package/dist/{seat-74G2KLZQ.js → seat-Z3E2FLDA.js} +2 -2
  107. package/dist/seat-Z3E2FLDA.js.map +1 -0
  108. package/dist/{select-P7565K5D.js → select-J4ES7Q67.js} +2 -2
  109. package/dist/{set-enabled-DE3TKKEK.js → set-enabled-S22TICYC.js} +2 -2
  110. package/dist/{sprint-tool-CK3SD4NZ.js → sprint-tool-NDF47EKV.js} +2 -2
  111. package/dist/status-PKHYFGZK.js +2 -0
  112. package/dist/status-PKHYFGZK.js.map +1 -0
  113. package/dist/{tool-X6DAR3KL.js → tool-52JRXZVA.js} +2 -2
  114. package/dist/tool-6NZIUXI7.js +4 -0
  115. package/dist/tool-6NZIUXI7.js.map +1 -0
  116. package/dist/{tool-XGB3PMXA.js → tool-RCCMOMEY.js} +2 -2
  117. package/dist/{tool-DWKCESVE.js → tool-Z2OVFGWW.js} +2 -2
  118. package/dist/wiki-HQKFZZSX.js +2 -0
  119. package/dist/wiki-HQKFZZSX.js.map +1 -0
  120. package/dist/wiki-enrich-7SZ5W2LF.js +2 -0
  121. package/dist/wiki-enrich-7SZ5W2LF.js.map +1 -0
  122. package/dist/workspace-setup-W5UO2WZI.js +2 -0
  123. package/dist/workspace-setup-W5UO2WZI.js.map +1 -0
  124. package/package.json +1 -1
  125. package/dist/agent-KXHSNUNY.js +0 -2
  126. package/dist/board-dashboard-QKOJEHXS.js.map +0 -1
  127. package/dist/chunk-3I3TBJZV.js.map +0 -1
  128. package/dist/chunk-AKDJGDLN.js.map +0 -1
  129. package/dist/chunk-AV7T3SYT.js +0 -111
  130. package/dist/chunk-AV7T3SYT.js.map +0 -1
  131. package/dist/chunk-EM72LW2F.js.map +0 -1
  132. package/dist/chunk-KE4SLJTC.js +0 -7
  133. package/dist/chunk-KE4SLJTC.js.map +0 -1
  134. package/dist/chunk-LBIU3OWW.js.map +0 -1
  135. package/dist/chunk-QTOOFB4N.js +0 -118
  136. package/dist/chunk-QTOOFB4N.js.map +0 -1
  137. package/dist/client-FXU56BIM.js +0 -2
  138. package/dist/config-mutate-633Q77K3.js +0 -2
  139. package/dist/config-mutator-LRZHJ3UN.js +0 -2
  140. package/dist/doctor-KCRL67QL.js +0 -2
  141. package/dist/hub-PG4OFRIQ.js +0 -2
  142. package/dist/program-QHE7PH65.js.map +0 -1
  143. package/dist/registry-DGGJJOVA.js +0 -2
  144. package/dist/routing-RAG6I37K.js +0 -2
  145. package/dist/schedule-tool-O5FJXSKO.js +0 -2
  146. package/dist/scheduler-TGP4B5KZ.js +0 -2
  147. package/dist/wiki-E45S2K6F.js +0 -2
  148. package/dist/wiki-enrich-LREINNTK.js +0 -2
  149. package/dist/workspace-setup-HAV4CQV7.js +0 -2
  150. /package/dist/{App-AUKNCAVD.js.map → App-FQRHQT5J.js.map} +0 -0
  151. /package/dist/{ChatApp-KYQIQZ6Q.js.map → ChatApp-WBCGSGJM.js.map} +0 -0
  152. /package/dist/{absorb-eval-TJN5WUYZ.js.map → absorb-eval-3IU37HZQ.js.map} +0 -0
  153. /package/dist/{adapter-VLNSNP6C.js.map → adapter-URFSOOFE.js.map} +0 -0
  154. /package/dist/{agent-KXHSNUNY.js.map → agent-P7XUCP3A.js.map} +0 -0
  155. /package/dist/{chunk-25U5MNNF.js.map → chunk-5VD2J4JN.js.map} +0 -0
  156. /package/dist/{chunk-S5A7QZVQ.js.map → chunk-C2VZHIIX.js.map} +0 -0
  157. /package/dist/{chunk-EFGAPAYZ.js.map → chunk-CAYY2IEV.js.map} +0 -0
  158. /package/dist/{chunk-7VHE7WLJ.js.map → chunk-CJI26AJC.js.map} +0 -0
  159. /package/dist/{chunk-SXL6R3HH.js.map → chunk-EMWSFITR.js.map} +0 -0
  160. /package/dist/{chunk-ORAQRC6A.js.map → chunk-EQPMQSJE.js.map} +0 -0
  161. /package/dist/{chunk-AHJ6FEHW.js.map → chunk-HX4R7RPR.js.map} +0 -0
  162. /package/dist/{chunk-QMFNIUW7.js.map → chunk-IAR5F3T5.js.map} +0 -0
  163. /package/dist/{chunk-QISI5WM2.js.map → chunk-JUSQMQ7L.js.map} +0 -0
  164. /package/dist/{chunk-O672XL5L.js.map → chunk-M4VYHPDS.js.map} +0 -0
  165. /package/dist/{chunk-6QVUXEVK.js.map → chunk-MAQFWGFT.js.map} +0 -0
  166. /package/dist/{chunk-BNTN3LKN.js.map → chunk-N6NZBAWR.js.map} +0 -0
  167. /package/dist/{chunk-RW2JLP5P.js.map → chunk-P65XGEB7.js.map} +0 -0
  168. /package/dist/{chunk-M6EQBW2F.js.map → chunk-QOEO27LF.js.map} +0 -0
  169. /package/dist/{chunk-KOZSBUXJ.js.map → chunk-RB7M2NPU.js.map} +0 -0
  170. /package/dist/{chunk-K34LYNGN.js.map → chunk-RUNCUVAH.js.map} +0 -0
  171. /package/dist/{chunk-4MJOSO7T.js.map → chunk-SLX3OHEW.js.map} +0 -0
  172. /package/dist/{chunk-R5TCPLWF.js.map → chunk-TV5BDCQA.js.map} +0 -0
  173. /package/dist/{chunk-J4AMQF7D.js.map → chunk-V3FSKTDF.js.map} +0 -0
  174. /package/dist/{chunk-W764F42W.js.map → chunk-VGYW3Q7F.js.map} +0 -0
  175. /package/dist/{chunk-6RJ7ERGC.js.map → chunk-WKR2OSCH.js.map} +0 -0
  176. /package/dist/{chunk-APULKE2J.js.map → chunk-Y2D6FQBL.js.map} +0 -0
  177. /package/dist/{chunk-UBLPD6DK.js.map → chunk-ZPCSPEGO.js.map} +0 -0
  178. /package/dist/{client-FXU56BIM.js.map → client-EOQLSAUW.js.map} +0 -0
  179. /package/dist/{config-IOQKEH47.js.map → config-SZZQFIJF.js.map} +0 -0
  180. /package/dist/{config-mutate-633Q77K3.js.map → config-mutate-66VDWR46.js.map} +0 -0
  181. /package/dist/{config-mutator-LRZHJ3UN.js.map → config-mutator-OILDQCAJ.js.map} +0 -0
  182. /package/dist/{contributions-3AE43OSI.js.map → contributions-LRQCDZCQ.js.map} +0 -0
  183. /package/dist/{doctor-KCRL67QL.js.map → doctor-QASDCIQ5.js.map} +0 -0
  184. /package/dist/{enrich-MZMIQ3SV.js.map → dotenv-DGZD3EDY.js.map} +0 -0
  185. /package/dist/{hub-PG4OFRIQ.js.map → enrich-NIUEEGPA.js.map} +0 -0
  186. /package/dist/{event-levels-PCFARGKL.js.map → event-levels-D6QSANGF.js.map} +0 -0
  187. /package/dist/{follow-up-tool-WLDWTZRW.js.map → follow-up-tool-QOO2TIQS.js.map} +0 -0
  188. /package/dist/{promote-DLM7N6V2.js.map → hub-6TKU6CHO.js.map} +0 -0
  189. /package/dist/{query-TBQGAIZG.js.map → keyring-EKFUNQAO.js.map} +0 -0
  190. /package/dist/{registry-DGGJJOVA.js.map → oauth-7J7DJMKN.js.map} +0 -0
  191. /package/dist/{routing-RAG6I37K.js.map → open-browser-BTEYT7G4.js.map} +0 -0
  192. /package/dist/{schedule-tool-O5FJXSKO.js.map → promote-D3KYLUBD.js.map} +0 -0
  193. /package/dist/{scheduler-TGP4B5KZ.js.map → providers-P76CWTGQ.js.map} +0 -0
  194. /package/dist/{seat-74G2KLZQ.js.map → query-D2TQ2PUO.js.map} +0 -0
  195. /package/dist/{query-settings-U6XNO5V4.js.map → query-settings-ILDX3HDF.js.map} +0 -0
  196. /package/dist/{wiki-E45S2K6F.js.map → registry-N3BY3HSI.js.map} +0 -0
  197. /package/dist/{request-planner-YQ4RTZNU.js.map → request-planner-CVCG5XQR.js.map} +0 -0
  198. /package/dist/{wiki-enrich-LREINNTK.js.map → resolve-JKXYBZ6R.js.map} +0 -0
  199. /package/dist/{review-candidates-OE5HDVWI.js.map → review-candidates-CKUN4PSY.js.map} +0 -0
  200. /package/dist/{workspace-setup-HAV4CQV7.js.map → routing-OCIRGUKK.js.map} +0 -0
  201. /package/dist/{rules-FBOLGE2S.js.map → rules-A5ES57QT.js.map} +0 -0
  202. /package/dist/{select-P7565K5D.js.map → select-J4ES7Q67.js.map} +0 -0
  203. /package/dist/{set-enabled-DE3TKKEK.js.map → set-enabled-S22TICYC.js.map} +0 -0
  204. /package/dist/{sprint-tool-CK3SD4NZ.js.map → sprint-tool-NDF47EKV.js.map} +0 -0
  205. /package/dist/{tool-X6DAR3KL.js.map → tool-52JRXZVA.js.map} +0 -0
  206. /package/dist/{tool-XGB3PMXA.js.map → tool-RCCMOMEY.js.map} +0 -0
  207. /package/dist/{tool-DWKCESVE.js.map → tool-Z2OVFGWW.js.map} +0 -0
@@ -1,10 +1,10 @@
1
- import{a as tt}from"./chunk-GTJIKXDB.js";import{H as rr,O as gr,k as H}from"./chunk-25U5MNNF.js";import{f as lr,g as dr,h as ur,l as pr}from"./chunk-KOZSBUXJ.js";import{b as sr}from"./chunk-2VDO2HEK.js";import{a as or,i as ir,l as ar,n as Qe,o as et,q as ie,r as Y,t as cr}from"./chunk-XPZSEDE3.js";import{t as tr,u as nr}from"./chunk-O672XL5L.js";import{d as Qn,e as er}from"./chunk-AQASR6KR.js";import{a as Un,b as Wn,d as jn,e as qn}from"./chunk-MNG2AMKZ.js";import{h as oe,j as Bn,l as Hn,m as Vn,n as Xn}from"./chunk-RX5O5637.js";import{a as zn,c as Kn,e as Gn,f as Ge,h as Yn,j as Jn,k as Zn,l as Ye,m as Je,n as Ze}from"./chunk-5ELIX7BQ.js";import{h as Ln,i as On,j as Pn,l as Mn,m as Fn}from"./chunk-ORAQRC6A.js";import{a as Cn,c as Nn}from"./chunk-KP7KDLZ2.js";import{c as we,d as In,e as Dn}from"./chunk-XVV7ZZ77.js";import{Aa as se,Ca as Ke,b as Ve,f as En,s as Xe,u as ze,xa as ye,ya as Rn,za as P}from"./chunk-K34LYNGN.js";import{a as he,b as re,e as _n}from"./chunk-7AB3QUGH.js";import{s as An}from"./chunk-QMFNIUW7.js";import{a as $n,b as be,e as Tn}from"./chunk-RW2JLP5P.js";import{b as G}from"./chunk-5ONH4ITT.js";import{a as Sn,c as He}from"./chunk-ILEC3IAV.js";import{a as vn}from"./chunk-QUFIUXMQ.js";import{B as me,C as un,D as pn,Db as wn,E as Qo,Eb as xn,Ob as kn,g as We,i as dn,m as Zo,qa as mn,ra as hn,ta as bn,ua as yn,ub as Be}from"./chunk-QTOOFB4N.js";import{a as je,h as ei}from"./chunk-VJ5HC63R.js";import{j as qe,q as gn,r as fn}from"./chunk-UEEB3UTU.js";import{existsSync as ti,readdirSync as ni,readFileSync as ri,statSync as si}from"fs";import{resolve as oi}from"path";function fr(t,e,n=Date.now(),r=7){let s=r*864e5,o=new Map;for(let i of e){let a=o.get(i.workflowId);a?a.push(i):o.set(i.workflowId,[i])}return t.map(i=>{let a=o.get(i.id)??[],c=a.filter(f=>n-f.at<=s),l=a.filter(f=>n-f.at>s&&n-f.at<=s*2),d=c.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&d*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:c.length,prior:l.length,failed:d,paused:u}}).sort((i,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[i.state]-c[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var xe=new Map;function tu(t,e=1e3){if(!ti(t))return[];let n=ni(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=oi(t,o);return{path:i,mtime:si(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of xe.keys())r.has(o)||xe.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=xe.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let c=ii(o,i);xe.set(o,{mtime:i,summary:c}),c&&s.push(c)}return s}function ii(t,e){try{let n=ri(t,"utf-8").split(`
2
- `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),s=r.run?.workflowId;if(!s)return null;let o=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),c=a.status??a.run?.status;if(c){o=c;break}}return{workflowId:s,status:o,at:e}}catch{return null}}var mr=7,ai={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},_={routines:200,summary:160,filters:6,filterValue:60,text:120},ci=(t,e,n)=>{try{return An(t,e,n)}catch{return null}},hr=864e5;function ou(t){let e=t.now??Date.now(),n={...ai,...t.thresholds},r=t.nextFire??ci,s=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",d=c.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:N(a.id,_.text),trigger:{schedule:N(a.schedule,_.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?nt(a.nextRun)??nt(r(a.schedule,new Date(e),l)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:fi(u.status==="success"?void 0:u.errorSummary,_.summary)}:null,lastSuccessAt:c.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:br(d),sampledRuns:c.length,flags:[],attention:null,recent:c.slice(0,mr).map(g=>({at:g.startedAt,status:g.status}))};p.flags=yr(p,d,a.schedule,l,null,e,n,r),s.push(wr(p))}let o=new Map(fr(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let c=i.get(a.workflowId);c?c.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(x=>x.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},d=a.state||"active",u=d==="active",p=(i.get(a.id)??[]).slice().sort((x,O)=>O.at-x.at),g=p.map(x=>({at:x.at,status:ui(x.status)})),f=g[0],b=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",k=typeof l.timezone=="string"?l.timezone:"UTC",h={id:`workflow:${a.id}`,source:"workflow",kind:b?"schedule":"event",name:N(a.title||a.id,_.text),trigger:b?{schedule:N(y,_.text),timezone:k}:{event:N(typeof l.event=="string"?l.event:"",_.text),filters:gi(l.filter,a)},agent:pi(a),enabled:u,state:d,nextRunAt:b&&u&&y?nt(r(y,new Date(e),k)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let x=g.find(O=>O.status==="success");return x?new Date(x.at).toISOString():null})(),consecutiveFailures:br(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,mr).map(x=>({at:new Date(x.at).toISOString(),status:x.status}))},m=Date.parse(a.updated||a.created||"");h.flags=b?yr(h,g,y,k,Number.isFinite(m)?m:null,e,n,r):li(h,o.get(a.id)?.state==="dormant",Number.isFinite(m)?m:null,e,n),s.push(wr(h))}return s.sort(di).slice(0,_.routines)}function br(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function yr(t,e,n,r,s,o,i,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=kr(l,s,o,i);return p&&c.push(p),c}if(t.consecutiveFailures>=i.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let d=new Date(l),u=null;for(let p=0;p<i.missedFires&&(u=a(n,d,r),!!u);p++)d=u;return u&&o>u.getTime()+i.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),c}function li(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=kr(i,n,r,s);return a&&o.push(a),o}return t.consecutiveFailures>=s.failStreak&&o.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?o.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&o.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),o}function kr(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*hr?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/hr)} days`:"Disabled and never ran"}}function wr(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var xr={critical:0,warning:1,info:2};function di(t,e){let n=t.attention?xr[t.attention]:3,r=e.attention?xr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ui(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function pi(t){if(t.ownerAgent)return N(t.ownerAgent,_.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?N(String(e.config.agentId),_.text):null}function gi(t,e){let n=[],r=e?.project;if(r&&n.push(N(`project=${r}`,_.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[s,o]of Object.entries(t)){let i=Array.isArray(o)?o.map(String):o==null?[]:[String(o)];i.length&&n.push(N(`${s}=${i.join(",")}`,_.filterValue))}return n.slice(0,_.filters)}function nt(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function N(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function fi(t,e){return t===void 0?void 0:N(t,e)}import{mkdirSync as mi,readFileSync as hi,renameSync as bi,writeFileSync as yi}from"fs";import{resolve as wi}from"path";function vr(t){return wi(et(t),"_state.json")}function A(t){try{let e=JSON.parse(hi(vr(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function ae(t,e){mi(et(t),{recursive:!0});let n=vr(t),r=`${n}.${process.pid}.tmp`;yi(r,JSON.stringify(e,null,2)+`
3
- `),bi(r,n)}function Sr(t,e,n,r=Date.now()){let s=A(t),o={};for(let[i,a]of Object.entries(s.snoozed))Date.parse(a)>r&&(o[i]=a);o[e]=n.toISOString(),ae(t,{...s,snoozed:o})}function du(t,e){ae(t,{...A(t),lastDigest:e})}function rt(t,e,n,r=Date.now()){let s=A(t),o=new Set(n),i={};for(let[c,l]of Object.entries(s.popped??{}))o.has(c)&&(i[c]=l);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(c=>c!==e&&o.has(c));ae(t,{...s,popped:i,wanted:a})}function Er(t,e){let n=A(t);ae(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function uu(t,e=Date.now()){ae(t,{...A(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as xi,readFileSync as ki}from"fs";kn();ei();function _r(t){let e=$n(t),n={};if(xi(e))try{n=wn(JSON.parse(ki(e,"utf-8")))}catch{n={}}let r=Be.safeParse(n?.requests);return r.success?r.data:Be.parse(void 0)}async function bu(t,e={}){let n=(t.channels??[]).filter(r=>!je.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...je].join(", ")}`}:be(r=>{let s=r.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[o]!==void 0&&(s[o]=t[o]);if(t.plans){let o=s.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(o[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((s.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let o=s.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(o[i]=t.catchPromises[i])}if(t.autoResend){let o=s.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(o[i]=t.autoResend[i])}if(t.flow){let o=s.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(o[i]=t.flow[i])}if(t.checkers){let o=s.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(o[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as W,readdirSync as Bi,readFileSync as ct,statSync as Hi}from"fs";import{dirname as Vr,resolve as E}from"path";import{randomBytes as Ar}from"crypto";import{existsSync as Si,mkdirSync as Ei,readdirSync as _i,readFileSync as $i,renameSync as Rr,unlinkSync as Ti,writeFileSync as Ai}from"fs";import{resolve as Ir}from"path";function $r(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var vi=t=>t.trim().split(`
4
- `).pop()?.slice(0,300)||"no output";async function Tr(t,e,n,r=tt){let s=await r(t.bin,[...$r(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${vi(s.stderr||s.stdout)}`}}async function xu(t,e,n,r,s=tt){return(await s(t.bin,[...$r(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Ri=2e3,Ii=t=>Tr(t.wacli,t.to,t.text);function st(t){return Ir(t,".agentx","whatsapp-triage","drafts")}var Di=t=>/^[a-z0-9-]{8,64}$/.test(t),ke=(t,e)=>Ir(st(t),`${e}.json`);function Dr(t,e){Ei(st(t),{recursive:!0});let n=ke(t,e.id),r=`${n}.${process.pid}.tmp`;Ai(r,JSON.stringify(e,null,2)+`
5
- `,{mode:384}),Rr(r,n)}function $u(t,e,n=Date.now()){let r=e.text.trim().slice(0,Ri);if(!r)throw new Error("empty draft");let s={...e,text:r,id:`${n.toString(36)}-${Ar(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Dr(t,s),s}function ve(t,e){if(!Di(e))return null;try{return JSON.parse($i(ke(t,e),"utf-8"))}catch{return null}}function Cr(t,e){let n=st(t);return Si(n)?_i(n).filter(r=>r.endsWith(".json")).map(r=>ve(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,s)=>r.created_at.localeCompare(s.created_at)):[]}async function Nr(t,e,n,r={}){let s=ve(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let o=`${ke(t,e)}.${process.pid}.${Ar(3).toString("hex")}.claim`;try{Rr(ke(t,e),o)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...s,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")i.status="rejected";else{let a=await(r.send??Ii)(s).catch(c=>({ok:!1,error:String(c?.message??c)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Dr(t,i);try{Ti(o)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as Ni,writeFileSync as Li}from"fs";import{resolve as Or}from"path";function ot(t,e,n,r){let s=t.agents?.[e];if(!s)return null;let o=s.integrations;if(!Array.isArray(o))return null;let i=o.find(a=>a.enabled!==!1&&a.kind===n&&(!r||a.label===r));return i?{agentId:e,integration:i}:null}function Ci(t,e){let r=(t.credentials??{})[e];if(!r)return{status:"no-credential",reason:`integration "${t.label}" has no ${String(e)} configured`};if(e==="auth"&&r==="keyring")return{status:"ok"};if(typeof r=="string"&&/^[A-Z][A-Z0-9_]*$/.test(r)){let s=process.env[r];return s?{status:"ok",value:s,envVar:r}:{status:"env-unset",envVar:r,reason:`env var ${r} is unset (declared by integration "${t.label}")`}}return typeof r=="string"?{status:"ok",value:r}:{status:"no-credential",reason:`unrecognized credential ref shape for ${String(e)}`}}function Au(t,e,n,r,s){let o=ot(t,e,n,s);return o?Ci(o.integration,r):{status:"kind-not-found",reason:`agent "${e}" has no integration of kind "${n}"${s?` with label "${s}"`:""}`}}var Pr="ready",Oi="202510";function Pi(t){let e=t.date??t.created_at.slice(0,10);return Or(t.workspace,Pr,`${e}-${t.platform}-${t.id}.txt`)}function Lr(t){let e=Pi(t);return Ni(Or(t.workspace,Pr),{recursive:!0}),Li(e,t.text.endsWith(`
1
+ import{a as tt}from"./chunk-GTJIKXDB.js";import{H as nr,O as gr,k as H}from"./chunk-5VD2J4JN.js";import{a as cr}from"./chunk-7QW4RECS.js";import{a as sr,i as or,l as ir,n as Ze,o as et,q as ie,r as Y,t as ar}from"./chunk-XPZSEDE3.js";import{f as lr,g as dr,h as ur,l as pr}from"./chunk-RB7M2NPU.js";import{b as rr}from"./chunk-2VDO2HEK.js";import{t as er,u as tr}from"./chunk-M4VYHPDS.js";import{d as Qn,e as Zn}from"./chunk-AQASR6KR.js";import{a as Fn,b as Un,d as Wn,e as jn}from"./chunk-MNG2AMKZ.js";import{h as oe,j as qn,l as Bn,m as Hn,n as Vn}from"./chunk-RX5O5637.js";import{a as Xn,c as zn,e as Kn,f as Ge,h as Gn,j as Yn,k as Jn,l as Ye,m as Je,n as Qe}from"./chunk-5ELIX7BQ.js";import{h as Nn,i as Ln,j as On,l as Pn,m as Mn}from"./chunk-EQPMQSJE.js";import{a as Dn,c as Cn}from"./chunk-KP7KDLZ2.js";import{c as we,d as Rn,e as In}from"./chunk-XVV7ZZ77.js";import{Aa as se,Ca as Ke,b as Ve,f as Sn,s as Xe,u as ze,xa as ye,ya as An,za as P}from"./chunk-RUNCUVAH.js";import{a as he,b as re,e as En}from"./chunk-7AB3QUGH.js";import{s as $n}from"./chunk-IAR5F3T5.js";import{a as _n,b as be,e as Tn}from"./chunk-P65XGEB7.js";import{b as G}from"./chunk-5ONH4ITT.js";import{a as vn,c as He}from"./chunk-ILEC3IAV.js";import{a as kn}from"./chunk-QUFIUXMQ.js";import{E as me,F as dn,G as un,Gb as yn,H as Zo,Hb as wn,Rb as xn,g as We,k as ln,p as Qo,ta as fn,ua as mn,wa as hn,xa as bn,xb as Be}from"./chunk-RIBANO2H.js";import{a as je,h as ei}from"./chunk-VJ5HC63R.js";import{j as qe,q as pn,r as gn}from"./chunk-UEEB3UTU.js";import{existsSync as ti,readdirSync as ni,readFileSync as ri,statSync as si}from"fs";import{resolve as oi}from"path";function fr(t,e,n=Date.now(),r=7){let s=r*864e5,o=new Map;for(let i of e){let a=o.get(i.workflowId);a?a.push(i):o.set(i.workflowId,[i])}return t.map(i=>{let a=o.get(i.id)??[],c=a.filter(f=>n-f.at<=s),l=a.filter(f=>n-f.at>s&&n-f.at<=s*2),d=c.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&d*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:c.length,prior:l.length,failed:d,paused:u}}).sort((i,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[i.state]-c[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var xe=new Map;function tu(t,e=1e3){if(!ti(t))return[];let n=ni(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=oi(t,o);return{path:i,mtime:si(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of xe.keys())r.has(o)||xe.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=xe.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let c=ii(o,i);xe.set(o,{mtime:i,summary:c}),c&&s.push(c)}return s}function ii(t,e){try{let n=ri(t,"utf-8").split(`
2
+ `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),s=r.run?.workflowId;if(!s)return null;let o=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),c=a.status??a.run?.status;if(c){o=c;break}}return{workflowId:s,status:o,at:e}}catch{return null}}var mr=7,ai={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},_={routines:200,summary:160,filters:6,filterValue:60,text:120},ci=(t,e,n)=>{try{return $n(t,e,n)}catch{return null}},hr=864e5;function ou(t){let e=t.now??Date.now(),n={...ai,...t.thresholds},r=t.nextFire??ci,s=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",d=c.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:N(a.id,_.text),trigger:{schedule:N(a.schedule,_.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?nt(a.nextRun)??nt(r(a.schedule,new Date(e),l)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:fi(u.status==="success"?void 0:u.errorSummary,_.summary)}:null,lastSuccessAt:c.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:br(d),sampledRuns:c.length,flags:[],attention:null,recent:c.slice(0,mr).map(g=>({at:g.startedAt,status:g.status}))};p.flags=yr(p,d,a.schedule,l,null,e,n,r),s.push(wr(p))}let o=new Map(fr(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let c=i.get(a.workflowId);c?c.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(x=>x.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},d=a.state||"active",u=d==="active",p=(i.get(a.id)??[]).slice().sort((x,O)=>O.at-x.at),g=p.map(x=>({at:x.at,status:ui(x.status)})),f=g[0],b=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",k=typeof l.timezone=="string"?l.timezone:"UTC",h={id:`workflow:${a.id}`,source:"workflow",kind:b?"schedule":"event",name:N(a.title||a.id,_.text),trigger:b?{schedule:N(y,_.text),timezone:k}:{event:N(typeof l.event=="string"?l.event:"",_.text),filters:gi(l.filter,a)},agent:pi(a),enabled:u,state:d,nextRunAt:b&&u&&y?nt(r(y,new Date(e),k)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let x=g.find(O=>O.status==="success");return x?new Date(x.at).toISOString():null})(),consecutiveFailures:br(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,mr).map(x=>({at:new Date(x.at).toISOString(),status:x.status}))},m=Date.parse(a.updated||a.created||"");h.flags=b?yr(h,g,y,k,Number.isFinite(m)?m:null,e,n,r):li(h,o.get(a.id)?.state==="dormant",Number.isFinite(m)?m:null,e,n),s.push(wr(h))}return s.sort(di).slice(0,_.routines)}function br(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function yr(t,e,n,r,s,o,i,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=kr(l,s,o,i);return p&&c.push(p),c}if(t.consecutiveFailures>=i.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let d=new Date(l),u=null;for(let p=0;p<i.missedFires&&(u=a(n,d,r),!!u);p++)d=u;return u&&o>u.getTime()+i.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),c}function li(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=kr(i,n,r,s);return a&&o.push(a),o}return t.consecutiveFailures>=s.failStreak&&o.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?o.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&o.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),o}function kr(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*hr?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/hr)} days`:"Disabled and never ran"}}function wr(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var xr={critical:0,warning:1,info:2};function di(t,e){let n=t.attention?xr[t.attention]:3,r=e.attention?xr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ui(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function pi(t){if(t.ownerAgent)return N(t.ownerAgent,_.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?N(String(e.config.agentId),_.text):null}function gi(t,e){let n=[],r=e?.project;if(r&&n.push(N(`project=${r}`,_.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[s,o]of Object.entries(t)){let i=Array.isArray(o)?o.map(String):o==null?[]:[String(o)];i.length&&n.push(N(`${s}=${i.join(",")}`,_.filterValue))}return n.slice(0,_.filters)}function nt(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function N(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function fi(t,e){return t===void 0?void 0:N(t,e)}import{mkdirSync as mi,readFileSync as hi,renameSync as bi,writeFileSync as yi}from"fs";import{resolve as wi}from"path";function vr(t){return wi(et(t),"_state.json")}function A(t){try{let e=JSON.parse(hi(vr(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function ae(t,e){mi(et(t),{recursive:!0});let n=vr(t),r=`${n}.${process.pid}.tmp`;yi(r,JSON.stringify(e,null,2)+`
3
+ `),bi(r,n)}function Sr(t,e,n,r=Date.now()){let s=A(t),o={};for(let[i,a]of Object.entries(s.snoozed))Date.parse(a)>r&&(o[i]=a);o[e]=n.toISOString(),ae(t,{...s,snoozed:o})}function du(t,e){ae(t,{...A(t),lastDigest:e})}function rt(t,e,n,r=Date.now()){let s=A(t),o=new Set(n),i={};for(let[c,l]of Object.entries(s.popped??{}))o.has(c)&&(i[c]=l);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(c=>c!==e&&o.has(c));ae(t,{...s,popped:i,wanted:a})}function Er(t,e){let n=A(t);ae(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function uu(t,e=Date.now()){ae(t,{...A(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as xi,readFileSync as ki}from"fs";xn();ei();function _r(t){let e=_n(t),n={};if(xi(e))try{n=yn(JSON.parse(ki(e,"utf-8")))}catch{n={}}let r=Be.safeParse(n?.requests);return r.success?r.data:Be.parse(void 0)}async function bu(t,e={}){let n=(t.channels??[]).filter(r=>!je.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...je].join(", ")}`}:be(r=>{let s=r.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[o]!==void 0&&(s[o]=t[o]);if(t.plans){let o=s.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(o[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((s.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let o=s.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(o[i]=t.catchPromises[i])}if(t.autoResend){let o=s.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(o[i]=t.autoResend[i])}if(t.flow){let o=s.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(o[i]=t.flow[i])}if(t.checkers){let o=s.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(o[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as W,readdirSync as qi,readFileSync as at,statSync as Bi}from"fs";import{dirname as Vr,resolve as E}from"path";import{randomBytes as Ar}from"crypto";import{existsSync as Si,mkdirSync as Ei,readdirSync as _i,readFileSync as Ti,renameSync as Rr,unlinkSync as $i,writeFileSync as Ai}from"fs";import{resolve as Ir}from"path";function Tr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var vi=t=>t.trim().split(`
4
+ `).pop()?.slice(0,300)||"no output";async function $r(t,e,n,r=tt){let s=await r(t.bin,[...Tr(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${vi(s.stderr||s.stdout)}`}}async function xu(t,e,n,r,s=tt){return(await s(t.bin,[...Tr(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Ri=2e3,Ii=t=>$r(t.wacli,t.to,t.text);function st(t){return Ir(t,".agentx","whatsapp-triage","drafts")}var Di=t=>/^[a-z0-9-]{8,64}$/.test(t),ke=(t,e)=>Ir(st(t),`${e}.json`);function Dr(t,e){Ei(st(t),{recursive:!0});let n=ke(t,e.id),r=`${n}.${process.pid}.tmp`;Ai(r,JSON.stringify(e,null,2)+`
5
+ `,{mode:384}),Rr(r,n)}function Tu(t,e,n=Date.now()){let r=e.text.trim().slice(0,Ri);if(!r)throw new Error("empty draft");let s={...e,text:r,id:`${n.toString(36)}-${Ar(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Dr(t,s),s}function ve(t,e){if(!Di(e))return null;try{return JSON.parse(Ti(ke(t,e),"utf-8"))}catch{return null}}function Cr(t,e){let n=st(t);return Si(n)?_i(n).filter(r=>r.endsWith(".json")).map(r=>ve(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,s)=>r.created_at.localeCompare(s.created_at)):[]}async function Nr(t,e,n,r={}){let s=ve(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let o=`${ke(t,e)}.${process.pid}.${Ar(3).toString("hex")}.claim`;try{Rr(ke(t,e),o)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...s,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")i.status="rejected";else{let a=await(r.send??Ii)(s).catch(c=>({ok:!1,error:String(c?.message??c)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Dr(t,i);try{$i(o)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as Ci,writeFileSync as Ni}from"fs";import{resolve as Or}from"path";var Pr="ready",Li="202510";function Oi(t){let e=t.date??t.created_at.slice(0,10);return Or(t.workspace,Pr,`${e}-${t.platform}-${t.id}.txt`)}function Lr(t){let e=Oi(t);return Ci(Or(t.workspace,Pr),{recursive:!0}),Ni(e,t.text.endsWith(`
6
6
  `)?t.text:`${t.text}
7
- `),e}function Mr(t,e,n){let r=ot(t.config,e,n);if(!r)return null;let s=t.env??process.env,o=r.integration.credentials?.tokenEnv,i=o?s[o]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function Fr(t,e,n){return Mr(t,e,n)!==null}async function Mi(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let s=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??Oi),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!s.ok)throw new Error(`LinkedIn said ${s.status}: ${(await s.text().catch(()=>"")).slice(0,200)}`);let o=s.headers.get("x-restli-id");return o?{url:`https://www.linkedin.com/feed/update/${o}/`}:{}}async function Fi(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let s=await r.json().catch(()=>({}));return s.data?.id?{url:`https://x.com/i/web/status/${s.data.id}`}:{}}async function Ui(t,e){let n=Mr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Lr(t)};let r=e.fetch??fetch;try{let s=t.platform==="linkedin"?await Mi(t.text,n,r):await Fi(t.text,n,r);return{ok:!0,posted:!0,...s.url?{url:s.url}:{}}}catch(s){let o=Lr(t);return{ok:!1,error:`not posted on ${oe[t.platform]}: ${s?.message??s}. Saved to paste by hand: ${o}`,file:o}}}function Ur(t){return e=>Ui(e,t)}fn();yn();yn();fn();var Mu=["done","skipped"],Wi=1e3;function ji(t){t.exec(`
7
+ `),e}function Mr(t,e,n){let r=cr(t.config,e,n);if(!r)return null;let s=t.env??process.env,o=r.integration.credentials?.tokenEnv,i=o?s[o]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function Fr(t,e,n){return Mr(t,e,n)!==null}async function Pi(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let s=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??Li),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!s.ok)throw new Error(`LinkedIn said ${s.status}: ${(await s.text().catch(()=>"")).slice(0,200)}`);let o=s.headers.get("x-restli-id");return o?{url:`https://www.linkedin.com/feed/update/${o}/`}:{}}async function Mi(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let s=await r.json().catch(()=>({}));return s.data?.id?{url:`https://x.com/i/web/status/${s.data.id}`}:{}}async function Fi(t,e){let n=Mr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Lr(t)};let r=e.fetch??fetch;try{let s=t.platform==="linkedin"?await Pi(t.text,n,r):await Mi(t.text,n,r);return{ok:!0,posted:!0,...s.url?{url:s.url}:{}}}catch(s){let o=Lr(t);return{ok:!1,error:`not posted on ${oe[t.platform]}: ${s?.message??s}. Saved to paste by hand: ${o}`,file:o}}}function Ur(t){return e=>Fi(e,t)}gn();bn();bn();gn();var Ou=["done","skipped"],Ui=1e3;function Wi(t){t.exec(`
8
8
  CREATE TABLE IF NOT EXISTS request_plans (
9
9
  request_id TEXT PRIMARY KEY,
10
10
  created_by TEXT NOT NULL,
@@ -60,17 +60,17 @@ import{a as tt}from"./chunk-GTJIKXDB.js";import{H as rr,O as gr,k as H}from"./ch
60
60
  told_at INTEGER,
61
61
  PRIMARY KEY (goal_key, day)
62
62
  );
63
- `),gn(t,"request_plan_steps",[["check_count","TEXT"],["last_count","INTEGER"],["last_count_at","INTEGER"]])}function jr(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function it(t){return{requestId:t.request_id,createdBy:t.created_by,createdAt:t.created_at,state:t.state,finishedAt:t.finished_at??null,notifiedAt:t.notified_at??null}}function Wr(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,checkCount:t.check_count??null,lastCount:t.last_count??null,lastCountAt:t.last_count_at??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var qi={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at",lastCount:"last_count",lastCountAt:"last_count_at"},Se=class{constructor(e){this.db=e;ji(e)}create(e,n,r,s){let o=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
63
+ `),pn(t,"request_plan_steps",[["check_count","TEXT"],["last_count","INTEGER"],["last_count_at","INTEGER"]])}function jr(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function ot(t){return{requestId:t.request_id,createdBy:t.created_by,createdAt:t.created_at,state:t.state,finishedAt:t.finished_at??null,notifiedAt:t.notified_at??null}}function Wr(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,checkCount:t.check_count??null,lastCount:t.last_count??null,lastCountAt:t.last_count_at??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var ji={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at",lastCount:"last_count",lastCountAt:"last_count_at"},Se=class{constructor(e){this.db=e;Wi(e)}create(e,n,r,s){let o=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
64
64
  to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)
65
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{o.run(e,n,s),r.forEach((a,c)=>{let l=c===0,d=l&&a.agentId===n&&a.kind!=="message";i.run(e,c+1,a.name,a.kind,a.agentId,a.doneWhen,l?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,d?s:null,s,a.checkCount??null)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,s)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?it(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(Wr)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?Wr(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(it)}updateStep(e,n,r){let s=[],o=[];for(let[i,a]of Object.entries(r)){let c=qi[i];!c||a===void 0||(s.push(`${c} = ?`),o.push(typeof a=="boolean"?a?1:0:a))}s.length&&this.db.prepare(`UPDATE request_plan_steps SET ${s.join(", ")} WHERE request_id = ? AND idx = ?`).run(...o,e,n)}finish(e,n,r){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,r,e).changes>0}markNotified(e,n){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(n,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(it)}event(e,n,r,s,o){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,o,r,s.replace(/\s+/g," ").trim().slice(0,Wi))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
65
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{o.run(e,n,s),r.forEach((a,c)=>{let l=c===0,d=l&&a.agentId===n&&a.kind!=="message";i.run(e,c+1,a.name,a.kind,a.agentId,a.doneWhen,l?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,d?s:null,s,a.checkCount??null)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,s)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?ot(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(Wr)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?Wr(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(ot)}updateStep(e,n,r){let s=[],o=[];for(let[i,a]of Object.entries(r)){let c=ji[i];!c||a===void 0||(s.push(`${c} = ?`),o.push(typeof a=="boolean"?a?1:0:a))}s.length&&this.db.prepare(`UPDATE request_plan_steps SET ${s.join(", ")} WHERE request_id = ? AND idx = ?`).run(...o,e,n)}finish(e,n,r){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,r,e).changes>0}markNotified(e,n){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(n,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(ot)}event(e,n,r,s,o){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,o,r,s.replace(/\s+/g," ").trim().slice(0,Ui))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
66
66
  ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,
67
- told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,s=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,s).reverse().map(o=>({requestId:o.request_id,step:o.step??null,at:o.at,kind:o.kind,detail:o.detail}))}},Fu=mn;var Xr=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],Vi=280;function R(t,e=Vi){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function J(t){if(t.configPath)return E(t.configPath);let e=[E(t.root,"agentx.json"),E(t.root,".agentx","config.json")];return e.find(n=>W(n))??e[0]}function j(t){return t.wikiDir?E(t.wikiDir):E(t.root,".agentx","wiki")}function Xi(t){return Y(t.root,"pending").map(zi)}function zi(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:R([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function Ki(t){let e=J(t);if(!W(e))return[];let n;try{n=JSON.parse(ct(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),s=[];for(let[o,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let c=i.timezone||"UTC",l=i.schedule?Ln(i.schedule):"",d=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",u=String(i.prompt??i.command??""),p=a.action==="create";s.push({key:`schedule:${o}`,kind:"schedule",title:p?`New schedule "${o}" for ${i.agent??"an agent"}`:`Delete schedule "${o}"`,ask:p?`Let ${i.agent??"the agent"} run this ${d}?`:`Remove the schedule "${o}" (${d})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:R(`${u}${p&&i.schedule?` \xB7 first run ${Pn(On(i.schedule,c,r),c)}`:""}`),more:"agentx schedule list"})}return s}function zr(t){let e=E(t,".agentx","memory");return W(e)?Bi(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Gi(t){let e=zr(t.root);if(e.length===0)return[];let n=new Ve(t.root),r=[];for(let s of e)for(let o of n.held(s))r.push({key:`memory:${s}/${o.id}`,kind:"memory",title:`Fact ${s} learned from ${o.source.channel}`,ask:`Let ${s} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:s,created_at:o.createdAt,detail:R(o.content),more:`agentx memory facts held --agent ${s}`});return r}function Yi(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function Ji(t){return er(j(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:R(`${Yi(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var qr=new Map;function Kr(t,e){let n=Hi(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,s=qr.get(t);if(s?.version===r)return s.value;let o=e();return qr.set(t,{version:r,value:o}),o}function Zi(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${R(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:R(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function Qi(t,e){let n=j(t);if(!W(E(n,"_facts.json")))return;let r=we(new G(n),"pending").find(s=>s.id===e);return r?Zi(r):void 0}function ea(t){let e=E(j(t),"_facts.json");if(!W(e))return;let n=Kr(e,()=>we(new G(Vr(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),s=n.filter(a=>r-a<864e5).length,o=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:s,...o?{newest:new Date(o).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${s?` (${s} new today)`:""}`,more:"agentx wiki facts proposals list"}}function ta(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function Gr(t){let e=j(t),n=new He(e);if(!W(n.path))return[];let r=Kr(n.path,()=>{let o=n.load();if(o.unreadable)throw new Error(`${n.path} is unreadable: ${o.unreadable}`);return o.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),s;return r.map(o=>{let i;if(o.kind==="contradiction"&&o.proposed&&o.factId){let a=(s??=new G(e)).get(o.factId);a&&(i=[a.value,o.proposed.value])}return{key:`question:${o.id}`,kind:"question",title:ta(o),ask:o.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${o.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:o.agentId,created_at:o.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function na(t){return Cr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:R(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function ra(t){return dr(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:R(`Last try not sent: ${e.error}`)}:{}}))}function sa(t){let e=Object.entries(Xe(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Ee(t).agents??{};return e.map(([r,s])=>{let o=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${o.name||r}", created by ${s.by}`,ask:`Let ${o.name||r} (${o.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:s.by,created_at:s.at,detail:R(`Workspace: ${o.workspace||"?"}. Instructions: ${o.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Ee(t){try{return JSON.parse(ct(J(t),"utf-8"))}catch{return{}}}function at(t){let e={};try{e=Object.fromEntries(vn(ct(E(Vr(J(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function oa(t){let e=Vn(t.root,"pending");if(e.length===0)return[];let n=Ee(t),r=at(t);return e.map(s=>{let o=oe[s.platform]??s.platform;return{key:`content:${s.id}`,kind:"content",title:`${o} post${s.topic?`: ${s.topic}`:""}${s.date?` (for ${s.date})`:""}`,ask:`Publish this on ${o}? "${s.text}"`,yes:Fr({config:n,env:r},s.agent,s.platform)?`post it on ${o}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:s.agent,created_at:s.created_at,detail:R(`Follows your past posts: ${s.samples.join(", ")}`),more:`agentx content show ${s.id}`,text_hash:Bn(s.text)}})}function V(t){if(t.requests)return t.requests;if(E(t.root)!==process.cwd()||!W(E(t.root,".agentx","db.sqlite")))return null;let e=qe({quiet:!0});if(!e)return null;let n=Br.get(e);return!n&&!hn(e)?null:(n||Br.set(e,n=new bn(e)),n)}var Br=new WeakMap;function pp(t){if(t.plans)return t.plans;if(t.requests||E(t.root)!==process.cwd()||!W(E(t.root,".agentx","db.sqlite")))return null;let e=qe({quiet:!0});if(!e||!jr(e))return null;let n=Hr.get(e);return n||Hr.set(e,n=new Se(e)),n}var Hr=new WeakMap;function ia(t){let e=V(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:H(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:R(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var Yr={card:Xi,schedule:Ki,agent:sa,memory:Gi,wiki:Ji,fact:()=>[],question:Gr,whatsapp:na,email:ra,content:oa,request:ia};function aa(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function Jr(t,e={}){let n=t.now??Date.now(),{snoozed:r}=A(t.root),s=[],o=[],i=[],a=0;for(let c of e.kinds??Xr){if(c==="fact"){try{let d=ea(t);d&&i.push(d)}catch(d){o.push({kind:c,error:String(d?.message??d).slice(0,200)})}continue}let l;try{l=Yr[c](t)}catch(d){o.push({kind:c,error:String(d?.message??d).slice(0,200)});continue}for(let d of l){let u=r[d.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){a++;continue}d.snoozed_until=u}s.push(d)}}return s.sort(aa),{items:s,snoozed:a,errors:o,backlog:i}}function Zr(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!Xr.includes(n)||!r?null:{kind:n,ref:r}}function ca(t,e,n){switch(e){case"card":return ie(t.root,n)?.status==="pending";case"wiki":return Qn(j(t),n)?.status==="pending";case"whatsapp":return ve(t.root,n)?.status==="pending";case"email":return lr(t.root,n)?.status==="pending";case"content":return Hn(t.root,n)?.status==="pending";default:return!!Qr(t,e,n)}}function Qr(t,e,n){return e==="fact"?Qi(t,n):Yr[e](t).find(r=>r.key===`${e}:${n}`)}async function es(t,e,n,r={}){let s=n==="later"?null:Zr(e),o;if(s)try{o=Qr(t,s.kind,s.ref)}catch{o=void 0}let i=await la(t,e,n,r);if(i.ok&&s&&n!=="later"){let a=typeof r.choice=="number"?o?.choices?.[r.choice-1]:r.choice;or(t.root,{key:e,kind:s.kind,title:o?.title??e,raised_by:o?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function la(t,e,n,r){let s=Zr(e);if(!s)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:o,ref:i}=s,a=t.now??Date.now(),c=r.by??"operator";if(n==="later"){if(!ca(t,o,i))return{ok:!1,error:`nothing waiting for "${e}"`};let d=r.laterHours&&r.laterHours>0?r.laterHours:24,u=new Date(a+d*36e5);return Sr(t.root,e,u,a),{ok:!0,message:`${e} put off until ${u.toISOString()}`}}let l=n==="yes";switch(o){case"card":{let d=cr(t.root,i,l?"yes":"no",{by:c,note:r.note,now:a,choice:r.choice,text:r.text});return d.ok?{ok:!0,message:`${e}: ${d.card.raised_by} will be told ${l?"yes":"no"}${d.card.choice?` (${d.card.choice}${d.card.choice_suggested?", the suggested option":""})`:""}`}:d}case"schedule":{let d=await(l?Mn:Fn)(i,{configPath:J(t),reload:t.reload});return d.success?{ok:!0,message:d.message}:{ok:!1,error:d.message}}case"agent":{if(Xe(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return ze(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let d=[],u=await be(p=>{Tn(p,`agents.${i}`);for(let[g,f]of Object.entries(p.crons??{}))f?.agent===i&&(delete p.crons[g],d.push(g))},{configPath:J(t),reload:t.reload});return u.success?(ze(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${d.length?`, with its schedules ${d.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:u.error||"could not remove it from agentx.json"}}case"memory":{let d=i.indexOf("/");if(d<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let u=i.slice(0,d),p=i.slice(d+1);if(!zr(t.root).includes(u))return{ok:!1,error:`no memory for agent "${u}"`};let g=new Ve(t.root);return g.held(u).some(f=>f.id===p)?(g.review(u,p,l?"approved":"rejected",c),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let d=j(t),u=l?tr(d,i,{by:c,force:r.force,now:a}):nr(d,i,{by:c,reason:r.note,now:a});return u.ok?{ok:!0,message:l?`${u.proposal.article.path} written to the shared wiki`:`${e} rejected`}:u}case"fact":return da(t,e,i,l,c,r);case"question":return pa(t,e,i,l,c,r);case"whatsapp":{let d=await Nr(t.root,i,l?"yes":"no",{by:c,now:a,send:t.sendWhatsApp});return d.ok?{ok:!0,message:l?`${e}: sent to ${d.draft.chat_name||d.draft.to}`:`${e}: dropped, nothing sent`}:d}case"email":{let d=t.sendEmail??pr(Ee(t),at(t)),u=await ur(t.root,i,l?"yes":"no",{by:c,now:a,text:r.text,send:d});return u.ok?{ok:!0,message:l?`${e}: sent to ${u.draft.to}${u.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:u}case"content":{let d=t.publishContent??Ur({config:Ee(t),env:at(t)}),u=await Xn(t.root,i,l?"yes":"no",{by:c,now:a,text:r.text,seen:r.seen,publish:d});if(!u.ok)return u;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let p=oe[u.draft.platform];return{ok:!0,message:u.draft.status==="posted"?`${e}: posted on ${p}${u.draft.url?` (${u.draft.url})`:""}`:`${e}: no ${p} connector is set, so it is saved ready to paste: ${u.draft.file}`}}case"request":{let d=V(t),u=d?.get(i);return!d||!u||u.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?_r(J(t)).enabled?(d.requestPickup(i,a),{ok:!0,message:`${e}: ${u.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(d.close(i,"dropped",r.note?.trim()||`dropped by ${c}`,a),{ok:!0,message:`${e}: dropped`})}}}function da(t,e,n,r,s,o){let i=new G(j(t));try{let a=we(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return Dn(i,a.id,s,o.note),{ok:!0,message:`${e}: claim dropped`};let c=In(i,a.id,s);return{ok:!0,message:`${e}: ${c.write.fact.subject} \xB7 ${c.write.fact.attribute} recorded as "${c.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function ua(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(s=>s.toLowerCase()===r)}function pa(t,e,n,r,s,o){let i=j(t),a=new He(i),c=a.list("open").find(l=>l.id===n);if(!c)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Sn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(c.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=Gr(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${c.id} "<value>"`};let d=ua(l.choices,o.choice);if(!d)return{ok:!1,error:`pick one of: ${l.choices.map((g,f)=>`${f+1}. ${g}`).join(", ")}`};let u=new G(i),p=c.factId?u.get(c.factId):void 0;return p&&u.write({subject:p.subject,attribute:p.attribute,value:d,source:"owner said",verifiedBy:s,volatility:p.volatility},{confirmedBy:s}),a.resolve(c.id,"answered",d),{ok:!0,message:`${e}: answered "${d}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var ga=3,fa=7,ma=50,dt=120,ha=280,lt=600,ns=36e5,ba=24*ns;function mp(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function Z(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var _e=t=>new Date(t).toISOString();function ya(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:Z(e.title,dt),...e.ask?{ask:Z(e.ask,lt)}:{},...e.detail?{facts:Z(e.detail,ha)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var wa={done:"Done",declined:"Declined",dropped:"Dropped"};function rs(t,e,n){let{record:r,links:s}=e,o=H(r,dt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:o.headline,need:o.need,...r.headline?{said:Z(o.said,lt)}:{},agent:r.agentId,askedAt:_e(r.createdAt),changedAt:_e(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return s.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:Z(r.question,lt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=s.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),c=t.now-r.updatedAt<(t.quietHours??ga)*ns;return{...i,column:a||c?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:_e(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:wa[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function xa(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function ka(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:Z(e.title,dt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:xa(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var I=t=>t&&Date.parse(t)||0,ts=(t,e)=>t.map(n=>n[e]).filter(n=>!!I(n)).sort((n,r)=>I(n)-I(r))[0];function ut(t){let e=[],n=[];for(let s of t.inbox){s.error&&n.push(`What waits on ${s.nodeName} could not be read: ${s.error}`);for(let o of s.items)e.push(ya(s,o,s.node===t.node))}let r=ss(t,e);for(let s of t.requests??[]){let o=rs(t,s,r);o?.column==="yours"&&e.push(o)}return{cards:e,errors:n}}function ss(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function hp(t){let e=ut(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,s=ss(t,n),o=[],i=[],a=[];for(let p of t.requests??[]){let g=rs(t,p,s);g&&g.column!=="yours"&&{agent:o,quiet:i,done:a}[g.column].push(g)}let c=t.now-(t.doneDays??fa)*ba;for(let p of t.cards)p.status!=="pending"&&I(p.decided_at)>=c&&a.push(ka(t,p));o.sort((p,g)=>I(g.changedAt)-I(p.changedAt)),i.sort((p,g)=>I(p.changedAt)-I(g.changedAt)),a.sort((p,g)=>I(g.changedAt)-I(p.changedAt));let l=a.filter(p=>I(p.changedAt)>=c).slice(0,ma),d=ts(n,"askedAt"),u=ts(i,"changedAt");return{ts:_e(t.now),cards:[...n,...o,...i,...l],figures:{yours:{count:n.length,...d?{oldest:d}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:o.length},quiet:{count:i.length,...u?{oldest:u}:{}},done:{count:l.length}},errors:r}}function va(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function Sa(t,e,n){let r=t.map(s=>s.askedAt).filter(s=>!!s&&!!Date.parse(s)).sort((s,o)=>Date.parse(s)-Date.parse(o));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function xp(t,e){let n=t.now??Date.now(),r=[],s=Jr(t,{includeSnoozed:!0});for(let d of s.errors)r.push(`What waits (${d.kind}) could not be read: ${d.error}`);let o=s.items.filter(d=>!d.snoozed_until),i=new Set(s.items.filter(d=>d.snoozed_until).map(d=>d.key)),a=null;try{let d=V(t);d&&(a=d.listByState("waiting_owner").map(u=>({record:u,links:d.links(u.id)})))}catch(d){r.push(`Requests could not be read: ${d?.message??d}`)}let{cards:c,errors:l}=ut({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:o.map(va)}],requests:a,deferred:i});return Sa(c,i.size,[...r,...l])}import{readFileSync as Ea}from"fs";var _a=1e4,os=/^[0-9a-f]{7,64}$/i;function Sp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&os.test(i)?{source:n,commit:i}:{source:n,commit:null,error:"this build does not carry its commit (run from source?)"}}let r;try{r=await e(n,{signal:AbortSignal.timeout(_a)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let s=await r.json().catch(()=>null),o=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,s);return typeof o=="string"&&os.test(o.trim())?{source:n,commit:o.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Ep(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Ea(n.tokenFile,"utf-8").trim().split(`
68
- `)[0].trim()||void 0}catch{}let s=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??s?.host??"https://gitlab.com",token:e?.gitlab?.token??s?.token}}}var is=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function $p(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/content"||t.startsWith("/content/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"}function Tp(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/events"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/channels\/[^/]+\/switch$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"||t==="/api/signals/stop-all"||t==="/api/signals/stop-all/report"||t==="/api/review-gate/replay"}function Ap(t){return is.has(t)}function Rp(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(is.has(t.remoteAddress))return{allowed:!0,reason:"loopback"};if(t.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.acceptedTokens.has(n)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function Ip(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let r of t.mesh?.peers||[])r.token&&n.add(r.token);return n}function Dp(t,e,n=process.env){let r=o=>o.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(o=>r(o.url)===e)?.token)||n.MESH_TOKEN||void 0}function $e(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function $a(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ta(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function Np(t,e=Ta()){let n=$e(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let s=$a(n),o=[$e(t.host),$e(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return s&&o.includes(s)?"same-origin":"foreign"}let r=$e(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function Lp(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var pt="/api/admin/pictures",Aa=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Ra=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function v(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function Ia(t){let e={agent:{},person:{}};for(let n of zn)for(let[r,s]of Object.entries(Yn(t,n)))e[n][r]=Jn(n,r,s);return e}function Mp(t,e,n,r,s){let o=n.match(Aa);if(!o)return!1;if((t.method||"GET").toUpperCase()!=="GET")return v(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(o[2]),a=Zn(s,o[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":Kn,"Content-Length":String(a.length),"Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'"}),e.end(a),!0):(v(e,404,{error:"no such picture"}),!0)}async function Fp(t,e,n,r){if(n!==pt&&!n.startsWith(`${pt}/`))return!1;let s=(t.method||"GET").toUpperCase();if(n===pt)return s!=="GET"?(v(e,405,{error:"GET only"}),!0):(v(e,200,{...Ia(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let o=n.match(Ra);if(!o)return v(e,404,{error:"not found"}),!0;if(s!=="PUT"&&s!=="DELETE")return v(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return v(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=o[1],c=decodeURIComponent(o[2]),l=a==="agent"?r.agentIds():r.personIds();if(!Gn.test(c)||!l.includes(c))return v(e,404,{error:a==="agent"?`no agent "${c}" in agentx.json`:`no person "${c}" in agentx.json`}),!0;if(s==="DELETE"){let d=Je(r.root,a,c);return v(e,200,{ok:!0,removed:d}),!0}try{let d=await Ze(t),u=await Ye(r.root,a,c,d);v(e,200,{ok:!0,url:u.url})}catch(d){if(d instanceof Ge)return v(e,d.status,{error:d.message}),!0;throw d}return!0}async function Up(t,e,n,r){let s=(t.method||"GET").toUpperCase();if(s!=="PUT"&&s!=="DELETE"){v(e,405,{error:"PUT or DELETE only"});return}let o=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(o);if(!i){v(e,403,{error:"Only an agent sets its own picture, from its own run: send X-AgentX-Task (or X-AgentX-Channel and X-AgentX-Chat) of a running turn. The owner sets pictures in Settings."});return}if(o&&o!==i){v(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${o}".`});return}if(s==="DELETE"){v(e,200,{ok:!0,agent:i,removed:Je(r.root,"agent",i)});return}try{let a=await Ye(r.root,"agent",i,await Ze(t));v(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof Ge){v(e,a.status,{error:a.message});return}throw a}}var as={};function qp(t){as=t}function Bp(){return as}var Hp=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
67
+ told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,s=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,s).reverse().map(o=>({requestId:o.request_id,step:o.step??null,at:o.at,kind:o.kind,detail:o.detail}))}},Pu=fn;var Xr=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],Hi=280;function R(t,e=Hi){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function J(t){if(t.configPath)return E(t.configPath);let e=[E(t.root,"agentx.json"),E(t.root,".agentx","config.json")];return e.find(n=>W(n))??e[0]}function j(t){return t.wikiDir?E(t.wikiDir):E(t.root,".agentx","wiki")}function Vi(t){return Y(t.root,"pending").map(Xi)}function Xi(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:R([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function zi(t){let e=J(t);if(!W(e))return[];let n;try{n=JSON.parse(at(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),s=[];for(let[o,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let c=i.timezone||"UTC",l=i.schedule?Nn(i.schedule):"",d=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",u=String(i.prompt??i.command??""),p=a.action==="create";s.push({key:`schedule:${o}`,kind:"schedule",title:p?`New schedule "${o}" for ${i.agent??"an agent"}`:`Delete schedule "${o}"`,ask:p?`Let ${i.agent??"the agent"} run this ${d}?`:`Remove the schedule "${o}" (${d})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:R(`${u}${p&&i.schedule?` \xB7 first run ${On(Ln(i.schedule,c,r),c)}`:""}`),more:"agentx schedule list"})}return s}function zr(t){let e=E(t,".agentx","memory");return W(e)?qi(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Ki(t){let e=zr(t.root);if(e.length===0)return[];let n=new Ve(t.root),r=[];for(let s of e)for(let o of n.held(s))r.push({key:`memory:${s}/${o.id}`,kind:"memory",title:`Fact ${s} learned from ${o.source.channel}`,ask:`Let ${s} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:s,created_at:o.createdAt,detail:R(o.content),more:`agentx memory facts held --agent ${s}`});return r}function Gi(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function Yi(t){return Zn(j(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:R(`${Gi(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var qr=new Map;function Kr(t,e){let n=Bi(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,s=qr.get(t);if(s?.version===r)return s.value;let o=e();return qr.set(t,{version:r,value:o}),o}function Ji(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${R(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:R(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function Qi(t,e){let n=j(t);if(!W(E(n,"_facts.json")))return;let r=we(new G(n),"pending").find(s=>s.id===e);return r?Ji(r):void 0}function Zi(t){let e=E(j(t),"_facts.json");if(!W(e))return;let n=Kr(e,()=>we(new G(Vr(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),s=n.filter(a=>r-a<864e5).length,o=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:s,...o?{newest:new Date(o).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${s?` (${s} new today)`:""}`,more:"agentx wiki facts proposals list"}}function ea(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function Gr(t){let e=j(t),n=new He(e);if(!W(n.path))return[];let r=Kr(n.path,()=>{let o=n.load();if(o.unreadable)throw new Error(`${n.path} is unreadable: ${o.unreadable}`);return o.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),s;return r.map(o=>{let i;if(o.kind==="contradiction"&&o.proposed&&o.factId){let a=(s??=new G(e)).get(o.factId);a&&(i=[a.value,o.proposed.value])}return{key:`question:${o.id}`,kind:"question",title:ea(o),ask:o.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${o.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:o.agentId,created_at:o.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function ta(t){return Cr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:R(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function na(t){return dr(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:R(`Last try not sent: ${e.error}`)}:{}}))}function ra(t){let e=Object.entries(Xe(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Ee(t).agents??{};return e.map(([r,s])=>{let o=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${o.name||r}", created by ${s.by}`,ask:`Let ${o.name||r} (${o.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:s.by,created_at:s.at,detail:R(`Workspace: ${o.workspace||"?"}. Instructions: ${o.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Ee(t){try{return JSON.parse(at(J(t),"utf-8"))}catch{return{}}}function it(t){let e={};try{e=Object.fromEntries(kn(at(E(Vr(J(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function sa(t){let e=Hn(t.root,"pending");if(e.length===0)return[];let n=Ee(t),r=it(t);return e.map(s=>{let o=oe[s.platform]??s.platform;return{key:`content:${s.id}`,kind:"content",title:`${o} post${s.topic?`: ${s.topic}`:""}${s.date?` (for ${s.date})`:""}`,ask:`Publish this on ${o}? "${s.text}"`,yes:Fr({config:n,env:r},s.agent,s.platform)?`post it on ${o}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:s.agent,created_at:s.created_at,detail:R(`Follows your past posts: ${s.samples.join(", ")}`),more:`agentx content show ${s.id}`,text_hash:qn(s.text)}})}function V(t){if(t.requests)return t.requests;if(E(t.root)!==process.cwd()||!W(E(t.root,".agentx","db.sqlite")))return null;let e=qe({quiet:!0});if(!e)return null;let n=Br.get(e);return!n&&!mn(e)?null:(n||Br.set(e,n=new hn(e)),n)}var Br=new WeakMap;function dp(t){if(t.plans)return t.plans;if(t.requests||E(t.root)!==process.cwd()||!W(E(t.root,".agentx","db.sqlite")))return null;let e=qe({quiet:!0});if(!e||!jr(e))return null;let n=Hr.get(e);return n||Hr.set(e,n=new Se(e)),n}var Hr=new WeakMap;function oa(t){let e=V(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:H(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:R(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var Yr={card:Vi,schedule:zi,agent:ra,memory:Ki,wiki:Yi,fact:()=>[],question:Gr,whatsapp:ta,email:na,content:sa,request:oa};function ia(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function Jr(t,e={}){let n=t.now??Date.now(),{snoozed:r}=A(t.root),s=[],o=[],i=[],a=0;for(let c of e.kinds??Xr){if(c==="fact"){try{let d=Zi(t);d&&i.push(d)}catch(d){o.push({kind:c,error:String(d?.message??d).slice(0,200)})}continue}let l;try{l=Yr[c](t)}catch(d){o.push({kind:c,error:String(d?.message??d).slice(0,200)});continue}for(let d of l){let u=r[d.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){a++;continue}d.snoozed_until=u}s.push(d)}}return s.sort(ia),{items:s,snoozed:a,errors:o,backlog:i}}function Qr(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!Xr.includes(n)||!r?null:{kind:n,ref:r}}function aa(t,e,n){switch(e){case"card":return ie(t.root,n)?.status==="pending";case"wiki":return Qn(j(t),n)?.status==="pending";case"whatsapp":return ve(t.root,n)?.status==="pending";case"email":return lr(t.root,n)?.status==="pending";case"content":return Bn(t.root,n)?.status==="pending";default:return!!Zr(t,e,n)}}function Zr(t,e,n){return e==="fact"?Qi(t,n):Yr[e](t).find(r=>r.key===`${e}:${n}`)}async function es(t,e,n,r={}){let s=n==="later"?null:Qr(e),o;if(s)try{o=Zr(t,s.kind,s.ref)}catch{o=void 0}let i=await ca(t,e,n,r);if(i.ok&&s&&n!=="later"){let a=typeof r.choice=="number"?o?.choices?.[r.choice-1]:r.choice;sr(t.root,{key:e,kind:s.kind,title:o?.title??e,raised_by:o?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function ca(t,e,n,r){let s=Qr(e);if(!s)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:o,ref:i}=s,a=t.now??Date.now(),c=r.by??"operator";if(n==="later"){if(!aa(t,o,i))return{ok:!1,error:`nothing waiting for "${e}"`};let d=r.laterHours&&r.laterHours>0?r.laterHours:24,u=new Date(a+d*36e5);return Sr(t.root,e,u,a),{ok:!0,message:`${e} put off until ${u.toISOString()}`}}let l=n==="yes";switch(o){case"card":{let d=ar(t.root,i,l?"yes":"no",{by:c,note:r.note,now:a,choice:r.choice,text:r.text});return d.ok?{ok:!0,message:`${e}: ${d.card.raised_by} will be told ${l?"yes":"no"}${d.card.choice?` (${d.card.choice}${d.card.choice_suggested?", the suggested option":""})`:""}`}:d}case"schedule":{let d=await(l?Pn:Mn)(i,{configPath:J(t),reload:t.reload});return d.success?{ok:!0,message:d.message}:{ok:!1,error:d.message}}case"agent":{if(Xe(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return ze(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let d=[],u=await be(p=>{Tn(p,`agents.${i}`);for(let[g,f]of Object.entries(p.crons??{}))f?.agent===i&&(delete p.crons[g],d.push(g))},{configPath:J(t),reload:t.reload});return u.success?(ze(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${d.length?`, with its schedules ${d.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:u.error||"could not remove it from agentx.json"}}case"memory":{let d=i.indexOf("/");if(d<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let u=i.slice(0,d),p=i.slice(d+1);if(!zr(t.root).includes(u))return{ok:!1,error:`no memory for agent "${u}"`};let g=new Ve(t.root);return g.held(u).some(f=>f.id===p)?(g.review(u,p,l?"approved":"rejected",c),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let d=j(t),u=l?er(d,i,{by:c,force:r.force,now:a}):tr(d,i,{by:c,reason:r.note,now:a});return u.ok?{ok:!0,message:l?`${u.proposal.article.path} written to the shared wiki`:`${e} rejected`}:u}case"fact":return la(t,e,i,l,c,r);case"question":return ua(t,e,i,l,c,r);case"whatsapp":{let d=await Nr(t.root,i,l?"yes":"no",{by:c,now:a,send:t.sendWhatsApp});return d.ok?{ok:!0,message:l?`${e}: sent to ${d.draft.chat_name||d.draft.to}`:`${e}: dropped, nothing sent`}:d}case"email":{let d=t.sendEmail??pr(Ee(t),it(t)),u=await ur(t.root,i,l?"yes":"no",{by:c,now:a,text:r.text,send:d});return u.ok?{ok:!0,message:l?`${e}: sent to ${u.draft.to}${u.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:u}case"content":{let d=t.publishContent??Ur({config:Ee(t),env:it(t)}),u=await Vn(t.root,i,l?"yes":"no",{by:c,now:a,text:r.text,seen:r.seen,publish:d});if(!u.ok)return u;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let p=oe[u.draft.platform];return{ok:!0,message:u.draft.status==="posted"?`${e}: posted on ${p}${u.draft.url?` (${u.draft.url})`:""}`:`${e}: no ${p} connector is set, so it is saved ready to paste: ${u.draft.file}`}}case"request":{let d=V(t),u=d?.get(i);return!d||!u||u.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?_r(J(t)).enabled?(d.requestPickup(i,a),{ok:!0,message:`${e}: ${u.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(d.close(i,"dropped",r.note?.trim()||`dropped by ${c}`,a),{ok:!0,message:`${e}: dropped`})}}}function la(t,e,n,r,s,o){let i=new G(j(t));try{let a=we(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return In(i,a.id,s,o.note),{ok:!0,message:`${e}: claim dropped`};let c=Rn(i,a.id,s);return{ok:!0,message:`${e}: ${c.write.fact.subject} \xB7 ${c.write.fact.attribute} recorded as "${c.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function da(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(s=>s.toLowerCase()===r)}function ua(t,e,n,r,s,o){let i=j(t),a=new He(i),c=a.list("open").find(l=>l.id===n);if(!c)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(vn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(c.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=Gr(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${c.id} "<value>"`};let d=da(l.choices,o.choice);if(!d)return{ok:!1,error:`pick one of: ${l.choices.map((g,f)=>`${f+1}. ${g}`).join(", ")}`};let u=new G(i),p=c.factId?u.get(c.factId):void 0;return p&&u.write({subject:p.subject,attribute:p.attribute,value:d,source:"owner said",verifiedBy:s,volatility:p.volatility},{confirmedBy:s}),a.resolve(c.id,"answered",d),{ok:!0,message:`${e}: answered "${d}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var pa=3,ga=7,fa=50,lt=120,ma=280,ct=600,ns=36e5,ha=24*ns;function gp(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function Q(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var _e=t=>new Date(t).toISOString();function ba(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:Q(e.title,lt),...e.ask?{ask:Q(e.ask,ct)}:{},...e.detail?{facts:Q(e.detail,ma)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var ya={done:"Done",declined:"Declined",dropped:"Dropped"};function rs(t,e,n){let{record:r,links:s}=e,o=H(r,lt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:o.headline,need:o.need,...r.headline?{said:Q(o.said,ct)}:{},agent:r.agentId,askedAt:_e(r.createdAt),changedAt:_e(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return s.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:Q(r.question,ct)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=s.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),c=t.now-r.updatedAt<(t.quietHours??pa)*ns;return{...i,column:a||c?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:_e(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:ya[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function wa(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function xa(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:Q(e.title,lt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:wa(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var I=t=>t&&Date.parse(t)||0,ts=(t,e)=>t.map(n=>n[e]).filter(n=>!!I(n)).sort((n,r)=>I(n)-I(r))[0];function dt(t){let e=[],n=[];for(let s of t.inbox){s.error&&n.push(`What waits on ${s.nodeName} could not be read: ${s.error}`);for(let o of s.items)e.push(ba(s,o,s.node===t.node))}let r=ss(t,e);for(let s of t.requests??[]){let o=rs(t,s,r);o?.column==="yours"&&e.push(o)}return{cards:e,errors:n}}function ss(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function fp(t){let e=dt(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,s=ss(t,n),o=[],i=[],a=[];for(let p of t.requests??[]){let g=rs(t,p,s);g&&g.column!=="yours"&&{agent:o,quiet:i,done:a}[g.column].push(g)}let c=t.now-(t.doneDays??ga)*ha;for(let p of t.cards)p.status!=="pending"&&I(p.decided_at)>=c&&a.push(xa(t,p));o.sort((p,g)=>I(g.changedAt)-I(p.changedAt)),i.sort((p,g)=>I(p.changedAt)-I(g.changedAt)),a.sort((p,g)=>I(g.changedAt)-I(p.changedAt));let l=a.filter(p=>I(p.changedAt)>=c).slice(0,fa),d=ts(n,"askedAt"),u=ts(i,"changedAt");return{ts:_e(t.now),cards:[...n,...o,...i,...l],figures:{yours:{count:n.length,...d?{oldest:d}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:o.length},quiet:{count:i.length,...u?{oldest:u}:{}},done:{count:l.length}},errors:r}}function ka(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function va(t,e,n){let r=t.map(s=>s.askedAt).filter(s=>!!s&&!!Date.parse(s)).sort((s,o)=>Date.parse(s)-Date.parse(o));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function yp(t,e){let n=t.now??Date.now(),r=[],s=Jr(t,{includeSnoozed:!0});for(let d of s.errors)r.push(`What waits (${d.kind}) could not be read: ${d.error}`);let o=s.items.filter(d=>!d.snoozed_until),i=new Set(s.items.filter(d=>d.snoozed_until).map(d=>d.key)),a=null;try{let d=V(t);d&&(a=d.listByState("waiting_owner").map(u=>({record:u,links:d.links(u.id)})))}catch(d){r.push(`Requests could not be read: ${d?.message??d}`)}let{cards:c,errors:l}=dt({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:o.map(ka)}],requests:a,deferred:i});return va(c,i.size,[...r,...l])}import{readFileSync as Sa}from"fs";var Ea=1e4,os=/^[0-9a-f]{7,64}$/i;function kp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&os.test(i)?{source:n,commit:i}:{source:n,commit:null,error:"this build does not carry its commit (run from source?)"}}let r;try{r=await e(n,{signal:AbortSignal.timeout(Ea)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let s=await r.json().catch(()=>null),o=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,s);return typeof o=="string"&&os.test(o.trim())?{source:n,commit:o.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function vp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Sa(n.tokenFile,"utf-8").trim().split(`
68
+ `)[0].trim()||void 0}catch{}let s=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??s?.host??"https://gitlab.com",token:e?.gitlab?.token??s?.token}}}var is=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function Ep(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"}function _p(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/events"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/channels\/[^/]+\/switch$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"||t==="/api/signals/stop-all"||t==="/api/signals/stop-all/report"||t==="/api/review-gate/replay"}function Tp(t){return is.has(t)}function $p(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(is.has(t.remoteAddress))return{allowed:!0,reason:"loopback"};if(t.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.acceptedTokens.has(n)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function Ap(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let r of t.mesh?.peers||[])r.token&&n.add(r.token);return n}function Rp(t,e,n=process.env){let r=o=>o.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(o=>r(o.url)===e)?.token)||n.MESH_TOKEN||void 0}function Te(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function _a(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ta(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function Dp(t,e=Ta()){let n=Te(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let s=_a(n),o=[Te(t.host),Te(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return s&&o.includes(s)?"same-origin":"foreign"}let r=Te(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function Cp(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var ut="/api/admin/pictures",$a=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Aa=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function v(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function Ra(t){let e={agent:{},person:{}};for(let n of Xn)for(let[r,s]of Object.entries(Gn(t,n)))e[n][r]=Yn(n,r,s);return e}function Op(t,e,n,r,s){let o=n.match($a);if(!o)return!1;if((t.method||"GET").toUpperCase()!=="GET")return v(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(o[2]),a=Jn(s,o[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":zn,"Content-Length":String(a.length),"Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'"}),e.end(a),!0):(v(e,404,{error:"no such picture"}),!0)}async function Pp(t,e,n,r){if(n!==ut&&!n.startsWith(`${ut}/`))return!1;let s=(t.method||"GET").toUpperCase();if(n===ut)return s!=="GET"?(v(e,405,{error:"GET only"}),!0):(v(e,200,{...Ra(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let o=n.match(Aa);if(!o)return v(e,404,{error:"not found"}),!0;if(s!=="PUT"&&s!=="DELETE")return v(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return v(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=o[1],c=decodeURIComponent(o[2]),l=a==="agent"?r.agentIds():r.personIds();if(!Kn.test(c)||!l.includes(c))return v(e,404,{error:a==="agent"?`no agent "${c}" in agentx.json`:`no person "${c}" in agentx.json`}),!0;if(s==="DELETE"){let d=Je(r.root,a,c);return v(e,200,{ok:!0,removed:d}),!0}try{let d=await Qe(t),u=await Ye(r.root,a,c,d);v(e,200,{ok:!0,url:u.url})}catch(d){if(d instanceof Ge)return v(e,d.status,{error:d.message}),!0;throw d}return!0}async function Mp(t,e,n,r){let s=(t.method||"GET").toUpperCase();if(s!=="PUT"&&s!=="DELETE"){v(e,405,{error:"PUT or DELETE only"});return}let o=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(o);if(!i){v(e,403,{error:"Only an agent sets its own picture, from its own run: send X-AgentX-Task (or X-AgentX-Channel and X-AgentX-Chat) of a running turn. The owner sets pictures in Settings."});return}if(o&&o!==i){v(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${o}".`});return}if(s==="DELETE"){v(e,200,{ok:!0,agent:i,removed:Je(r.root,"agent",i)});return}try{let a=await Ye(r.root,"agent",i,await Qe(t));v(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof Ge){v(e,a.status,{error:a.message});return}throw a}}var as={};function Wp(t){as=t}function jp(){return as}var qp=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
69
69
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">
70
70
  <link rel="preconnect" href="https://fonts.googleapis.com">
71
71
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
72
72
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&family=Roboto+Mono:wght@400;500;600&display=swap" rel="stylesheet">
73
- <script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,Vp=`
73
+ <script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,Bp=`
74
74
  .ax-topbar{display:flex;align-items:center;justify-content:space-between;
75
75
  padding:8px 18px;border-bottom:1px solid var(--ax-border);
76
76
  background:var(--ax-bg-elev);position:sticky;top:0;z-index:20;gap:10px;flex-wrap:nowrap}
@@ -151,7 +151,7 @@ import{a as tt}from"./chunk-GTJIKXDB.js";import{H as rr,O as gr,k as H}from"./ch
151
151
  background:var(--ax-bg-elev);border-bottom:1px solid var(--ax-border);
152
152
  flex-wrap:wrap}
153
153
  .ax-subheader > * {flex-shrink:0}
154
- .ax-subheader .spacer{flex:1}`,Xp=`<script>
154
+ .ax-subheader .spacer{flex:1}`,Hp=`<script>
155
155
  (function(){
156
156
  function wireTheme(){
157
157
  var sw = document.querySelectorAll('[data-theme-opt]');
@@ -346,7 +346,7 @@ import{a as tt}from"./chunk-GTJIKXDB.js";import{H as rr,O as gr,k as H}from"./ch
346
346
  document.addEventListener('DOMContentLoaded', wire);
347
347
  } else { wire(); }
348
348
  })();
349
- </script>`;function zp(t){let e=n=>typeof n=="string"&&n?n:null;return{node:e(t?.node?.id),version:e(t?.version),commit:e(t?.commit),startedAt:e(t?.startedAt),diskNewer:t?.build?.newer===!0}}var Da='<span class="ax-build" hidden></span>';function Kp(t){let e=t.peers&&t.peers.length>0?t.peers:[{id:"local",name:"this daemon",dashboardUrl:"",primary:!0}],n=t.currentPeerId||e.find(l=>l.primary)?.id||e[0].id,r=e.find(l=>l.id===n)||e[0],s=e.map(l=>{let d=l.id===n,u=l.primary?' <span style="color:var(--ax-muted);font-size:10px">\xB7 primary</span>':"",p=!!l.tokenScope&&!l.primary,g=p?"#":l.dashboardUrl?`${l.dashboardUrl.replace(/\/+$/,"")}/admin`:"#",f=p?` data-peer-id="${M(l.id)}" data-peer-action="proxy"`:l.primary?' data-peer-id="primary" data-peer-action="proxy"':"",b=p?'<div class="url" style="color:var(--ax-accent)">manage from this dashboard \u2713</div>':l.tokenScope?`<div class="url">${M(l.tokenScope)}</div>`:l.dashboardUrl?'<div class="url" style="color:var(--ax-muted)">(open peer dashboard \u2197)</div>':"";return`<a href="${M(g)}" class="${d?"is-current":""}"${f}>
349
+ </script>`;function Vp(t){let e=n=>typeof n=="string"&&n?n:null;return{node:e(t?.node?.id),version:e(t?.version),commit:e(t?.commit),startedAt:e(t?.startedAt),diskNewer:t?.build?.newer===!0}}var Ia='<span class="ax-build" hidden></span>';function Xp(t){let e=t.peers&&t.peers.length>0?t.peers:[{id:"local",name:"this daemon",dashboardUrl:"",primary:!0}],n=t.currentPeerId||e.find(l=>l.primary)?.id||e[0].id,r=e.find(l=>l.id===n)||e[0],s=e.map(l=>{let d=l.id===n,u=l.primary?' <span style="color:var(--ax-muted);font-size:10px">\xB7 primary</span>':"",p=!!l.tokenScope&&!l.primary,g=p?"#":l.dashboardUrl?`${l.dashboardUrl.replace(/\/+$/,"")}/admin`:"#",f=p?` data-peer-id="${M(l.id)}" data-peer-action="proxy"`:l.primary?' data-peer-id="primary" data-peer-action="proxy"':"",b=p?'<div class="url" style="color:var(--ax-accent)">manage from this dashboard \u2713</div>':l.tokenScope?`<div class="url">${M(l.tokenScope)}</div>`:l.dashboardUrl?'<div class="url" style="color:var(--ax-muted)">(open peer dashboard \u2197)</div>':"";return`<a href="${M(g)}" class="${d?"is-current":""}"${f}>
350
350
  <div class="row"><span class="dot"></span><span>${M(l.name)}${u}</span></div>
351
351
  ${l.dashboardUrl?`<div class="url">${M(l.dashboardUrl)}</div>`:""}
352
352
  ${b}
@@ -355,7 +355,7 @@ import{a as tt}from"./chunk-GTJIKXDB.js";import{H as rr,O as gr,k as H}from"./ch
355
355
  <span class="name">${M(r.name)}</span>
356
356
  <span class="chev">\u25BE</span>
357
357
  <div class="ax-mesh-menu" role="menu">${s}</div>
358
- </div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:he,href:re},{id:"live",label:"Live",href:`${re}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:_n},{id:"people",label:"People",href:`${re}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:`${re}#page=settings`}]}].map(l=>{let d=l.tabs.map(u=>{let p=u.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=u.external?' target="_blank" rel="noopener"':"",f=u.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${u.href}" class="${p}"${g}>${u.label}${f}</a>`}).join("");return`<div class="ax-topbar__group" title="${M(l.name)} tier"><span class="ax-topbar__group-label">${M(l.name)}</span>${d}</div>`}).join("");return`<header class="ax-topbar">
358
+ </div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:he,href:re},{id:"live",label:"Live",href:`${re}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:En},{id:"people",label:"People",href:`${re}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:`${re}#page=settings`}]}].map(l=>{let d=l.tabs.map(u=>{let p=u.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=u.external?' target="_blank" rel="noopener"':"",f=u.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${u.href}" class="${p}"${g}>${u.label}${f}</a>`}).join("");return`<div class="ax-topbar__group" title="${M(l.name)} tier"><span class="ax-topbar__group-label">${M(l.name)}</span>${d}</div>`}).join("");return`<header class="ax-topbar">
359
359
  <div class="ax-topbar__left">
360
360
  <div class="ax-brand">
361
361
  <span class="ax-brand__mark">AX</span>
@@ -366,14 +366,14 @@ import{a as tt}from"./chunk-GTJIKXDB.js";import{H as rr,O as gr,k as H}from"./ch
366
366
  </div>
367
367
  <div class="ax-topbar__right">
368
368
  ${t.rightExtras||""}
369
- ${Da}
369
+ ${Ia}
370
370
  ${o}
371
371
  <div class="ax-theme-switch" role="tablist" aria-label="Theme">
372
372
  <button data-theme-opt="dark">Dark</button>
373
373
  <button data-theme-opt="light">Light</button>
374
374
  </div>
375
375
  </div>
376
- </header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function M(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}import{existsSync as Cs,mkdirSync as ic,readFileSync as ac,renameSync as cc,writeFileSync as lc}from"fs";import{homedir as dc}from"os";import{dirname as uc,join as pc}from"path";import{execFile as qa,execFileSync as Ba}from"child_process";import{execFileSync as Ca}from"child_process";import{existsSync as ls,mkdirSync as Na,readdirSync as La,readFileSync as ds,renameSync as Oa,writeFileSync as Pa}from"fs";import{homedir as us}from"os";import{join as ft}from"path";var D="siri:",ps="com.apple.ttsbundle.gryphon-neural_",gs=t=>!!t&&t.startsWith(ps),Ma=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],Fa=()=>{try{return Ca("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},gt;function mt(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&gt!==void 0)return gt;let{platform:n=process.platform,exists:r=ls,prefDomain:s=Fa}=t,o=n==="darwin"&&Ma.every(i=>r(i))&&s();return e||(gt=o),o}var fs=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],ms={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},ht=t=>ms[t.toLowerCase()]??null;function Te(t){let e=/^com\.apple\.ttsbundle\.gryphon-neural_([a-z]+)_([a-z]{2}-[A-Z]{2})_premium$/.exec(t);return e?{name:e[1],locale:e[2]}:null}var Ua=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function Wa(t){let e=new Map;for(let n of t)for(let[,r,s,o]of n.matchAll(Ua)){let i=`${r}-${s}`,a=`${ps}${o}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:o[0].toUpperCase()+o.slice(1),locale:i,quality:"premium",gender:ms[o]??null,siri:!0})}return[...e.values()]}function Ae(t=fs,e={}){if(!mt(e))return[];let n=[];for(let r of t){let s;try{s=La(r)}catch{continue}for(let o of s)try{n.push(ds(ft(r,o,"Info.plist"),"latin1"))}catch{}}return Wa(n)}var cs=`#!/bin/sh
376
+ </header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function M(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}import{existsSync as Cs,mkdirSync as oc,readFileSync as ic,renameSync as ac,writeFileSync as cc}from"fs";import{homedir as lc}from"os";import{dirname as dc,join as uc}from"path";import{execFile as ja,execFileSync as qa}from"child_process";import{execFileSync as Da}from"child_process";import{existsSync as ls,mkdirSync as Ca,readdirSync as Na,readFileSync as ds,renameSync as La,writeFileSync as Oa}from"fs";import{homedir as us}from"os";import{join as gt}from"path";var D="siri:",ps="com.apple.ttsbundle.gryphon-neural_",gs=t=>!!t&&t.startsWith(ps),Pa=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],Ma=()=>{try{return Da("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},pt;function ft(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&pt!==void 0)return pt;let{platform:n=process.platform,exists:r=ls,prefDomain:s=Ma}=t,o=n==="darwin"&&Pa.every(i=>r(i))&&s();return e||(pt=o),o}var fs=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],ms={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},mt=t=>ms[t.toLowerCase()]??null;function $e(t){let e=/^com\.apple\.ttsbundle\.gryphon-neural_([a-z]+)_([a-z]{2}-[A-Z]{2})_premium$/.exec(t);return e?{name:e[1],locale:e[2]}:null}var Fa=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function Ua(t){let e=new Map;for(let n of t)for(let[,r,s,o]of n.matchAll(Fa)){let i=`${r}-${s}`,a=`${ps}${o}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:o[0].toUpperCase()+o.slice(1),locale:i,quality:"premium",gender:ms[o]??null,siri:!0})}return[...e.values()]}function Ae(t=fs,e={}){if(!ft(e))return[];let n=[];for(let r of t){let s;try{s=Na(r)}catch{continue}for(let o of s)try{n.push(ds(gt(r,o,"Info.plist"),"latin1"))}catch{}}return Ua(n)}var cs=`#!/bin/sh
377
377
  # Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
378
378
  # siri-say.sh [voice] < text speak one line. A Siri voice id switches
379
379
  # the OS default for it; any other id is
@@ -478,20 +478,20 @@ wait "$say_pid"
478
478
  status=$?
479
479
  say_pid=
480
480
  finish $status
481
- `,ja=(t=us())=>ft(t,".agentx","voice","siri-say.sh");function hs(t=us()){let e=ja(t);return ls(e)&&ds(e,"utf8")===cs||(Na(ft(t,".agentx","voice"),{recursive:!0}),Pa(`${e}.tmp`,cs,{mode:493}),Oa(`${e}.tmp`,e)),e}var bs=`ObjC.import("AVFoundation")
481
+ `,Wa=(t=us())=>gt(t,".agentx","voice","siri-say.sh");function hs(t=us()){let e=Wa(t);return ls(e)&&ds(e,"utf8")===cs||(Ca(gt(t,".agentx","voice"),{recursive:!0}),Oa(`${e}.tmp`,cs,{mode:493}),La(`${e}.tmp`,e)),e}var bs=`ObjC.import("AVFoundation")
482
482
  const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
483
483
  for (let i = 0; i < vs.count; i++) {
484
484
  const v = vs.objectAtIndex(i)
485
485
  out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
486
486
  }
487
- out.join("\\n")`,Ha=new Set(["Fred","Kathy","Ralph","Junior"]),Va={Flo:"female",Sandy:"female",Shelley:"female",Grandma:"female",Kathy:"female",Eddy:"male",Reed:"male",Rocko:"male",Grandpa:"male",Fred:"male",Ralph:"male",Junior:"male"};function ys(t){let e=[];for(let n of t.split(`
488
- `)){let[r,s,o,i,a]=n.split(" ");!r||!s||!o||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!Ha.has(s)||e.push({id:r,name:s,locale:o,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":Va[s]??null})}return e}var Xa=10*60*1e3,rg=60*1e3,Q=null,bt=!1;function yt(t=Date.now(),e=Xa){if(process.platform!=="darwin")return[];if(Q)t-Q.at>e&&!bt&&(bt=!0,qa("osascript",["-l","JavaScript","-e",bs],{timeout:1e4},(n,r)=>{bt=!1,n||(Q={at:Date.now(),voices:[...ys(String(r)),...Ae()]})}));else try{Q={at:t,voices:[...ys(Ba("osascript",["-l","JavaScript","-e",bs],{encoding:"utf8",timeout:1e4})),...Ae()]}}catch(n){wt(`[voice] could not list system voices: ${String(n?.message??n).split(`
489
- `)[0]}`),Q={at:t,voices:Ae()}}return Q.voices}var wt=t=>process.stderr.write(t+`
490
- `),Re=new Set;function sg(t){wt=t}function X(t,e){Re.has(t)||(Re.add(t),wt(e))}function ks(t){for(let e of Re)t(e)&&Re.delete(e)}var vs=()=>{};function og(t){vs=t}function Ss(t){try{vs(t)}catch(e){X("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var za={premium:3,enhanced:2,standard:1},Ka=new Set(["Grandma","Grandpa"]);function ws(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!Ka.has(t.name)?1:0;return za[t.quality]*10+e}var ee=t=>t.toLowerCase().split(/[-_]/)[0],xs=t=>t.id.startsWith("com.apple.voice.");function xt(t,e,n,r=new Set){let s=ce(t.filter(a=>!a.siri&&ee(a.locale)===ee(e)),e);if(s.some(xs)&&(s=s.filter(xs)),n==="female"||n==="male"){let a=s.filter(c=>c.gender===n);a.length&&(s=a)}if(!s.length)return null;let o=s.filter(a=>a.quality===s[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return o.find(a=>!i.has(a.name.toLowerCase()))??o[0]}function ce(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=ee(e),s=t.filter(o=>ee(o.locale)===r);return(s.length?s:t).slice().sort((o,i)=>ws(i)-ws(o)||+(i.locale.toLowerCase()===n)-+(o.locale.toLowerCase()===n)||o.name.localeCompare(i.name)||o.locale.localeCompare(i.locale))}function le(t,e,n="en"){let r=t.trim();if(!r)return null;let s=e.find(l=>l.id===r);if(s)return s;if(r.toLowerCase().startsWith(D)){let l=r.slice(D.length).trim().toLowerCase(),d=ce(e.filter(p=>p.siri&&p.name.toLowerCase()===l),n)[0];if(d||!l)return d??null;let u=le(l,e.filter(p=>ee(p.locale)===ee(n)),n);return u&&X(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${u.name} (${u.locale}) instead.`),u}e=e.filter(l=>!l.siri);let o=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(o?o[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=ce(e.filter(l=>l.name.toLowerCase()===i),n);return(o?a.find(l=>l.quality===o[2].toLowerCase()):void 0)??a[0]??null}function Es(t,e,n=new Set){let r=new Map;if(!e.length)return r;let s=new Set([...n].map(i=>i.toLowerCase())),o="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",c=a?i.gender:o,l=e.filter(u=>!s.has(u.name.toLowerCase())),d=l.find(u=>u.gender===c)??(a?e.find(u=>u.gender===c):void 0)??l[0]??e[r.size%e.length];r.set(i.id,d),s.add(d.name.toLowerCase()),a||(o=o==="female"?"male":"female")}return r}un();var kt="system",Ga=t=>t.trim().toLowerCase()===kt,Ya="21m00Tcm4TlvDq8ikWAM";function vt(t,e,n={},r=yt()){let s=e[t],o=s?.name||t,i=s?.voice,a=Et(e,n,r).get(t)??null,c=ec(t,i?.system,i?.gender,n,r);return{agentId:t,name:o,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?De(a):null,systemByLanguage:c,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||nc(o,s?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var De=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function Ja(t,e,n,r){if(!e||!n.length)return null;let s=le(e,n,r);return s||(X(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Ss(e)),s}function As(t,e){let n=t.trim();if(n.toLowerCase().startsWith(D))return{locale:e,gender:ht(n.slice(D.length).trim())};let r=Te(n);return r?{locale:r.locale,gender:ht(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var Rs=t=>t.toLowerCase().split(/[-_]/)[0],_s=(t,e)=>typeof t=="string"?t:t?.[Rs(e)];function Ie(t,e,n,r){if(e!==void 0)return Ga(e)?null:Ja(t,e,n,r)??void 0}var St=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function Za(t,e,n,r=new Set){let s=e.locale??"en",o=new Map,i=[],a=Ie("voice.system",_s(e.system,s),n,s),c=()=>new Set([...r,...[...o.values()].flatMap(d=>d?[d.name]:[])]);for(let d of t){let u=_s(d.system,s),p=Ie(d.id,u,n,s),g=p!==void 0?p:u!==void 0&&n.length?Qa(d,u,s,a,n,c()):a!==void 0&&St(a,d.gender)?a:void 0;g!==void 0?o.set(d.id,g):i.push({id:d.id,gender:d.gender??null})}let l=c();for(let[d,u]of Es(i,ce(n.filter(p=>!p.siri),s),l))o.set(d,u);return o}function Qa(t,e,n,r,s,o){for(let a of t.fallbacks??[]){let c=Ie(`${t.id}.fallbacks`,a,s,n);if(c!==void 0)return c}if(r!==void 0&&St(r,t.gender))return r;let i=As(e,n);return xt(s,i.locale,t.gender??i.gender,o)??void 0}function ec(t,e,n,r,s){if(typeof e=="string")return{};let o={},i=(a,c,l)=>{if(!(!c||typeof c=="string"))for(let[d,u]of Object.entries(c)){let p=Ie(`${a}.${d}`,u,s,d);p===void 0&&s.length&&(p=xt(s,d,n??As(u,d).gender)??void 0),p!==void 0&&l(p)&&(o[Rs(d)]=p)}};return i("voice.system",r.system,a=>St(a,n)),i(t,e,()=>!0),o}function dg(t,e){let n=e?me(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?De(r):null}}function Et(t,e={},n=yt()){let r=Object.entries(t).map(([s,o])=>({id:s,system:o.voice?.system,gender:o.voice?.gender,fallbacks:o.voice?.fallbacks}));return Za(r,e,n)}function _t(t,e){let n={provider:t.provider,elevenlabs:tc(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([s,o])=>[s,o?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function tc(t,e){return t||e||process.env.AGENTX_VOICE_ID||Ya}function nc(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let s=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[o,...i]=s.split(/,\s*/),a=i.join(", ");return a&&o.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(s)&&s.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${s}.`:`Hello, this is ${t}, ${s}.`}var rc=8*60*60*1e3,sc=500,$s=class{constructor(e=rc){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let s=this.lastSpoke.get(Ts(e,n));return s===void 0||r-s>this.gapMs}spoke(e,n,r=Date.now()){let s=Ts(e,n);this.lastSpoke.delete(s),this.lastSpoke.set(s,r),this.lastSpoke.size>sc&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},Ts=(t,e)=>`${t}\0${e}`;function Is(t,e){let n=t.style?` Your speaking manner: ${t.style}.`:"";return e?`[VOICE INTRO] This is your first spoken exchange with this person in a while. Open with one short sentence introducing yourself in your own manner, along the lines of "${t.intro}", then answer.${n}`:"[VOICE CASUAL] You have already introduced yourself in this voice conversation. Do not introduce yourself or greet again; talk casually, like a colleague in the same office."+n}function ug(t,e,n,r={}){let s=e[t],o=vt(t,e,r),i=(s?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:o.name,voice:_t(o),persona:i||`You are ${o.name}.`,introLine:Is(o,n)}}var oc="[VOICE MODE] This question arrived by voice and your reply will be spoken aloud by a TTS engine. Answer in two or three short sentences. Plain language, no markdown, no code blocks, no bullet points, no URLs. Speak conversationally.";function pg(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=o=>typeof o=="string"?o.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),s={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:r||"Hello."};return`${oc}
491
- ${Is(s,e.voice.introduce===!0&&!!r)}`}var gc="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Ns=(t=dc())=>pc(t,".agentx","voice","health.json");function fc(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===kt)return!0;if(r.toLowerCase().startsWith(D)){let s=r.slice(D.length).trim().toLowerCase();return e.some(o=>o.siri&&o.name.toLowerCase()===s)}return le(r,e,n)!==null}function mc(t){let e=t.voice?.locale??"en",n=[],r=(s,o)=>{if(typeof o=="string")n.push({owner:s,name:o,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(o??{}))n.push({owner:s,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[s,o]of Object.entries(t.agents))(o.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(s,o.voice?.system);return n}function hc(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:s,name:o,locale:i,perLanguage:a}of mc(t)){if(fc(o,e,i))continue;r??=Et(t.agents,t.voice,e);let c=n.get(o)??{voice:o,agents:[],speaksWith:{}};c.agents.includes(s)||c.agents.push(s);let l=r.get(s);s!=="voice.system"&&!a&&(c.speaksWith[s]=l?De(l):"the OS default voice"),n.set(o,c)}return[...n.values()]}function $t(t){let e=Te(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(D)){let n=t.slice(D.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function bc(t){let e=t.map(n=>{let r=n.agents.map(s=>n.speaksWith[s]?`${s} (now ${n.speaksWith[s]})`:s).join(", ");return`\u2022 ${$t(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
487
+ out.join("\\n")`,Ba=new Set(["Fred","Kathy","Ralph","Junior"]),Ha={Flo:"female",Sandy:"female",Shelley:"female",Grandma:"female",Kathy:"female",Eddy:"male",Reed:"male",Rocko:"male",Grandpa:"male",Fred:"male",Ralph:"male",Junior:"male"};function ys(t){let e=[];for(let n of t.split(`
488
+ `)){let[r,s,o,i,a]=n.split(" ");!r||!s||!o||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!Ba.has(s)||e.push({id:r,name:s,locale:o,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":Ha[s]??null})}return e}var Va=10*60*1e3,tg=60*1e3,Z=null,ht=!1;function bt(t=Date.now(),e=Va){if(process.platform!=="darwin")return[];if(Z)t-Z.at>e&&!ht&&(ht=!0,ja("osascript",["-l","JavaScript","-e",bs],{timeout:1e4},(n,r)=>{ht=!1,n||(Z={at:Date.now(),voices:[...ys(String(r)),...Ae()]})}));else try{Z={at:t,voices:[...ys(qa("osascript",["-l","JavaScript","-e",bs],{encoding:"utf8",timeout:1e4})),...Ae()]}}catch(n){yt(`[voice] could not list system voices: ${String(n?.message??n).split(`
489
+ `)[0]}`),Z={at:t,voices:Ae()}}return Z.voices}var yt=t=>process.stderr.write(t+`
490
+ `),Re=new Set;function ng(t){yt=t}function X(t,e){Re.has(t)||(Re.add(t),yt(e))}function ks(t){for(let e of Re)t(e)&&Re.delete(e)}var vs=()=>{};function rg(t){vs=t}function Ss(t){try{vs(t)}catch(e){X("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var Xa={premium:3,enhanced:2,standard:1},za=new Set(["Grandma","Grandpa"]);function ws(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!za.has(t.name)?1:0;return Xa[t.quality]*10+e}var ee=t=>t.toLowerCase().split(/[-_]/)[0],xs=t=>t.id.startsWith("com.apple.voice.");function wt(t,e,n,r=new Set){let s=ce(t.filter(a=>!a.siri&&ee(a.locale)===ee(e)),e);if(s.some(xs)&&(s=s.filter(xs)),n==="female"||n==="male"){let a=s.filter(c=>c.gender===n);a.length&&(s=a)}if(!s.length)return null;let o=s.filter(a=>a.quality===s[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return o.find(a=>!i.has(a.name.toLowerCase()))??o[0]}function ce(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=ee(e),s=t.filter(o=>ee(o.locale)===r);return(s.length?s:t).slice().sort((o,i)=>ws(i)-ws(o)||+(i.locale.toLowerCase()===n)-+(o.locale.toLowerCase()===n)||o.name.localeCompare(i.name)||o.locale.localeCompare(i.locale))}function le(t,e,n="en"){let r=t.trim();if(!r)return null;let s=e.find(l=>l.id===r);if(s)return s;if(r.toLowerCase().startsWith(D)){let l=r.slice(D.length).trim().toLowerCase(),d=ce(e.filter(p=>p.siri&&p.name.toLowerCase()===l),n)[0];if(d||!l)return d??null;let u=le(l,e.filter(p=>ee(p.locale)===ee(n)),n);return u&&X(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${u.name} (${u.locale}) instead.`),u}e=e.filter(l=>!l.siri);let o=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(o?o[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=ce(e.filter(l=>l.name.toLowerCase()===i),n);return(o?a.find(l=>l.quality===o[2].toLowerCase()):void 0)??a[0]??null}function Es(t,e,n=new Set){let r=new Map;if(!e.length)return r;let s=new Set([...n].map(i=>i.toLowerCase())),o="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",c=a?i.gender:o,l=e.filter(u=>!s.has(u.name.toLowerCase())),d=l.find(u=>u.gender===c)??(a?e.find(u=>u.gender===c):void 0)??l[0]??e[r.size%e.length];r.set(i.id,d),s.add(d.name.toLowerCase()),a||(o=o==="female"?"male":"female")}return r}dn();var xt="system",Ka=t=>t.trim().toLowerCase()===xt,Ga="21m00Tcm4TlvDq8ikWAM";function kt(t,e,n={},r=bt()){let s=e[t],o=s?.name||t,i=s?.voice,a=St(e,n,r).get(t)??null,c=Za(t,i?.system,i?.gender,n,r);return{agentId:t,name:o,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?De(a):null,systemByLanguage:c,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||tc(o,s?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var De=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function Ya(t,e,n,r){if(!e||!n.length)return null;let s=le(e,n,r);return s||(X(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Ss(e)),s}function As(t,e){let n=t.trim();if(n.toLowerCase().startsWith(D))return{locale:e,gender:mt(n.slice(D.length).trim())};let r=$e(n);return r?{locale:r.locale,gender:mt(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var Rs=t=>t.toLowerCase().split(/[-_]/)[0],_s=(t,e)=>typeof t=="string"?t:t?.[Rs(e)];function Ie(t,e,n,r){if(e!==void 0)return Ka(e)?null:Ya(t,e,n,r)??void 0}var vt=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function Ja(t,e,n,r=new Set){let s=e.locale??"en",o=new Map,i=[],a=Ie("voice.system",_s(e.system,s),n,s),c=()=>new Set([...r,...[...o.values()].flatMap(d=>d?[d.name]:[])]);for(let d of t){let u=_s(d.system,s),p=Ie(d.id,u,n,s),g=p!==void 0?p:u!==void 0&&n.length?Qa(d,u,s,a,n,c()):a!==void 0&&vt(a,d.gender)?a:void 0;g!==void 0?o.set(d.id,g):i.push({id:d.id,gender:d.gender??null})}let l=c();for(let[d,u]of Es(i,ce(n.filter(p=>!p.siri),s),l))o.set(d,u);return o}function Qa(t,e,n,r,s,o){for(let a of t.fallbacks??[]){let c=Ie(`${t.id}.fallbacks`,a,s,n);if(c!==void 0)return c}if(r!==void 0&&vt(r,t.gender))return r;let i=As(e,n);return wt(s,i.locale,t.gender??i.gender,o)??void 0}function Za(t,e,n,r,s){if(typeof e=="string")return{};let o={},i=(a,c,l)=>{if(!(!c||typeof c=="string"))for(let[d,u]of Object.entries(c)){let p=Ie(`${a}.${d}`,u,s,d);p===void 0&&s.length&&(p=wt(s,d,n??As(u,d).gender)??void 0),p!==void 0&&l(p)&&(o[Rs(d)]=p)}};return i("voice.system",r.system,a=>vt(a,n)),i(t,e,()=>!0),o}function cg(t,e){let n=e?me(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?De(r):null}}function St(t,e={},n=bt()){let r=Object.entries(t).map(([s,o])=>({id:s,system:o.voice?.system,gender:o.voice?.gender,fallbacks:o.voice?.fallbacks}));return Ja(r,e,n)}function Et(t,e){let n={provider:t.provider,elevenlabs:ec(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([s,o])=>[s,o?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function ec(t,e){return t||e||process.env.AGENTX_VOICE_ID||Ga}function tc(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let s=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[o,...i]=s.split(/,\s*/),a=i.join(", ");return a&&o.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(s)&&s.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${s}.`:`Hello, this is ${t}, ${s}.`}var nc=8*60*60*1e3,rc=500,Ts=class{constructor(e=nc){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let s=this.lastSpoke.get($s(e,n));return s===void 0||r-s>this.gapMs}spoke(e,n,r=Date.now()){let s=$s(e,n);this.lastSpoke.delete(s),this.lastSpoke.set(s,r),this.lastSpoke.size>rc&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},$s=(t,e)=>`${t}\0${e}`;function Is(t,e){let n=t.style?` Your speaking manner: ${t.style}.`:"";return e?`[VOICE INTRO] This is your first spoken exchange with this person in a while. Open with one short sentence introducing yourself in your own manner, along the lines of "${t.intro}", then answer.${n}`:"[VOICE CASUAL] You have already introduced yourself in this voice conversation. Do not introduce yourself or greet again; talk casually, like a colleague in the same office."+n}function lg(t,e,n,r={}){let s=e[t],o=kt(t,e,r),i=(s?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:o.name,voice:Et(o),persona:i||`You are ${o.name}.`,introLine:Is(o,n)}}var sc="[VOICE MODE] This question arrived by voice and your reply will be spoken aloud by a TTS engine. Answer in two or three short sentences. Plain language, no markdown, no code blocks, no bullet points, no URLs. Speak conversationally.";function dg(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=o=>typeof o=="string"?o.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),s={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:r||"Hello."};return`${sc}
491
+ ${Is(s,e.voice.introduce===!0&&!!r)}`}var pc="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Ns=(t=lc())=>uc(t,".agentx","voice","health.json");function gc(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===xt)return!0;if(r.toLowerCase().startsWith(D)){let s=r.slice(D.length).trim().toLowerCase();return e.some(o=>o.siri&&o.name.toLowerCase()===s)}return le(r,e,n)!==null}function fc(t){let e=t.voice?.locale??"en",n=[],r=(s,o)=>{if(typeof o=="string")n.push({owner:s,name:o,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(o??{}))n.push({owner:s,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[s,o]of Object.entries(t.agents))(o.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(s,o.voice?.system);return n}function mc(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:s,name:o,locale:i,perLanguage:a}of fc(t)){if(gc(o,e,i))continue;r??=St(t.agents,t.voice,e);let c=n.get(o)??{voice:o,agents:[],speaksWith:{}};c.agents.includes(s)||c.agents.push(s);let l=r.get(s);s!=="voice.system"&&!a&&(c.speaksWith[s]=l?De(l):"the OS default voice"),n.set(o,c)}return[...n.values()]}function _t(t){let e=$e(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(D)){let n=t.slice(D.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function hc(t){let e=t.map(n=>{let r=n.agents.map(s=>n.speaksWith[s]?`${s} (now ${n.speaksWith[s]})`:s).join(", ");return`\u2022 ${_t(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
492
492
  `)}
493
- Reinstall in ${gc}. Agents switch back on their own once it is installed.`}}function yc(t=Ns()){if(!Cs(t))return null;try{let e=JSON.parse(ac(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function wc(t,e){ic(uc(t),{recursive:!0}),lc(`${t}.tmp`,JSON.stringify(e,null,2)+`
494
- `),cc(`${t}.tmp`,t)}var Ds=class{constructor(e){this.deps=e}running=!1;missingNow=!1;hasMissing(){return this.missingNow}async check(e,n,r=new Date){if(this.running||!n.length)return null;this.running=!0;try{let s=this.deps.file??Ns(),o=new Map((yc(s)?.missing??[]).map(u=>[u.voice,u])),i=hc(e,n),a=i.map(u=>({...u,since:o.get(u.voice)?.since??r.toISOString(),...o.get(u.voice)?.notifiedAt?{notifiedAt:o.get(u.voice).notifiedAt}:{}})),c=[...o.keys()].filter(u=>!i.some(p=>p.voice===u));for(let u of c)this.deps.log(`[voice] ${$t(u)} is installed again; its agents speak with it again`);c.length&&ks(u=>c.some(p=>u===p||u.endsWith(`:${p}`)));let l=a.filter(u=>!u.notifiedAt);if(l.length){let{title:u,message:p}=bc(l);try{await this.deps.notify(u,p);for(let g of l)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${l.map(g=>$t(g.voice)).join(", ")} not installed`)}catch(g){this.deps.log(`[voice] could not send the missing-voice notice: ${g?.message??g}`)}}this.missingNow=a.length>0;let d={checkedAt:r.toISOString(),missing:a};return(!Cs(s)||JSON.stringify(a)!==JSON.stringify([...o.values()]))&&wc(s,d),d}finally{this.running=!1}}};import{randomBytes as Ls}from"crypto";var z={content:32e3,messagesPerConversation:200,conversationsPerDevice:100,toolsPerMessage:50,filesPerMessage:P.perMessage},xc=/^[a-f0-9]{32}$/,kc=/^c[a-z0-9]{8,32}$/,vc=/^#[0-9a-fA-F]{6}$/;function Tt(t){return kc.test(t)}var Os=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS app_chat_conversations (
493
+ Reinstall in ${pc}. Agents switch back on their own once it is installed.`}}function bc(t=Ns()){if(!Cs(t))return null;try{let e=JSON.parse(ic(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function yc(t,e){oc(dc(t),{recursive:!0}),cc(`${t}.tmp`,JSON.stringify(e,null,2)+`
494
+ `),ac(`${t}.tmp`,t)}var Ds=class{constructor(e){this.deps=e}running=!1;missingNow=!1;hasMissing(){return this.missingNow}async check(e,n,r=new Date){if(this.running||!n.length)return null;this.running=!0;try{let s=this.deps.file??Ns(),o=new Map((bc(s)?.missing??[]).map(u=>[u.voice,u])),i=mc(e,n),a=i.map(u=>({...u,since:o.get(u.voice)?.since??r.toISOString(),...o.get(u.voice)?.notifiedAt?{notifiedAt:o.get(u.voice).notifiedAt}:{}})),c=[...o.keys()].filter(u=>!i.some(p=>p.voice===u));for(let u of c)this.deps.log(`[voice] ${_t(u)} is installed again; its agents speak with it again`);c.length&&ks(u=>c.some(p=>u===p||u.endsWith(`:${p}`)));let l=a.filter(u=>!u.notifiedAt);if(l.length){let{title:u,message:p}=hc(l);try{await this.deps.notify(u,p);for(let g of l)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${l.map(g=>_t(g.voice)).join(", ")} not installed`)}catch(g){this.deps.log(`[voice] could not send the missing-voice notice: ${g?.message??g}`)}}this.missingNow=a.length>0;let d={checkedAt:r.toISOString(),missing:a};return(!Cs(s)||JSON.stringify(a)!==JSON.stringify([...o.values()]))&&yc(s,d),d}finally{this.running=!1}}};import{randomBytes as Ls}from"crypto";var z={content:32e3,messagesPerConversation:200,conversationsPerDevice:100,toolsPerMessage:50,filesPerMessage:P.perMessage},wc=/^[a-f0-9]{32}$/,xc=/^c[a-z0-9]{8,32}$/,kc=/^#[0-9a-fA-F]{6}$/;function Tt(t){return xc.test(t)}var Os=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS app_chat_conversations (
495
495
  id TEXT PRIMARY KEY, device_id TEXT NOT NULL, title TEXT NOT NULL,
496
496
  node TEXT NOT NULL, node_name TEXT NOT NULL, agent TEXT NOT NULL, agent_name TEXT,
497
497
  created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
@@ -504,8 +504,8 @@ Reinstall in ${gc}. Agents switch back on their own once it is installed.`}}func
504
504
  id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, message_id INTEGER NOT NULL,
505
505
  path TEXT NOT NULL, name TEXT NOT NULL, mime TEXT NOT NULL, kind TEXT NOT NULL, created_at INTEGER NOT NULL);
506
506
  CREATE INDEX IF NOT EXISTS app_chat_files_conversation ON app_chat_files(conversation_id);`),e.prepare("PRAGMA table_info(app_chat_messages)").all().some(s=>s.name==="files")||e.exec("ALTER TABLE app_chat_messages ADD COLUMN files TEXT");let r=e.prepare("PRAGMA table_info(app_chat_conversations)").all();r.some(s=>s.name==="read_at")||e.transaction(()=>{e.prepare("PRAGMA table_info(app_chat_conversations)").all().some(o=>o.name==="read_at")||(e.exec("ALTER TABLE app_chat_conversations ADD COLUMN read_at INTEGER"),e.exec("UPDATE app_chat_conversations SET read_at = updated_at"))}).immediate(),r.some(s=>s.name==="color")||e.exec("ALTER TABLE app_chat_conversations ADD COLUMN color TEXT"),e.exec(`CREATE TABLE IF NOT EXISTS app_chat_delivered (
507
- key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return Tt(e)?this.db.prepare("SELECT device_id FROM app_chat_conversations WHERE id = ?").get(e)?.device_id??null:null}appendOnce(e,n,r,s,o=[],i=Date.now()){return!r||r.length>200?null:this.db.transaction(()=>!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e)||this.db.prepare("INSERT OR IGNORE INTO app_chat_delivered (key, conversation_id, at) VALUES (?, ?, ?)").run(r,n,i).changes===0?null:(this.db.prepare("DELETE FROM app_chat_delivered WHERE at < ?").run(i-30*24*60*6e4),this.appendWithFiles(e,n,s,o))).immediate()}create(e,n,r,s=Date.now()){let o=`c${s.toString(36)}${Ls(4).toString("hex")}`,{color:i,...a}=n,c=i&&vc.test(i)?i:void 0,l={id:o,title:Ms(r),...a,...c?{color:c}:{},createdAt:s,updatedAt:s,messages:[]};return this.db.prepare(`INSERT INTO app_chat_conversations
508
- (id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(o,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,c??null,s,s,s),this.pruneDevice(e),l}get(e,n){if(!Tt(n))return null;let r=this.db.prepare("SELECT * FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e);if(!r)return null;let s=this.db.prepare("SELECT * FROM app_chat_messages WHERE conversation_id = ? ORDER BY id").all(n).map(Sc);return{...Ps(r),messages:s}}list(e,n=z.conversationsPerDevice){return this.db.prepare(`SELECT c.*,
507
+ key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return Tt(e)?this.db.prepare("SELECT device_id FROM app_chat_conversations WHERE id = ?").get(e)?.device_id??null:null}appendOnce(e,n,r,s,o=[],i=Date.now()){return!r||r.length>200?null:this.db.transaction(()=>!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e)||this.db.prepare("INSERT OR IGNORE INTO app_chat_delivered (key, conversation_id, at) VALUES (?, ?, ?)").run(r,n,i).changes===0?null:(this.db.prepare("DELETE FROM app_chat_delivered WHERE at < ?").run(i-30*24*60*6e4),this.appendWithFiles(e,n,s,o))).immediate()}create(e,n,r,s=Date.now()){let o=`c${s.toString(36)}${Ls(4).toString("hex")}`,{color:i,...a}=n,c=i&&kc.test(i)?i:void 0,l={id:o,title:Ms(r),...a,...c?{color:c}:{},createdAt:s,updatedAt:s,messages:[]};return this.db.prepare(`INSERT INTO app_chat_conversations
508
+ (id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(o,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,c??null,s,s,s),this.pruneDevice(e),l}get(e,n){if(!Tt(n))return null;let r=this.db.prepare("SELECT * FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e);if(!r)return null;let s=this.db.prepare("SELECT * FROM app_chat_messages WHERE conversation_id = ? ORDER BY id").all(n).map(vc);return{...Ps(r),messages:s}}list(e,n=z.conversationsPerDevice){return this.db.prepare(`SELECT c.*,
509
509
  (SELECT COUNT(*) FROM app_chat_messages m WHERE m.conversation_id = c.id) AS n,
510
510
  (SELECT substr(m.content, 1, 240) FROM app_chat_messages m WHERE m.conversation_id = c.id ORDER BY m.id DESC LIMIT 1) AS last
511
511
  FROM app_chat_conversations c WHERE c.device_id = ? ORDER BY c.updated_at DESC, c.rowid DESC LIMIT ?`).all(e,Math.max(0,n)).map(s=>{let o=typeof s.last=="string"?s.last.replace(/\s+/g," ").trim().slice(0,120):"";return{...Ps(s),messages:s.n,...o?{last:o}:{}}})}markRead(e,n,r=Date.now()){Tt(n)&&this.db.prepare("UPDATE app_chat_conversations SET read_at = MAX(COALESCE(read_at, 0), ?) WHERE id = ? AND device_id = ?").run(r,n,e)}latestWith(e,n){let r=this.db.prepare(`SELECT id, device_id FROM app_chat_conversations WHERE node = ? AND agent = ?
@@ -520,18 +520,18 @@ Reinstall in ${gc}. Agents switch back on their own once it is installed.`}}func
520
520
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,r.role,i,r.status??null,r.error?.slice(0,500)??null,r.ui?JSON.stringify(r.ui):null,a?.length?JSON.stringify(a):null,l.length?JSON.stringify(l):null,r.at),u=this.db.prepare(`INSERT INTO app_chat_files (id, conversation_id, message_id, path, name, mime, kind, created_at)
521
521
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let p of c)u.run(p.id,n,Number(d.lastInsertRowid),p.path,p.name,p.mime,p.kind,r.at);return this.db.prepare(`DELETE FROM app_chat_messages WHERE conversation_id = ? AND id NOT IN
522
522
  (SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,z.messagesPerConversation),this.db.prepare(`DELETE FROM app_chat_files WHERE conversation_id = ? AND message_id NOT IN
523
- (SELECT id FROM app_chat_messages WHERE conversation_id = ?)`).run(n,n),this.db.prepare("UPDATE app_chat_conversations SET updated_at = ? WHERE id = ?").run(r.at,n),l}getFile(e,n){if(!xc.test(n))return null;let r=this.db.prepare(`SELECT f.*, c.node, c.agent FROM app_chat_files f
523
+ (SELECT id FROM app_chat_messages WHERE conversation_id = ?)`).run(n,n),this.db.prepare("UPDATE app_chat_conversations SET updated_at = ? WHERE id = ?").run(r.at,n),l}getFile(e,n){if(!wc.test(n))return null;let r=this.db.prepare(`SELECT f.*, c.node, c.agent FROM app_chat_files f
524
524
  JOIN app_chat_conversations c ON c.id = f.conversation_id WHERE f.id = ? AND c.device_id = ?`).get(n,e);return r?{id:r.id,name:r.name,mime:r.mime,kind:r.kind,path:r.path,conversationId:r.conversation_id,node:r.node,agent:r.agent}:null}pruneDevice(e){let n=this.db.prepare(`SELECT id FROM app_chat_conversations WHERE device_id = ?
525
- ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,z.conversationsPerDevice);for(let{id:r}of n)this.db.prepare("DELETE FROM app_chat_files WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_messages WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_conversations WHERE id = ?").run(r)}};function Ps(t){return{id:t.id,title:t.title,node:t.node,nodeName:t.node_name,agent:t.agent,...t.agent_name?{agentName:t.agent_name}:{},...t.color?{color:t.color}:{},createdAt:t.created_at,updatedAt:t.updated_at}}function Sc(t){let e=o=>{if(o)try{return JSON.parse(o)}catch{return}},n=e(t.ui),r=e(t.tools),s=e(t.files);return{role:t.role,content:t.content,at:t.at,...t.status?{status:t.status}:{},...t.error?{error:t.error}:{},...n?{ui:n}:{},...r?{tools:r}:{},...s?{files:s}:{}}}function Ms(t){let e=/^\[Call answered\][^"]*"([^"]+)"/.exec(t);if(e)return Ms(`Call: ${e[1]}`);let n=t.replace(/\s+/g," ").trim();return(n.length>60?n.slice(0,59)+"\u2026":n)||"Untitled"}import{readFileSync as Rt,writeFileSync as Bs,existsSync as It,readdirSync as Nc,statSync as Lc}from"fs";import{resolve as Dt,join as Oc}from"path";import{existsSync as Fs,mkdirSync as Ec,readFileSync as _c,writeFileSync as Us}from"fs";import{dirname as $c,resolve as Ws}from"path";import{z as w}from"zod";var Tc=w.object({type:w.enum(["gitlab","github"]),host:w.string().optional(),project:w.string(),iid:w.number().int().positive(),url:w.string()}),Ac=w.object({id:w.string(),title:w.string(),description:w.string().optional(),assignee:w.string().optional(),labels:w.array(w.string()).default([]),milestone:w.string().optional(),status:w.enum(["todo","doing","blocked","done"]).default("todo"),priority:w.number().int().optional(),estimatedSeconds:w.number().int().optional(),source:Tc.optional(),importedAt:w.string().optional(),createdAt:w.string(),updatedAt:w.string(),blocker:w.string().optional(),doneNote:w.string().optional()}),Rc=w.object({version:w.literal(1),items:w.array(Ac).default([])}),Ce=class{constructor(e){this.path=e}jsonPath(){return Ws(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Ws(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return Fs(this.jsonPath())}load(){let e=this.jsonPath();if(!Fs(e))return{version:1,items:[]};let n=_c(e,"utf-8");try{return Rc.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Ec($c(n),{recursive:!0}),Us(n,JSON.stringify(e,null,2)+`
525
+ ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,z.conversationsPerDevice);for(let{id:r}of n)this.db.prepare("DELETE FROM app_chat_files WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_messages WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_conversations WHERE id = ?").run(r)}};function Ps(t){return{id:t.id,title:t.title,node:t.node,nodeName:t.node_name,agent:t.agent,...t.agent_name?{agentName:t.agent_name}:{},...t.color?{color:t.color}:{},createdAt:t.created_at,updatedAt:t.updated_at}}function vc(t){let e=o=>{if(o)try{return JSON.parse(o)}catch{return}},n=e(t.ui),r=e(t.tools),s=e(t.files);return{role:t.role,content:t.content,at:t.at,...t.status?{status:t.status}:{},...t.error?{error:t.error}:{},...n?{ui:n}:{},...r?{tools:r}:{},...s?{files:s}:{}}}function Ms(t){let e=/^\[Call answered\][^"]*"([^"]+)"/.exec(t);if(e)return Ms(`Call: ${e[1]}`);let n=t.replace(/\s+/g," ").trim();return(n.length>60?n.slice(0,59)+"\u2026":n)||"Untitled"}import{readFileSync as At,writeFileSync as Bs,existsSync as Rt,readdirSync as Cc,statSync as Nc}from"fs";import{resolve as It,join as Lc}from"path";import{existsSync as Fs,mkdirSync as Sc,readFileSync as Ec,writeFileSync as Us}from"fs";import{dirname as _c,resolve as Ws}from"path";import{z as w}from"zod";var Tc=w.object({type:w.enum(["gitlab","github"]),host:w.string().optional(),project:w.string(),iid:w.number().int().positive(),url:w.string()}),$c=w.object({id:w.string(),title:w.string(),description:w.string().optional(),assignee:w.string().optional(),labels:w.array(w.string()).default([]),milestone:w.string().optional(),status:w.enum(["todo","doing","blocked","done"]).default("todo"),priority:w.number().int().optional(),estimatedSeconds:w.number().int().optional(),source:Tc.optional(),importedAt:w.string().optional(),createdAt:w.string(),updatedAt:w.string(),blocker:w.string().optional(),doneNote:w.string().optional()}),Ac=w.object({version:w.literal(1),items:w.array($c).default([])}),Ce=class{constructor(e){this.path=e}jsonPath(){return Ws(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Ws(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return Fs(this.jsonPath())}load(){let e=this.jsonPath();if(!Fs(e))return{version:1,items:[]};let n=Ec(e,"utf-8");try{return Ac.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Sc(_c(n),{recursive:!0}),Us(n,JSON.stringify(e,null,2)+`
526
526
  `),Us(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(n=>n.id===e)}add(e){let n=this.load();if(n.items.some(o=>o.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),s={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return n.items.push(s),this.save(n),s}addMany(e){let n=this.load(),r=new Set(n.items.map(i=>i.id)),s=new Date().toISOString(),o=[];for(let i of e){if(r.has(i.id))continue;let a={...i,labels:i.labels??[],status:i.status??"todo",createdAt:i.createdAt??s,updatedAt:s};n.items.push(a),o.push(a),r.add(a.id)}return o.length&&this.save(n),o}update(e,n){let r=this.load(),s=r.items.findIndex(i=>i.id===e);if(s<0)throw new Error(`backlog item ${e} not found`);let o={...r.items[s],...n,id:r.items[s].id,createdAt:r.items[s].createdAt,updatedAt:new Date().toISOString()};return r.items[s]=o,this.save(r),o}remove(e){let n=this.load(),r=n.items.length;return n.items=n.items.filter(s=>s.id!==e),n.items.length===r?!1:(this.save(n),!0)}toMarkdown(e){let n=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],r={doing:[],blocked:[],todo:[],done:[]};for(let o of e.items)r[o.status].push(o);let s=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[o,i]of s)if(r[o].length){n.push(`## ${i}`,"");for(let a of r[o]){let c=o==="done"?"x":" ",l=a.assignee?`@${a.assignee} `:"",d=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",u=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${c}] ${l}${a.title}${d}${u}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
527
- `)}};function Tg(t){return`${t.type}:${t.project}:${t.iid}`}function js(t,e,n){let r=[];if(e.type==="gitlab"){let s=n.channels.gitlab?.agentMappings??[];for(let o of t){let i=s.find(a=>a.agentId===o);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(o)}}else if(e.type==="github"){let s=n.channels.github?.agentMappings??[];for(let o of t){let i=s.find(a=>a.agentId===o);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(o)}}return r}async function At(t,e,n,r=()=>{}){return t.source?Ic(t.source,e,n,r):{ok:!0,attempts:[]}}async function Ic(t,e,n,r=()=>{}){return t.type==="gitlab"?Dc(t,e,n,r):t.type==="github"?Cc(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Dc(t,e,n,r){let s=n.channels.gitlab,o=s?.token,i=s?.host||(t.host?`https://${t.host}`:void 0);if(!o||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],c=async(g,f={})=>fetch(`${i}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":o,"Content-Type":"application/json",...f.headers||{}}}),l=encodeURIComponent(t.project),d;e.assigneeUsernames!==void 0&&(d=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let b=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":o}});if(!b.ok)return null;let y=await b.json();return Array.isArray(y)&&y[0]?.id?y[0].id:null}catch{return null}}))).filter(f=>typeof f=="number"));let u;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")u=0;else try{let g=await c(`/projects/${l}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let f=await g.json();Array.isArray(f)&&f[0]?.id&&(u=f[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.description=e.description),e.labels!==void 0&&(p.labels=e.labels.join(",")),e.addLabels?.length&&(p.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(p.remove_labels=e.removeLabels.join(",")),d!==void 0&&(p.assignee_ids=d),u!==void 0&&(p.milestone_id=u),e.state&&(p.state_event=e.state==="closed"?"close":"reopen"),Object.keys(p).length)try{let g=await c(`/projects/${l}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(p)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${f.slice(0,200)}`,url:t.url}}}catch(g){return a.push({kind:"PUT issue",ok:!1,error:g.message}),{ok:!1,attempts:a,error:g.message,url:t.url}}if(e.note)try{let g=await c(`/projects/${l}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function Cc(t,e,n,r){let o=n.channels.github?.token;if(!o)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(p,g={})=>fetch(`https://api.github.com${p}`,{...g,headers:{Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),c=t.project,l;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")l=null;else try{let p=await a(`/repos/${c}/milestones?state=all&per_page=100`);if(p.ok){let g=await p.json(),f=Array.isArray(g)?g.find(b=>b.title===e.milestoneTitle):null;f?.number&&(l=f.number)}}catch(p){r(`[backlog-sync] github milestone lookup failed: ${p.message}`)}let d;if(e.labels!==void 0)d=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let p=await a(`/repos/${c}/issues/${t.iid}`);if(p.ok){let g=await p.json(),f=Array.isArray(g.labels)?g.labels.map(y=>typeof y=="string"?y:y.name):[],b=new Set([...f,...e.addLabels??[]]);for(let y of e.removeLabels??[])b.delete(y);d=[...b]}}catch(p){r(`[backlog-sync] github label fetch failed: ${p.message}`)}if(d===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let u={};if(e.title!==void 0&&(u.title=e.title),e.description!==void 0&&(u.body=e.description),d!==void 0&&(u.labels=d),e.assigneeUsernames!==void 0&&(u.assignees=e.assigneeUsernames),l!==void 0&&(u.milestone=l),e.state&&(u.state=e.state),Object.keys(u).length)try{let p=await a(`/repos/${c}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(u)});if(i.push({kind:"PATCH issue",ok:p.ok,status:p.status}),!p.ok){let g=await p.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${p.status}: ${g.slice(0,200)}`,url:t.url}}}catch(p){return i.push({kind:"PATCH issue",ok:!1,error:p.message}),{ok:!1,attempts:i,error:p.message,url:t.url}}if(e.note)try{let p=await a(`/repos/${c}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:p.ok,status:p.status})}catch(p){i.push({kind:"POST comment",ok:!1,error:p.message})}return{ok:i.every(p=>p.ok),attempts:i,url:t.url}}var Ct=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,Ne=/@([a-z0-9_-]+)/i,qs=/\[time:\s*([0-9hm\s]+)\]/i;function Pc(t){let e=t.match(/(\d+)\s*h/i),n=t.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(n?parseInt(n[1],10)*60:0)}var Nt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new Ce(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=Dt(process.cwd(),this.path);return It(e)?Rt(e,"utf-8").split(`
528
- `):[]}writeMd(e){let n=Dt(process.cwd(),this.path);Bs(n,e.join(`
529
- `))}async listOpen(e){if(this.store.exists())return this.store.list().filter(o=>o.status!=="done"&&(!o.assignee||o.assignee.toLowerCase()===e.toLowerCase())).map(o=>this.toWorkItem(o));let n=this.readMd(),r=[];for(let s=0;s<n.length;s++){let o=n[s].match(Ct);if(!o||o[2].toLowerCase()==="x")continue;let a=o[3],c=a.match(Ne);if(c&&c[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(qs),d=a.replace(Ne,"").replace(qs,"").trim();r.push({id:`backlog:${s}`,title:d||`Task at line ${s+1}`,assignee:c?c[1]:void 0,estimatedSeconds:l?Pc(l[1]):void 0,priority:s})}return r}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let r=this.store.findById(n);if(!r)return;let s=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(s.source&&this.daemon){let o=js([s.assignee||e],s.source,this.daemon);At(s,{assigneeUsernames:o,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(i=>this.log(`[backlog-sync] claim failed for ${n}: ${i?.message??i}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let c=this.store.update(e,a);if(c.source&&this.daemon){let l={};n.status==="done"?(l.addLabels=["Done"],l.removeLabels=["Doing"]):n.status==="blocked"&&(l.addLabels=["Blocked"]),n.note&&(l.note=n.note),Object.keys(l).length&&At(c,l,this.daemon,this.log).catch(d=>this.log(`[backlog-sync] report failed for ${e}: ${d?.message??d}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let r=parseInt(e.slice(8),10),s=this.readMd(),o=s[r];if(!o)throw new Error(`backlog line ${r} missing`);if(!o.match(Ct))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){s[r]=o.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";s.splice(r+1,0,a)}else n.status==="blocked"?s.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&s.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(s)}toWorkItem(e){let n={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},Lt=class{constructor(e,n){this.root=e;this.glob=n}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,n){if(It(e))for(let r of Nc(e)){let s=Oc(e,r);Lc(s).isDirectory()?this.walk(s,n):r.endsWith(".md")&&n.push(s)}}async listOpen(e){let n=[];this.walk(Dt(process.cwd(),this.root),n);let r=[];for(let s of n){let o=Rt(s,"utf-8").split(`
530
- `);for(let i=0;i<o.length;i++){let a=o[i].match(Ct);if(!a||a[2].toLowerCase()==="x")continue;let c=a[3].match(Ne);!c||c[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${s}:${i}`,title:a[3].replace(Ne,"").trim(),assignee:c[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),s=parseInt(r[r.length-1],10),o=r.slice(1,-1).join(":");if(!It(o))return;let i=Rt(o,"utf-8").split(`
527
+ `)}};function _g(t){return`${t.type}:${t.project}:${t.iid}`}function js(t,e,n){let r=[];if(e.type==="gitlab"){let s=n.channels.gitlab?.agentMappings??[];for(let o of t){let i=s.find(a=>a.agentId===o);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(o)}}else if(e.type==="github"){let s=n.channels.github?.agentMappings??[];for(let o of t){let i=s.find(a=>a.agentId===o);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(o)}}return r}async function $t(t,e,n,r=()=>{}){return t.source?Rc(t.source,e,n,r):{ok:!0,attempts:[]}}async function Rc(t,e,n,r=()=>{}){return t.type==="gitlab"?Ic(t,e,n,r):t.type==="github"?Dc(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Ic(t,e,n,r){let s=n.channels.gitlab,o=s?.token,i=s?.host||(t.host?`https://${t.host}`:void 0);if(!o||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],c=async(g,f={})=>fetch(`${i}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":o,"Content-Type":"application/json",...f.headers||{}}}),l=encodeURIComponent(t.project),d;e.assigneeUsernames!==void 0&&(d=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let b=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":o}});if(!b.ok)return null;let y=await b.json();return Array.isArray(y)&&y[0]?.id?y[0].id:null}catch{return null}}))).filter(f=>typeof f=="number"));let u;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")u=0;else try{let g=await c(`/projects/${l}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let f=await g.json();Array.isArray(f)&&f[0]?.id&&(u=f[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.description=e.description),e.labels!==void 0&&(p.labels=e.labels.join(",")),e.addLabels?.length&&(p.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(p.remove_labels=e.removeLabels.join(",")),d!==void 0&&(p.assignee_ids=d),u!==void 0&&(p.milestone_id=u),e.state&&(p.state_event=e.state==="closed"?"close":"reopen"),Object.keys(p).length)try{let g=await c(`/projects/${l}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(p)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${f.slice(0,200)}`,url:t.url}}}catch(g){return a.push({kind:"PUT issue",ok:!1,error:g.message}),{ok:!1,attempts:a,error:g.message,url:t.url}}if(e.note)try{let g=await c(`/projects/${l}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function Dc(t,e,n,r){let o=n.channels.github?.token;if(!o)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(p,g={})=>fetch(`https://api.github.com${p}`,{...g,headers:{Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),c=t.project,l;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")l=null;else try{let p=await a(`/repos/${c}/milestones?state=all&per_page=100`);if(p.ok){let g=await p.json(),f=Array.isArray(g)?g.find(b=>b.title===e.milestoneTitle):null;f?.number&&(l=f.number)}}catch(p){r(`[backlog-sync] github milestone lookup failed: ${p.message}`)}let d;if(e.labels!==void 0)d=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let p=await a(`/repos/${c}/issues/${t.iid}`);if(p.ok){let g=await p.json(),f=Array.isArray(g.labels)?g.labels.map(y=>typeof y=="string"?y:y.name):[],b=new Set([...f,...e.addLabels??[]]);for(let y of e.removeLabels??[])b.delete(y);d=[...b]}}catch(p){r(`[backlog-sync] github label fetch failed: ${p.message}`)}if(d===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let u={};if(e.title!==void 0&&(u.title=e.title),e.description!==void 0&&(u.body=e.description),d!==void 0&&(u.labels=d),e.assigneeUsernames!==void 0&&(u.assignees=e.assigneeUsernames),l!==void 0&&(u.milestone=l),e.state&&(u.state=e.state),Object.keys(u).length)try{let p=await a(`/repos/${c}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(u)});if(i.push({kind:"PATCH issue",ok:p.ok,status:p.status}),!p.ok){let g=await p.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${p.status}: ${g.slice(0,200)}`,url:t.url}}}catch(p){return i.push({kind:"PATCH issue",ok:!1,error:p.message}),{ok:!1,attempts:i,error:p.message,url:t.url}}if(e.note)try{let p=await a(`/repos/${c}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:p.ok,status:p.status})}catch(p){i.push({kind:"POST comment",ok:!1,error:p.message})}return{ok:i.every(p=>p.ok),attempts:i,url:t.url}}var Dt=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,Ne=/@([a-z0-9_-]+)/i,qs=/\[time:\s*([0-9hm\s]+)\]/i;function Oc(t){let e=t.match(/(\d+)\s*h/i),n=t.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(n?parseInt(n[1],10)*60:0)}var Ct=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new Ce(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=It(process.cwd(),this.path);return Rt(e)?At(e,"utf-8").split(`
528
+ `):[]}writeMd(e){let n=It(process.cwd(),this.path);Bs(n,e.join(`
529
+ `))}async listOpen(e){if(this.store.exists())return this.store.list().filter(o=>o.status!=="done"&&(!o.assignee||o.assignee.toLowerCase()===e.toLowerCase())).map(o=>this.toWorkItem(o));let n=this.readMd(),r=[];for(let s=0;s<n.length;s++){let o=n[s].match(Dt);if(!o||o[2].toLowerCase()==="x")continue;let a=o[3],c=a.match(Ne);if(c&&c[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(qs),d=a.replace(Ne,"").replace(qs,"").trim();r.push({id:`backlog:${s}`,title:d||`Task at line ${s+1}`,assignee:c?c[1]:void 0,estimatedSeconds:l?Oc(l[1]):void 0,priority:s})}return r}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let r=this.store.findById(n);if(!r)return;let s=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(s.source&&this.daemon){let o=js([s.assignee||e],s.source,this.daemon);$t(s,{assigneeUsernames:o,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(i=>this.log(`[backlog-sync] claim failed for ${n}: ${i?.message??i}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let c=this.store.update(e,a);if(c.source&&this.daemon){let l={};n.status==="done"?(l.addLabels=["Done"],l.removeLabels=["Doing"]):n.status==="blocked"&&(l.addLabels=["Blocked"]),n.note&&(l.note=n.note),Object.keys(l).length&&$t(c,l,this.daemon,this.log).catch(d=>this.log(`[backlog-sync] report failed for ${e}: ${d?.message??d}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let r=parseInt(e.slice(8),10),s=this.readMd(),o=s[r];if(!o)throw new Error(`backlog line ${r} missing`);if(!o.match(Dt))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){s[r]=o.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";s.splice(r+1,0,a)}else n.status==="blocked"?s.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&s.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(s)}toWorkItem(e){let n={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},Nt=class{constructor(e,n){this.root=e;this.glob=n}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,n){if(Rt(e))for(let r of Cc(e)){let s=Lc(e,r);Nc(s).isDirectory()?this.walk(s,n):r.endsWith(".md")&&n.push(s)}}async listOpen(e){let n=[];this.walk(It(process.cwd(),this.root),n);let r=[];for(let s of n){let o=At(s,"utf-8").split(`
530
+ `);for(let i=0;i<o.length;i++){let a=o[i].match(Dt);if(!a||a[2].toLowerCase()==="x")continue;let c=a[3].match(Ne);!c||c[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${s}:${i}`,title:a[3].replace(Ne,"").trim(),assignee:c[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),s=parseInt(r[r.length-1],10),o=r.slice(1,-1).join(":");if(!Rt(o))return;let i=At(o,"utf-8").split(`
531
531
  `);n.status==="done"&&i[s]&&(i[s]=i[s].replace(/- \[ \]/,"- [x]"),Bs(o,i.join(`
532
- `)))}},Ot=class{constructor(e,n,r,s,o){this.host=e;this.token=n;this.projects=r;this.agentUsernames=s;this.log=o}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(s=>s.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,s=[],o;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(o=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),s=o.map(l=>l.name)):s=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),c=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:c?this.usernameToAgent(c)||c:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:s,labelDetails:o,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],s=this.projects.length?this.projects:["__ALL__"];for(let o of n)for(let i of s)try{let a=`assignee_username=${encodeURIComponent(o)}&state=opened&scope=all&per_page=20`,c=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(c);for(let d of l){let u=this.mapIssue(d,i);u.assignee=e,r.push(u)}}catch(a){this.log(`[business] GitLab listOpen failed for ${o} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:s,type:o}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${o==="issue"?"issues":"merge_requests"}/${s}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:s,type:o}=this.parseId(e),i=o==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),c=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}/add_spent_time?duration=${encodeURIComponent(c)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),s=new URLSearchParams,o=e.state??"opened";s.set("state",o),s.set("updated_after",r),s.set("scope","all"),s.set("per_page","100"),s.set("with_labels_details","true"),s.set("order_by","updated_at"),s.set("sort","desc"),e.labels?.length&&s.set("labels",e.labels.join(",")),e.milestone&&s.set("milestone",e.milestone),e.search&&s.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of i)try{let d=l==="__ALL__"?`/issues?${s.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${s.toString()}`,u=await this.api(d);for(let p of u)a.push(this.mapIssue(p,l))}catch(d){this.log(`[business] GitLab listAll failed on ${l}: ${d.message}`)}let c=a;if(e.notLabels?.length){let l=new Set(e.notLabels);c=c.filter(d=>!(d.labels||[]).some(u=>l.has(u)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";c=c.filter(d=>!(d.labels||[]).some(u=>u.startsWith(l)))}return c}async setState(e,n){let{project:r,iid:s,type:o}=this.parseId(e),i=o==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let s=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(s,n),descriptionHtml:s.description_html||void 0,createdAt:s.created_at,author:s.author?{username:s.author.username,name:s.author.name,avatarUrl:s.author.avatar_url}:void 0,allLabels:Array.isArray(s.labels)?typeof s.labels[0]=="object"?s.labels.map(i=>i.name):s.labels:[]}}catch(s){return this.log(`[board] GitLab getItem failed for ${e}: ${s.message}`),null}}async updateItem(e,n){let{project:r,iid:s}=this.parseId(e),o;n.assigneeUsernames&&(o=(await Promise.all(n.assigneeUsernames.map(async d=>{try{let u=await this.api(`/users?username=${encodeURIComponent(d)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch{return null}}))).filter(d=>typeof d=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),o!==void 0&&(a.assignee_ids=o),i!==void 0&&(a.milestone_id=i);let c=await this.api(`/projects/${encodeURIComponent(r)}/issues/${s}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(c,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let s of r)s.username&&!e.has(s.username)&&e.set(s.username,{username:s.username,name:s.name,avatarUrl:s.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let s=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let o of s)o.title&&!e.has(o.title)&&e.set(o.title,{id:o.id,title:o.title,state:o.state,dueDate:o.due_date})}catch(s){this.log(`[board] listMilestones failed for ${r}: ${s.message}`)}let n=[...e.values()];return n.sort((r,s)=>r.state!==s.state?r.state==="active"?-1:1:r.title.localeCompare(s.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,s=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];s.length&&(r=(await Promise.all(s.map(async l=>{try{let d=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(d)&&d[0]?.id?d[0].id:null}catch(d){return this.log(`[board] user lookup failed for ${l}: ${d.message}`),null}}))).filter(l=>typeof l=="number"));let o;if(e.milestoneTitle)try{let c=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(c)&&c[0]?.id&&(o=c[0].id)}catch(c){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${c.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),o!==void 0&&(i.milestone_id=o);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:s,iid:o,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",c=new URLSearchParams;n.length&&c.set("add_labels",n.join(",")),r.length&&c.set("remove_labels",r.join(",")),c.toString()&&await this.api(`/projects/${encodeURIComponent(s)}/${a}/${o}?${c.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),s=r.pop(),o=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:o,iid:s}}};function Lg(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Nt(r.path,e,n);case"wiki":return new Lt(r.path,r.glob);case"gitlab":{let s=e.channels.gitlab;if(!s?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let o={};for(let a of s.agentMappings)a.gitlabUsernames.length&&(o[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:s.routes.map(a=>a.project);return new Ot(s.host,s.token,i,o,n)}}}Zo();var Pt="unmapped";function Mt(t,e=[]){if(!t)return Pt;let n=e.find(s=>s.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function Mc(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},s=new Map;for(let i of dn(t)){let a=We(i.from),c=We(i.to);i.type==="reports-to"&&a.kind==="agent"&&c.kind==="agent"&&s.set(a.id,c.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Mt(i.id,n)));let o=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let c=s.get(i);if(!c)return;let l=o(c,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))o(i);return e}function Fc(t,e,n=[]){if(!n.length)return;let r=n.filter(s=>!s.channel||s.channel===t);return r.find(s=>s.chatId&&e.chatId&&s.chatId===e.chatId)??r.find(s=>s.username&&e.username&&s.username===e.username)??r.find(s=>s.senderId&&e.senderId&&s.senderId===e.senderId)??r.find(s=>s.channel&&!s.chatId&&!s.username&&!s.senderId)}function Mg(t,e){let n=Fc(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Mt(t.project,e.projects);if(t.agentId){let r=Mc(e).get(t.agentId);if(r)return r}return Pt}function Fg(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,s,...o]=n,i=o.join(":"),a={agentId:e||r,channel:s};return s==="gitlab"||s==="github"?a.project=i.split(":")[0]:s==="cron"||s==="api"||(a.chatId=i.split("@")[0]),a}var Uc=t=>t===Pt?"internal":"client";function Wc(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Uc(t),respondWithinMinutes:jc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function Ug(t){let e=new Set;for(let n of t.projects??[])e.add(Mt(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>Wc(n,t))}function jc(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}import{createHash as qc}from"crypto";var qg={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},Bc=40,Hc=20,Bg=90,Vc=2e3,Hs=36e5;function Xc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
533
- ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<Bc?null:`text:${qc("sha256").update(r).digest("hex").slice(0,24)}`}function Hg(t){let e=t.indexOf(`
534
- `);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function Ft(t){t.exec(`
532
+ `)))}},Lt=class{constructor(e,n,r,s,o){this.host=e;this.token=n;this.projects=r;this.agentUsernames=s;this.log=o}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(s=>s.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,s=[],o;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(o=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),s=o.map(l=>l.name)):s=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),c=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:c?this.usernameToAgent(c)||c:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:s,labelDetails:o,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],s=this.projects.length?this.projects:["__ALL__"];for(let o of n)for(let i of s)try{let a=`assignee_username=${encodeURIComponent(o)}&state=opened&scope=all&per_page=20`,c=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(c);for(let d of l){let u=this.mapIssue(d,i);u.assignee=e,r.push(u)}}catch(a){this.log(`[business] GitLab listOpen failed for ${o} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:s,type:o}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${o==="issue"?"issues":"merge_requests"}/${s}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:s,type:o}=this.parseId(e),i=o==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),c=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}/add_spent_time?duration=${encodeURIComponent(c)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),s=new URLSearchParams,o=e.state??"opened";s.set("state",o),s.set("updated_after",r),s.set("scope","all"),s.set("per_page","100"),s.set("with_labels_details","true"),s.set("order_by","updated_at"),s.set("sort","desc"),e.labels?.length&&s.set("labels",e.labels.join(",")),e.milestone&&s.set("milestone",e.milestone),e.search&&s.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of i)try{let d=l==="__ALL__"?`/issues?${s.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${s.toString()}`,u=await this.api(d);for(let p of u)a.push(this.mapIssue(p,l))}catch(d){this.log(`[business] GitLab listAll failed on ${l}: ${d.message}`)}let c=a;if(e.notLabels?.length){let l=new Set(e.notLabels);c=c.filter(d=>!(d.labels||[]).some(u=>l.has(u)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";c=c.filter(d=>!(d.labels||[]).some(u=>u.startsWith(l)))}return c}async setState(e,n){let{project:r,iid:s,type:o}=this.parseId(e),i=o==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let s=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(s,n),descriptionHtml:s.description_html||void 0,createdAt:s.created_at,author:s.author?{username:s.author.username,name:s.author.name,avatarUrl:s.author.avatar_url}:void 0,allLabels:Array.isArray(s.labels)?typeof s.labels[0]=="object"?s.labels.map(i=>i.name):s.labels:[]}}catch(s){return this.log(`[board] GitLab getItem failed for ${e}: ${s.message}`),null}}async updateItem(e,n){let{project:r,iid:s}=this.parseId(e),o;n.assigneeUsernames&&(o=(await Promise.all(n.assigneeUsernames.map(async d=>{try{let u=await this.api(`/users?username=${encodeURIComponent(d)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch{return null}}))).filter(d=>typeof d=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),o!==void 0&&(a.assignee_ids=o),i!==void 0&&(a.milestone_id=i);let c=await this.api(`/projects/${encodeURIComponent(r)}/issues/${s}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(c,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let s of r)s.username&&!e.has(s.username)&&e.set(s.username,{username:s.username,name:s.name,avatarUrl:s.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let s=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let o of s)o.title&&!e.has(o.title)&&e.set(o.title,{id:o.id,title:o.title,state:o.state,dueDate:o.due_date})}catch(s){this.log(`[board] listMilestones failed for ${r}: ${s.message}`)}let n=[...e.values()];return n.sort((r,s)=>r.state!==s.state?r.state==="active"?-1:1:r.title.localeCompare(s.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,s=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];s.length&&(r=(await Promise.all(s.map(async l=>{try{let d=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(d)&&d[0]?.id?d[0].id:null}catch(d){return this.log(`[board] user lookup failed for ${l}: ${d.message}`),null}}))).filter(l=>typeof l=="number"));let o;if(e.milestoneTitle)try{let c=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(c)&&c[0]?.id&&(o=c[0].id)}catch(c){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${c.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),o!==void 0&&(i.milestone_id=o);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:s,iid:o,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",c=new URLSearchParams;n.length&&c.set("add_labels",n.join(",")),r.length&&c.set("remove_labels",r.join(",")),c.toString()&&await this.api(`/projects/${encodeURIComponent(s)}/${a}/${o}?${c.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),s=r.pop(),o=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:o,iid:s}}};function Cg(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Ct(r.path,e,n);case"wiki":return new Nt(r.path,r.glob);case"gitlab":{let s=e.channels.gitlab;if(!s?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let o={};for(let a of s.agentMappings)a.gitlabUsernames.length&&(o[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:s.routes.map(a=>a.project);return new Lt(s.host,s.token,i,o,n)}}}Qo();var Ot="unmapped";function Pt(t,e=[]){if(!t)return Ot;let n=e.find(s=>s.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function Pc(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},s=new Map;for(let i of ln(t)){let a=We(i.from),c=We(i.to);i.type==="reports-to"&&a.kind==="agent"&&c.kind==="agent"&&s.set(a.id,c.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Pt(i.id,n)));let o=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let c=s.get(i);if(!c)return;let l=o(c,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))o(i);return e}function Mc(t,e,n=[]){if(!n.length)return;let r=n.filter(s=>!s.channel||s.channel===t);return r.find(s=>s.chatId&&e.chatId&&s.chatId===e.chatId)??r.find(s=>s.username&&e.username&&s.username===e.username)??r.find(s=>s.senderId&&e.senderId&&s.senderId===e.senderId)??r.find(s=>s.channel&&!s.chatId&&!s.username&&!s.senderId)}function Og(t,e){let n=Mc(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Pt(t.project,e.projects);if(t.agentId){let r=Pc(e).get(t.agentId);if(r)return r}return Ot}function Pg(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,s,...o]=n,i=o.join(":"),a={agentId:e||r,channel:s};return s==="gitlab"||s==="github"?a.project=i.split(":")[0]:s==="cron"||s==="api"||(a.chatId=i.split("@")[0]),a}var Fc=t=>t===Ot?"internal":"client";function Uc(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Fc(t),respondWithinMinutes:Wc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function Mg(t){let e=new Set;for(let n of t.projects??[])e.add(Pt(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>Uc(n,t))}function Wc(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}import{createHash as jc}from"crypto";var Wg={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},qc=40,Bc=20,jg=90,Hc=2e3,Hs=36e5;function Vc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
533
+ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<qc?null:`text:${jc("sha256").update(r).digest("hex").slice(0,24)}`}function qg(t){let e=t.indexOf(`
534
+ `);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function Mt(t){t.exec(`
535
535
  CREATE TABLE IF NOT EXISTS owner_told (
536
536
  id INTEGER PRIMARY KEY AUTOINCREMENT,
537
537
  at INTEGER NOT NULL,
@@ -549,34 +549,34 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<Bc?null:`text:${q
549
549
  CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
550
550
  CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
551
551
  CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
552
- `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of zc)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(s){if(!/duplicate column/i.test(String(s?.message)))throw s}}var zc=[["urgent","INTEGER NOT NULL DEFAULT 0"],["seen_at","INTEGER"],["seen_via","TEXT"],["answered_at","INTEGER"],["answered_via","TEXT"],["escalated_at","INTEGER"],["escalation_of","INTEGER"]];function Le(t){return{id:t.id,at:t.at,key:t.item_key,requestId:t.request_id??null,kind:t.kind,channel:t.channel,chatId:t.chat_id,from:t.sender??null,title:t.title,text:t.text,outcome:t.outcome,digestedAt:t.digested_at??null,urgent:t.urgent===1,seenAt:t.seen_at??null,seenVia:t.seen_via??null,answeredAt:t.answered_at??null,answeredVia:t.answered_via??null,escalatedAt:t.escalated_at??null,escalationOf:t.escalation_of??null,state:t.answered_at!=null?"answered":t.seen_at!=null?"seen":"sent"}}var Vs=class{constructor(e){this.db=e;Ft(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
553
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,Vc),e.outcome,e.urgent?1:0,e.escalationOf??null).lastInsertRowid)}get(e){let n=this.db.prepare("SELECT * FROM owner_told WHERE id = ?").get(e);return n?Le(n):null}setOutcome(e,n){this.db.prepare("UPDATE owner_told SET outcome = ? WHERE id = ?").run(n,e)}lastTold(e,n,r=!0){let s=this.db.prepare(`SELECT * FROM owner_told WHERE item_key = ? AND at >= ? AND outcome IN ('sent', 'held'${r?", 'digest'":""}) ORDER BY at DESC LIMIT 1`).get(e,n);return s?Le(s):null}waitingForDigest(e=500){return this.db.prepare("SELECT * FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL ORDER BY at LIMIT ?").all(e).map(Le)}waitingCount(){return this.db.prepare("SELECT COUNT(*) AS n FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL").get().n}markDigested(e,n){let r=this.db.prepare("UPDATE owner_told SET digested_at = ? WHERE id = ?");this.db.transaction(()=>{for(let s of e)r.run(n,s)})()}since(e,n=200){return this.db.prepare("SELECT * FROM owner_told WHERE at >= ? ORDER BY at DESC, id DESC LIMIT ?").all(e,n).map(Le)}counts(e){let n={sent:0,held:0,digest:0,repeat:0,failed:0};for(let r of this.db.prepare("SELECT outcome, COUNT(*) AS n FROM owner_told WHERE at >= ? GROUP BY outcome").all(e))n[r.outcome]=r.n;return n}states(e){let n=this.db.prepare(`SELECT SUM(CASE WHEN answered_at IS NULL AND seen_at IS NULL THEN 1 ELSE 0 END) AS sent,
552
+ `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of Xc)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(s){if(!/duplicate column/i.test(String(s?.message)))throw s}}var Xc=[["urgent","INTEGER NOT NULL DEFAULT 0"],["seen_at","INTEGER"],["seen_via","TEXT"],["answered_at","INTEGER"],["answered_via","TEXT"],["escalated_at","INTEGER"],["escalation_of","INTEGER"]];function Le(t){return{id:t.id,at:t.at,key:t.item_key,requestId:t.request_id??null,kind:t.kind,channel:t.channel,chatId:t.chat_id,from:t.sender??null,title:t.title,text:t.text,outcome:t.outcome,digestedAt:t.digested_at??null,urgent:t.urgent===1,seenAt:t.seen_at??null,seenVia:t.seen_via??null,answeredAt:t.answered_at??null,answeredVia:t.answered_via??null,escalatedAt:t.escalated_at??null,escalationOf:t.escalation_of??null,state:t.answered_at!=null?"answered":t.seen_at!=null?"seen":"sent"}}var Vs=class{constructor(e){this.db=e;Mt(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
553
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,Hc),e.outcome,e.urgent?1:0,e.escalationOf??null).lastInsertRowid)}get(e){let n=this.db.prepare("SELECT * FROM owner_told WHERE id = ?").get(e);return n?Le(n):null}setOutcome(e,n){this.db.prepare("UPDATE owner_told SET outcome = ? WHERE id = ?").run(n,e)}lastTold(e,n,r=!0){let s=this.db.prepare(`SELECT * FROM owner_told WHERE item_key = ? AND at >= ? AND outcome IN ('sent', 'held'${r?", 'digest'":""}) ORDER BY at DESC LIMIT 1`).get(e,n);return s?Le(s):null}waitingForDigest(e=500){return this.db.prepare("SELECT * FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL ORDER BY at LIMIT ?").all(e).map(Le)}waitingCount(){return this.db.prepare("SELECT COUNT(*) AS n FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL").get().n}markDigested(e,n){let r=this.db.prepare("UPDATE owner_told SET digested_at = ? WHERE id = ?");this.db.transaction(()=>{for(let s of e)r.run(n,s)})()}since(e,n=200){return this.db.prepare("SELECT * FROM owner_told WHERE at >= ? ORDER BY at DESC, id DESC LIMIT ?").all(e,n).map(Le)}counts(e){let n={sent:0,held:0,digest:0,repeat:0,failed:0};for(let r of this.db.prepare("SELECT outcome, COUNT(*) AS n FROM owner_told WHERE at >= ? GROUP BY outcome").all(e))n[r.outcome]=r.n;return n}states(e){let n=this.db.prepare(`SELECT SUM(CASE WHEN answered_at IS NULL AND seen_at IS NULL THEN 1 ELSE 0 END) AS sent,
554
554
  SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
555
555
  SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
556
- FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},Xs=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),s=this.now(),o=Xc(n,e.title,e.text),i=n.kind??"notice",a=(o?.startsWith("text:")?Math.min(r.repeatWindowHours,Hc):r.repeatWindowHours)*Hs,c=r.digestNags&&r.digestAvailable!==!1,l="send";!n.urgent&&o&&this.ledger.lastTold(o,s-a,c)?l="repeat":!n.urgent&&i==="nag"&&c&&(l="digest");let d=this.ledger.add({at:s,key:o??`once:${s}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:l==="send"?"sent":l,urgent:n.urgent===!0});return{verdict:l,key:o,rowId:d}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:Kc(e),ids:e.map(n=>n.id)}:null}markDigested(e){this.ledger.markDigested(e,this.now())}report(e,n=50){return{counts:this.ledger.counts(e),landed:this.ledger.states(e),waitingForDigest:this.ledger.waitingCount(),items:this.ledger.since(e,n)}}prune(e){return this.ledger.prune(this.now()-e*24*Hs)}};function Vg(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,s=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,o=r(n.from,100)??r(e,100);return{...r(n.key,190)?{key:`send:${r(n.key,190)}`}:{},...r(n.requestId,100)?{requestId:r(n.requestId,100)}:{},...s?{kind:s}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...o?{from:o}:{}}}function Kc(t,e=5,n=3){let r=new Map;for(let a of t){let[c,...l]=a.title.split(": "),d=l.join(": ").trim(),u=r.get(c.trim())??{count:0,names:[]};u.count++,d&&!u.names.includes(d)&&u.names.push(d),r.set(c.trim(),u)}let s=[...r.entries()].sort((a,c)=>c[1].count-a[1].count),o=s.slice(0,e).map(([a,{count:c,names:l}])=>{let d=l.length?` (${l.slice(0,n).join(", ")}${l.length>n?", \u2026":""})`:"";return`${a}${c>1?` \xD7${c}`:""}${d}`}),i=s.length>e?`; ${s.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${o.join("; ")}${i}.`}var Gc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,Yc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Oe(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(Yc)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],s=Jc(r);if(!s)return{cleanText:t};let o=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,o)+i+t.slice(o+n[0].length)).trim(),ui:s}}function zg(t){if(!t||!t.includes("agentx:ui"))return t;let e=Gc.exec(t);return e?t.slice(0,e.index).trimEnd():t}function Jc(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let r=[],s=[],o=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?r.push({label:i.label,url:i.url}):typeof i.reply=="string"&&i.reply.trim()?s.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&o.push(i.label));r.length&&(n.buttons=r),s.length&&(n.replies=s),o.length&&(n.skippedActions=o)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,s=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(s)&&s.filter(o=>typeof o=="string").length>=2&&(n.poll={question:r,options:s.filter(o=>typeof o=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:s,caption:o}=e.media;["image","document","audio","video"].includes(r)&&typeof s=="string"&&s&&(n.media={type:r,url:s,...typeof o=="string"?{caption:o}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(s=>typeof s=="string"&&s.trim()).map(s=>s.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function Gg(t,e){let n=`${e}/call?to=${encodeURIComponent(t.from)}&callId=${encodeURIComponent(t.callId)}`;return t.reason==="camera"?`\u{1F4F7} ${t.from} is sharing a phone camera \u2014 tap to watch: ${n}&watch=1`:`\u{1F4DE} ${t.from} is calling \u2014 tap to join: ${n}`}var Zc=5*6e4;function q(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var zs=class{subs=new Set;log;forwarder;localName;allowedCallers;pending=new Map;cleanupTimer;ringHandler;recentRings=new Map;constructor(e,n=[],r=console.error.bind(console,"[webrtc]")){this.localName=e,this.allowedCallers=new Set(n.map(q)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${q(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let s=r.filter(o=>o.expiresAt>e);s.length===0?this.pending.delete(n):s.length!==r.length&&this.pending.set(n,s)}for(let[n,r]of this.recentRings)r<=e&&this.recentRings.delete(n)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,n,r){return this.addSubscriber(e,n,{kind:"sse",res:r})}subscribeInternal(e,n,r){return this.addSubscriber(e,n,{kind:"callback",deliver:r})}addSubscriber(e,n,r){let s={callId:e,recipient:n,sink:r};this.subs.add(s);let o=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${o}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let c=Date.now(),l=a.filter(d=>d.expiresAt>c);for(let{signal:d}of l)this.deliverTo(s,d);this.pending.delete(i),l.length&&this.log(`flushed ${l.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(s),this.log(`unsubscribe[${o}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
556
+ FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},Xs=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),s=this.now(),o=Vc(n,e.title,e.text),i=n.kind??"notice",a=(o?.startsWith("text:")?Math.min(r.repeatWindowHours,Bc):r.repeatWindowHours)*Hs,c=r.digestNags&&r.digestAvailable!==!1,l="send";!n.urgent&&o&&this.ledger.lastTold(o,s-a,c)?l="repeat":!n.urgent&&i==="nag"&&c&&(l="digest");let d=this.ledger.add({at:s,key:o??`once:${s}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:l==="send"?"sent":l,urgent:n.urgent===!0});return{verdict:l,key:o,rowId:d}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:zc(e),ids:e.map(n=>n.id)}:null}markDigested(e){this.ledger.markDigested(e,this.now())}report(e,n=50){return{counts:this.ledger.counts(e),landed:this.ledger.states(e),waitingForDigest:this.ledger.waitingCount(),items:this.ledger.since(e,n)}}prune(e){return this.ledger.prune(this.now()-e*24*Hs)}};function Bg(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,s=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,o=r(n.from,100)??r(e,100);return{...r(n.key,190)?{key:`send:${r(n.key,190)}`}:{},...r(n.requestId,100)?{requestId:r(n.requestId,100)}:{},...s?{kind:s}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...o?{from:o}:{}}}function zc(t,e=5,n=3){let r=new Map;for(let a of t){let[c,...l]=a.title.split(": "),d=l.join(": ").trim(),u=r.get(c.trim())??{count:0,names:[]};u.count++,d&&!u.names.includes(d)&&u.names.push(d),r.set(c.trim(),u)}let s=[...r.entries()].sort((a,c)=>c[1].count-a[1].count),o=s.slice(0,e).map(([a,{count:c,names:l}])=>{let d=l.length?` (${l.slice(0,n).join(", ")}${l.length>n?", \u2026":""})`:"";return`${a}${c>1?` \xD7${c}`:""}${d}`}),i=s.length>e?`; ${s.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${o.join("; ")}${i}.`}var Kc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,Gc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Oe(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(Gc)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],s=Yc(r);if(!s)return{cleanText:t};let o=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,o)+i+t.slice(o+n[0].length)).trim(),ui:s}}function Vg(t){if(!t||!t.includes("agentx:ui"))return t;let e=Kc.exec(t);return e?t.slice(0,e.index).trimEnd():t}function Yc(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let r=[],s=[],o=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?r.push({label:i.label,url:i.url}):typeof i.reply=="string"&&i.reply.trim()?s.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&o.push(i.label));r.length&&(n.buttons=r),s.length&&(n.replies=s),o.length&&(n.skippedActions=o)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,s=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(s)&&s.filter(o=>typeof o=="string").length>=2&&(n.poll={question:r,options:s.filter(o=>typeof o=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:s,caption:o}=e.media;["image","document","audio","video"].includes(r)&&typeof s=="string"&&s&&(n.media={type:r,url:s,...typeof o=="string"?{caption:o}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(s=>typeof s=="string"&&s.trim()).map(s=>s.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function zg(t,e){let n=`${e}/call?to=${encodeURIComponent(t.from)}&callId=${encodeURIComponent(t.callId)}`;return t.reason==="camera"?`\u{1F4F7} ${t.from} is sharing a phone camera \u2014 tap to watch: ${n}&watch=1`:`\u{1F4DE} ${t.from} is calling \u2014 tap to join: ${n}`}var Jc=5*6e4;function q(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var zs=class{subs=new Set;log;forwarder;localName;allowedCallers;pending=new Map;cleanupTimer;ringHandler;recentRings=new Map;constructor(e,n=[],r=console.error.bind(console,"[webrtc]")){this.localName=e,this.allowedCallers=new Set(n.map(q)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${q(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let s=r.filter(o=>o.expiresAt>e);s.length===0?this.pending.delete(n):s.length!==r.length&&this.pending.set(n,s)}for(let[n,r]of this.recentRings)r<=e&&this.recentRings.delete(n)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,n,r){return this.addSubscriber(e,n,{kind:"sse",res:r})}subscribeInternal(e,n,r){return this.addSubscriber(e,n,{kind:"callback",deliver:r})}addSubscriber(e,n,r){let s={callId:e,recipient:n,sink:r};this.subs.add(s);let o=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${o}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let c=Date.now(),l=a.filter(d=>d.expiresAt>c);for(let{signal:d}of l)this.deliverTo(s,d);this.pending.delete(i),l.length&&this.log(`flushed ${l.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(s),this.log(`unsubscribe[${o}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
557
557
  data: ${JSON.stringify(n)}
558
558
 
559
- `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=q(e.to);if(n===q(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let s=await this.forwarder(e.to,e);return s?{ok:s}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&q(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(q(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),s=this.recentRings.get(e.callId);if(s&&s>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+Zc),this.ringHandler)try{this.ringHandler(e)}catch(o){this.log(`ringHandler threw: ${o.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),s=this.pending.get(r)||[];s.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,s),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${s.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=q(e.to);for(let s of this.subs)s.callId===e.callId&&q(s.recipient)===r&&(this.deliverTo(s,e)?n++:this.subs.delete(s));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as Qc,readFileSync as Ks,renameSync as el,rmSync as tl,writeFileSync as nl}from"fs";import{homedir as rl}from"os";import{dirname as sl,join as ol}from"path";var Gs=ol(rl(),".agentx","call.json");function il(t=Gs,e=Date.now()){try{let n=JSON.parse(Ks(t,"utf-8"));if(n?.active===!0&&!(n.until&&Date.parse(n.until)<=e))return{active:!0,mode:"call",reason:`in a call${n.reason?`: ${n.reason}`:""}`}}catch{}return{active:!1,mode:null,reason:"not in a call"}}function Ys(t=Cn,e=il){let n=t();return n.active?n:e()}function tf(t,e,n=Gs,r=Date.now()){let s=null;try{s=JSON.parse(Ks(n,"utf-8"))}catch{}if(s&&s.source&&s.source!=="daemon")return;if(!t){s&&tl(n,{force:!0});return}Qc(sl(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;nl(o,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
560
- `),el(o,n)}var Js="owner",Pe=6e4,no=60*Pe,al=24*no,cl=7*24*no,ll=2*Pe,sf={enabled:!1,escalateAfterMinutes:10,ladder:[]};function dl(t){t.exec(`
559
+ `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=q(e.to);if(n===q(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let s=await this.forwarder(e.to,e);return s?{ok:s}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&q(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(q(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),s=this.recentRings.get(e.callId);if(s&&s>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+Jc),this.ringHandler)try{this.ringHandler(e)}catch(o){this.log(`ringHandler threw: ${o.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),s=this.pending.get(r)||[];s.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,s),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${s.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=q(e.to);for(let s of this.subs)s.callId===e.callId&&q(s.recipient)===r&&(this.deliverTo(s,e)?n++:this.subs.delete(s));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as Qc,readFileSync as Ks,renameSync as Zc,rmSync as el,writeFileSync as tl}from"fs";import{homedir as nl}from"os";import{dirname as rl,join as sl}from"path";var Gs=sl(nl(),".agentx","call.json");function ol(t=Gs,e=Date.now()){try{let n=JSON.parse(Ks(t,"utf-8"));if(n?.active===!0&&!(n.until&&Date.parse(n.until)<=e))return{active:!0,mode:"call",reason:`in a call${n.reason?`: ${n.reason}`:""}`}}catch{}return{active:!1,mode:null,reason:"not in a call"}}function Ys(t=Dn,e=ol){let n=t();return n.active?n:e()}function Zg(t,e,n=Gs,r=Date.now()){let s=null;try{s=JSON.parse(Ks(n,"utf-8"))}catch{}if(s&&s.source&&s.source!=="daemon")return;if(!t){s&&el(n,{force:!0});return}Qc(rl(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;tl(o,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
560
+ `),Zc(o,n)}var Js="owner",Pe=6e4,no=60*Pe,il=24*no,al=7*24*no,cl=2*Pe,nf={enabled:!1,escalateAfterMinutes:10,ladder:[]};function ll(t){t.exec(`
561
561
  CREATE TABLE IF NOT EXISTS owner_presence (
562
562
  person TEXT NOT NULL,
563
563
  surface TEXT NOT NULL,
564
564
  at INTEGER NOT NULL,
565
565
  PRIMARY KEY (person, surface)
566
566
  );
567
- `)}var Zs=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;dl(e)}written=new Map;touch(e,n=Js){let r=this.now(),s=`${n}
567
+ `)}var Qs=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;ll(e)}written=new Map;touch(e,n=Js){let r=this.now(),s=`${n}
568
568
  ${e}`;r-(this.written.get(s)??-1/0)<this.throttleMs||(this.written.set(s,r),this.db.prepare(`INSERT INTO owner_presence (person, surface, at) VALUES (?, ?, ?)
569
- ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=Js){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function of(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var Qs=class{constructor(e,n=Date.now){this.db=e;this.now=n;Ft(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
569
+ ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=Js){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function rf(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var Zs=class{constructor(e,n=Date.now){this.db=e;this.now=n;Mt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
570
570
  WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
571
- ORDER BY at DESC LIMIT 500`).all(this.now()-cl)}seenByRequest(e,n){return this.byRequest(e,r=>this.seen(r,n))}answeredByRequest(e,n,r=this.now()){return this.byRequest(e,s=>this.answered(s,n,r),r)}seenPush(e,n="phone"){let r=[],s=this.db.prepare("SELECT id, title FROM owner_told WHERE channel = 'push' AND outcome IN ('sent', 'held') AND at BETWEEN ? AND ? ORDER BY at DESC");for(let o of e){let i=o.title.endsWith("\u2026")?o.title.slice(0,-1):o.title,c=s.all(o.at-ll,o.at).find(l=>l.title===o.title||i!==o.title&&l.title.startsWith(i));c&&r.push(c.id)}return this.seen(r,n)}seen(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET seen_at = ?, seen_via = ?
571
+ ORDER BY at DESC LIMIT 500`).all(this.now()-al)}seenByRequest(e,n){return this.byRequest(e,r=>this.seen(r,n))}answeredByRequest(e,n,r=this.now()){return this.byRequest(e,s=>this.answered(s,n,r),r)}seenPush(e,n="phone"){let r=[],s=this.db.prepare("SELECT id, title FROM owner_told WHERE channel = 'push' AND outcome IN ('sent', 'held') AND at BETWEEN ? AND ? ORDER BY at DESC");for(let o of e){let i=o.title.endsWith("\u2026")?o.title.slice(0,-1):o.title,c=s.all(o.at-cl,o.at).find(l=>l.title===o.title||i!==o.title&&l.title.startsWith(i));c&&r.push(c.id)}return this.seen(r,n)}seen(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET seen_at = ?, seen_via = ?
572
572
  WHERE seen_at IS NULL AND (${eo(e)})`).run(r,n,...e,...e,...e).changes:0}answered(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET answered_at = ?, answered_via = ?, seen_at = COALESCE(seen_at, ?), seen_via = COALESCE(seen_via, ?)
573
- WHERE answered_at IS NULL AND (${eo(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let s=new Set(e.filter(Boolean));if(!s.size)return 0;let o=this.openRequestRows().filter(i=>s.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(o)}};function eo(t){let e=t.map(()=>"?").join(", ");return`id IN (${e}) OR escalation_of IN (${e}) OR id IN (SELECT escalation_of FROM owner_told WHERE id IN (${e}) AND escalation_of IS NOT NULL)`}function af(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(o=>`${o}:default`),...e.addresses],s=[];for(let o of r){let i=o.trim(),a=de(i);a&&n(a)&&!s.includes(i)&&s.push(i)}return s}function de(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function ul(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function pl(t){return de(t)==="push"?["phone","desk"]:[t]}function cf(t,e,n){let r=t.filter(o=>n(de(o)));if(!r.length)return null;let s=null;for(let o of r){let i=Math.max(-1/0,...e.filter(a=>pl(o).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!s||i>s.at)&&(s={stop:o,at:i})}return s?.stop??r[0]}function gl(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(o=>o!==e&&n(de(o)))??null}var fl=3;async function lf(t){let{db:e,ledger:n,settings:r,now:s}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let o=r.escalateAfterMinutes*Pe,i=e.prepare(`SELECT id FROM owner_told
573
+ WHERE answered_at IS NULL AND (${eo(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let s=new Set(e.filter(Boolean));if(!s.size)return 0;let o=this.openRequestRows().filter(i=>s.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(o)}};function eo(t){let e=t.map(()=>"?").join(", ");return`id IN (${e}) OR escalation_of IN (${e}) OR id IN (SELECT escalation_of FROM owner_told WHERE id IN (${e}) AND escalation_of IS NOT NULL)`}function sf(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(o=>`${o}:default`),...e.addresses],s=[];for(let o of r){let i=o.trim(),a=de(i);a&&n(a)&&!s.includes(i)&&s.push(i)}return s}function de(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function dl(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function ul(t){return de(t)==="push"?["phone","desk"]:[t]}function of(t,e,n){let r=t.filter(o=>n(de(o)));if(!r.length)return null;let s=null;for(let o of r){let i=Math.max(-1/0,...e.filter(a=>ul(o).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!s||i>s.at)&&(s={stop:o,at:i})}return s?.stop??r[0]}function pl(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(o=>o!==e&&n(de(o)))??null}var gl=3;async function af(t){let{db:e,ledger:n,settings:r,now:s}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let o=r.escalateAfterMinutes*Pe,i=e.prepare(`SELECT id FROM owner_told
574
574
  WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
575
575
  AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
576
576
  AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
577
- ORDER BY at LIMIT 20`).all(Math.max(s-fl*o,s-al),s-o),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),c=0;for(let{id:l}of i){if(a.run(s,l).changes!==1)continue;let d=n.get(l);if(!d)continue;let u=`${d.channel}:${d.chatId}`,p=gl(t.stops,u,t.up);if(!p){t.log(`[reach] urgent "${d.title.slice(0,80)}" ${d.outcome==="failed"?"failed":"unseen"} on ${u}; no other address to try`);continue}let g=Math.round((s-d.at)/Pe),f=d.outcome==="failed"?`it could not be sent on ${d.channel}`:`not seen on ${d.channel} for ${g} min`,b=`${d.text?`${d.text}
577
+ ORDER BY at LIMIT 20`).all(Math.max(s-gl*o,s-il),s-o),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),c=0;for(let{id:l}of i){if(a.run(s,l).changes!==1)continue;let d=n.get(l);if(!d)continue;let u=`${d.channel}:${d.chatId}`,p=pl(t.stops,u,t.up);if(!p){t.log(`[reach] urgent "${d.title.slice(0,80)}" ${d.outcome==="failed"?"failed":"unseen"} on ${u}; no other address to try`);continue}let g=Math.round((s-d.at)/Pe),f=d.outcome==="failed"?`it could not be sent on ${d.channel}`:`not seen on ${d.channel} for ${g} min`,b=`${d.text?`${d.text}
578
578
 
579
- `:""}(Sent again here: ${f}.)`,y=n.add({at:s,key:d.key,requestId:d.requestId,kind:d.kind,channel:de(p),chatId:ul(p),from:d.from,title:d.title,text:b,outcome:"sent",urgent:!0,escalationOf:d.id});try{await t.send(p,d,b),c++,t.log(`[reach] urgent "${d.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch(k){n.setOutcome(y,"failed"),t.log(`[reach] urgent "${d.title.slice(0,80)}": escalation to ${p} failed: ${k?.message??k}`)}}return c}var to=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,s]of Object.entries(this.opts.read())){let o=this.state.get(r)??{downSince:null,checks:0,told:!1};if(s.up){o.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}o.downSince??=e,o.checks++,o.reason=s.reason,!o.told&&o.checks>=n&&(o.told=!0,this.opts.log(`[reach] channel ${r} is down: ${s.reason??"no reason given"}`),this.opts.notice(r,s.reason??"no reason given")),this.state.set(r,o)}}downSince(e){return this.state.get(e)?.downSince??void 0}};var ml={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},ro=class{constructor(e=ml,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(s=>r-s<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},hl="That code didn't work. Check it, or run agentx app pair for a new one.",bl=400;async function pf(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),s=t.socket.remoteAddress||"unknown",o=e.limiter.retryAfter(s);if(o>0)return r(`[app] pair-code refused from ${s}: locked out for ${o}s more`),{status:429,body:{error:"too many attempts",retryAfter:o},retryAfter:o};let i=null;try{i=(await sr(t,1024)).code}catch{}let a=e.codes.redeem(i),c=a?e.verify(a.token):null;return await yl(n,e.minMs??bl),!a||!c?(e.limiter.fail(s),r(`[app] pair-code failed from ${s}`),{status:401,body:{error:hl}}):(e.limiter.succeed(s),r(`[app] pair-code paired ${a.tokenId} (${c}) from ${s}`),{status:200,body:{device:c},token:a.token})}async function yl(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as Ol}from"child_process";import{mkdtempSync as Al,rmSync as Rl,writeFileSync as Il}from"fs";import{tmpdir as Dl}from"os";import{join as co}from"path";import{randomBytes as wl}from"crypto";function $(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var F={top:8,side:32,bottom:60},Ut={height:56,keep:52},so=`
579
+ `:""}(Sent again here: ${f}.)`,y=n.add({at:s,key:d.key,requestId:d.requestId,kind:d.kind,channel:de(p),chatId:dl(p),from:d.from,title:d.title,text:b,outcome:"sent",urgent:!0,escalationOf:d.id});try{await t.send(p,d,b),c++,t.log(`[reach] urgent "${d.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch(k){n.setOutcome(y,"failed"),t.log(`[reach] urgent "${d.title.slice(0,80)}": escalation to ${p} failed: ${k?.message??k}`)}}return c}var to=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,s]of Object.entries(this.opts.read())){let o=this.state.get(r)??{downSince:null,checks:0,told:!1};if(s.up){o.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}o.downSince??=e,o.checks++,o.reason=s.reason,!o.told&&o.checks>=n&&(o.told=!0,this.opts.log(`[reach] channel ${r} is down: ${s.reason??"no reason given"}`),this.opts.notice(r,s.reason??"no reason given")),this.state.set(r,o)}}downSince(e){return this.state.get(e)?.downSince??void 0}};var fl={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},ro=class{constructor(e=fl,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(s=>r-s<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},ml="That code didn't work. Check it, or run agentx app pair for a new one.",hl=400;async function df(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),s=t.socket.remoteAddress||"unknown",o=e.limiter.retryAfter(s);if(o>0)return r(`[app] pair-code refused from ${s}: locked out for ${o}s more`),{status:429,body:{error:"too many attempts",retryAfter:o},retryAfter:o};let i=null;try{i=(await rr(t,1024)).code}catch{}let a=e.codes.redeem(i),c=a?e.verify(a.token):null;return await bl(n,e.minMs??hl),!a||!c?(e.limiter.fail(s),r(`[app] pair-code failed from ${s}`),{status:401,body:{error:ml}}):(e.limiter.succeed(s),r(`[app] pair-code paired ${a.tokenId} (${c}) from ${s}`),{status:200,body:{device:c},token:a.token})}async function bl(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as Ll}from"child_process";import{mkdtempSync as $l,rmSync as Al,writeFileSync as Rl}from"fs";import{tmpdir as Il}from"os";import{join as co}from"path";import{randomBytes as yl}from"crypto";function T(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var F={top:8,side:32,bottom:60},Ft={height:56,keep:52},so=`
580
580
  :root {
581
581
  --ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
582
582
  --ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
@@ -705,29 +705,29 @@ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: v
705
705
  button.primary:disabled { opacity: .55; cursor: not-allowed; }
706
706
  kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
707
707
  button.primary kbd { color: inherit; opacity: .7; }
708
- `;var oo=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),io=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function xl(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?oo(n):io(n)}`}function kl(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[io(n)],oo(n)].join(" ")}function vl(t){let e=t.trim().split(/[\s_-]+/).filter(Boolean);return(e.length>1?e[0][0]+e[1][0]:t.trim().slice(0,1)).toUpperCase()}function Sl(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var Wt=t=>`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`,El=Wt('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),_l=Wt('<path d="m6 15 6-6 6 6"/>'),$l=Wt('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function ao(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,s=wl(12).toString("base64"),o=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",c=qn(t),l=o.map((p,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${$(p)}</span>${g===c.index?'<i class="dot"></i>':""}</button>`).join(""),d=t.recommend?`<span class="rec"><i class="dot"></i>${$(r)} recommends</span>`:"",u={choices:o,draft:t.draft??"",placeholder:Wn,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=o.length?e.pick-1:c.index};return`<!doctype html>
708
+ `;var oo=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),io=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function wl(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?oo(n):io(n)}`}function xl(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[io(n)],oo(n)].join(" ")}function kl(t){let e=t.trim().split(/[\s_-]+/).filter(Boolean);return(e.length>1?e[0][0]+e[1][0]:t.trim().slice(0,1)).toUpperCase()}function vl(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var Ut=t=>`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`,Sl=Ut('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),El=Ut('<path d="m6 15 6-6 6 6"/>'),_l=Ut('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function ao(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,s=yl(12).toString("base64"),o=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",c=jn(t),l=o.map((p,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${T(p)}</span>${g===c.index?'<i class="dot"></i>':""}</button>`).join(""),d=t.recommend?`<span class="rec"><i class="dot"></i>${T(r)} recommends</span>`:"",u={choices:o,draft:t.draft??"",placeholder:Un,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=o.length?e.pick-1:c.index};return`<!doctype html>
709
709
  <html lang="en"><head><meta charset="utf-8">
710
710
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${s}'">
711
711
  <title>AgentX</title>
712
712
  <style>${so}</style></head>
713
713
  <body><div class="wrap"><main class="card${e.still?" still":""}">
714
- <div class="head" title="Drag to move"><span class="avatar">${$(vl(r))}</span>
715
- <div class="who"><b>${$(r)}</b><span>${$(xl(t.created_at,n))}</span></div>
714
+ <div class="head" title="Drag to move"><span class="avatar">${T(kl(r))}</span>
715
+ <div class="who"><b>${T(r)}</b><span>${T(wl(t.created_at,n))}</span></div>
716
716
  <span class="kind${i?"":" decision"}">${i?"Reminder":a?"Request":"Decision"}</span>
717
- <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${_l}</button></div>
718
- <div class="body"><h1 dir="auto">${$(t.title)}</h1>
719
- ${t.context?`<p class="context" dir="auto">${$(t.context)}</p>`:""}
720
- <p class="ask" dir="auto">${$(t.ask)}</p>
717
+ <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${El}</button></div>
718
+ <div class="body"><h1 dir="auto">${T(t.title)}</h1>
719
+ ${t.context?`<p class="context" dir="auto">${T(t.context)}</p>`:""}
720
+ <p class="ask" dir="auto">${T(t.ask)}</p>
721
721
  ${l||d?`<div class="label-row">${l?'<span class="label">Pick one</span>':""}${d}</div>`:""}
722
722
  ${l?`<div class="options" role="radiogroup">${l}</div>`:""}
723
- ${c.why?`<p class="why" dir="auto">${$(c.why)}</p>`:""}
723
+ ${c.why?`<p class="why" dir="auto">${T(c.why)}</p>`:""}
724
724
  ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><span class="edited"><i class="dot"></i>Edited</span><button class="reset" id="reset">Reset</button></div>
725
725
  <textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
726
- <div class="notes"><div>${El}<span>${a?`It stays on the ${he} until you close it.`:`If you don't answer by ${$(kl(t.expires,n))}: ${$(t.if_silent)}.`}</span></div>
727
- <div>${$l}<span>Nothing goes out until you click.</span></div></div>
726
+ <div class="notes"><div>${Sl}<span>${a?`It stays on the ${he} until you close it.`:`If you don't answer by ${T(xl(t.expires,n))}: ${T(t.if_silent)}.`}</span></div>
727
+ <div>${_l}<span>Nothing goes out until you click.</span></div></div>
728
728
  </div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
729
729
  <button class="btn" id="no">${a?"Drop":"No"}</button>
730
- <button class="btn primary" id="yes">${Sl(t)}<kbd>\u2318\u21A9</kbd></button></div>
730
+ <button class="btn primary" id="yes">${vl(t)}<kbd>\u2318\u21A9</kbd></button></div>
731
731
  </main></div>
732
732
  <script type="application/json" id="data">${JSON.stringify(u).replace(/</g,"\\u003c")}</script>
733
733
  <script nonce="${s}">${Tl}</script>
@@ -820,10 +820,10 @@ ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><sp
820
820
  });
821
821
  } catch (e) {}
822
822
  })();
823
- `;var Cl=440,Nl=`
823
+ `;var Dl=440,Cl=`
824
824
  ObjC.import("Cocoa"); ObjC.import("WebKit")
825
825
  function run(argv) {
826
- var path = argv[0], side = ${F.side}, gripTop = ${F.top}, gripEnd = ${F.top+Ut.height}, keep = ${Ut.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
826
+ var path = argv[0], side = ${F.side}, gripTop = ${F.top}, gripEnd = ${F.top+Ft.height}, keep = ${Ft.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
827
827
  var app = $.NSApplication.sharedApplication
828
828
  app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
829
829
  ObjC.registerSubclass({ name: "AgentXCardView", superclass: "WKWebView", methods: {
@@ -895,27 +895,29 @@ function run(argv) {
895
895
  }
896
896
  function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
897
897
  function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
898
- `;function Ll(t,e){let n=t.trim().split(`
898
+ `;function Nl(t,e){let n=t.trim().split(`
899
899
  `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&uo.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let s=e.choices??[],o;if(s.length){if(typeof r.choice!="string"||!s.includes(r.choice))return{action:"dismiss"};o=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
900
- `).trim():"",!i||i.length>Un.text)?{action:"dismiss"}:{action:"yes",...o?{choice:o}:{},...i?{text:i}:{}}}async function lo(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=Al(co(Dl(),"agentx-card-"));try{let o=co(s,"card.html");Il(o,ao(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",Nl,o,String(Cl),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?Ll(a.stdout,t):null}finally{Rl(s,{recursive:!0,force:!0})}}var uo=["not now","timed out","closed"],Pl=(t,e,n)=>new Promise(r=>{try{Ol(t,e,{timeout:n},(s,o)=>r({ok:!s,stdout:String(o??"")}))}catch{r({ok:!1,stdout:""})}}),po=160,jt=15e3;function go(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>po?e.slice(0,po):e}async function Ml(t,e,n,r,s){let o=e.sound==="chime"?r?"":"Glass":e.sound,i=o?rr(o):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],jt),!!e.speak)if(s){let a;await Promise.race([s(go(t)),new Promise(c=>{a=setTimeout(c,jt)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",go(t)],jt)}}function ho(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function Fl(t,e,n){return ho(["on run argv","set opts to items 3 thru -1 of argv",'set pick to choose from list opts with title (item 1 of argv) with prompt (item 2 of argv) OK button name "Next" cancel button name "Not now"','if pick is false then return ""',"return item 1 of pick","end run"],[t,e,...n])}function fo(t,e,n,r,s){return ho(["on run argv","set AppleScript's text item delimiters to linefeed","set btns to text items of (item 3 of argv)","set secs to (item 5 of argv) as integer","if (count of argv) > 5 then","set r to display dialog (item 2 of argv) with title (item 1 of argv) default answer (item 6 of argv) buttons btns default button (item 4 of argv) giving up after secs","else","set r to display dialog (item 2 of argv) with title (item 1 of argv) buttons btns default button (item 4 of argv) giving up after secs","end if",'if gave up of r then return ""',"if (count of argv) > 5 then return (button returned of r) & linefeed & (text returned of r)","return button returned of r","end run"],[t,e,n.join(`
900
+ `).trim():"",!i||i.length>Fn.text)?{action:"dismiss"}:{action:"yes",...o?{choice:o}:{},...i?{text:i}:{}}}async function lo(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=$l(co(Il(),"agentx-card-"));try{let o=co(s,"card.html");Rl(o,ao(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",Cl,o,String(Dl),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?Nl(a.stdout,t):null}finally{Al(s,{recursive:!0,force:!0})}}var uo=["not now","timed out","closed"],Ol=(t,e,n)=>new Promise(r=>{try{Ll(t,e,{timeout:n},(s,o)=>r({ok:!s,stdout:String(o??"")}))}catch{r({ok:!1,stdout:""})}}),po=160,Wt=15e3;function go(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>po?e.slice(0,po):e}async function Pl(t,e,n,r,s){let o=e.sound==="chime"?r?"":"Glass":e.sound,i=o?nr(o):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],Wt),!!e.speak)if(s){let a;await Promise.race([s(go(t)),new Promise(c=>{a=setTimeout(c,Wt)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",go(t)],Wt)}}function ho(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function Ml(t,e,n){return ho(["on run argv","set opts to items 3 thru -1 of argv",'set pick to choose from list opts with title (item 1 of argv) with prompt (item 2 of argv) OK button name "Next" cancel button name "Not now"','if pick is false then return ""',"return item 1 of pick","end run"],[t,e,...n])}function fo(t,e,n,r,s){return ho(["on run argv","set AppleScript's text item delimiters to linefeed","set btns to text items of (item 3 of argv)","set secs to (item 5 of argv) as integer","if (count of argv) > 5 then","set r to display dialog (item 2 of argv) with title (item 1 of argv) default answer (item 6 of argv) buttons btns default button (item 4 of argv) giving up after secs","else","set r to display dialog (item 2 of argv) with title (item 1 of argv) buttons btns default button (item 4 of argv) giving up after secs","end if",'if gave up of r then return ""',"if (count of argv) > 5 then return (button returned of r) & linefeed & (text returned of r)","return button returned of r","end run"],[t,e,n.join(`
901
901
  `),n[n.length-1],String(r),...s!==void 0?[s]:[]])}function mo(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
902
- `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function qt(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
902
+ `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function jt(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
903
903
 
904
- `)}async function bo(t,e,n={}){let r=n.run??Pl,s=(e.style??"card")==="card",o=Ml(t,e,r,s,n.speak).catch(()=>{});if(s){let i=await lo(t,{timeoutSeconds:e.timeoutSeconds,sound:e.sound,volume:e.volume,theme:e.theme,from:n.from,capture:n.capture,pick:n.pick},r).catch(()=>null);if(i)return i}return await o,Ul(t,e,r)}async function Ul(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=(r+5)*1e3,o=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let l=await n("/usr/bin/osascript",Fl(o,qt(t),t.choices),s);if(i=l.stdout.replace(/\n$/,""),!l.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let l=i?`${i}
904
+ `)}async function bo(t,e,n={}){let r=n.run??Ol,s=(e.style??"card")==="card",o=Pl(t,e,r,s,n.speak).catch(()=>{});if(s){let i=await lo(t,{timeoutSeconds:e.timeoutSeconds,sound:e.sound,volume:e.volume,theme:e.theme,from:n.from,capture:n.capture,pick:n.pick},r).catch(()=>null);if(i)return i}return await o,Fl(t,e,r)}async function Fl(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=(r+5)*1e3,o=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let l=await n("/usr/bin/osascript",Ml(o,jt(t),t.choices),s);if(i=l.stdout.replace(/\n$/,""),!l.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let l=i?`${i}
905
905
 
906
- Message (edit it if you like):`:`${qt(t)}
906
+ Message (edit it if you like):`:`${jt(t)}
907
907
 
908
- Message (edit it if you like):`,u=await n("/usr/bin/osascript",fo(o,l,i?["Cancel","Send"]:["Not now","No","Send"],r,jn(t.draft,i)),s),p=u.ok?mo(u.stdout):null;if(p?.button==="Send"){let g=p.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return p?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",fo(o,qt(t),["Not now","No","Yes"],r),s),c=a.ok?mo(a.stdout):null;return c?.button==="Yes"?{action:"yes"}:c?.button==="No"?{action:"no"}:{action:"dismiss"}}var Vt=24*36e5,Bt=!1,Wl=10*6e4,yo=-1/0;function wo(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s,passAt:o,wanted:i=[]}=A(t.root),a=o?Date.parse(o):NaN,c=Y(t.root,"pending").filter(d=>Date.parse(d.expires)>n),l=c.find(d=>i.includes(`card:${d.id}`));if(l)return l;for(let d of c){let u=`card:${d.id}`;if(r[u]||!e(d)||gr(t.root,d.id,n))continue;let p=s[u];if(p&&Date.parse(p)>n)continue;let g=Date.parse(d.created_at);if(!(n-g>Vt&&!(g<=a)))return d}return null}function Ht(t){try{return V(t)?.listByState("needs_attention")??[]}catch{return[]}}var xo=new Map;function jl(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s}=A(t.root);return e({})?Ht(t).find(o=>{let i=`request:${o.id}`,a=s[i];return xo.get(o.id)===H(o,Qe.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-o.updatedAt<=Vt})??null:null}function ql(t,e){return{id:t.id,title:H(t,Qe.title).headline,context:t.attentionReason??"It is not finished and nothing is retrying it.",ask:`Hand it back to ${t.agentId}, or drop it?`,say:"A request you made is not finished.",recommend:"",if_silent:"keep",expires:new Date(e+Vt).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Hf(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(Bt)return"busy";let s=wo(e,t.reaches)?null:jl(e,t.reaches),o=s?ql(s,e.now??Date.now()):wo(e,t.reaches);if(!o)return"none";let i=(t.focus??Ys)();if(i.active)return"held";let a=`${s?"request":"card"}:${o.id}`,c=(A(e.root).wanted??[]).includes(a)?null:ir(o);if(c){if(s)xo.set(s.id,o.title);else{let l=[...Y(e.root,"pending").map(d=>`card:${d.id}`),...Ht(e).map(d=>`request:${d.id}`)];rt(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${o.raised_by}: ${c}`),t.returnToAuthor?.(o,ar(o,c)),"returned"}Bt=!0;try{let l=[...Y(e.root,"pending").map(y=>`card:${y.id}`),...Ht(e).map(y=>`request:${y.id}`)];rt(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${o.raised_by}`);let d=e.now??Date.now(),u=!!s&&d-yo<Wl;s&&n.speak&&(yo=d);let p=t.agentName?.(o.raised_by)??(o.node?`${o.raised_by} on ${o.node}`:void 0),g=await(t.show??bo)(o,u?{...n,speak:!1}:n,{from:p,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${Nn(i)} when shown)`),"shown";if(!(s?V(e)?.get(s.id)?.state==="needs_attention":ie(e.root,o.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let b=await es(e,a,g.action,{by:"operator (popup)",...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(b.ok?`[approvals] popup: ${b.message}`:`[approvals] popup: ${a} not recorded: ${b.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{Bt=!1}}function Vf(t,e,n){if(!n)return{ok:!1,error:"the Mac popup is off; turn it on with `agentx approvals settings --popup on`"};let r=e.startsWith("card:")?ie(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Er(t.root,e),{ok:!0,message:`${e} will show on the Mac within a minute`}):{ok:!1,error:`no card "${e}"; the popup shows decision cards only`}}import{existsSync as Bl,mkdirSync as Hl,readFileSync as Vl,renameSync as Xl,writeFileSync as zl}from"fs";import{dirname as Kl,resolve as Gl}from"path";var Yl=["all","urgent","off"],Jl=24*36e5,ko=24*36e5,Zl=30*24*36e5,vo=t=>Yl.includes(t);function Gf(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:vo(e)?e:"off",computer:vo(n)?n:t.popupEnabled?"all":"off"}}function Eo(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=Jl}function So(t,e,n){return t==="all"||t==="urgent"&&Eo(e,n)}function _o(t){return Gl(t,".agentx","desk-routed.json")}function Ql(t){let e=_o(t);if(!Bl(e))return null;try{let n=JSON.parse(Vl(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function Xt(t,e){let n=_o(t);Hl(Kl(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;zl(r,JSON.stringify(e,null,2)),Xl(r,n)}async function Yf(t){let{root:e,now:n,list:r,routing:s,log:o}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),c=Ql(e);if(!c){let u={};for(let p of r.items)u[p.key]={at:a,seen:a};return Xt(e,{items:u}),i.primed=!0,i}let l=[],d=[];for(let u of r.items){let p=c.items[u.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>ko&&delete p.computerHeld,p.computerHeld&&d.push(u);continue}c.items[u.key]={at:a,seen:a};let g=u.askedAt?Date.parse(u.askedAt):n;n-g<=ko&&l.push(u)}for(let[u,p]of Object.entries(c.items))n-Date.parse(p.seen)>Zl&&delete c.items[u];Xt(e,c);for(let u of l)if(So(s.phone,u,n))try{await t.phone(u,Eo(u,n)),i.phone.push(u.key)}catch(p){o(`[desk] ${u.key}: not sent to the phone: ${p?.message??p}`)}if(t.computer){let u=!1;for(let p of[...d,...l]){let g=c.items[p.key];if(!So(s.computer,p,n)){g.computerHeld&&(delete g.computerHeld,u=!0);continue}try{let f=await t.computer(p);f&&i.computer.push(p.key),f&&g.computerHeld&&(delete g.computerHeld,u=!0),!f&&!g.computerHeld&&(g.computerHeld=!0,u=!0)}catch(f){o(`[desk] ${p.key}: not shown on this computer: ${f?.message??f}`),g.computerHeld&&(delete g.computerHeld,u=!0)}}u&&Xt(e,c)}return(i.phone.length||i.computer.length)&&o(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Jf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
909
- Answer it on the Desk.`}}import{closeSync as ue,createReadStream as ed,fstatSync as td,openSync as nd,realpathSync as $o}from"fs";import{isAbsolute as rd,resolve as To,sep as Ao}from"path";var rm="/app-files",sd=/^[A-Za-z0-9_.:-]{1,64}$/;function od(t,e,n=process.cwd()){if(!e||e.length>P.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:`the path leaves the workspace: copy the file into ${Ke}/ first`};if(!se(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=$o(To(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let s;try{s=$o(rd(e)?e:To(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!s.startsWith(r+Ao))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Ke}/ first`};let o=se(s);return o?{ok:!0,path:s,...o}:{ok:!1,status:415,error:"this type of file is not served"}}function id(t,e){let n=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\;]/g,"_").slice(0,120)||"file";return`${e==="file"?"attachment":"inline"}; filename="${n}"; filename*=UTF-8''${encodeURIComponent(t.slice(0,120))}`}function ad(t,e,n){return{"Content-Type":t,"Content-Disposition":id(e,n),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; img-src 'self'; media-src 'self'; sandbox","Cache-Control":"private, max-age=3600","Accept-Ranges":"bytes"}}function cd(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,s;return n[1]?(r=Number(n[1]),s=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),s=e-1),r>s||r>=e?"unsatisfiable":{start:r,end:s}}function sm(t,e,n,r){let s=(k,h)=>{e.writeHead(k,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(h))};if(t.method!=="GET"&&t.method!=="HEAD")return s(405,{error:"GET only"});let o=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!sd.test(o))return s(400,{error:"bad agent id"});let a=r.workspaceOf(o);if(!a)return s(404,{error:`no agent "${o}" on this computer`});let c=od(a,i,r.cwd);if(!c.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${o}: ${c.error}`),s(c.status,{error:c.error});let l;try{l=nd(c.path,"r")}catch{return s(404,{error:"file not found"})}let d;try{let k=td(l);if(!k.isFile())return ue(l),s(404,{error:"not a file"});d=k.size}catch{return ue(l),s(404,{error:"file not found"})}if(d>P.bytes)return ue(l),s(413,{error:`the file is larger than ${P.bytes/1024/1024} MB`});let u=c.path.split(Ao).pop()||"file",p=ad(c.mime,u,c.kind),g=cd(t.headers.range,d);if(g==="unsatisfiable"){ue(l),e.writeHead(416,{...p,"Content-Range":`bytes */${d}`}),e.end();return}let{start:f,end:b}=g??{start:0,end:d-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(d?b-f+1:0),...g?{"Content-Range":`bytes ${f}-${b}/${d}`}:{}}),t.method==="HEAD"||d===0){ue(l),e.end();return}let y=ed("",{fd:l,start:f,end:b,autoClose:!0});y.on("error",()=>e.destroy()),e.on("close",()=>y.destroy()),y.pipe(e)}import{spawn as pe}from"child_process";import{readFileSync as ld,writeFileSync as dd}from"fs";import{tmpdir as ud}from"os";import{join as pd}from"path";un();var Ro=t=>t&&t!==1?Math.round(175*t):null,Me=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function gd(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=ld(t,"utf8").trim();if(e)return e}catch{}return null}function gm(t=gd()){let e=0;return async(n,r)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...Me(n.voice.rate)?{voice_settings:{speed:Me(n.voice.rate)}}:{}}),signal:r});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text()).slice(0,160)}`);let o=pd(ud(),`agentx-say-${process.pid}-${++e}.mp3`);return dd(o,Buffer.from(await s.arrayBuffer())),o}catch(s){if(r.aborted||!n.voice.fallback)throw s;return X(`elevenlabs:${String(s?.message??s).slice(0,40)}`,`[voice] ElevenLabs failed (${String(s?.message??s).slice(0,160)}); speaking with the system voice`),null}}}function Io(t,e){let n=t.languages&&me(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var fd=(t,e="")=>{let n=Io(t,e),r=Ro(t.rate);return[...n&&!gs(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function md(t,e,n){if(!n)return["say",fd(t,e)];let r=Io(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function fm(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function mm(t=zt()){if(t)try{pe("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function hm(t=zt()){if(t)try{pe("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function zt(t={},e){if(!mt(t))return null;try{return hs(e)}catch(n){return X("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
910
- `)[0]}); Siri voices will not switch`),null}}var bm=(t,e)=>{if(!t){let[n,r]=md(e.voice,e.text,zt()),s=Ro(e.voice.rate),o=s?{...process.env,AGENTX_SAY_RATE:String(s)}:process.env,i=pe(n,r,{stdio:["pipe","ignore","ignore"],env:o});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?pe("afplay",[t],{stdio:"ignore"}):pe("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Do}from"child_process";import{accessSync as hd,constants as bd,readFileSync as Co}from"fs";import{homedir as yd}from"os";import{basename as te,delimiter as No,dirname as wd,extname as xd,join as Kt}from"path";var B={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function Lo(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>B.ms+2e3?{status:413,error:Yt()}:null}var Yt=()=>`The recording is longer than ${B.ms/6e4} minutes.`,kd={"audio/webm":"webm","video/webm":"webm","audio/ogg":"ogg","audio/mp4":"m4a","video/mp4":"m4a","audio/x-m4a":"m4a","audio/aac":"aac","audio/mpeg":"mp3","audio/wav":"wav","audio/x-wav":"wav","audio/wave":"wav"};function Oo(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return kd[e]??null}function Po(t,e){let n=[];return t!=="local"&&e.key&&n.push("elevenlabs"),e.ffmpeg&&(e.mlx?n.push("mlx-whisper"):e.whisper&&n.push("whisper")),n}function Jt(t,e){return t==="local"&&e.key&&!e.ffmpeg?"Speech to text is set to local, and this computer has no ffmpeg.":(e.mlx||e.whisper)&&!e.ffmpeg?"This computer has Whisper but no ffmpeg to read the recording.":"Add an ElevenLabs key on this computer, or install mlx-whisper and ffmpeg."}function Gt(t,e,n=process.env.PATH??""){let r=yd(),s=[Kt(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(No).filter(Boolean)];for(let o of[e,...s.map(i=>Kt(i,t))])if(o)try{return hd(o,bd.X_OK),o}catch{}return null}function Sm(t){return{key:t,mlx:Gt("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:Gt("whisper",process.env.AGENTX_WHISPER),ffmpeg:vd()}}var vd=()=>Gt("ffmpeg",process.env.AGENTX_FFMPEG);async function Mo(t,e){return e?Sd(t,e):null}async function Sd(t,e){let n=String(B.ms/1e3+5);try{let s=[...(await Ed(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],o=s[s.length-1];return o?Number(o[1])*3600+Number(o[2])*60+Number(o[3]):null}catch{return null}}async function Fo(t,e,n,r){let s=new FormData;s.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),s.set("file",new Blob([Co(t)],{type:e}),te(t));let o=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:s,signal:r??AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text().catch(()=>"")).slice(0,160)}`);let i=await o.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function Uo(t,e,n,r,s){let o=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",s,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",s,"--fp16","False"],i={...process.env,PATH:`${wd(r)}${No}${process.env.PATH??""}`};await _d(e,o,12e4,i);try{return Co(Kt(s,te(n,xd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Ed(t,e,n){return new Promise((r,s)=>{let o=Do(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{o.kill("SIGKILL"),s(new Error(`${te(t)} took too long`))},n);o.stderr.on("data",c=>{i=(i+c).slice(-8192)}),o.on("error",c=>{clearTimeout(a),s(c)}),o.on("exit",c=>{clearTimeout(a),c===0?r(i):s(new Error(`${te(t)} exited ${c}`))})})}function _d(t,e,n,r=process.env){return new Promise((s,o)=>{let i=Do(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",c="",l=setTimeout(()=>{i.kill("SIGKILL"),o(new Error(`${te(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",d=>{a.length<4096&&(a+=d)}),i.stderr.on("data",d=>{c.length<4096&&(c+=d)}),i.on("error",d=>{clearTimeout(l),o(d)}),i.on("exit",d=>{clearTimeout(l),d===0?s(a):o(new Error(`${te(t)} exited ${d}: ${c.trim().split(`
911
- `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as $d,rm as Td,writeFile as Ad}from"fs/promises";import{tmpdir as Rd}from"os";import{join as Wo}from"path";Qo();var Id=64*1024,Dd=2,Zt=0;function Lm(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Om(t,e,n,r){return t.method!=="POST"?S(e,405,{error:"POST"}):n==="/voice/transcribe"?Cd(t,e,r):Od(t,e,r)}async function Cd(t,e,n){let r=String(t.headers["content-type"]||""),s=Oo(r);if(!s)return S(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let o=Lo(t.headers["x-audio-duration-ms"]);if(o)return t.resume(),S(e,o.status,{error:o.error});let i=await jo(t,B.bytes);if(!i)return S(e,413,{error:Fd()});if(!i.length)return S(e,400,{error:"The recording is empty."});if(Zt>=Dd)return S(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),c=n.host(),l=Po(a,c);if(!c.ffmpeg&&!n.allowUnmeasured?.()){let u=n.nodeName?`on ${n.nodeName}`:"on this computer",p=l.length?"":" "+Jt(a,c);return S(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${u} for voice input from the phone.${p}`,setup:!1})}if(!l.length)return S(e,503,{error:"Voice input isn't set up on this computer.",hint:Jt(a,c),setup:!1});Zt++;let d;try{let u=await $d(Wo(Rd(),"agentx-phone-voice-"));try{d=await Nd(u,`speech.${s}`,i,r,c,l,n)}finally{await Td(u,{recursive:!0,force:!0}).catch(()=>{})}}finally{Zt--}S(e,d[0],d[1])}async function Nd(t,e,n,r,s,o,i){let a=Wo(t,e);if(await Ad(a,n,{mode:384}),s.ffmpeg){let l=await(i.measure??Mo)(a,s.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>B.ms+2e3)return[413,{error:Yt()}]}let c=[];for(let l of o)try{let d=await Ld(l,a,r,s,t,i);return i.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),d?[200,{text:d,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(d){let u=String(d?.message??d).split(`
912
- `)[0].slice(0,200);c.push(`${l}: ${u}`),i.log(`[voice] phone transcription with ${l} failed: ${u}`)}return[502,{error:"Speech to text failed on this computer.",detail:c.join("; ")}]}function Ld(t,e,n,r,s,o){let i=o.engines?.[t];if(i)return i(e,n,r,s);if(t==="elevenlabs")return Fo(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return Uo(t,a,e,r.ffmpeg,s)}async function Od(t,e,n){let r=await jo(t,Id);if(!r)return S(e,413,{error:"request too large"});let s;try{s=JSON.parse(r.toString("utf8")||"{}")}catch{return S(e,400,{error:"expected JSON"})}let o=typeof s?.agent=="string"?s.agent:"",i=typeof s?.peer=="string"&&s.peer?s.peer:void 0;if(!o)return S(e,400,{error:"agent is required"});let a=Pd(typeof s?.text=="string"?s.text:"",n.spokenMaxChars?.());if(!a)return S(e,422,{error:"Nothing in this answer can be said aloud."});let c=n.pronounce?n.pronounce(a):a,l=n.voiceOf(o,i);if(!l)return S(e,404,{error:`Unknown agent: ${o}`});let d=(p,g=200)=>S(e,g,{fallback:"browser",reason:p,text:c});if(l.provider!=="elevenlabs")return d("This agent speaks with a system voice, which only plays on the computer.");let u=n.elevenLabsKey();if(!u)return d("No ElevenLabs key is set on this computer.");try{let p=await(n.synth??Md)(u,l,c);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(c.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
913
- `)[0].slice(0,160)}`),d("ElevenLabs could not speak this answer.",502)}}function Pd(t,e){let n=Oe(ye(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return pn(n,e)}async function Md(t,e,n){let r=Me(e.rate),s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(e.elevenlabs)}?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n,model_id:"eleven_flash_v2_5",...r?{voice_settings:{speed:r}}:{}}),signal:AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await s.arrayBuffer())}var Fd=()=>`The recording is larger than ${B.bytes/1024/1024} MB, more than ${B.ms/6e4} minutes of speech.`;function Pm(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let s=n.agents??{};return s[t]?_t(vt(t,s,n.voice)):null}function jo(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let s=[],o=0;t.on("data",i=>{if(!(o>e)){if(o+=i.length,o>e){s.length=0,n(null);return}s.push(i)}}),t.on("end",()=>{o<=e&&n(Buffer.concat(s))}),t.on("error",r)})}function S(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}var Ud="operator",Wd=50,qo=4,Bo=500;function jd(t){let e={channel:"app",chatId:t.chatId,sender:Ud,...t.spoken?{via:"voice"}:{}};return t.node==="local"?{path:"/task",body:{agent:t.agent,message:t.message,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:t.message,stream:!0,context:e}}}async function jm(t,e,n,r){let{path:s,body:o}=jd(e),i="",a=!1,c=[],l=new Map,d=(u,p,g)=>{let f=u!=="done",b=a?{text:Rn(p,f),artifacts:[]}:ye(p,P.perMessage,f),{cleanText:y,ui:k}=u==="done"?Oe(b.text):{cleanText:b.text,ui:void 0},h=a?void 0:Bd(k);return{status:u,text:y,tools:c,files:b.artifacts,...h?{ui:h}:{},...g?{error:g}:{}}};try{let u=await fetch(t.url.replace(/\/+$/,"")+s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(o),signal:n});if(!u.ok||!u.body){let p=await u.json().then(g=>g?.error).catch(()=>"");return d("error",i,p||`AgentX answered HTTP ${u.status}.`)}for await(let p of Hd(u.body)){r(p.event,p.data);let g=p.data??{};if(p.event==="start")a=g.rich===!1;else if(p.event==="text"&&typeof g.text=="string")i+=g.text;else if(p.event==="tool"&&g.status==="start"&&c.length<Wd){let f={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};c.push(f),g.id&&l.set(String(g.id),f)}else if(p.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(p.event==="done")return d("done",typeof g.content=="string"&&g.content?g.content:i);if(p.event==="error")return d("error",i,qd(g.error))}}return n.aborted?d("stopped",i):d("error",i,"The connection to the agent closed before it answered.")}catch(u){return n.aborted?d("stopped",i):d("error",i,`Could not reach AgentX: ${u?.message||u}`)}}function qd(t){let e=String(t||"The agent could not answer.");return En(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function Bd(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let s=(t.quickReplies??[]).slice(0,qo).map(i=>i.slice(0,Bo));s.length&&(n.quickReplies=s);let o=(t.replies??[]).slice(0,qo).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,Bo)}));return o.length&&(n.replies=o),Object.keys(n).length?n:void 0}async function*Hd(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:s,value:o}=await e.read();if(s)break;r+=n.decode(o,{stream:!0}).replace(/\r\n/g,`
908
+ Message (edit it if you like):`,u=await n("/usr/bin/osascript",fo(o,l,i?["Cancel","Send"]:["Not now","No","Send"],r,Wn(t.draft,i)),s),p=u.ok?mo(u.stdout):null;if(p?.button==="Send"){let g=p.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return p?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",fo(o,jt(t),["Not now","No","Yes"],r),s),c=a.ok?mo(a.stdout):null;return c?.button==="Yes"?{action:"yes"}:c?.button==="No"?{action:"no"}:{action:"dismiss"}}var Ht=24*36e5,qt=!1,Ul=10*6e4,yo=-1/0;function wo(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s,passAt:o,wanted:i=[]}=A(t.root),a=o?Date.parse(o):NaN,c=Y(t.root,"pending").filter(d=>Date.parse(d.expires)>n),l=c.find(d=>i.includes(`card:${d.id}`));if(l)return l;for(let d of c){let u=`card:${d.id}`;if(r[u]||!e(d)||gr(t.root,d.id,n))continue;let p=s[u];if(p&&Date.parse(p)>n)continue;let g=Date.parse(d.created_at);if(!(n-g>Ht&&!(g<=a)))return d}return null}function Bt(t){try{return V(t)?.listByState("needs_attention")??[]}catch{return[]}}var xo=new Map;function Wl(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s}=A(t.root);return e({})?Bt(t).find(o=>{let i=`request:${o.id}`,a=s[i];return xo.get(o.id)===H(o,Ze.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-o.updatedAt<=Ht})??null:null}function jl(t,e){return{id:t.id,title:H(t,Ze.title).headline,context:t.attentionReason??"It is not finished and nothing is retrying it.",ask:`Hand it back to ${t.agentId}, or drop it?`,say:"A request you made is not finished.",recommend:"",if_silent:"keep",expires:new Date(e+Ht).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function qf(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(qt)return"busy";let s=wo(e,t.reaches)?null:Wl(e,t.reaches),o=s?jl(s,e.now??Date.now()):wo(e,t.reaches);if(!o)return"none";let i=(t.focus??Ys)();if(i.active)return"held";let a=`${s?"request":"card"}:${o.id}`,c=(A(e.root).wanted??[]).includes(a)?null:or(o);if(c){if(s)xo.set(s.id,o.title);else{let l=[...Y(e.root,"pending").map(d=>`card:${d.id}`),...Bt(e).map(d=>`request:${d.id}`)];rt(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${o.raised_by}: ${c}`),t.returnToAuthor?.(o,ir(o,c)),"returned"}qt=!0;try{let l=[...Y(e.root,"pending").map(y=>`card:${y.id}`),...Bt(e).map(y=>`request:${y.id}`)];rt(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${o.raised_by}`);let d=e.now??Date.now(),u=!!s&&d-yo<Ul;s&&n.speak&&(yo=d);let p=t.agentName?.(o.raised_by)??(o.node?`${o.raised_by} on ${o.node}`:void 0),g=await(t.show??bo)(o,u?{...n,speak:!1}:n,{from:p,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${Cn(i)} when shown)`),"shown";if(!(s?V(e)?.get(s.id)?.state==="needs_attention":ie(e.root,o.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let b=await es(e,a,g.action,{by:"operator (popup)",...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(b.ok?`[approvals] popup: ${b.message}`:`[approvals] popup: ${a} not recorded: ${b.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{qt=!1}}function Bf(t,e,n){if(!n)return{ok:!1,error:"the Mac popup is off; turn it on with `agentx approvals settings --popup on`"};let r=e.startsWith("card:")?ie(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Er(t.root,e),{ok:!0,message:`${e} will show on the Mac within a minute`}):{ok:!1,error:`no card "${e}"; the popup shows decision cards only`}}import{existsSync as ql,mkdirSync as Bl,readFileSync as Hl,renameSync as Vl,writeFileSync as Xl}from"fs";import{dirname as zl,resolve as Kl}from"path";var Gl=["all","urgent","off"],Yl=24*36e5,ko=24*36e5,Jl=30*24*36e5,vo=t=>Gl.includes(t);function zf(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:vo(e)?e:"off",computer:vo(n)?n:t.popupEnabled?"all":"off"}}function Eo(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=Yl}function So(t,e,n){return t==="all"||t==="urgent"&&Eo(e,n)}function _o(t){return Kl(t,".agentx","desk-routed.json")}function Ql(t){let e=_o(t);if(!ql(e))return null;try{let n=JSON.parse(Hl(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function Vt(t,e){let n=_o(t);Bl(zl(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Xl(r,JSON.stringify(e,null,2)),Vl(r,n)}async function Kf(t){let{root:e,now:n,list:r,routing:s,log:o}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),c=Ql(e);if(!c){let u={};for(let p of r.items)u[p.key]={at:a,seen:a};return Vt(e,{items:u}),i.primed=!0,i}let l=[],d=[];for(let u of r.items){let p=c.items[u.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>ko&&delete p.computerHeld,p.computerHeld&&d.push(u);continue}c.items[u.key]={at:a,seen:a};let g=u.askedAt?Date.parse(u.askedAt):n;n-g<=ko&&l.push(u)}for(let[u,p]of Object.entries(c.items))n-Date.parse(p.seen)>Jl&&delete c.items[u];Vt(e,c);for(let u of l)if(So(s.phone,u,n))try{await t.phone(u,Eo(u,n)),i.phone.push(u.key)}catch(p){o(`[desk] ${u.key}: not sent to the phone: ${p?.message??p}`)}if(t.computer){let u=!1;for(let p of[...d,...l]){let g=c.items[p.key];if(!So(s.computer,p,n)){g.computerHeld&&(delete g.computerHeld,u=!0);continue}try{let f=await t.computer(p);f&&i.computer.push(p.key),f&&g.computerHeld&&(delete g.computerHeld,u=!0),!f&&!g.computerHeld&&(g.computerHeld=!0,u=!0)}catch(f){o(`[desk] ${p.key}: not shown on this computer: ${f?.message??f}`),g.computerHeld&&(delete g.computerHeld,u=!0)}}u&&Vt(e,c)}return(i.phone.length||i.computer.length)&&o(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Gf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
909
+ Answer it on the Desk.`}}import{closeSync as ue,createReadStream as Zl,fstatSync as ed,openSync as td,realpathSync as To}from"fs";import{isAbsolute as nd,resolve as $o,sep as Ao}from"path";var tm="/app-files",rd=/^[A-Za-z0-9_.:-]{1,64}$/;function sd(t,e,n=process.cwd()){if(!e||e.length>P.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:`the path leaves the workspace: copy the file into ${Ke}/ first`};if(!se(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=To($o(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let s;try{s=To(nd(e)?e:$o(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!s.startsWith(r+Ao))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Ke}/ first`};let o=se(s);return o?{ok:!0,path:s,...o}:{ok:!1,status:415,error:"this type of file is not served"}}function od(t,e){let n=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\;]/g,"_").slice(0,120)||"file";return`${e==="file"?"attachment":"inline"}; filename="${n}"; filename*=UTF-8''${encodeURIComponent(t.slice(0,120))}`}function id(t,e,n){return{"Content-Type":t,"Content-Disposition":od(e,n),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; img-src 'self'; media-src 'self'; sandbox","Cache-Control":"private, max-age=3600","Accept-Ranges":"bytes"}}function ad(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,s;return n[1]?(r=Number(n[1]),s=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),s=e-1),r>s||r>=e?"unsatisfiable":{start:r,end:s}}function nm(t,e,n,r){let s=(k,h)=>{e.writeHead(k,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(h))};if(t.method!=="GET"&&t.method!=="HEAD")return s(405,{error:"GET only"});let o=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!rd.test(o))return s(400,{error:"bad agent id"});let a=r.workspaceOf(o);if(!a)return s(404,{error:`no agent "${o}" on this computer`});let c=sd(a,i,r.cwd);if(!c.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${o}: ${c.error}`),s(c.status,{error:c.error});let l;try{l=td(c.path,"r")}catch{return s(404,{error:"file not found"})}let d;try{let k=ed(l);if(!k.isFile())return ue(l),s(404,{error:"not a file"});d=k.size}catch{return ue(l),s(404,{error:"file not found"})}if(d>P.bytes)return ue(l),s(413,{error:`the file is larger than ${P.bytes/1024/1024} MB`});let u=c.path.split(Ao).pop()||"file",p=id(c.mime,u,c.kind),g=ad(t.headers.range,d);if(g==="unsatisfiable"){ue(l),e.writeHead(416,{...p,"Content-Range":`bytes */${d}`}),e.end();return}let{start:f,end:b}=g??{start:0,end:d-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(d?b-f+1:0),...g?{"Content-Range":`bytes ${f}-${b}/${d}`}:{}}),t.method==="HEAD"||d===0){ue(l),e.end();return}let y=Zl("",{fd:l,start:f,end:b,autoClose:!0});y.on("error",()=>e.destroy()),e.on("close",()=>y.destroy()),y.pipe(e)}import{spawn as pe}from"child_process";import{readFileSync as cd,writeFileSync as ld}from"fs";import{tmpdir as dd}from"os";import{join as ud}from"path";dn();var Ro=t=>t&&t!==1?Math.round(175*t):null,Me=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function pd(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=cd(t,"utf8").trim();if(e)return e}catch{}return null}function um(t=pd()){let e=0;return async(n,r)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...Me(n.voice.rate)?{voice_settings:{speed:Me(n.voice.rate)}}:{}}),signal:r});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text()).slice(0,160)}`);let o=ud(dd(),`agentx-say-${process.pid}-${++e}.mp3`);return ld(o,Buffer.from(await s.arrayBuffer())),o}catch(s){if(r.aborted||!n.voice.fallback)throw s;return X(`elevenlabs:${String(s?.message??s).slice(0,40)}`,`[voice] ElevenLabs failed (${String(s?.message??s).slice(0,160)}); speaking with the system voice`),null}}}function Io(t,e){let n=t.languages&&me(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var gd=(t,e="")=>{let n=Io(t,e),r=Ro(t.rate);return[...n&&!gs(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function fd(t,e,n){if(!n)return["say",gd(t,e)];let r=Io(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function pm(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function gm(t=Xt()){if(t)try{pe("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function fm(t=Xt()){if(t)try{pe("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Xt(t={},e){if(!ft(t))return null;try{return hs(e)}catch(n){return X("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
910
+ `)[0]}); Siri voices will not switch`),null}}var mm=(t,e)=>{if(!t){let[n,r]=fd(e.voice,e.text,Xt()),s=Ro(e.voice.rate),o=s?{...process.env,AGENTX_SAY_RATE:String(s)}:process.env,i=pe(n,r,{stdio:["pipe","ignore","ignore"],env:o});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?pe("afplay",[t],{stdio:"ignore"}):pe("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Do}from"child_process";import{accessSync as md,constants as hd,readFileSync as Co}from"fs";import{homedir as bd}from"os";import{basename as te,delimiter as No,dirname as yd,extname as wd,join as zt}from"path";var B={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function Lo(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>B.ms+2e3?{status:413,error:Gt()}:null}var Gt=()=>`The recording is longer than ${B.ms/6e4} minutes.`,xd={"audio/webm":"webm","video/webm":"webm","audio/ogg":"ogg","audio/mp4":"m4a","video/mp4":"m4a","audio/x-m4a":"m4a","audio/aac":"aac","audio/mpeg":"mp3","audio/wav":"wav","audio/x-wav":"wav","audio/wave":"wav"};function Oo(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return xd[e]??null}function Po(t,e){let n=[];return t!=="local"&&e.key&&n.push("elevenlabs"),e.ffmpeg&&(e.mlx?n.push("mlx-whisper"):e.whisper&&n.push("whisper")),n}function Yt(t,e){return t==="local"&&e.key&&!e.ffmpeg?"Speech to text is set to local, and this computer has no ffmpeg.":(e.mlx||e.whisper)&&!e.ffmpeg?"This computer has Whisper but no ffmpeg to read the recording.":"Add an ElevenLabs key on this computer, or install mlx-whisper and ffmpeg."}function Kt(t,e,n=process.env.PATH??""){let r=bd(),s=[zt(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(No).filter(Boolean)];for(let o of[e,...s.map(i=>zt(i,t))])if(o)try{return md(o,hd.X_OK),o}catch{}return null}function km(t){return{key:t,mlx:Kt("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:Kt("whisper",process.env.AGENTX_WHISPER),ffmpeg:kd()}}var kd=()=>Kt("ffmpeg",process.env.AGENTX_FFMPEG);async function Mo(t,e){return e?vd(t,e):null}async function vd(t,e){let n=String(B.ms/1e3+5);try{let s=[...(await Sd(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],o=s[s.length-1];return o?Number(o[1])*3600+Number(o[2])*60+Number(o[3]):null}catch{return null}}async function Fo(t,e,n,r){let s=new FormData;s.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),s.set("file",new Blob([Co(t)],{type:e}),te(t));let o=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:s,signal:r??AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text().catch(()=>"")).slice(0,160)}`);let i=await o.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function Uo(t,e,n,r,s){let o=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",s,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",s,"--fp16","False"],i={...process.env,PATH:`${yd(r)}${No}${process.env.PATH??""}`};await Ed(e,o,12e4,i);try{return Co(zt(s,te(n,wd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Sd(t,e,n){return new Promise((r,s)=>{let o=Do(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{o.kill("SIGKILL"),s(new Error(`${te(t)} took too long`))},n);o.stderr.on("data",c=>{i=(i+c).slice(-8192)}),o.on("error",c=>{clearTimeout(a),s(c)}),o.on("exit",c=>{clearTimeout(a),c===0?r(i):s(new Error(`${te(t)} exited ${c}`))})})}function Ed(t,e,n,r=process.env){return new Promise((s,o)=>{let i=Do(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",c="",l=setTimeout(()=>{i.kill("SIGKILL"),o(new Error(`${te(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",d=>{a.length<4096&&(a+=d)}),i.stderr.on("data",d=>{c.length<4096&&(c+=d)}),i.on("error",d=>{clearTimeout(l),o(d)}),i.on("exit",d=>{clearTimeout(l),d===0?s(a):o(new Error(`${te(t)} exited ${d}: ${c.trim().split(`
911
+ `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as _d,rm as Td,writeFile as $d}from"fs/promises";import{tmpdir as Ad}from"os";import{join as Wo}from"path";Zo();var Rd=64*1024,Id=2,Jt=0;function Cm(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Nm(t,e,n,r){return t.method!=="POST"?S(e,405,{error:"POST"}):n==="/voice/transcribe"?Dd(t,e,r):Ld(t,e,r)}async function Dd(t,e,n){let r=String(t.headers["content-type"]||""),s=Oo(r);if(!s)return S(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let o=Lo(t.headers["x-audio-duration-ms"]);if(o)return t.resume(),S(e,o.status,{error:o.error});let i=await jo(t,B.bytes);if(!i)return S(e,413,{error:Md()});if(!i.length)return S(e,400,{error:"The recording is empty."});if(Jt>=Id)return S(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),c=n.host(),l=Po(a,c);if(!c.ffmpeg&&!n.allowUnmeasured?.()){let u=n.nodeName?`on ${n.nodeName}`:"on this computer",p=l.length?"":" "+Yt(a,c);return S(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${u} for voice input from the phone.${p}`,setup:!1})}if(!l.length)return S(e,503,{error:"Voice input isn't set up on this computer.",hint:Yt(a,c),setup:!1});Jt++;let d;try{let u=await _d(Wo(Ad(),"agentx-phone-voice-"));try{d=await Cd(u,`speech.${s}`,i,r,c,l,n)}finally{await Td(u,{recursive:!0,force:!0}).catch(()=>{})}}finally{Jt--}S(e,d[0],d[1])}async function Cd(t,e,n,r,s,o,i){let a=Wo(t,e);if(await $d(a,n,{mode:384}),s.ffmpeg){let l=await(i.measure??Mo)(a,s.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>B.ms+2e3)return[413,{error:Gt()}]}let c=[];for(let l of o)try{let d=await Nd(l,a,r,s,t,i);return i.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),d?[200,{text:d,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(d){let u=String(d?.message??d).split(`
912
+ `)[0].slice(0,200);c.push(`${l}: ${u}`),i.log(`[voice] phone transcription with ${l} failed: ${u}`)}return[502,{error:"Speech to text failed on this computer.",detail:c.join("; ")}]}function Nd(t,e,n,r,s,o){let i=o.engines?.[t];if(i)return i(e,n,r,s);if(t==="elevenlabs")return Fo(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return Uo(t,a,e,r.ffmpeg,s)}async function Ld(t,e,n){let r=await jo(t,Rd);if(!r)return S(e,413,{error:"request too large"});let s;try{s=JSON.parse(r.toString("utf8")||"{}")}catch{return S(e,400,{error:"expected JSON"})}let o=typeof s?.agent=="string"?s.agent:"",i=typeof s?.peer=="string"&&s.peer?s.peer:void 0;if(!o)return S(e,400,{error:"agent is required"});let a=Od(typeof s?.text=="string"?s.text:"",n.spokenMaxChars?.());if(!a)return S(e,422,{error:"Nothing in this answer can be said aloud."});let c=n.pronounce?n.pronounce(a):a,l=n.voiceOf(o,i);if(!l)return S(e,404,{error:`Unknown agent: ${o}`});let d=(p,g=200)=>S(e,g,{fallback:"browser",reason:p,text:c});if(l.provider!=="elevenlabs")return d("This agent speaks with a system voice, which only plays on the computer.");let u=n.elevenLabsKey();if(!u)return d("No ElevenLabs key is set on this computer.");try{let p=await(n.synth??Pd)(u,l,c);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(c.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
913
+ `)[0].slice(0,160)}`),d("ElevenLabs could not speak this answer.",502)}}function Od(t,e){let n=Oe(ye(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return un(n,e)}async function Pd(t,e,n){let r=Me(e.rate),s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(e.elevenlabs)}?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n,model_id:"eleven_flash_v2_5",...r?{voice_settings:{speed:r}}:{}}),signal:AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await s.arrayBuffer())}var Md=()=>`The recording is larger than ${B.bytes/1024/1024} MB, more than ${B.ms/6e4} minutes of speech.`;function Lm(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let s=n.agents??{};return s[t]?Et(kt(t,s,n.voice)):null}function jo(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let s=[],o=0;t.on("data",i=>{if(!(o>e)){if(o+=i.length,o>e){s.length=0,n(null);return}s.push(i)}}),t.on("end",()=>{o<=e&&n(Buffer.concat(s))}),t.on("error",r)})}function S(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}var Fd="[Live voice call on the owner's watch or headset. Your answer is read aloud to them and they can't see a screen. Answer what they just said, in a few short spoken sentences.]",Ud="operator",Wd=50,qo=4,Bo=500;function jd(t){let e={channel:"app",chatId:t.chatId,sender:Ud,...t.spoken?{via:"voice"}:{}},n=t.call==="watch"?`${Fd}
914
+
915
+ ${t.message}`:t.message;return t.node==="local"?{path:"/task",body:{agent:t.agent,message:n,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:n,stream:!0,context:e}}}async function Um(t,e,n,r){let{path:s,body:o}=jd(e),i="",a=!1,c=[],l=new Map,d=(u,p,g)=>{let f=u!=="done",b=a?{text:An(p,f),artifacts:[]}:ye(p,P.perMessage,f),{cleanText:y,ui:k}=u==="done"?Oe(b.text):{cleanText:b.text,ui:void 0},h=a?void 0:Bd(k);return{status:u,text:y,tools:c,files:b.artifacts,...h?{ui:h}:{},...g?{error:g}:{}}};try{let u=await fetch(t.url.replace(/\/+$/,"")+s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(o),signal:n});if(!u.ok||!u.body){let p=await u.json().then(g=>g?.error).catch(()=>"");return d("error",i,p||`AgentX answered HTTP ${u.status}.`)}for await(let p of Hd(u.body)){r(p.event,p.data);let g=p.data??{};if(p.event==="start")a=g.rich===!1;else if(p.event==="text"&&typeof g.text=="string")i+=g.text;else if(p.event==="tool"&&g.status==="start"&&c.length<Wd){let f={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};c.push(f),g.id&&l.set(String(g.id),f)}else if(p.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(p.event==="done")return d("done",typeof g.content=="string"&&g.content?g.content:i);if(p.event==="error")return d("error",i,qd(g.error))}}return n.aborted?d("stopped",i):d("error",i,"The connection to the agent closed before it answered.")}catch(u){return n.aborted?d("stopped",i):d("error",i,`Could not reach AgentX: ${u?.message||u}`)}}function qd(t){let e=String(t||"The agent could not answer.");return Sn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function Bd(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let s=(t.quickReplies??[]).slice(0,qo).map(i=>i.slice(0,Bo));s.length&&(n.quickReplies=s);let o=(t.replies??[]).slice(0,qo).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,Bo)}));return o.length&&(n.replies=o),Object.keys(n).length?n:void 0}async function*Hd(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:s,value:o}=await e.read();if(s)break;r+=n.decode(o,{stream:!0}).replace(/\r\n/g,`
914
916
  `);let i;for(;(i=r.indexOf(`
915
917
 
916
918
  `))!==-1;){let a=r.slice(0,i);r=r.slice(i+2);let c="message",l=[];for(let d of a.split(`
917
919
  `))d.startsWith("event:")?c=d.slice(6).trim():d.startsWith("data:")&&l.push(d.slice(5).replace(/^ /,""));if(l.length)try{yield{event:c,data:JSON.parse(l.join(`
918
- `))}}catch{}}}}finally{e.releaseLock()}}var Ho=["custom","announce"];function Bm(t,e){let n=t.nodeName,r=t.recent().filter(o=>Ho.includes(o.kind)).slice(-500),s=(e?.list()??[]).slice(-500).map(o=>({...o,node:n}));return{node:n,events:r,wakes:s}}function Hm(t,e={}){let n=e.now??Date.now(),r=Math.max(1,Math.min(200,Math.floor(e.limit||50))),s=new Map;for(let h of t)for(let m of h.events)Ho.includes(m.kind)&&!s.has(m.id)&&s.set(m.id,m);let o=[...s.values()].sort((h,m)=>Date.parse(h.at)-Date.parse(m.at)||h.id.localeCompare(m.id)),i=new Map,a=new Map,c=new Set;for(let h of t)for(let m of h.wakes){let x=m.node||h.node,O=`${x}#${m.agentId}#${m.eventId}`;if(c.has(O))continue;c.add(O);let an=i.get(m.eventId)??[];if(an.push(Xd(m,x,n)),i.set(m.eventId,an),m.status!=="skipped"){let cn=`${m.agentId}#${m.rootId}`,ln=a.get(cn)??[];ln.push({eventId:m.eventId,at:m.decidedAt}),a.set(cn,ln)}}for(let h of i.values())h.sort((m,x)=>m.decidedAt-x.decidedAt||m.agentId.localeCompare(x.agentId));let l=new Map,d=[];for(let h of o){let m=Vd(h,s,a,d);m&&m!==h.id&&l.set(h.id,m),d.push(h)}let u=h=>{let m=h;for(let x=0;x<50;x++){let O=l.get(m);if(!O)return m;m=O}return m},p=new Map,g=h=>({event:h,wakes:i.get(h.id)??[]});for(let h of o){let m=u(h.id);m===h.id?p.set(h.id,{...g(h),replies:[]}):p.get(m)?.replies.push(g(h))}let f=h=>Math.max(Date.parse(h.event.at),...h.replies.map(m=>Date.parse(m.event.at))),b=[...p.values()].sort((h,m)=>f(m)-f(h)),y=[...i.values()].flat(),k=h=>y.filter(m=>h.includes(m.status)).length;return{threads:b.slice(0,r),total:b.length,counts:{events:o.length,wakes:y.length,ran:k(["ran"]),waiting:k(["waiting","held","running"]),timedOut:k(["timed-out","dropped"]),failed:k(["failed"]),skipped:k(["skipped"])}}}function Vd(t,e,n,r){if(t.parentId&&e.has(t.parentId))return t.parentId;let s=Date.parse(t.at);if(t.agentId){let o=(n.get(`${t.agentId}#${t.rootId}`)??[]).filter(i=>i.eventId!==t.id&&e.has(i.eventId)&&Date.parse(e.get(i.eventId).at)<=s).sort((i,a)=>a.at-i.at)[0];if(o)return o.eventId}if(t.rootId!==t.id)for(let o=r.length-1;o>=0;o--){let i=r[o];if(i.rootId===t.rootId&&(i.agentId??i.node)!==(t.agentId??t.node))return i.id}}function Xd(t,e,n){let r={agentId:t.agentId,node:e,status:t.status,decidedAt:t.decidedAt,attempts:t.attempts};if(t.reason&&(r.reason=t.reason),t.startedAt&&(r.startedAt=t.startedAt),t.endedAt&&(r.endedAt=t.endedAt),t.taskId&&(r.taskId=t.taskId),t.error&&(r.error=t.error),t.status!=="skipped"){let s=t.startedAt??t.endedAt??n;r.waitedMs=Math.max(0,s-t.decidedAt)}return r}import{existsSync as C,readFileSync as nn,writeFileSync as rn,mkdirSync as Fe,readdirSync as tn,rmSync as zd,statSync as L}from"fs";import{resolve as Vo,relative as Kd,dirname as sn,join as K,extname as ge,basename as on}from"path";var T=200*1024,Xo=new Set([".md",".markdown",".txt"]),ne=new Set([".md",".markdown",".txt",".json",".jsonc",".yaml",".yml",".toml",".sh",".bash",".zsh",".py",".js",".mjs",".ts",".tsx",".jsx",".css",".html",".lock",".cfg",".ini",".env",".gitignore"]),Gd=6,Yd=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function U(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=Vo(t);if(C(n)||Fe(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=Vo(n,e);if(Kd(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function zo(t){let e=ge(t).toLowerCase();if(!Xo.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Qt(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Km(t){let e=U(t,"."),n=[],r=new Set,s=[];try{s=tn(e)}catch{}for(let a of Yd){let c=K(e,a);if(C(c)&&L(c).isFile()){let l=L(c).size,d=l>0&&l<T?en(c):"";n.push({path:a,title:Qt(d,a),size:l,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of s){if(r.has(a))continue;let c=K(e,a);try{let l=L(c);if(!l.isFile()||!Xo.has(ge(a).toLowerCase()))continue;let d=l.size>0&&l.size<T?en(c):"";n.push({path:a,title:Qt(d,a),size:l.size,exists:!0})}catch{}}let o=[],i=K(e,".claude","skills");if(C(i))try{for(let a of tn(i)){let c=K(i,a),l;try{l=L(c)}catch{continue}if(!l.isDirectory())continue;let d=K(c,"SKILL.md");if(!C(d))continue;let u=L(d),p=u.size<T?en(d):"";o.push({slug:a,title:Qt(p,a),size:u.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return o.sort((a,c)=>a.slug.localeCompare(c.slug)),{identity:n,skills:o,workspace:e}}function en(t){try{return nn(t,"utf-8")}catch{return""}}function Gm(t,e){let n=U(t,e);if(zo(n),!C(n))return{path:e,content:""};if(L(n).size>T)throw new Error(`File is too large to edit in the admin panel (> ${T/1024} KB).`);return{path:e,content:nn(n,"utf-8")}}function Ym(t,e,n){let r=U(t,e);zo(r);let s=Buffer.from(n,"utf-8");if(s.length>T)throw new Error(`File too large (${s.length} > ${T} bytes).`);return Fe(sn(r),{recursive:!0}),rn(r,s),{path:e,bytes:s.length}}function Jm(t,e,n={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let r=`.claude/skills/${e}/SKILL.md`,s=U(t,r);if(C(s))throw new Error(`Skill "${e}" already exists.`);Fe(sn(s),{recursive:!0});let o=n.content?.trim()?n.content:Jd(e,n.title);return rn(s,o),{slug:e,path:r}}function Zm(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=U(t,`.claude/skills/${e}`);if(!C(n))throw new Error(`Skill "${e}" not found.`);if(!L(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return zd(n,{recursive:!0,force:!0}),{slug:e}}function Qm(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=U(t,`.claude/skills/${e}`);if(!C(n))throw new Error(`Skill "${e}" not found.`);let r=[];return s(n,"",0,r),r.sort((o,i)=>o.kind!==i.kind?o.kind==="dir"?-1:1:o.path.localeCompare(i.path)),r;function s(o,i,a,c){if(a>Gd)return;let l=[];try{l=tn(o)}catch{return}for(let d of l){if(d==="node_modules"||d===".git")continue;let u=K(o,d),p=i?`${i}/${d}`:d,g;try{g=L(u)}catch{continue}if(g.isDirectory())c.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),s(u,p,a+1,c);else if(g.isFile()){let f=ge(d).toLowerCase(),b=ne.has(f)||ne.has(d.toLowerCase());c.push({path:p,kind:"file",size:g.size,editable:b&&g.size<T})}}}}function eh(t,e,n){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let r=U(t,`.claude/skills/${e}/${n}`);if(!C(r)||!L(r).isFile())throw new Error(`File not found: ${n}`);let s=ge(r).toLowerCase(),o=on(r).toLowerCase();if(!ne.has(s)&&!ne.has(o))throw new Error(`File type not editable: ${n}`);if(L(r).size>T)throw new Error(`File too large to edit (> ${T/1024} KB): ${n}`);return{path:n,content:nn(r,"utf-8")}}function th(t,e,n,r){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let s=U(t,`.claude/skills/${e}/${n}`),o=ge(s).toLowerCase(),i=on(s).toLowerCase();if(!ne.has(o)&&!ne.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>T)throw new Error(`File too large (${a.length} > ${T} bytes).`);return Fe(sn(s),{recursive:!0}),rn(s,a),{path:n,bytes:a.length}}function nh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=U(t,`.claude/skills/${e}`);if(!C(n))throw new Error(`Skill "${e}" not found.`);let r=s=>C(K(n,s));return r("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:r("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:r("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:r("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:r("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function Jd(t,e){return`# ${e?.trim()||t}
920
+ `))}}catch{}}}}finally{e.releaseLock()}}var Ho=["custom","announce"];function jm(t,e){let n=t.nodeName,r=t.recent().filter(o=>Ho.includes(o.kind)).slice(-500),s=(e?.list()??[]).slice(-500).map(o=>({...o,node:n}));return{node:n,events:r,wakes:s}}function qm(t,e={}){let n=e.now??Date.now(),r=Math.max(1,Math.min(200,Math.floor(e.limit||50))),s=new Map;for(let h of t)for(let m of h.events)Ho.includes(m.kind)&&!s.has(m.id)&&s.set(m.id,m);let o=[...s.values()].sort((h,m)=>Date.parse(h.at)-Date.parse(m.at)||h.id.localeCompare(m.id)),i=new Map,a=new Map,c=new Set;for(let h of t)for(let m of h.wakes){let x=m.node||h.node,O=`${x}#${m.agentId}#${m.eventId}`;if(c.has(O))continue;c.add(O);let on=i.get(m.eventId)??[];if(on.push(Xd(m,x,n)),i.set(m.eventId,on),m.status!=="skipped"){let an=`${m.agentId}#${m.rootId}`,cn=a.get(an)??[];cn.push({eventId:m.eventId,at:m.decidedAt}),a.set(an,cn)}}for(let h of i.values())h.sort((m,x)=>m.decidedAt-x.decidedAt||m.agentId.localeCompare(x.agentId));let l=new Map,d=[];for(let h of o){let m=Vd(h,s,a,d);m&&m!==h.id&&l.set(h.id,m),d.push(h)}let u=h=>{let m=h;for(let x=0;x<50;x++){let O=l.get(m);if(!O)return m;m=O}return m},p=new Map,g=h=>({event:h,wakes:i.get(h.id)??[]});for(let h of o){let m=u(h.id);m===h.id?p.set(h.id,{...g(h),replies:[]}):p.get(m)?.replies.push(g(h))}let f=h=>Math.max(Date.parse(h.event.at),...h.replies.map(m=>Date.parse(m.event.at))),b=[...p.values()].sort((h,m)=>f(m)-f(h)),y=[...i.values()].flat(),k=h=>y.filter(m=>h.includes(m.status)).length;return{threads:b.slice(0,r),total:b.length,counts:{events:o.length,wakes:y.length,ran:k(["ran"]),waiting:k(["waiting","held","running"]),timedOut:k(["timed-out","dropped"]),failed:k(["failed"]),skipped:k(["skipped"])}}}function Vd(t,e,n,r){if(t.parentId&&e.has(t.parentId))return t.parentId;let s=Date.parse(t.at);if(t.agentId){let o=(n.get(`${t.agentId}#${t.rootId}`)??[]).filter(i=>i.eventId!==t.id&&e.has(i.eventId)&&Date.parse(e.get(i.eventId).at)<=s).sort((i,a)=>a.at-i.at)[0];if(o)return o.eventId}if(t.rootId!==t.id)for(let o=r.length-1;o>=0;o--){let i=r[o];if(i.rootId===t.rootId&&(i.agentId??i.node)!==(t.agentId??t.node))return i.id}}function Xd(t,e,n){let r={agentId:t.agentId,node:e,status:t.status,decidedAt:t.decidedAt,attempts:t.attempts};if(t.reason&&(r.reason=t.reason),t.startedAt&&(r.startedAt=t.startedAt),t.endedAt&&(r.endedAt=t.endedAt),t.taskId&&(r.taskId=t.taskId),t.error&&(r.error=t.error),t.status!=="skipped"){let s=t.startedAt??t.endedAt??n;r.waitedMs=Math.max(0,s-t.decidedAt)}return r}import{existsSync as C,readFileSync as tn,writeFileSync as nn,mkdirSync as Fe,readdirSync as en,rmSync as zd,statSync as L}from"fs";import{resolve as Vo,relative as Kd,dirname as rn,join as K,extname as ge,basename as sn}from"path";var $=200*1024,Xo=new Set([".md",".markdown",".txt"]),ne=new Set([".md",".markdown",".txt",".json",".jsonc",".yaml",".yml",".toml",".sh",".bash",".zsh",".py",".js",".mjs",".ts",".tsx",".jsx",".css",".html",".lock",".cfg",".ini",".env",".gitignore"]),Gd=6,Yd=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function U(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=Vo(t);if(C(n)||Fe(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=Vo(n,e);if(Kd(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function zo(t){let e=ge(t).toLowerCase();if(!Xo.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Qt(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Xm(t){let e=U(t,"."),n=[],r=new Set,s=[];try{s=en(e)}catch{}for(let a of Yd){let c=K(e,a);if(C(c)&&L(c).isFile()){let l=L(c).size,d=l>0&&l<$?Zt(c):"";n.push({path:a,title:Qt(d,a),size:l,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of s){if(r.has(a))continue;let c=K(e,a);try{let l=L(c);if(!l.isFile()||!Xo.has(ge(a).toLowerCase()))continue;let d=l.size>0&&l.size<$?Zt(c):"";n.push({path:a,title:Qt(d,a),size:l.size,exists:!0})}catch{}}let o=[],i=K(e,".claude","skills");if(C(i))try{for(let a of en(i)){let c=K(i,a),l;try{l=L(c)}catch{continue}if(!l.isDirectory())continue;let d=K(c,"SKILL.md");if(!C(d))continue;let u=L(d),p=u.size<$?Zt(d):"";o.push({slug:a,title:Qt(p,a),size:u.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return o.sort((a,c)=>a.slug.localeCompare(c.slug)),{identity:n,skills:o,workspace:e}}function Zt(t){try{return tn(t,"utf-8")}catch{return""}}function zm(t,e){let n=U(t,e);if(zo(n),!C(n))return{path:e,content:""};if(L(n).size>$)throw new Error(`File is too large to edit in the admin panel (> ${$/1024} KB).`);return{path:e,content:tn(n,"utf-8")}}function Km(t,e,n){let r=U(t,e);zo(r);let s=Buffer.from(n,"utf-8");if(s.length>$)throw new Error(`File too large (${s.length} > ${$} bytes).`);return Fe(rn(r),{recursive:!0}),nn(r,s),{path:e,bytes:s.length}}function Gm(t,e,n={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let r=`.claude/skills/${e}/SKILL.md`,s=U(t,r);if(C(s))throw new Error(`Skill "${e}" already exists.`);Fe(rn(s),{recursive:!0});let o=n.content?.trim()?n.content:Jd(e,n.title);return nn(s,o),{slug:e,path:r}}function Ym(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=U(t,`.claude/skills/${e}`);if(!C(n))throw new Error(`Skill "${e}" not found.`);if(!L(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return zd(n,{recursive:!0,force:!0}),{slug:e}}function Jm(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=U(t,`.claude/skills/${e}`);if(!C(n))throw new Error(`Skill "${e}" not found.`);let r=[];return s(n,"",0,r),r.sort((o,i)=>o.kind!==i.kind?o.kind==="dir"?-1:1:o.path.localeCompare(i.path)),r;function s(o,i,a,c){if(a>Gd)return;let l=[];try{l=en(o)}catch{return}for(let d of l){if(d==="node_modules"||d===".git")continue;let u=K(o,d),p=i?`${i}/${d}`:d,g;try{g=L(u)}catch{continue}if(g.isDirectory())c.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),s(u,p,a+1,c);else if(g.isFile()){let f=ge(d).toLowerCase(),b=ne.has(f)||ne.has(d.toLowerCase());c.push({path:p,kind:"file",size:g.size,editable:b&&g.size<$})}}}}function Qm(t,e,n){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let r=U(t,`.claude/skills/${e}/${n}`);if(!C(r)||!L(r).isFile())throw new Error(`File not found: ${n}`);let s=ge(r).toLowerCase(),o=sn(r).toLowerCase();if(!ne.has(s)&&!ne.has(o))throw new Error(`File type not editable: ${n}`);if(L(r).size>$)throw new Error(`File too large to edit (> ${$/1024} KB): ${n}`);return{path:n,content:tn(r,"utf-8")}}function Zm(t,e,n,r){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let s=U(t,`.claude/skills/${e}/${n}`),o=ge(s).toLowerCase(),i=sn(s).toLowerCase();if(!ne.has(o)&&!ne.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>$)throw new Error(`File too large (${a.length} > ${$} bytes).`);return Fe(rn(s),{recursive:!0}),nn(s,a),{path:n,bytes:a.length}}function eh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=U(t,`.claude/skills/${e}`);if(!C(n))throw new Error(`Skill "${e}" not found.`);let r=s=>C(K(n,s));return r("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:r("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:r("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:r("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:r("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function Jd(t,e){return`# ${e?.trim()||t}
919
921
 
920
922
  Describe what this skill does and when the agent should use it. Keep it under ~5 lines \u2014 the agent reads this to decide whether to invoke the skill.
921
923
 
@@ -928,7 +930,7 @@ Document the arguments, commands, or files the skill expects. Example:
928
930
 
929
931
  \`\`\`bash
930
932
  # Example invocation
931
- claude-code ${on(t)} --arg value
933
+ claude-code ${sn(t)} --arg value
932
934
  \`\`\`
933
- `}kn();var Ko={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Go(t){return{...Ko,...t??{},regions:{...t?.regions??{}},buffer:{...Ko.buffer,...t?.buffer??{}}}}function oh(t){try{return Go(xn(t).screen)}catch{return Go(void 0)}}var Zd=/^[a-z][\w-]*$/,Yo=["window","screen","menubar","notifications"];function fe(t,e,n,r){let s=Number(t);if(t===""||t===null||!Number.isFinite(s)||!n(s))throw new Error(`${e} must be ${r}`);return s}var Ue=(t,e)=>fe(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Jo(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function ih(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Ue(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Ue(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Ue(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=fe(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=fe(e.changeThreshold,"changeThreshold",s=>s>=0&&s<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let s={...n.regions??{}};for(let[o,i]of Object.entries(e.regions)){if(!Zd.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=Jo(i)}n.regions=s}if(e.buffer&&typeof e.buffer=="object"){let s=e.buffer,o={...n.buffer??{}};"enabled"in s&&(o.enabled=!!s.enabled),"seconds"in s&&(o.seconds=fe(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=fe(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=Ue(s.maxPixels,"buffer.maxPixels")),"region"in s&&(o.region=String(s.region).trim()),n.buffer=o}let r=n.buffer?.region;if(r!==void 0&&!Yo.includes(r)&&!n.regions?.[r])try{Jo(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Yo,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{fr as a,tu as b,Mt as c,Mc as d,Fc as e,Mg as f,Fg as g,Ug as h,qg as i,Bg as j,Hg as k,Vs as l,Xs as m,Vg as n,Oe as o,zg as p,Gg as q,q as r,zs as s,_ as t,ou as u,Ys as v,tf as w,sf as x,Zs as y,of as z,Qs as A,af as B,de as C,ul as D,cf as E,lf as F,to as G,xu as H,Ii as I,$u as J,Nr as K,Au as L,A as M,du as N,uu as O,Mu as P,Se as Q,Fu as R,_r as S,bu as T,V as U,pp as V,Jr as W,es as X,fa as Y,ma as Z,mp as _,hp as $,va as aa,xp as ba,ro as ca,pf as da,Sp as ea,Ep as fa,js as ga,At as ha,Ic as ia,$ as ja,bo as ka,Hf as la,Vf as ma,Yl as na,Gf as oa,So as pa,Yf as qa,Jf as ra,rm as sa,od as ta,ad as ua,sm as va,$p as wa,Tp as xa,Ap as ya,Rp as za,Ip as Aa,Dp as Ba,Np as Ca,Lp as Da,Mp as Ea,Fp as Fa,Up as Ga,qp as Ha,Bp as Ia,Hp as Ja,Vp as Ka,Xp as La,zp as Ma,Kp as Na,rg as Oa,yt as Pa,sg as Qa,og as Ra,ce as Sa,le as Ta,gd as Ua,gm as Va,fm as Wa,mm as Xa,hm as Ya,zt as Za,bm as _a,kt as $a,vt as ab,De as bb,Za as cb,ec as db,dg as eb,Et as fb,_t as gb,tc as hb,nc as ib,$s as jb,Is as kb,ug as lb,oc as mb,pg as nb,gc as ob,hc as pb,$t as qb,yc as rb,Ds as sb,B as tb,Lo as ub,Oo as vb,Po as wb,Gt as xb,Sm as yb,vd as zb,Fo as Ab,Uo as Bb,Lm as Cb,Om as Db,Fd as Eb,Pm as Fb,jo as Gb,Os as Hb,jm as Ib,Bd as Jb,Bm as Kb,Hm as Lb,Ce as Mb,Tg as Nb,Ot as Ob,Lg as Pb,Km as Qb,Gm as Rb,Ym as Sb,Jm as Tb,Zm as Ub,Qm as Vb,eh as Wb,th as Xb,nh as Yb,Ko as Zb,Go as _b,oh as $b,Yo as ac,ih as bc};
934
- //# sourceMappingURL=chunk-AKDJGDLN.js.map
935
+ `}xn();var Ko={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Go(t){return{...Ko,...t??{},regions:{...t?.regions??{}},buffer:{...Ko.buffer,...t?.buffer??{}}}}function rh(t){try{return Go(wn(t).screen)}catch{return Go(void 0)}}var Qd=/^[a-z][\w-]*$/,Yo=["window","screen","menubar","notifications"];function fe(t,e,n,r){let s=Number(t);if(t===""||t===null||!Number.isFinite(s)||!n(s))throw new Error(`${e} must be ${r}`);return s}var Ue=(t,e)=>fe(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Jo(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function sh(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Ue(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Ue(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Ue(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=fe(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=fe(e.changeThreshold,"changeThreshold",s=>s>=0&&s<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let s={...n.regions??{}};for(let[o,i]of Object.entries(e.regions)){if(!Qd.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=Jo(i)}n.regions=s}if(e.buffer&&typeof e.buffer=="object"){let s=e.buffer,o={...n.buffer??{}};"enabled"in s&&(o.enabled=!!s.enabled),"seconds"in s&&(o.seconds=fe(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=fe(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=Ue(s.maxPixels,"buffer.maxPixels")),"region"in s&&(o.region=String(s.region).trim()),n.buffer=o}let r=n.buffer?.region;if(r!==void 0&&!Yo.includes(r)&&!n.regions?.[r])try{Jo(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Yo,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{fr as a,tu as b,Pt as c,Pc as d,Mc as e,Og as f,Pg as g,Mg as h,Wg as i,jg as j,qg as k,Vs as l,Xs as m,Bg as n,Oe as o,Vg as p,zg as q,q as r,zs as s,_ as t,ou as u,Ys as v,Zg as w,nf as x,Qs as y,rf as z,Zs as A,sf as B,de as C,dl as D,of as E,af as F,to as G,xu as H,Ii as I,Tu as J,Nr as K,A as L,du as M,uu as N,Ou as O,Se as P,Pu as Q,_r as R,bu as S,V as T,dp as U,Jr as V,es as W,ga as X,fa as Y,gp as Z,fp as _,ka as $,yp as aa,ro as ba,df as ca,kp as da,vp as ea,js as fa,$t as ga,Rc as ha,T as ia,bo as ja,qf as ka,Bf as la,Gl as ma,zf as na,So as oa,Kf as pa,Gf as qa,tm as ra,sd as sa,id as ta,nm as ua,Ep as va,_p as wa,Tp as xa,$p as ya,Ap as za,Rp as Aa,Dp as Ba,Cp as Ca,Op as Da,Pp as Ea,Mp as Fa,Wp as Ga,jp as Ha,qp as Ia,Bp as Ja,Hp as Ka,Vp as La,Xp as Ma,tg as Na,bt as Oa,ng as Pa,rg as Qa,ce as Ra,le as Sa,pd as Ta,um as Ua,pm as Va,gm as Wa,fm as Xa,Xt as Ya,mm as Za,xt as _a,kt as $a,De as ab,Ja as bb,Za as cb,cg as db,St as eb,Et as fb,ec as gb,tc as hb,Ts as ib,Is as jb,lg as kb,sc as lb,dg as mb,pc as nb,mc as ob,_t as pb,bc as qb,Ds as rb,B as sb,Lo as tb,Oo as ub,Po as vb,Kt as wb,km as xb,kd as yb,Fo as zb,Uo as Ab,Cm as Bb,Nm as Cb,Md as Db,Lm as Eb,jo as Fb,Os as Gb,Um as Hb,Bd as Ib,jm as Jb,qm as Kb,Ce as Lb,_g as Mb,Lt as Nb,Cg as Ob,Xm as Pb,zm as Qb,Km as Rb,Gm as Sb,Ym as Tb,Jm as Ub,Qm as Vb,Zm as Wb,eh as Xb,Ko as Yb,Go as Zb,rh as _b,Yo as $b,sh as ac};
936
+ //# sourceMappingURL=chunk-FCDMB2JA.js.map