agentix-cli 0.158.0 → 0.160.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 (186) hide show
  1. package/README.md +25 -20
  2. package/dist/{App-AFRBV666.js → App-ENNAIXFU.js} +2 -2
  3. package/dist/{ChatApp-EBTSY27Z.js → ChatApp-UNYTCNPZ.js} +2 -2
  4. package/dist/{absorb-eval-OCR3G5TE.js → absorb-eval-UVOIKIBZ.js} +2 -2
  5. package/dist/{agent-QZ4QTZKW.js → agent-JFDIUUCZ.js} +2 -2
  6. package/dist/{board-dashboard-QJ2CWJKI.js → board-dashboard-BOQSP6XB.js} +950 -435
  7. package/dist/board-dashboard-BOQSP6XB.js.map +1 -0
  8. package/dist/{chunk-SRUIUZOC.js → chunk-3MSNOHKU.js} +59 -58
  9. package/dist/chunk-3MSNOHKU.js.map +1 -0
  10. package/dist/{chunk-BY2AAMOO.js → chunk-4QVGHA4B.js} +2 -2
  11. package/dist/chunk-6LVCXEQE.js +181 -0
  12. package/dist/chunk-6LVCXEQE.js.map +1 -0
  13. package/dist/{chunk-TRGNLW43.js → chunk-7NRBMQE6.js} +2 -2
  14. package/dist/{chunk-LLJZMS23.js → chunk-AYK2MO3B.js} +2 -2
  15. package/dist/{chunk-KPNAXVET.js → chunk-CI5OJ2JN.js} +2 -2
  16. package/dist/{chunk-E4O32ZYZ.js → chunk-CXBTGXFO.js} +2 -2
  17. package/dist/{chunk-3ZMVYNFH.js → chunk-DEXEPOHH.js} +2 -2
  18. package/dist/{chunk-B3I4EBLE.js → chunk-H2KVHGAP.js} +2 -2
  19. package/dist/{chunk-DNPL3YOH.js → chunk-HYNP5WYF.js} +3 -3
  20. package/dist/{chunk-EWBUH2IU.js → chunk-IMNN5RBR.js} +2 -2
  21. package/dist/{chunk-5XPXYOWB.js → chunk-IMSIYVBM.js} +2 -2
  22. package/dist/{chunk-DPNCWHJW.js → chunk-ITIW4UUJ.js} +2 -2
  23. package/dist/{chunk-ZSVCHDYT.js → chunk-LRP2LTLC.js} +2 -2
  24. package/dist/chunk-M4AQRADJ.js +41 -0
  25. package/dist/chunk-M4AQRADJ.js.map +1 -0
  26. package/dist/{chunk-OYPKAYCH.js → chunk-M5L3SOS2.js} +2 -2
  27. package/dist/{chunk-MKLRCNOX.js → chunk-N3VQ5NSV.js} +268 -269
  28. package/dist/chunk-N3VQ5NSV.js.map +1 -0
  29. package/dist/chunk-NHD6DUBL.js +36 -0
  30. package/dist/{chunk-QH3RKKD3.js.map → chunk-NHD6DUBL.js.map} +1 -1
  31. package/dist/{chunk-VHHKS7S4.js → chunk-NURZPCUE.js} +2 -2
  32. package/dist/{chunk-2NLPGLLL.js → chunk-ORAZ3WHL.js} +16 -7
  33. package/dist/chunk-ORAZ3WHL.js.map +1 -0
  34. package/dist/{chunk-5NTWGUSJ.js → chunk-PFNGZ27Y.js} +2 -2
  35. package/dist/{chunk-4UMMAI3Z.js → chunk-QEJD3KFG.js} +2 -2
  36. package/dist/{chunk-NY5ZY2WV.js → chunk-QJDYXEEB.js} +2 -2
  37. package/dist/chunk-QPABR72X.js +2 -0
  38. package/dist/chunk-QPABR72X.js.map +1 -0
  39. package/dist/{chunk-FM6RZI52.js → chunk-RJWFVKBK.js} +2 -2
  40. package/dist/{chunk-GVMV3TWS.js → chunk-RW3MTYHG.js} +2 -2
  41. package/dist/{chunk-P5RTEJUB.js → chunk-SCEQJFQO.js} +2 -2
  42. package/dist/chunk-TFN6A3KI.js +90 -0
  43. package/dist/chunk-TFN6A3KI.js.map +1 -0
  44. package/dist/{chunk-FEF432WU.js → chunk-TZHVLA3D.js} +2 -2
  45. package/dist/{chunk-EMGB23H5.js → chunk-UKUH662W.js} +2 -2
  46. package/dist/chunk-UKUH662W.js.map +1 -0
  47. package/dist/{chunk-JJV7O7YK.js → chunk-VDXHZAMX.js} +2 -2
  48. package/dist/{chunk-5TTHN7DP.js → chunk-VL74KOR7.js} +18 -13
  49. package/dist/chunk-VL74KOR7.js.map +1 -0
  50. package/dist/{chunk-JYSJDHNS.js → chunk-VUEQ4SL5.js} +18 -9
  51. package/dist/{chunk-JYSJDHNS.js.map → chunk-VUEQ4SL5.js.map} +1 -1
  52. package/dist/{chunk-UIBUZ2N3.js → chunk-XHAPSFAB.js} +18 -7
  53. package/dist/chunk-XHAPSFAB.js.map +1 -0
  54. package/dist/chunk-XIRM45DH.js +11 -0
  55. package/dist/chunk-XIRM45DH.js.map +1 -0
  56. package/dist/{chunk-PA3KFAXH.js → chunk-Y4KVFLQZ.js} +2 -2
  57. package/dist/{chunk-MBPYC6QF.js → chunk-ZFMG4GFE.js} +2 -2
  58. package/dist/cli.js +1 -1
  59. package/dist/{client-7ZJZT5H7.js → client-LUZU6O45.js} +2 -2
  60. package/dist/{config-NFDEJ3NB.js → config-54LNSYJF.js} +2 -2
  61. package/dist/config-mutate-DPI3LUG5.js +2 -0
  62. package/dist/config-mutator-W5QTLGCY.js +2 -0
  63. package/dist/{contributions-ECGVSETO.js → contributions-FCKXPCOL.js} +2 -2
  64. package/dist/doctor-ZGL3U4XJ.js +2 -0
  65. package/dist/{failure-candidates-NQX2JMMS.js → failure-candidates-HNENLQJC.js} +2 -2
  66. package/dist/{follow-up-tool-FNO2IG72.js → follow-up-tool-ARGSSE7Q.js} +2 -2
  67. package/dist/hub-NK7Q4F2X.js +2 -0
  68. package/dist/index.d.ts +124 -1
  69. package/dist/index.js +1 -1
  70. package/dist/index.js.map +1 -1
  71. package/dist/processes-GRS7BSIU.js +2 -0
  72. package/dist/{program-7UMVHRD3.js → program-DJJBDNID.js} +284 -267
  73. package/dist/program-DJJBDNID.js.map +1 -0
  74. package/dist/{promote-AAEZYPBP.js → promote-BKHGOZB2.js} +2 -2
  75. package/dist/{query-WWZEARB4.js → query-SPGPGSHG.js} +2 -2
  76. package/dist/{query-settings-3FE555NP.js → query-settings-L6FOADK7.js} +2 -2
  77. package/dist/{registry-JPZLE5XX.js → registry-2JIZ3LOU.js} +2 -2
  78. package/dist/{request-planner-2AU3VK4P.js → request-planner-JCRREXJX.js} +2 -2
  79. package/dist/{review-candidates-CIEGXF7K.js → review-candidates-OKHRZROS.js} +2 -2
  80. package/dist/routing-B3B3ANA5.js +2 -0
  81. package/dist/schedule-tool-GUEADWVH.js +2 -0
  82. package/dist/scheduler-OKSJXZBX.js +2 -0
  83. package/dist/{seat-JWRCBUKR.js → seat-FQ53NWXV.js} +2 -2
  84. package/dist/{select-KIDX6WWF.js → select-YE4C3DZS.js} +2 -2
  85. package/dist/{set-enabled-F4D3VWKI.js → set-enabled-66ZBGZ2O.js} +2 -2
  86. package/dist/{surface-usage-WSY4SHHL.js → surface-usage-JOOZOGOH.js} +2 -2
  87. package/dist/token-store-F2PHHO5A.js +2 -0
  88. package/dist/token-tracker-B2UFOH46.js +2 -0
  89. package/dist/tool-QNIODAFO.js +6 -0
  90. package/dist/tool-QNIODAFO.js.map +1 -0
  91. package/dist/{tool-YSS2C2UX.js → tool-U2HRYX3V.js} +2 -2
  92. package/dist/traces-G4HRLRA3.js +2 -0
  93. package/dist/wiki-3HUDGN6J.js +2 -0
  94. package/dist/wiki-enrich-XQ3ZQBWZ.js +2 -0
  95. package/dist/{workflow-pilot-HCPSMGIC.js → workflow-pilot-25NMZYUO.js} +2 -2
  96. package/package.json +1 -1
  97. package/dist/board-dashboard-QJ2CWJKI.js.map +0 -1
  98. package/dist/chunk-2NLPGLLL.js.map +0 -1
  99. package/dist/chunk-36AXN6ZB.js +0 -11
  100. package/dist/chunk-36AXN6ZB.js.map +0 -1
  101. package/dist/chunk-5TTHN7DP.js.map +0 -1
  102. package/dist/chunk-EMGB23H5.js.map +0 -1
  103. package/dist/chunk-LSDUL7EW.js +0 -181
  104. package/dist/chunk-LSDUL7EW.js.map +0 -1
  105. package/dist/chunk-MKLRCNOX.js.map +0 -1
  106. package/dist/chunk-O5H6BCUN.js +0 -77
  107. package/dist/chunk-O5H6BCUN.js.map +0 -1
  108. package/dist/chunk-PVWHEPF3.js +0 -41
  109. package/dist/chunk-PVWHEPF3.js.map +0 -1
  110. package/dist/chunk-QH3RKKD3.js +0 -36
  111. package/dist/chunk-SRUIUZOC.js.map +0 -1
  112. package/dist/chunk-UIBUZ2N3.js.map +0 -1
  113. package/dist/config-mutate-JYW5G7T6.js +0 -2
  114. package/dist/config-mutator-OMWL5XHO.js +0 -2
  115. package/dist/doctor-D6OVZAFB.js +0 -2
  116. package/dist/hub-MOAG5BEQ.js +0 -2
  117. package/dist/processes-XM77XGOO.js +0 -2
  118. package/dist/program-7UMVHRD3.js.map +0 -1
  119. package/dist/routing-XJ25QONX.js +0 -2
  120. package/dist/schedule-tool-5T4CH4CM.js +0 -2
  121. package/dist/scheduler-UKJWO2TR.js +0 -2
  122. package/dist/token-store-AY6OBDVI.js +0 -2
  123. package/dist/token-tracker-W7DFDEFN.js +0 -2
  124. package/dist/tool-7FFJSFTS.js +0 -6
  125. package/dist/tool-7FFJSFTS.js.map +0 -1
  126. package/dist/traces-GVEQZX24.js +0 -2
  127. package/dist/wiki-5Y4GSCYL.js +0 -2
  128. package/dist/wiki-enrich-TJIL4B3V.js +0 -2
  129. /package/dist/{App-AFRBV666.js.map → App-ENNAIXFU.js.map} +0 -0
  130. /package/dist/{ChatApp-EBTSY27Z.js.map → ChatApp-UNYTCNPZ.js.map} +0 -0
  131. /package/dist/{absorb-eval-OCR3G5TE.js.map → absorb-eval-UVOIKIBZ.js.map} +0 -0
  132. /package/dist/{agent-QZ4QTZKW.js.map → agent-JFDIUUCZ.js.map} +0 -0
  133. /package/dist/{chunk-BY2AAMOO.js.map → chunk-4QVGHA4B.js.map} +0 -0
  134. /package/dist/{chunk-TRGNLW43.js.map → chunk-7NRBMQE6.js.map} +0 -0
  135. /package/dist/{chunk-LLJZMS23.js.map → chunk-AYK2MO3B.js.map} +0 -0
  136. /package/dist/{chunk-KPNAXVET.js.map → chunk-CI5OJ2JN.js.map} +0 -0
  137. /package/dist/{chunk-E4O32ZYZ.js.map → chunk-CXBTGXFO.js.map} +0 -0
  138. /package/dist/{chunk-3ZMVYNFH.js.map → chunk-DEXEPOHH.js.map} +0 -0
  139. /package/dist/{chunk-B3I4EBLE.js.map → chunk-H2KVHGAP.js.map} +0 -0
  140. /package/dist/{chunk-DNPL3YOH.js.map → chunk-HYNP5WYF.js.map} +0 -0
  141. /package/dist/{chunk-EWBUH2IU.js.map → chunk-IMNN5RBR.js.map} +0 -0
  142. /package/dist/{chunk-5XPXYOWB.js.map → chunk-IMSIYVBM.js.map} +0 -0
  143. /package/dist/{chunk-DPNCWHJW.js.map → chunk-ITIW4UUJ.js.map} +0 -0
  144. /package/dist/{chunk-ZSVCHDYT.js.map → chunk-LRP2LTLC.js.map} +0 -0
  145. /package/dist/{chunk-OYPKAYCH.js.map → chunk-M5L3SOS2.js.map} +0 -0
  146. /package/dist/{chunk-VHHKS7S4.js.map → chunk-NURZPCUE.js.map} +0 -0
  147. /package/dist/{chunk-5NTWGUSJ.js.map → chunk-PFNGZ27Y.js.map} +0 -0
  148. /package/dist/{chunk-4UMMAI3Z.js.map → chunk-QEJD3KFG.js.map} +0 -0
  149. /package/dist/{chunk-NY5ZY2WV.js.map → chunk-QJDYXEEB.js.map} +0 -0
  150. /package/dist/{chunk-FM6RZI52.js.map → chunk-RJWFVKBK.js.map} +0 -0
  151. /package/dist/{chunk-GVMV3TWS.js.map → chunk-RW3MTYHG.js.map} +0 -0
  152. /package/dist/{chunk-P5RTEJUB.js.map → chunk-SCEQJFQO.js.map} +0 -0
  153. /package/dist/{chunk-FEF432WU.js.map → chunk-TZHVLA3D.js.map} +0 -0
  154. /package/dist/{chunk-JJV7O7YK.js.map → chunk-VDXHZAMX.js.map} +0 -0
  155. /package/dist/{chunk-PA3KFAXH.js.map → chunk-Y4KVFLQZ.js.map} +0 -0
  156. /package/dist/{chunk-MBPYC6QF.js.map → chunk-ZFMG4GFE.js.map} +0 -0
  157. /package/dist/{client-7ZJZT5H7.js.map → client-LUZU6O45.js.map} +0 -0
  158. /package/dist/{config-NFDEJ3NB.js.map → config-54LNSYJF.js.map} +0 -0
  159. /package/dist/{config-mutate-JYW5G7T6.js.map → config-mutate-DPI3LUG5.js.map} +0 -0
  160. /package/dist/{config-mutator-OMWL5XHO.js.map → config-mutator-W5QTLGCY.js.map} +0 -0
  161. /package/dist/{contributions-ECGVSETO.js.map → contributions-FCKXPCOL.js.map} +0 -0
  162. /package/dist/{doctor-D6OVZAFB.js.map → doctor-ZGL3U4XJ.js.map} +0 -0
  163. /package/dist/{failure-candidates-NQX2JMMS.js.map → failure-candidates-HNENLQJC.js.map} +0 -0
  164. /package/dist/{follow-up-tool-FNO2IG72.js.map → follow-up-tool-ARGSSE7Q.js.map} +0 -0
  165. /package/dist/{hub-MOAG5BEQ.js.map → hub-NK7Q4F2X.js.map} +0 -0
  166. /package/dist/{processes-XM77XGOO.js.map → processes-GRS7BSIU.js.map} +0 -0
  167. /package/dist/{promote-AAEZYPBP.js.map → promote-BKHGOZB2.js.map} +0 -0
  168. /package/dist/{query-WWZEARB4.js.map → query-SPGPGSHG.js.map} +0 -0
  169. /package/dist/{query-settings-3FE555NP.js.map → query-settings-L6FOADK7.js.map} +0 -0
  170. /package/dist/{registry-JPZLE5XX.js.map → registry-2JIZ3LOU.js.map} +0 -0
  171. /package/dist/{request-planner-2AU3VK4P.js.map → request-planner-JCRREXJX.js.map} +0 -0
  172. /package/dist/{review-candidates-CIEGXF7K.js.map → review-candidates-OKHRZROS.js.map} +0 -0
  173. /package/dist/{routing-XJ25QONX.js.map → routing-B3B3ANA5.js.map} +0 -0
  174. /package/dist/{schedule-tool-5T4CH4CM.js.map → schedule-tool-GUEADWVH.js.map} +0 -0
  175. /package/dist/{scheduler-UKJWO2TR.js.map → scheduler-OKSJXZBX.js.map} +0 -0
  176. /package/dist/{seat-JWRCBUKR.js.map → seat-FQ53NWXV.js.map} +0 -0
  177. /package/dist/{select-KIDX6WWF.js.map → select-YE4C3DZS.js.map} +0 -0
  178. /package/dist/{set-enabled-F4D3VWKI.js.map → set-enabled-66ZBGZ2O.js.map} +0 -0
  179. /package/dist/{surface-usage-WSY4SHHL.js.map → surface-usage-JOOZOGOH.js.map} +0 -0
  180. /package/dist/{token-store-AY6OBDVI.js.map → token-store-F2PHHO5A.js.map} +0 -0
  181. /package/dist/{token-tracker-W7DFDEFN.js.map → token-tracker-B2UFOH46.js.map} +0 -0
  182. /package/dist/{tool-YSS2C2UX.js.map → tool-U2HRYX3V.js.map} +0 -0
  183. /package/dist/{traces-GVEQZX24.js.map → traces-G4HRLRA3.js.map} +0 -0
  184. /package/dist/{wiki-5Y4GSCYL.js.map → wiki-3HUDGN6J.js.map} +0 -0
  185. /package/dist/{wiki-enrich-TJIL4B3V.js.map → wiki-enrich-XQ3ZQBWZ.js.map} +0 -0
  186. /package/dist/{workflow-pilot-HCPSMGIC.js.map → workflow-pilot-25NMZYUO.js.map} +0 -0
@@ -1,8 +1,8 @@
1
- import{a as Ne}from"./chunk-GTJIKXDB.js";import{C as dn,J as mn,k as O}from"./chunk-QH3RKKD3.js";import{a as w}from"./chunk-JYSJDHNS.js";import{f as pn,i as gn,k as De,l as Ce,n as X,o as W,q as fn}from"./chunk-LQS27HSV.js";import{t as ln,u as cn}from"./chunk-KPNAXVET.js";import{d as on,e as an}from"./chunk-AQASR6KR.js";import{b as un}from"./chunk-2VDO2HEK.js";import{a as tn,b as nn,d as rn,e as sn}from"./chunk-MNG2AMKZ.js";import{g as Jt,h as Yt,i as Zt,k as Qt,l as en}from"./chunk-E4O32ZYZ.js";import{a as Kt,c as Gt}from"./chunk-KP7KDLZ2.js";import{X as Xt,Z as oe,_ as Ie,aa as Te,b as Ae}from"./chunk-PVWHEPF3.js";import{q as zt}from"./chunk-OYPKAYCH.js";import{a as Bt,b as Ht}from"./chunk-EWBUH2IU.js";import{$ as Ut,Ya as Ee,_ as Mt,aa as Ft,ba as Wt,eb as qt,fb as jt,n as se,o as Ot,ob as Vt,p as Pt,q as Cs}from"./chunk-O5H6BCUN.js";import{a as Re,h as Ns}from"./chunk-BRK6M6LA.js";import{f as _e,n as Ls}from"./chunk-UIBUZ2N3.js";import{existsSync as Os,readdirSync as Ps,readFileSync as Ms,statSync as Us}from"fs";import{resolve as Fs}from"path";function hn(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)??[],l=a.filter(f=>n-f.at<=s),d=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.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?d.length>0&&l.length===0?"dormant":l.length>0&&c*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:d.length,failed:c,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ie=new Map;function ec(t,e=1e3){if(!Os(t))return[];let n=Ps(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=Fs(t,o);return{path:i,mtime:Us(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of ie.keys())r.has(o)||ie.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=ie.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=Ws(o,i);ie.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function Ws(t,e){try{let n=Ms(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]),l=a.status??a.run?.status;if(l){o=l;break}}return{workflowId:s,status:o,at:e}}catch{return null}}var qs={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},js=(t,e,n)=>{try{return zt(t,e,n)}catch{return null}},bn=864e5;function sc(t){let e=t.now??Date.now(),n={...qs,...t.thresholds},r=t.nextFire??js,s=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],d=a.timezone||"UTC",c=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:E(a.id,k.text),trigger:{schedule:E(a.schedule,k.text),timezone:d},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Le(a.nextRun)??Le(r(a.schedule,new Date(e),d)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:Ks(u.status==="success"?void 0:u.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:yn(c),sampledRuns:l.length,flags:[],attention:null};p.flags=wn(p,c,a.schedule,d,null,e,n,r),s.push(kn(p))}let o=new Map(hn(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 l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(T=>T.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let d=l.config??{},c=a.state||"active",u=c==="active",p=(i.get(a.id)??[]).slice().sort((T,$e)=>$e.at-T.at),g=p.map(T=>({at:T.at,status:Hs(T.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof d.spec=="string"?d.spec:"",x=typeof d.timezone=="string"?d.timezone:"UTC",F={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:E(a.title||a.id,k.text),trigger:m?{schedule:E(b,k.text),timezone:x}:{event:E(typeof d.event=="string"?d.event:"",k.text),filters:Xs(d.filter,a)},agent:zs(a),enabled:u,state:c,nextRunAt:m&&u&&b?Le(r(b,new Date(e),x)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let T=g.find($e=>$e.status==="success");return T?new Date(T.at).toISOString():null})(),consecutiveFailures:yn(g),sampledRuns:p.length,flags:[],attention:null},re=Date.parse(a.updated||a.created||"");F.flags=m?wn(F,g,b,x,Number.isFinite(re)?re:null,e,n,r):Vs(F,o.get(a.id)?.state==="dormant",Number.isFinite(re)?re:null,e,n),s.push(kn(F))}return s.sort(Bs).slice(0,k.routines)}function yn(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 wn(t,e,n,r,s,o,i,a){let l=[],d=e.length?e[0].at:null;if(!t.enabled){let p=xn(d,s,o,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),d===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let c=new Date(d),u=null;for(let p=0;p<i.missedFires&&(u=a(n,c,r),!!u);p++)c=u;return u&&o>u.getTime()+i.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(d).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function Vs(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=xn(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 xn(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*bn?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/bn)} days`:"Disabled and never ran"}}function kn(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 Sn={critical:0,warning:1,info:2};function Bs(t,e){let n=t.attention?Sn[t.attention]:3,r=e.attention?Sn[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Hs(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 zs(t){if(t.ownerAgent)return E(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?E(String(e.config.agentId),k.text):null}function Xs(t,e){let n=[],r=e?.project;if(r&&n.push(E(`project=${r}`,k.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(E(`${s}=${i.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Le(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function E(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ks(t,e){return t===void 0?void 0:E(t,e)}import{mkdirSync as Gs,readFileSync as Js,renameSync as Ys,writeFileSync as Zs}from"fs";import{resolve as Qs}from"path";function vn(t){return Qs(Ce(t),"_state.json")}function v(t){try{let e=JSON.parse(Js(vn(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 K(t,e){Gs(Ce(t),{recursive:!0});let n=vn(t),r=`${n}.${process.pid}.tmp`;Zs(r,JSON.stringify(e,null,2)+`
3
- `),Ys(r,n)}function $n(t,e,n,r=Date.now()){let s=v(t),o={};for(let[i,a]of Object.entries(s.snoozed))Date.parse(a)>r&&(o[i]=a);o[e]=n.toISOString(),K(t,{...s,snoozed:o})}function cc(t,e){K(t,{...v(t),lastDigest:e})}function Oe(t,e,n,r=Date.now()){let s=v(t),o=new Set(n),i={};for(let[l,d]of Object.entries(s.popped??{}))o.has(l)&&(i[l]=d);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(l=>l!==e&&o.has(l));K(t,{...s,popped:i,wanted:a})}function Rn(t,e){let n=v(t);K(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function dc(t,e=Date.now()){K(t,{...v(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as eo,readFileSync as to}from"fs";Vt();Ns();function _n(t){let e=Bt(t),n={};if(eo(e))try{n=qt(JSON.parse(to(e,"utf-8")))}catch{n={}}let r=Ee.safeParse(n?.requests);return r.success?r.data:Ee.parse(void 0)}async function hc(t,e={}){let n=(t.channels??[]).filter(r=>!Re.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Re].join(", ")}`}:Ht(r=>{let s=r.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])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.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 G,readdirSync as ho,readFileSync as bo}from"fs";import{resolve as A}from"path";import{randomBytes as In}from"crypto";import{existsSync as ro,mkdirSync as so,readdirSync as oo,readFileSync as io,renameSync as Tn,unlinkSync as ao,writeFileSync as lo}from"fs";import{resolve as Dn}from"path";function En(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var no=t=>t.trim().split(`
4
- `).pop()?.slice(0,300)||"no output";async function An(t,e,n,r=Ne){let s=await r(t.bin,[...En(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${no(s.stderr||s.stdout)}`}}async function wc(t,e,n,r,s=Ne){return(await s(t.bin,[...En(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var co=2e3,uo=t=>An(t.wacli,t.to,t.text);function Pe(t){return Dn(t,".agentx","whatsapp-triage","drafts")}var po=t=>/^[a-z0-9-]{8,64}$/.test(t),ae=(t,e)=>Dn(Pe(t),`${e}.json`);function Cn(t,e){so(Pe(t),{recursive:!0});let n=ae(t,e.id),r=`${n}.${process.pid}.tmp`;lo(r,JSON.stringify(e,null,2)+`
5
- `,{mode:384}),Tn(r,n)}function Rc(t,e,n=Date.now()){let r=e.text.trim().slice(0,co);if(!r)throw new Error("empty draft");let s={...e,text:r,id:`${n.toString(36)}-${In(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Cn(t,s),s}function le(t,e){if(!po(e))return null;try{return JSON.parse(io(ae(t,e),"utf-8"))}catch{return null}}function Nn(t,e){let n=Pe(t);return ro(n)?oo(n).filter(r=>r.endsWith(".json")).map(r=>le(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,s)=>r.created_at.localeCompare(s.created_at)):[]}async function Ln(t,e,n,r={}){let s=le(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let o=`${ae(t,e)}.${process.pid}.${In(3).toString("hex")}.claim`;try{Tn(ae(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??uo)(s).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Cn(t,i);try{ao(o)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}Ls();Wt();Wt();var Ac=["done","skipped"],go=1e3;function fo(t){t.exec(`
1
+ import{a as Ne}from"./chunk-GTJIKXDB.js";import{C as dn,J as mn,k as O}from"./chunk-NHD6DUBL.js";import{a as w}from"./chunk-VUEQ4SL5.js";import{f as pn,i as gn,k as De,l as Ce,n as X,o as W,q as fn}from"./chunk-LQS27HSV.js";import{t as ln,u as cn}from"./chunk-CI5OJ2JN.js";import{d as on,e as an}from"./chunk-AQASR6KR.js";import{b as un}from"./chunk-2VDO2HEK.js";import{a as tn,b as nn,d as rn,e as sn}from"./chunk-MNG2AMKZ.js";import{g as Jt,h as Yt,i as Zt,k as Qt,l as en}from"./chunk-CXBTGXFO.js";import{a as Kt,c as Gt}from"./chunk-KP7KDLZ2.js";import{b as Ae,da as Xt,fa as oe,ga as Ie,ia as Te}from"./chunk-M4AQRADJ.js";import{q as zt}from"./chunk-M5L3SOS2.js";import{a as Bt,b as Ht}from"./chunk-IMNN5RBR.js";import{$ as Ut,Za as Ee,_ as Mt,ba as Ft,ca as Wt,fb as qt,gb as jt,n as se,o as Ot,p as Pt,pb as Vt,q as Ns}from"./chunk-TFN6A3KI.js";import{a as Re,h as Ls}from"./chunk-BRK6M6LA.js";import{i as _e,q as Os}from"./chunk-XHAPSFAB.js";import{existsSync as Ps,readdirSync as Ms,readFileSync as Us,statSync as Fs}from"fs";import{resolve as Ws}from"path";function hn(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)??[],l=a.filter(f=>n-f.at<=s),d=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.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?d.length>0&&l.length===0?"dormant":l.length>0&&c*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:d.length,failed:c,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ie=new Map;function rc(t,e=1e3){if(!Ps(t))return[];let n=Ms(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=Ws(t,o);return{path:i,mtime:Fs(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of ie.keys())r.has(o)||ie.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=ie.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=qs(o,i);ie.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function qs(t,e){try{let n=Us(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]),l=a.status??a.run?.status;if(l){o=l;break}}return{workflowId:s,status:o,at:e}}catch{return null}}var js={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},Vs=(t,e,n)=>{try{return zt(t,e,n)}catch{return null}},bn=864e5;function ac(t){let e=t.now??Date.now(),n={...js,...t.thresholds},r=t.nextFire??Vs,s=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],d=a.timezone||"UTC",c=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:E(a.id,k.text),trigger:{schedule:E(a.schedule,k.text),timezone:d},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Le(a.nextRun)??Le(r(a.schedule,new Date(e),d)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:Gs(u.status==="success"?void 0:u.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:yn(c),sampledRuns:l.length,flags:[],attention:null};p.flags=wn(p,c,a.schedule,d,null,e,n,r),s.push(kn(p))}let o=new Map(hn(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 l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(T=>T.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let d=l.config??{},c=a.state||"active",u=c==="active",p=(i.get(a.id)??[]).slice().sort((T,$e)=>$e.at-T.at),g=p.map(T=>({at:T.at,status:zs(T.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof d.spec=="string"?d.spec:"",x=typeof d.timezone=="string"?d.timezone:"UTC",F={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:E(a.title||a.id,k.text),trigger:m?{schedule:E(b,k.text),timezone:x}:{event:E(typeof d.event=="string"?d.event:"",k.text),filters:Ks(d.filter,a)},agent:Xs(a),enabled:u,state:c,nextRunAt:m&&u&&b?Le(r(b,new Date(e),x)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let T=g.find($e=>$e.status==="success");return T?new Date(T.at).toISOString():null})(),consecutiveFailures:yn(g),sampledRuns:p.length,flags:[],attention:null},re=Date.parse(a.updated||a.created||"");F.flags=m?wn(F,g,b,x,Number.isFinite(re)?re:null,e,n,r):Bs(F,o.get(a.id)?.state==="dormant",Number.isFinite(re)?re:null,e,n),s.push(kn(F))}return s.sort(Hs).slice(0,k.routines)}function yn(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 wn(t,e,n,r,s,o,i,a){let l=[],d=e.length?e[0].at:null;if(!t.enabled){let p=xn(d,s,o,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),d===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let c=new Date(d),u=null;for(let p=0;p<i.missedFires&&(u=a(n,c,r),!!u);p++)c=u;return u&&o>u.getTime()+i.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(d).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function Bs(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=xn(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 xn(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*bn?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/bn)} days`:"Disabled and never ran"}}function kn(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 Sn={critical:0,warning:1,info:2};function Hs(t,e){let n=t.attention?Sn[t.attention]:3,r=e.attention?Sn[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function zs(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 Xs(t){if(t.ownerAgent)return E(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?E(String(e.config.agentId),k.text):null}function Ks(t,e){let n=[],r=e?.project;if(r&&n.push(E(`project=${r}`,k.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(E(`${s}=${i.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Le(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function E(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Gs(t,e){return t===void 0?void 0:E(t,e)}import{mkdirSync as Js,readFileSync as Ys,renameSync as Zs,writeFileSync as Qs}from"fs";import{resolve as eo}from"path";function vn(t){return eo(Ce(t),"_state.json")}function v(t){try{let e=JSON.parse(Ys(vn(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 K(t,e){Js(Ce(t),{recursive:!0});let n=vn(t),r=`${n}.${process.pid}.tmp`;Qs(r,JSON.stringify(e,null,2)+`
3
+ `),Zs(r,n)}function $n(t,e,n,r=Date.now()){let s=v(t),o={};for(let[i,a]of Object.entries(s.snoozed))Date.parse(a)>r&&(o[i]=a);o[e]=n.toISOString(),K(t,{...s,snoozed:o})}function pc(t,e){K(t,{...v(t),lastDigest:e})}function Oe(t,e,n,r=Date.now()){let s=v(t),o=new Set(n),i={};for(let[l,d]of Object.entries(s.popped??{}))o.has(l)&&(i[l]=d);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(l=>l!==e&&o.has(l));K(t,{...s,popped:i,wanted:a})}function Rn(t,e){let n=v(t);K(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function gc(t,e=Date.now()){K(t,{...v(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as to,readFileSync as no}from"fs";Vt();Ls();function _n(t){let e=Bt(t),n={};if(to(e))try{n=qt(JSON.parse(no(e,"utf-8")))}catch{n={}}let r=Ee.safeParse(n?.requests);return r.success?r.data:Ee.parse(void 0)}async function wc(t,e={}){let n=(t.channels??[]).filter(r=>!Re.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Re].join(", ")}`}:Ht(r=>{let s=r.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])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.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 G,readdirSync as bo,readFileSync as yo}from"fs";import{resolve as A}from"path";import{randomBytes as In}from"crypto";import{existsSync as so,mkdirSync as oo,readdirSync as io,readFileSync as ao,renameSync as Tn,unlinkSync as lo,writeFileSync as co}from"fs";import{resolve as Dn}from"path";function En(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ro=t=>t.trim().split(`
4
+ `).pop()?.slice(0,300)||"no output";async function An(t,e,n,r=Ne){let s=await r(t.bin,[...En(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ro(s.stderr||s.stdout)}`}}async function xc(t,e,n,r,s=Ne){return(await s(t.bin,[...En(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var uo=2e3,po=t=>An(t.wacli,t.to,t.text);function Pe(t){return Dn(t,".agentx","whatsapp-triage","drafts")}var go=t=>/^[a-z0-9-]{8,64}$/.test(t),ae=(t,e)=>Dn(Pe(t),`${e}.json`);function Cn(t,e){oo(Pe(t),{recursive:!0});let n=ae(t,e.id),r=`${n}.${process.pid}.tmp`;co(r,JSON.stringify(e,null,2)+`
5
+ `,{mode:384}),Tn(r,n)}function Ac(t,e,n=Date.now()){let r=e.text.trim().slice(0,uo);if(!r)throw new Error("empty draft");let s={...e,text:r,id:`${n.toString(36)}-${In(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Cn(t,s),s}function le(t,e){if(!go(e))return null;try{return JSON.parse(ao(ae(t,e),"utf-8"))}catch{return null}}function Nn(t,e){let n=Pe(t);return so(n)?io(n).filter(r=>r.endsWith(".json")).map(r=>le(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,s)=>r.created_at.localeCompare(s.created_at)):[]}async function Ln(t,e,n,r={}){let s=le(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let o=`${ae(t,e)}.${process.pid}.${In(3).toString("hex")}.claim`;try{Tn(ae(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??po)(s).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Cn(t,i);try{lo(o)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}Os();Wt();Wt();var Dc=["done","skipped"],fo=1e3;function mo(t){t.exec(`
6
6
  CREATE TABLE IF NOT EXISTS request_plans (
7
7
  request_id TEXT PRIMARY KEY,
8
8
  created_by TEXT NOT NULL,
@@ -50,9 +50,10 @@ import{a as Ne}from"./chunk-GTJIKXDB.js";import{C as dn,J as mn,k as O}from"./ch
50
50
  FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
51
51
  );
52
52
  CREATE INDEX IF NOT EXISTS idx_request_plan_events ON request_plan_events(request_id, at);
53
- `)}function Pn(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function Me(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 On(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,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 mo={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"},ce=class{constructor(e){this.db=e;fo(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,
53
+ `)}function Pn(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function Me(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 On(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,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 ho={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"},ce=class{constructor(e){this.db=e;mo(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,
54
54
  to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at)
55
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{o.run(e,n,s),r.forEach((a,l)=>{let d=l===0,c=d&&a.agentId===n&&a.kind!=="message";i.run(e,l+1,a.name,a.kind,a.agentId,a.doneWhen,d?"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,c?s:null,s)}),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?Me(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(On)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?On(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(Me)}updateStep(e,n,r){let s=[],o=[];for(let[i,a]of Object.entries(r)){let l=mo[i];!l||a===void 0||(s.push(`${l} = ?`),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(Me)}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,go))}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, rowid LIMIT ?").all(e,n).map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}},Ic=Mt;var Fn=["card","schedule","memory","wiki","whatsapp","request"],yo=280;function q(t,e=yo){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Ue(t){if(t.configPath)return A(t.configPath);let e=[A(t.root,"agentx.json"),A(t.root,".agentx","config.json")];return e.find(n=>G(n))??e[0]}function Fe(t){return t.wikiDir?A(t.wikiDir):A(t.root,".agentx","wiki")}function wo(t){return W(t.root,"pending").map(ko)}function ko(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:q([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function So(t){let e=Ue(t);if(!G(e))return[];let n;try{n=JSON.parse(bo(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 l=i.timezone||"UTC",d=i.schedule?Jt(i.schedule):"",c=i.schedule?`${d.charAt(0).toLowerCase()}${d.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 ${c}?`:`Remove the schedule "${o}" (${c})?`,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:q(`${u}${p&&i.schedule?` \xB7 first run ${Zt(Yt(i.schedule,l,r),l)}`:""}`),more:"agentx schedule list"})}return s}function Wn(t){let e=A(t,".agentx","memory");return G(e)?ho(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function xo(t){let e=Wn(t.root);if(e.length===0)return[];let n=new Ae(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:q(o.content),more:`agentx memory facts held --agent ${s}`});return r}function vo(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 $o(t){return an(Fe(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:q(`${vo(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function Ro(t){return Nn(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:q(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function P(t){if(t.requests)return t.requests;if(A(t.root)!==process.cwd()||!G(A(t.root,".agentx","db.sqlite")))return null;let e=_e({quiet:!0});if(!e)return null;let n=Mn.get(e);return!n&&!Ut(e)?null:(n||Mn.set(e,n=new Ft(e)),n)}var Mn=new WeakMap;function Hc(t){if(t.plans)return t.plans;if(t.requests||A(t.root)!==process.cwd()||!G(A(t.root,".agentx","db.sqlite")))return null;let e=_e({quiet:!0});if(!e||!Pn(e))return null;let n=Un.get(e);return n||Un.set(e,n=new ce(e)),n}var Un=new WeakMap;function _o(t){let e=P(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:O(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:q(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var qn={card:wo,schedule:So,memory:xo,wiki:$o,whatsapp:Ro,request:_o};function Eo(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 jn(t,e={}){let n=t.now??Date.now(),{snoozed:r}=v(t.root),s=[],o=[],i=0;for(let a of e.kinds??Fn){let l;try{l=qn[a](t)}catch(d){o.push({kind:a,error:String(d?.message??d).slice(0,200)});continue}for(let d of l){let c=r[d.key];if(c&&Date.parse(c)>n){if(!e.includeSnoozed){i++;continue}d.snoozed_until=c}s.push(d)}}return s.sort(Eo),{items:s,snoozed:i,errors:o}}function Ao(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!Fn.includes(n)||!r?null:{kind:n,ref:r}}function Io(t,e,n){switch(e){case"card":return X(t.root,n)?.status==="pending";case"wiki":return on(Fe(t),n)?.status==="pending";case"whatsapp":return le(t.root,n)?.status==="pending";default:return qn[e](t).some(r=>r.key===`${e}:${n}`)}}async function Vn(t,e,n,r={}){let s=Ao(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(),l=r.by??"operator";if(n==="later"){if(!Io(t,o,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,u=new Date(a+c*36e5);return $n(t.root,e,u,a),{ok:!0,message:`${e} put off until ${u.toISOString()}`}}let d=n==="yes";switch(o){case"card":{let c=fn(t.root,i,d?"yes":"no",{by:l,note:r.note,now:a,choice:r.choice,text:r.text});return c.ok?{ok:!0,message:`${e}: ${c.card.raised_by} will be told ${d?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(d?Qt:en)(i,{configPath:Ue(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let u=i.slice(0,c),p=i.slice(c+1);if(!Wn(t.root).includes(u))return{ok:!1,error:`no memory for agent "${u}"`};let g=new Ae(t.root);return g.held(u).some(f=>f.id===p)?(g.review(u,p,d?"approved":"rejected",l),{ok:!0,message:`${e} ${d?"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 c=Fe(t),u=d?ln(c,i,{by:l,force:r.force,now:a}):cn(c,i,{by:l,reason:r.note,now:a});return u.ok?{ok:!0,message:d?`${u.proposal.article.path} written to the shared wiki`:`${e} rejected`}:u}case"whatsapp":{let c=await Ln(t.root,i,d?"yes":"no",{by:l,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:d?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"request":{let c=P(t),u=c?.get(i);return!c||!u||u.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:d?_n(Ue(t)).enabled?(c.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."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${l}`,a),{ok:!0,message:`${e}: dropped`})}}}var To=3,Do=7,Co=50,qe=120,No=280,We=600,Hn=36e5,Lo=24*Hn;function Kc(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 j(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var de=t=>new Date(t).toISOString();function Oo(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:j(e.title,qe),...e.ask?{ask:j(e.ask,We)}:{},...e.detail?{facts:j(e.detail,No)}:{},...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 Po={done:"Done",declined:"Declined",dropped:"Dropped"};function zn(t,e,n){let{record:r,links:s}=e,o=O(r,qe),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:o.headline,need:o.need,...r.headline?{said:j(o.said,We)}:{},agent:r.agentId,askedAt:de(r.createdAt),changedAt:de(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:j(r.question,We)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=s.some(d=>d.kind==="run"&&!!t.liveRuns?.has(d.ref)),l=t.now-r.updatedAt<(t.quietHours??To)*Hn;return{...i,column:a||l?"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:de(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Po[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Mo(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 Uo(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:j(e.title,qe),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Mo(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var $=t=>t&&Date.parse(t)||0,Bn=(t,e)=>t.map(n=>n[e]).filter(n=>!!$(n)).sort((n,r)=>$(n)-$(r))[0];function je(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(Oo(s,o,s.node===t.node))}let r=Xn(t,e);for(let s of t.requests??[]){let o=zn(t,s,r);o?.column==="yours"&&e.push(o)}return{cards:e,errors:n}}function Xn(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Gc(t){let e=je(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=Xn(t,n),o=[],i=[],a=[];for(let p of t.requests??[]){let g=zn(t,p,s);g&&g.column!=="yours"&&{agent:o,quiet:i,done:a}[g.column].push(g)}let l=t.now-(t.doneDays??Do)*Lo;for(let p of t.cards)p.status!=="pending"&&$(p.decided_at)>=l&&a.push(Uo(t,p));o.sort((p,g)=>$(g.changedAt)-$(p.changedAt)),i.sort((p,g)=>$(p.changedAt)-$(g.changedAt)),a.sort((p,g)=>$(g.changedAt)-$(p.changedAt));let d=a.filter(p=>$(p.changedAt)>=l).slice(0,Co),c=Bn(n,"askedAt"),u=Bn(i,"changedAt");return{ts:de(t.now),cards:[...n,...o,...i,...d],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:o.length},quiet:{count:i.length,...u?{oldest:u}:{}},done:{count:d.length}},errors:r}}function Fo(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 Wo(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 Qc(t,e){let n=t.now??Date.now(),r=[],s=jn(t,{includeSnoozed:!0});for(let c of s.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let o=s.items.filter(c=>!c.snoozed_until),i=new Set(s.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=P(t);c&&(a=c.listByState("waiting_owner").map(u=>({record:u,links:c.links(u.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:l,errors:d}=je({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:o.map(Fo)}],requests:a,deferred:i});return Wo(l,i.size,[...r,...d])}var Kn=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function td(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||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"||/^\/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/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 nd(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||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/review-gate/replay"}function rd(t){return Kn.has(t)}function sd(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Kn.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 od(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 id(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 ue(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function qo(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function jo(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function ld(t,e=jo()){let n=ue(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let s=qo(n),o=[ue(t.host),ue(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return s&&o.includes(s)?"same-origin":"foreign"}let r=ue(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function cd(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{existsSync as wr,mkdirSync as bi,readFileSync as yi,renameSync as wi,writeFileSync as ki}from"fs";import{homedir as Si}from"os";import{dirname as xi,join as vi}from"path";import{execFile as Qo,execFileSync as ei}from"child_process";import{execFileSync as Vo}from"child_process";import{existsSync as Jn,mkdirSync as Bo,readdirSync as Ho,readFileSync as Yn,renameSync as zo,writeFileSync as Xo}from"fs";import{homedir as Zn}from"os";import{join as Be}from"path";var R="siri:",Qn="com.apple.ttsbundle.gryphon-neural_",er=t=>!!t&&t.startsWith(Qn),Ko=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],Go=()=>{try{return Vo("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},Ve;function He(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&Ve!==void 0)return Ve;let{platform:n=process.platform,exists:r=Jn,prefDomain:s=Go}=t,o=n==="darwin"&&Ko.every(i=>r(i))&&s();return e||(Ve=o),o}var tr=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],nr={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"},ze=t=>nr[t.toLowerCase()]??null;function pe(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 Jo=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function Yo(t){let e=new Map;for(let n of t)for(let[,r,s,o]of n.matchAll(Jo)){let i=`${r}-${s}`,a=`${Qn}${o}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:o[0].toUpperCase()+o.slice(1),locale:i,quality:"premium",gender:nr[o]??null,siri:!0})}return[...e.values()]}function ge(t=tr,e={}){if(!He(e))return[];let n=[];for(let r of t){let s;try{s=Ho(r)}catch{continue}for(let o of s)try{n.push(Yn(Be(r,o,"Info.plist"),"latin1"))}catch{}}return Yo(n)}var Gn=`#!/bin/sh
55
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{o.run(e,n,s),r.forEach((a,l)=>{let d=l===0,c=d&&a.agentId===n&&a.kind!=="message";i.run(e,l+1,a.name,a.kind,a.agentId,a.doneWhen,d?"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,c?s:null,s)}),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?Me(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(On)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?On(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(Me)}updateStep(e,n,r){let s=[],o=[];for(let[i,a]of Object.entries(r)){let l=ho[i];!l||a===void 0||(s.push(`${l} = ?`),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(Me)}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,fo))}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, rowid LIMIT ?").all(e,n).map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}},Cc=Mt;var Fn=["card","schedule","memory","wiki","whatsapp","request"],wo=280;function q(t,e=wo){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Ue(t){if(t.configPath)return A(t.configPath);let e=[A(t.root,"agentx.json"),A(t.root,".agentx","config.json")];return e.find(n=>G(n))??e[0]}function Fe(t){return t.wikiDir?A(t.wikiDir):A(t.root,".agentx","wiki")}function ko(t){return W(t.root,"pending").map(So)}function So(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:q([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function xo(t){let e=Ue(t);if(!G(e))return[];let n;try{n=JSON.parse(yo(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 l=i.timezone||"UTC",d=i.schedule?Jt(i.schedule):"",c=i.schedule?`${d.charAt(0).toLowerCase()}${d.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 ${c}?`:`Remove the schedule "${o}" (${c})?`,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:q(`${u}${p&&i.schedule?` \xB7 first run ${Zt(Yt(i.schedule,l,r),l)}`:""}`),more:"agentx schedule list"})}return s}function Wn(t){let e=A(t,".agentx","memory");return G(e)?bo(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function vo(t){let e=Wn(t.root);if(e.length===0)return[];let n=new Ae(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:q(o.content),more:`agentx memory facts held --agent ${s}`});return r}function $o(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 Ro(t){return an(Fe(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:q(`${$o(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function _o(t){return Nn(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:q(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function P(t){if(t.requests)return t.requests;if(A(t.root)!==process.cwd()||!G(A(t.root,".agentx","db.sqlite")))return null;let e=_e({quiet:!0});if(!e)return null;let n=Mn.get(e);return!n&&!Ut(e)?null:(n||Mn.set(e,n=new Ft(e)),n)}var Mn=new WeakMap;function Kc(t){if(t.plans)return t.plans;if(t.requests||A(t.root)!==process.cwd()||!G(A(t.root,".agentx","db.sqlite")))return null;let e=_e({quiet:!0});if(!e||!Pn(e))return null;let n=Un.get(e);return n||Un.set(e,n=new ce(e)),n}var Un=new WeakMap;function Eo(t){let e=P(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:O(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:q(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var qn={card:ko,schedule:xo,memory:vo,wiki:Ro,whatsapp:_o,request:Eo};function Ao(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 jn(t,e={}){let n=t.now??Date.now(),{snoozed:r}=v(t.root),s=[],o=[],i=0;for(let a of e.kinds??Fn){let l;try{l=qn[a](t)}catch(d){o.push({kind:a,error:String(d?.message??d).slice(0,200)});continue}for(let d of l){let c=r[d.key];if(c&&Date.parse(c)>n){if(!e.includeSnoozed){i++;continue}d.snoozed_until=c}s.push(d)}}return s.sort(Ao),{items:s,snoozed:i,errors:o}}function Io(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!Fn.includes(n)||!r?null:{kind:n,ref:r}}function To(t,e,n){switch(e){case"card":return X(t.root,n)?.status==="pending";case"wiki":return on(Fe(t),n)?.status==="pending";case"whatsapp":return le(t.root,n)?.status==="pending";default:return qn[e](t).some(r=>r.key===`${e}:${n}`)}}async function Vn(t,e,n,r={}){let s=Io(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(),l=r.by??"operator";if(n==="later"){if(!To(t,o,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,u=new Date(a+c*36e5);return $n(t.root,e,u,a),{ok:!0,message:`${e} put off until ${u.toISOString()}`}}let d=n==="yes";switch(o){case"card":{let c=fn(t.root,i,d?"yes":"no",{by:l,note:r.note,now:a,choice:r.choice,text:r.text});return c.ok?{ok:!0,message:`${e}: ${c.card.raised_by} will be told ${d?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(d?Qt:en)(i,{configPath:Ue(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let u=i.slice(0,c),p=i.slice(c+1);if(!Wn(t.root).includes(u))return{ok:!1,error:`no memory for agent "${u}"`};let g=new Ae(t.root);return g.held(u).some(f=>f.id===p)?(g.review(u,p,d?"approved":"rejected",l),{ok:!0,message:`${e} ${d?"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 c=Fe(t),u=d?ln(c,i,{by:l,force:r.force,now:a}):cn(c,i,{by:l,reason:r.note,now:a});return u.ok?{ok:!0,message:d?`${u.proposal.article.path} written to the shared wiki`:`${e} rejected`}:u}case"whatsapp":{let c=await Ln(t.root,i,d?"yes":"no",{by:l,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:d?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"request":{let c=P(t),u=c?.get(i);return!c||!u||u.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:d?_n(Ue(t)).enabled?(c.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."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${l}`,a),{ok:!0,message:`${e}: dropped`})}}}var Do=3,Co=7,No=50,qe=120,Lo=280,We=600,Hn=36e5,Oo=24*Hn;function Yc(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 j(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var de=t=>new Date(t).toISOString();function Po(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:j(e.title,qe),...e.ask?{ask:j(e.ask,We)}:{},...e.detail?{facts:j(e.detail,Lo)}:{},...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 Mo={done:"Done",declined:"Declined",dropped:"Dropped"};function zn(t,e,n){let{record:r,links:s}=e,o=O(r,qe),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:o.headline,need:o.need,...r.headline?{said:j(o.said,We)}:{},agent:r.agentId,askedAt:de(r.createdAt),changedAt:de(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:j(r.question,We)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=s.some(d=>d.kind==="run"&&!!t.liveRuns?.has(d.ref)),l=t.now-r.updatedAt<(t.quietHours??Do)*Hn;return{...i,column:a||l?"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:de(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Mo[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Uo(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 Fo(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:j(e.title,qe),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Uo(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var $=t=>t&&Date.parse(t)||0,Bn=(t,e)=>t.map(n=>n[e]).filter(n=>!!$(n)).sort((n,r)=>$(n)-$(r))[0];function je(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(Po(s,o,s.node===t.node))}let r=Xn(t,e);for(let s of t.requests??[]){let o=zn(t,s,r);o?.column==="yours"&&e.push(o)}return{cards:e,errors:n}}function Xn(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Zc(t){let e=je(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=Xn(t,n),o=[],i=[],a=[];for(let p of t.requests??[]){let g=zn(t,p,s);g&&g.column!=="yours"&&{agent:o,quiet:i,done:a}[g.column].push(g)}let l=t.now-(t.doneDays??Co)*Oo;for(let p of t.cards)p.status!=="pending"&&$(p.decided_at)>=l&&a.push(Fo(t,p));o.sort((p,g)=>$(g.changedAt)-$(p.changedAt)),i.sort((p,g)=>$(p.changedAt)-$(g.changedAt)),a.sort((p,g)=>$(g.changedAt)-$(p.changedAt));let d=a.filter(p=>$(p.changedAt)>=l).slice(0,No),c=Bn(n,"askedAt"),u=Bn(i,"changedAt");return{ts:de(t.now),cards:[...n,...o,...i,...d],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:o.length},quiet:{count:i.length,...u?{oldest:u}:{}},done:{count:d.length}},errors:r}}function Wo(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 qo(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 nd(t,e){let n=t.now??Date.now(),r=[],s=jn(t,{includeSnoozed:!0});for(let c of s.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let o=s.items.filter(c=>!c.snoozed_until),i=new Set(s.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=P(t);c&&(a=c.listByState("waiting_owner").map(u=>({record:u,links:c.links(u.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:l,errors:d}=je({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:o.map(Wo)}],requests:a,deferred:i});return qo(l,i.size,[...r,...d])}import{readFileSync as jo}from"fs";var Vo=1e4,Kn=/^[0-9a-f]{7,64}$/i;function od(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&Kn.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(Vo)})}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"&&Kn.test(o.trim())?{source:n,commit:o.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function id(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=jo(n.tokenFile,"utf-8").trim().split(`
56
+ `)[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 Gn=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function ld(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||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"||/^\/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/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 cd(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||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/review-gate/replay"}function dd(t){return Gn.has(t)}function ud(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Gn.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 pd(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 gd(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 ue(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Bo(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ho(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function md(t,e=Ho()){let n=ue(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let s=Bo(n),o=[ue(t.host),ue(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return s&&o.includes(s)?"same-origin":"foreign"}let r=ue(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function hd(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{existsSync as kr,mkdirSync as ki,readFileSync as Si,renameSync as xi,writeFileSync as vi}from"fs";import{homedir as $i}from"os";import{dirname as Ri,join as _i}from"path";import{execFile as ni,execFileSync as ri}from"child_process";import{execFileSync as zo}from"child_process";import{existsSync as Yn,mkdirSync as Xo,readdirSync as Ko,readFileSync as Zn,renameSync as Go,writeFileSync as Jo}from"fs";import{homedir as Qn}from"os";import{join as Be}from"path";var R="siri:",er="com.apple.ttsbundle.gryphon-neural_",tr=t=>!!t&&t.startsWith(er),Yo=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],Zo=()=>{try{return zo("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},Ve;function He(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&Ve!==void 0)return Ve;let{platform:n=process.platform,exists:r=Yn,prefDomain:s=Zo}=t,o=n==="darwin"&&Yo.every(i=>r(i))&&s();return e||(Ve=o),o}var nr=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],rr={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"},ze=t=>rr[t.toLowerCase()]??null;function pe(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 Qo=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function ei(t){let e=new Map;for(let n of t)for(let[,r,s,o]of n.matchAll(Qo)){let i=`${r}-${s}`,a=`${er}${o}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:o[0].toUpperCase()+o.slice(1),locale:i,quality:"premium",gender:rr[o]??null,siri:!0})}return[...e.values()]}function ge(t=nr,e={}){if(!He(e))return[];let n=[];for(let r of t){let s;try{s=Ko(r)}catch{continue}for(let o of s)try{n.push(Zn(Be(r,o,"Info.plist"),"latin1"))}catch{}}return ei(n)}var Jn=`#!/bin/sh
56
57
  # Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
57
58
  # siri-say.sh [voice] < text speak one line. A Siri voice id switches
58
59
  # the OS default for it; any other id is
@@ -64,7 +65,7 @@ D=com.apple.Accessibility K=SpokenContentDefaultVoiceSelectionsByLanguage
64
65
  dir="$HOME/.agentx/voice" lock="$HOME/.agentx/voice/siri.lock" saved="$HOME/.agentx/voice/siri-saved.plist"
65
66
  stops="$dir/stop"
66
67
  read_s=\${AGENTX_SAY_READ_S:-5} stale_s=\${AGENTX_SAY_STALE_S:-30} max_s=\${AGENTX_SAY_MAX_S:-300}
67
- assets=\${AGENTX_SIRI_ASSET_DIRS:-"${tr.join(" ")}"}
68
+ assets=\${AGENTX_SIRI_ASSET_DIRS:-"${nr.join(" ")}"}
68
69
  if [ "$1" = --stop ]; then
69
70
  mkdir -p "$dir" || exit 1
70
71
  # Queued lines see this change and drop. The owner's trap stops say,
@@ -157,28 +158,28 @@ wait "$say_pid"
157
158
  status=$?
158
159
  say_pid=
159
160
  finish $status
160
- `,Zo=(t=Zn())=>Be(t,".agentx","voice","siri-say.sh");function rr(t=Zn()){let e=Zo(t);return Jn(e)&&Yn(e,"utf8")===Gn||(Bo(Be(t,".agentx","voice"),{recursive:!0}),Xo(`${e}.tmp`,Gn,{mode:493}),zo(`${e}.tmp`,e)),e}var sr=`ObjC.import("AVFoundation")
161
+ `,ti=(t=Qn())=>Be(t,".agentx","voice","siri-say.sh");function sr(t=Qn()){let e=ti(t);return Yn(e)&&Zn(e,"utf8")===Jn||(Xo(Be(t,".agentx","voice"),{recursive:!0}),Jo(`${e}.tmp`,Jn,{mode:493}),Go(`${e}.tmp`,e)),e}var or=`ObjC.import("AVFoundation")
161
162
  const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
162
163
  for (let i = 0; i < vs.count; i++) {
163
164
  const v = vs.objectAtIndex(i)
164
165
  out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
165
166
  }
166
- out.join("\\n")`,ti=new Set(["Fred","Kathy","Ralph","Junior"]),ni={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 or(t){let e=[];for(let n of t.split(`
167
- `)){let[r,s,o,i,a]=n.split(" ");!r||!s||!o||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!ti.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":ni[s]??null})}return e}var ri=10*60*1e3,yd=60*1e3,V=null,Xe=!1;function Ke(t=Date.now(),e=ri){if(process.platform!=="darwin")return[];if(V)t-V.at>e&&!Xe&&(Xe=!0,Qo("osascript",["-l","JavaScript","-e",sr],{timeout:1e4},(n,r)=>{Xe=!1,n||(V={at:Date.now(),voices:[...or(String(r)),...ge()]})}));else try{V={at:t,voices:[...or(ei("osascript",["-l","JavaScript","-e",sr],{encoding:"utf8",timeout:1e4})),...ge()]}}catch(n){Ge(`[voice] could not list system voices: ${String(n?.message??n).split(`
167
+ out.join("\\n")`,si=new Set(["Fred","Kathy","Ralph","Junior"]),oi={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 ir(t){let e=[];for(let n of t.split(`
168
+ `)){let[r,s,o,i,a]=n.split(" ");!r||!s||!o||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!si.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":oi[s]??null})}return e}var ii=10*60*1e3,Rd=60*1e3,V=null,Xe=!1;function Ke(t=Date.now(),e=ii){if(process.platform!=="darwin")return[];if(V)t-V.at>e&&!Xe&&(Xe=!0,ni("osascript",["-l","JavaScript","-e",or],{timeout:1e4},(n,r)=>{Xe=!1,n||(V={at:Date.now(),voices:[...ir(String(r)),...ge()]})}));else try{V={at:t,voices:[...ir(ri("osascript",["-l","JavaScript","-e",or],{encoding:"utf8",timeout:1e4})),...ge()]}}catch(n){Ge(`[voice] could not list system voices: ${String(n?.message??n).split(`
168
169
  `)[0]}`),V={at:t,voices:ge()}}return V.voices}var Ge=t=>process.stderr.write(t+`
169
- `),fe=new Set;function wd(t){Ge=t}function M(t,e){fe.has(t)||(fe.add(t),Ge(e))}function lr(t){for(let e of fe)t(e)&&fe.delete(e)}var cr=()=>{};function kd(t){cr=t}function dr(t){try{cr(t)}catch(e){M("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var si={premium:3,enhanced:2,standard:1},oi=new Set(["Grandma","Grandpa"]);function ir(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!oi.has(t.name)?1:0;return si[t.quality]*10+e}var B=t=>t.toLowerCase().split(/[-_]/)[0],ar=t=>t.id.startsWith("com.apple.voice.");function Je(t,e,n,r=new Set){let s=J(t.filter(a=>!a.siri&&B(a.locale)===B(e)),e);if(s.some(ar)&&(s=s.filter(ar)),n==="female"||n==="male"){let a=s.filter(l=>l.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 J(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=B(e),s=t.filter(o=>B(o.locale)===r);return(s.length?s:t).slice().sort((o,i)=>ir(i)-ir(o)||+(i.locale.toLowerCase()===n)-+(o.locale.toLowerCase()===n)||o.name.localeCompare(i.name)||o.locale.localeCompare(i.locale))}function Y(t,e,n="en"){let r=t.trim();if(!r)return null;let s=e.find(d=>d.id===r);if(s)return s;if(r.toLowerCase().startsWith(R)){let d=r.slice(R.length).trim().toLowerCase(),c=J(e.filter(p=>p.siri&&p.name.toLowerCase()===d),n)[0];if(c||!d)return c??null;let u=Y(d,e.filter(p=>B(p.locale)===B(n)),n);return u&&M(`siri:${d}`,`[voice] Siri voice "${d}" is not installed; speaking with ${u.name} (${u.locale}) instead.`),u}e=e.filter(d=>!d.siri);let o=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(o?o[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=J(e.filter(d=>d.name.toLowerCase()===i),n);return(o?a.find(d=>d.quality===o[2].toLowerCase()):void 0)??a[0]??null}function ur(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",l=a?i.gender:o,d=e.filter(u=>!s.has(u.name.toLowerCase())),c=d.find(u=>u.gender===l)??(a?e.find(u=>u.gender===l):void 0)??d[0]??e[r.size%e.length];r.set(i.id,c),s.add(c.name.toLowerCase()),a||(o=o==="female"?"male":"female")}return r}Ot();var Ye="system",ii=t=>t.trim().toLowerCase()===Ye,ai="21m00Tcm4TlvDq8ikWAM";function Ze(t,e,n={},r=Ke()){let s=e[t],o=s?.name||t,i=s?.voice,a=et(e,n,r).get(t)??null,l=ui(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?he(a):null,systemByLanguage:l,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||gi(o,s?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var he=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function li(t,e,n,r){if(!e||!n.length)return null;let s=Y(e,n,r);return s||(M(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),dr(e)),s}function mr(t,e){let n=t.trim();if(n.toLowerCase().startsWith(R))return{locale:e,gender:ze(n.slice(R.length).trim())};let r=pe(n);return r?{locale:r.locale,gender:ze(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var hr=t=>t.toLowerCase().split(/[-_]/)[0],pr=(t,e)=>typeof t=="string"?t:t?.[hr(e)];function me(t,e,n,r){if(e!==void 0)return ii(e)?null:li(t,e,n,r)??void 0}var Qe=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function ci(t,e,n,r=new Set){let s=e.locale??"en",o=new Map,i=[],a=me("voice.system",pr(e.system,s),n,s),l=()=>new Set([...r,...[...o.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let u=pr(c.system,s),p=me(c.id,u,n,s),g=p!==void 0?p:u!==void 0&&n.length?di(c,u,s,a,n,l()):a!==void 0&&Qe(a,c.gender)?a:void 0;g!==void 0?o.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let d=l();for(let[c,u]of ur(i,J(n.filter(p=>!p.siri),s),d))o.set(c,u);return o}function di(t,e,n,r,s,o){for(let a of t.fallbacks??[]){let l=me(`${t.id}.fallbacks`,a,s,n);if(l!==void 0)return l}if(r!==void 0&&Qe(r,t.gender))return r;let i=mr(e,n);return Je(s,i.locale,t.gender??i.gender,o)??void 0}function ui(t,e,n,r,s){if(typeof e=="string")return{};let o={},i=(a,l,d)=>{if(!(!l||typeof l=="string"))for(let[c,u]of Object.entries(l)){let p=me(`${a}.${c}`,u,s,c);p===void 0&&s.length&&(p=Je(s,c,n??mr(u,c).gender)??void 0),p!==void 0&&d(p)&&(o[hr(c)]=p)}};return i("voice.system",r.system,a=>Qe(a,n)),i(t,e,()=>!0),o}function Rd(t,e){let n=e?se(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?he(r):null}}function et(t,e={},n=Ke()){let r=Object.entries(t).map(([s,o])=>({id:s,system:o.voice?.system,gender:o.voice?.gender,fallbacks:o.voice?.fallbacks}));return ci(r,e,n)}function tt(t,e){let n={provider:t.provider,elevenlabs:pi(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 pi(t,e){return t||e||process.env.AGENTX_VOICE_ID||ai}function gi(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 fi=8*60*60*1e3,mi=500,gr=class{constructor(e=fi){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let s=this.lastSpoke.get(fr(e,n));return s===void 0||r-s>this.gapMs}spoke(e,n,r=Date.now()){let s=fr(e,n);this.lastSpoke.delete(s),this.lastSpoke.set(s,r),this.lastSpoke.size>mi&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},fr=(t,e)=>`${t}\0${e}`;function br(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 _d(t,e,n,r={}){let s=e[t],o=Ze(t,e,r),i=(s?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:o.name,voice:tt(o),persona:i||`You are ${o.name}.`,introLine:br(o,n)}}var hi="[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 Ed(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`${hi}
170
- ${br(s,e.voice.introduce===!0&&!!r)}`}var $i="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",kr=(t=Si())=>vi(t,".agentx","voice","health.json");function Ri(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===Ye)return!0;if(r.toLowerCase().startsWith(R)){let s=r.slice(R.length).trim().toLowerCase();return e.some(o=>o.siri&&o.name.toLowerCase()===s)}return Y(r,e,n)!==null}function _i(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 Ei(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:s,name:o,locale:i,perLanguage:a}of _i(t)){if(Ri(o,e,i))continue;r??=et(t.agents,t.voice,e);let l=n.get(o)??{voice:o,agents:[],speaksWith:{}};l.agents.includes(s)||l.agents.push(s);let d=r.get(s);s!=="voice.system"&&!a&&(l.speaksWith[s]=d?he(d):"the OS default voice"),n.set(o,l)}return[...n.values()]}function nt(t){let e=pe(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(R)){let n=t.slice(R.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function Ai(t){let e=t.map(n=>{let r=n.agents.map(s=>n.speaksWith[s]?`${s} (now ${n.speaksWith[s]})`:s).join(", ");return`\u2022 ${nt(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
170
+ `),fe=new Set;function _d(t){Ge=t}function M(t,e){fe.has(t)||(fe.add(t),Ge(e))}function cr(t){for(let e of fe)t(e)&&fe.delete(e)}var dr=()=>{};function Ed(t){dr=t}function ur(t){try{dr(t)}catch(e){M("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var ai={premium:3,enhanced:2,standard:1},li=new Set(["Grandma","Grandpa"]);function ar(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!li.has(t.name)?1:0;return ai[t.quality]*10+e}var B=t=>t.toLowerCase().split(/[-_]/)[0],lr=t=>t.id.startsWith("com.apple.voice.");function Je(t,e,n,r=new Set){let s=J(t.filter(a=>!a.siri&&B(a.locale)===B(e)),e);if(s.some(lr)&&(s=s.filter(lr)),n==="female"||n==="male"){let a=s.filter(l=>l.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 J(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=B(e),s=t.filter(o=>B(o.locale)===r);return(s.length?s:t).slice().sort((o,i)=>ar(i)-ar(o)||+(i.locale.toLowerCase()===n)-+(o.locale.toLowerCase()===n)||o.name.localeCompare(i.name)||o.locale.localeCompare(i.locale))}function Y(t,e,n="en"){let r=t.trim();if(!r)return null;let s=e.find(d=>d.id===r);if(s)return s;if(r.toLowerCase().startsWith(R)){let d=r.slice(R.length).trim().toLowerCase(),c=J(e.filter(p=>p.siri&&p.name.toLowerCase()===d),n)[0];if(c||!d)return c??null;let u=Y(d,e.filter(p=>B(p.locale)===B(n)),n);return u&&M(`siri:${d}`,`[voice] Siri voice "${d}" is not installed; speaking with ${u.name} (${u.locale}) instead.`),u}e=e.filter(d=>!d.siri);let o=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(o?o[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=J(e.filter(d=>d.name.toLowerCase()===i),n);return(o?a.find(d=>d.quality===o[2].toLowerCase()):void 0)??a[0]??null}function pr(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",l=a?i.gender:o,d=e.filter(u=>!s.has(u.name.toLowerCase())),c=d.find(u=>u.gender===l)??(a?e.find(u=>u.gender===l):void 0)??d[0]??e[r.size%e.length];r.set(i.id,c),s.add(c.name.toLowerCase()),a||(o=o==="female"?"male":"female")}return r}Ot();var Ye="system",ci=t=>t.trim().toLowerCase()===Ye,di="21m00Tcm4TlvDq8ikWAM";function Ze(t,e,n={},r=Ke()){let s=e[t],o=s?.name||t,i=s?.voice,a=et(e,n,r).get(t)??null,l=fi(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?he(a):null,systemByLanguage:l,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||hi(o,s?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var he=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function ui(t,e,n,r){if(!e||!n.length)return null;let s=Y(e,n,r);return s||(M(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),ur(e)),s}function hr(t,e){let n=t.trim();if(n.toLowerCase().startsWith(R))return{locale:e,gender:ze(n.slice(R.length).trim())};let r=pe(n);return r?{locale:r.locale,gender:ze(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var br=t=>t.toLowerCase().split(/[-_]/)[0],gr=(t,e)=>typeof t=="string"?t:t?.[br(e)];function me(t,e,n,r){if(e!==void 0)return ci(e)?null:ui(t,e,n,r)??void 0}var Qe=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function pi(t,e,n,r=new Set){let s=e.locale??"en",o=new Map,i=[],a=me("voice.system",gr(e.system,s),n,s),l=()=>new Set([...r,...[...o.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let u=gr(c.system,s),p=me(c.id,u,n,s),g=p!==void 0?p:u!==void 0&&n.length?gi(c,u,s,a,n,l()):a!==void 0&&Qe(a,c.gender)?a:void 0;g!==void 0?o.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let d=l();for(let[c,u]of pr(i,J(n.filter(p=>!p.siri),s),d))o.set(c,u);return o}function gi(t,e,n,r,s,o){for(let a of t.fallbacks??[]){let l=me(`${t.id}.fallbacks`,a,s,n);if(l!==void 0)return l}if(r!==void 0&&Qe(r,t.gender))return r;let i=hr(e,n);return Je(s,i.locale,t.gender??i.gender,o)??void 0}function fi(t,e,n,r,s){if(typeof e=="string")return{};let o={},i=(a,l,d)=>{if(!(!l||typeof l=="string"))for(let[c,u]of Object.entries(l)){let p=me(`${a}.${c}`,u,s,c);p===void 0&&s.length&&(p=Je(s,c,n??hr(u,c).gender)??void 0),p!==void 0&&d(p)&&(o[br(c)]=p)}};return i("voice.system",r.system,a=>Qe(a,n)),i(t,e,()=>!0),o}function Cd(t,e){let n=e?se(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?he(r):null}}function et(t,e={},n=Ke()){let r=Object.entries(t).map(([s,o])=>({id:s,system:o.voice?.system,gender:o.voice?.gender,fallbacks:o.voice?.fallbacks}));return pi(r,e,n)}function tt(t,e){let n={provider:t.provider,elevenlabs:mi(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 mi(t,e){return t||e||process.env.AGENTX_VOICE_ID||di}function hi(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 bi=8*60*60*1e3,yi=500,fr=class{constructor(e=bi){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let s=this.lastSpoke.get(mr(e,n));return s===void 0||r-s>this.gapMs}spoke(e,n,r=Date.now()){let s=mr(e,n);this.lastSpoke.delete(s),this.lastSpoke.set(s,r),this.lastSpoke.size>yi&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},mr=(t,e)=>`${t}\0${e}`;function yr(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 Nd(t,e,n,r={}){let s=e[t],o=Ze(t,e,r),i=(s?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:o.name,voice:tt(o),persona:i||`You are ${o.name}.`,introLine:yr(o,n)}}var wi="[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 Ld(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`${wi}
171
+ ${yr(s,e.voice.introduce===!0&&!!r)}`}var Ei="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Sr=(t=$i())=>_i(t,".agentx","voice","health.json");function Ai(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===Ye)return!0;if(r.toLowerCase().startsWith(R)){let s=r.slice(R.length).trim().toLowerCase();return e.some(o=>o.siri&&o.name.toLowerCase()===s)}return Y(r,e,n)!==null}function Ii(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 Ti(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:s,name:o,locale:i,perLanguage:a}of Ii(t)){if(Ai(o,e,i))continue;r??=et(t.agents,t.voice,e);let l=n.get(o)??{voice:o,agents:[],speaksWith:{}};l.agents.includes(s)||l.agents.push(s);let d=r.get(s);s!=="voice.system"&&!a&&(l.speaksWith[s]=d?he(d):"the OS default voice"),n.set(o,l)}return[...n.values()]}function nt(t){let e=pe(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(R)){let n=t.slice(R.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function Di(t){let e=t.map(n=>{let r=n.agents.map(s=>n.speaksWith[s]?`${s} (now ${n.speaksWith[s]})`:s).join(", ");return`\u2022 ${nt(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
171
172
  `)}
172
- Reinstall in ${$i}. Agents switch back on their own once it is installed.`}}function Ii(t=kr()){if(!wr(t))return null;try{let e=JSON.parse(yi(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function Ti(t,e){bi(xi(t),{recursive:!0}),ki(`${t}.tmp`,JSON.stringify(e,null,2)+`
173
- `),wi(`${t}.tmp`,t)}var yr=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??kr(),o=new Map((Ii(s)?.missing??[]).map(u=>[u.voice,u])),i=Ei(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}:{}})),l=[...o.keys()].filter(u=>!i.some(p=>p.voice===u));for(let u of l)this.deps.log(`[voice] ${nt(u)} is installed again; its agents speak with it again`);l.length&&lr(u=>l.some(p=>u===p||u.endsWith(`:${p}`)));let d=a.filter(u=>!u.notifiedAt);if(d.length){let{title:u,message:p}=Ai(d);try{await this.deps.notify(u,p);for(let g of d)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${d.map(g=>nt(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 c={checkedAt:r.toISOString(),missing:a};return(!wr(s)||JSON.stringify(a)!==JSON.stringify([...o.values()]))&&Ti(s,c),c}finally{this.running=!1}}};import{readFileSync as st,writeFileSync as _r,existsSync as ot,readdirSync as Wi,statSync as qi}from"fs";import{resolve as it,join as ji}from"path";import{existsSync as Sr,mkdirSync as Di,readFileSync as Ci,writeFileSync as xr}from"fs";import{dirname as Ni,resolve as vr}from"path";import{z as h}from"zod";var Li=h.object({type:h.enum(["gitlab","github"]),host:h.string().optional(),project:h.string(),iid:h.number().int().positive(),url:h.string()}),Oi=h.object({id:h.string(),title:h.string(),description:h.string().optional(),assignee:h.string().optional(),labels:h.array(h.string()).default([]),milestone:h.string().optional(),status:h.enum(["todo","doing","blocked","done"]).default("todo"),priority:h.number().int().optional(),estimatedSeconds:h.number().int().optional(),source:Li.optional(),importedAt:h.string().optional(),createdAt:h.string(),updatedAt:h.string(),blocker:h.string().optional(),doneNote:h.string().optional()}),Pi=h.object({version:h.literal(1),items:h.array(Oi).default([])}),be=class{constructor(e){this.path=e}jsonPath(){return vr(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return vr(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return Sr(this.jsonPath())}load(){let e=this.jsonPath();if(!Sr(e))return{version:1,items:[]};let n=Ci(e,"utf-8");try{return Pi.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Di(Ni(n),{recursive:!0}),xr(n,JSON.stringify(e,null,2)+`
174
- `),xr(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 l=o==="done"?"x":" ",d=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",u=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${l}] ${d}${a.title}${c}${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(`
175
- `)}};function Fd(t){return`${t.type}:${t.project}:${t.iid}`}function $r(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 rt(t,e,n,r=()=>{}){return t.source?Mi(t.source,e,n,r):{ok:!0,attempts:[]}}async function Mi(t,e,n,r=()=>{}){return t.type==="gitlab"?Ui(t,e,n,r):t.type==="github"?Fi(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Ui(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=[],l=async(g,f={})=>fetch(`${i}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":o,"Content-Type":"application/json",...f.headers||{}}}),d=encodeURIComponent(t.project),c;e.assigneeUsernames!==void 0&&(c=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let m=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":o}});if(!m.ok)return null;let b=await m.json();return Array.isArray(b)&&b[0]?.id?b[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 l(`/projects/${d}/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(",")),c!==void 0&&(p.assignee_ids=c),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 l(`/projects/${d}/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 l(`/projects/${d}/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 Fi(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||{}}}),l=t.project,d;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")d=null;else try{let p=await a(`/repos/${l}/milestones?state=all&per_page=100`);if(p.ok){let g=await p.json(),f=Array.isArray(g)?g.find(m=>m.title===e.milestoneTitle):null;f?.number&&(d=f.number)}}catch(p){r(`[backlog-sync] github milestone lookup failed: ${p.message}`)}let c;if(e.labels!==void 0)c=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let p=await a(`/repos/${l}/issues/${t.iid}`);if(p.ok){let g=await p.json(),f=Array.isArray(g.labels)?g.labels.map(b=>typeof b=="string"?b:b.name):[],m=new Set([...f,...e.addLabels??[]]);for(let b of e.removeLabels??[])m.delete(b);c=[...m]}}catch(p){r(`[backlog-sync] github label fetch failed: ${p.message}`)}if(c===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),c!==void 0&&(u.labels=c),e.assigneeUsernames!==void 0&&(u.assignees=e.assigneeUsernames),d!==void 0&&(u.milestone=d),e.state&&(u.state=e.state),Object.keys(u).length)try{let p=await a(`/repos/${l}/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/${l}/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 at=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,ye=/@([a-z0-9_-]+)/i,Rr=/\[time:\s*([0-9hm\s]+)\]/i;function Vi(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 lt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new be(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 ot(e)?st(e,"utf-8").split(`
176
- `):[]}writeMd(e){let n=it(process.cwd(),this.path);_r(n,e.join(`
177
- `))}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(at);if(!o||o[2].toLowerCase()==="x")continue;let a=o[3],l=a.match(ye);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let d=a.match(Rr),c=a.replace(ye,"").replace(Rr,"").trim();r.push({id:`backlog:${s}`,title:c||`Task at line ${s+1}`,assignee:l?l[1]:void 0,estimatedSeconds:d?Vi(d[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=$r([s.assignee||e],s.source,this.daemon);rt(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 l=this.store.update(e,a);if(l.source&&this.daemon){let d={};n.status==="done"?(d.addLabels=["Done"],d.removeLabels=["Doing"]):n.status==="blocked"&&(d.addLabels=["Blocked"]),n.note&&(d.note=n.note),Object.keys(d).length&&rt(l,d,this.daemon,this.log).catch(c=>this.log(`[backlog-sync] report failed for ${e}: ${c?.message??c}`))}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(at))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"}}},ct=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(ot(e))for(let r of Wi(e)){let s=ji(e,r);qi(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=st(s,"utf-8").split(`
173
+ Reinstall in ${Ei}. Agents switch back on their own once it is installed.`}}function Ci(t=Sr()){if(!kr(t))return null;try{let e=JSON.parse(Si(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function Ni(t,e){ki(Ri(t),{recursive:!0}),vi(`${t}.tmp`,JSON.stringify(e,null,2)+`
174
+ `),xi(`${t}.tmp`,t)}var wr=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??Sr(),o=new Map((Ci(s)?.missing??[]).map(u=>[u.voice,u])),i=Ti(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}:{}})),l=[...o.keys()].filter(u=>!i.some(p=>p.voice===u));for(let u of l)this.deps.log(`[voice] ${nt(u)} is installed again; its agents speak with it again`);l.length&&cr(u=>l.some(p=>u===p||u.endsWith(`:${p}`)));let d=a.filter(u=>!u.notifiedAt);if(d.length){let{title:u,message:p}=Di(d);try{await this.deps.notify(u,p);for(let g of d)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${d.map(g=>nt(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 c={checkedAt:r.toISOString(),missing:a};return(!kr(s)||JSON.stringify(a)!==JSON.stringify([...o.values()]))&&Ni(s,c),c}finally{this.running=!1}}};import{readFileSync as st,writeFileSync as Er,existsSync as ot,readdirSync as Vi,statSync as Bi}from"fs";import{resolve as it,join as Hi}from"path";import{existsSync as xr,mkdirSync as Li,readFileSync as Oi,writeFileSync as vr}from"fs";import{dirname as Pi,resolve as $r}from"path";import{z as h}from"zod";var Mi=h.object({type:h.enum(["gitlab","github"]),host:h.string().optional(),project:h.string(),iid:h.number().int().positive(),url:h.string()}),Ui=h.object({id:h.string(),title:h.string(),description:h.string().optional(),assignee:h.string().optional(),labels:h.array(h.string()).default([]),milestone:h.string().optional(),status:h.enum(["todo","doing","blocked","done"]).default("todo"),priority:h.number().int().optional(),estimatedSeconds:h.number().int().optional(),source:Mi.optional(),importedAt:h.string().optional(),createdAt:h.string(),updatedAt:h.string(),blocker:h.string().optional(),doneNote:h.string().optional()}),Fi=h.object({version:h.literal(1),items:h.array(Ui).default([])}),be=class{constructor(e){this.path=e}jsonPath(){return $r(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return $r(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return xr(this.jsonPath())}load(){let e=this.jsonPath();if(!xr(e))return{version:1,items:[]};let n=Oi(e,"utf-8");try{return Fi.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Li(Pi(n),{recursive:!0}),vr(n,JSON.stringify(e,null,2)+`
175
+ `),vr(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 l=o==="done"?"x":" ",d=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",u=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${l}] ${d}${a.title}${c}${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(`
176
+ `)}};function zd(t){return`${t.type}:${t.project}:${t.iid}`}function Rr(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 rt(t,e,n,r=()=>{}){return t.source?Wi(t.source,e,n,r):{ok:!0,attempts:[]}}async function Wi(t,e,n,r=()=>{}){return t.type==="gitlab"?qi(t,e,n,r):t.type==="github"?ji(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function qi(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=[],l=async(g,f={})=>fetch(`${i}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":o,"Content-Type":"application/json",...f.headers||{}}}),d=encodeURIComponent(t.project),c;e.assigneeUsernames!==void 0&&(c=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let m=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":o}});if(!m.ok)return null;let b=await m.json();return Array.isArray(b)&&b[0]?.id?b[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 l(`/projects/${d}/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(",")),c!==void 0&&(p.assignee_ids=c),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 l(`/projects/${d}/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 l(`/projects/${d}/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 ji(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||{}}}),l=t.project,d;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")d=null;else try{let p=await a(`/repos/${l}/milestones?state=all&per_page=100`);if(p.ok){let g=await p.json(),f=Array.isArray(g)?g.find(m=>m.title===e.milestoneTitle):null;f?.number&&(d=f.number)}}catch(p){r(`[backlog-sync] github milestone lookup failed: ${p.message}`)}let c;if(e.labels!==void 0)c=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let p=await a(`/repos/${l}/issues/${t.iid}`);if(p.ok){let g=await p.json(),f=Array.isArray(g.labels)?g.labels.map(b=>typeof b=="string"?b:b.name):[],m=new Set([...f,...e.addLabels??[]]);for(let b of e.removeLabels??[])m.delete(b);c=[...m]}}catch(p){r(`[backlog-sync] github label fetch failed: ${p.message}`)}if(c===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),c!==void 0&&(u.labels=c),e.assigneeUsernames!==void 0&&(u.assignees=e.assigneeUsernames),d!==void 0&&(u.milestone=d),e.state&&(u.state=e.state),Object.keys(u).length)try{let p=await a(`/repos/${l}/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/${l}/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 at=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,ye=/@([a-z0-9_-]+)/i,_r=/\[time:\s*([0-9hm\s]+)\]/i;function zi(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 lt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new be(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 ot(e)?st(e,"utf-8").split(`
177
+ `):[]}writeMd(e){let n=it(process.cwd(),this.path);Er(n,e.join(`
178
+ `))}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(at);if(!o||o[2].toLowerCase()==="x")continue;let a=o[3],l=a.match(ye);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let d=a.match(_r),c=a.replace(ye,"").replace(_r,"").trim();r.push({id:`backlog:${s}`,title:c||`Task at line ${s+1}`,assignee:l?l[1]:void 0,estimatedSeconds:d?zi(d[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=Rr([s.assignee||e],s.source,this.daemon);rt(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 l=this.store.update(e,a);if(l.source&&this.daemon){let d={};n.status==="done"?(d.addLabels=["Done"],d.removeLabels=["Doing"]):n.status==="blocked"&&(d.addLabels=["Blocked"]),n.note&&(d.note=n.note),Object.keys(d).length&&rt(l,d,this.daemon,this.log).catch(c=>this.log(`[backlog-sync] report failed for ${e}: ${c?.message??c}`))}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(at))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"}}},ct=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(ot(e))for(let r of Vi(e)){let s=Hi(e,r);Bi(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=st(s,"utf-8").split(`
178
179
  `);for(let i=0;i<o.length;i++){let a=o[i].match(at);if(!a||a[2].toLowerCase()==="x")continue;let l=a[3].match(ye);!l||l[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${s}:${i}`,title:a[3].replace(ye,"").trim(),assignee:l[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(!ot(o))return;let i=st(o,"utf-8").split(`
179
- `);n.status==="done"&&i[s]&&(i[s]=i[s].replace(/- \[ \]/,"- [x]"),_r(o,i.join(`
180
- `)))}},dt=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(d=>({name:d.name,color:d.color,text_color:d.text_color})),s=o.map(d=>d.name)):s=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(d=>({username:d.username,name:d.name,avatarUrl:d.avatar_url})),l=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:l?this.usernameToAgent(l)||l: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`,l=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,d=await this.api(l);for(let c of d){let u=this.mapIssue(c,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)),l=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(l)}`,{method:"POST"})}catch(d){this.log(`[business] add_spent_time failed: ${d.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 d of i)try{let c=d==="__ALL__"?`/issues?${s.toString()}`:`/projects/${encodeURIComponent(d)}/issues?${s.toString()}`,u=await this.api(c);for(let p of u)a.push(this.mapIssue(p,d))}catch(c){this.log(`[business] GitLab listAll failed on ${d}: ${c.message}`)}let l=a;if(e.notLabels?.length){let d=new Set(e.notLabels);l=l.filter(c=>!(c.labels||[]).some(u=>d.has(u)))}if(e.withoutScopedPrefix){let d=e.withoutScopedPrefix+"::";l=l.filter(c=>!(c.labels||[]).some(u=>u.startsWith(d)))}return l}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 c=>{try{let u=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let d=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(i=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${d.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 l=await this.api(`/projects/${encodeURIComponent(r)}/issues/${s}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(l,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 d=>{try{let c=await this.api(`/users?username=${encodeURIComponent(d)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${d}: ${c.message}`),null}}))).filter(d=>typeof d=="number"));let o;if(e.milestoneTitle)try{let l=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(o=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${l.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",l=new URLSearchParams;n.length&&l.set("add_labels",n.join(",")),r.length&&l.set("remove_labels",r.join(",")),l.toString()&&await this.api(`/projects/${encodeURIComponent(s)}/${a}/${o}?${l.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 zd(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new lt(r.path,e,n);case"wiki":return new ct(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 dt(s.host,s.token,i,o,n)}}}var ut="unmapped";function pt(t,e=[]){if(!t)return ut;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 Bi(t){let e=new Map,n=t.projects??[],r=t.orgChart??{};for(let o of n)o.pm&&(e.has(o.pm)||e.set(o.pm,pt(o.id,n)));let s=(o,i=new Set)=>{if(e.has(o))return e.get(o);if(i.has(o))return;i.add(o);let a=r[o]?.reportsTo;if(!a)return;let l=s(a,i);return l&&e.set(o,l),l};for(let o of Object.keys(r))s(o);return e}function Hi(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 Kd(t,e){let n=Hi(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=Bi(e).get(t.agentId);if(r)return r}return ut}function Gd(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 zi=t=>t===ut?"internal":"client";function Xi(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??zi(t),respondWithinMinutes:Ki(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function Jd(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=>Xi(n,t))}function Ki(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 Gi}from"crypto";var Qd={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},Ji=40,Yi=20,eu=90,Zi=2e3,Er=36e5;function Qi(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
181
- ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<Ji?null:`text:${Gi("sha256").update(r).digest("hex").slice(0,24)}`}function tu(t){let e=t.indexOf(`
180
+ `);n.status==="done"&&i[s]&&(i[s]=i[s].replace(/- \[ \]/,"- [x]"),Er(o,i.join(`
181
+ `)))}},dt=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(d=>({name:d.name,color:d.color,text_color:d.text_color})),s=o.map(d=>d.name)):s=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(d=>({username:d.username,name:d.name,avatarUrl:d.avatar_url})),l=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:l?this.usernameToAgent(l)||l: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`,l=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,d=await this.api(l);for(let c of d){let u=this.mapIssue(c,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)),l=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(l)}`,{method:"POST"})}catch(d){this.log(`[business] add_spent_time failed: ${d.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 d of i)try{let c=d==="__ALL__"?`/issues?${s.toString()}`:`/projects/${encodeURIComponent(d)}/issues?${s.toString()}`,u=await this.api(c);for(let p of u)a.push(this.mapIssue(p,d))}catch(c){this.log(`[business] GitLab listAll failed on ${d}: ${c.message}`)}let l=a;if(e.notLabels?.length){let d=new Set(e.notLabels);l=l.filter(c=>!(c.labels||[]).some(u=>d.has(u)))}if(e.withoutScopedPrefix){let d=e.withoutScopedPrefix+"::";l=l.filter(c=>!(c.labels||[]).some(u=>u.startsWith(d)))}return l}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 c=>{try{let u=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let d=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(i=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${d.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 l=await this.api(`/projects/${encodeURIComponent(r)}/issues/${s}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(l,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 d=>{try{let c=await this.api(`/users?username=${encodeURIComponent(d)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${d}: ${c.message}`),null}}))).filter(d=>typeof d=="number"));let o;if(e.milestoneTitle)try{let l=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(o=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${l.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",l=new URLSearchParams;n.length&&l.set("add_labels",n.join(",")),r.length&&l.set("remove_labels",r.join(",")),l.toString()&&await this.api(`/projects/${encodeURIComponent(s)}/${a}/${o}?${l.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 Qd(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new lt(r.path,e,n);case"wiki":return new ct(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 dt(s.host,s.token,i,o,n)}}}var ut="unmapped";function pt(t,e=[]){if(!t)return ut;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 Xi(t){let e=new Map,n=t.projects??[],r=t.orgChart??{};for(let o of n)o.pm&&(e.has(o.pm)||e.set(o.pm,pt(o.id,n)));let s=(o,i=new Set)=>{if(e.has(o))return e.get(o);if(i.has(o))return;i.add(o);let a=r[o]?.reportsTo;if(!a)return;let l=s(a,i);return l&&e.set(o,l),l};for(let o of Object.keys(r))s(o);return e}function Ki(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 tu(t,e){let n=Ki(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=Xi(e).get(t.agentId);if(r)return r}return ut}function nu(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 Gi=t=>t===ut?"internal":"client";function Ji(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Gi(t),respondWithinMinutes:Yi(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function ru(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=>Ji(n,t))}function Yi(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 Zi}from"crypto";var iu={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},Qi=40,ea=20,au=90,ta=2e3,Ar=36e5;function na(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
182
+ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<Qi?null:`text:${Zi("sha256").update(r).digest("hex").slice(0,24)}`}function lu(t){let e=t.indexOf(`
182
183
  `);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function gt(t){t.exec(`
183
184
  CREATE TABLE IF NOT EXISTS owner_told (
184
185
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -197,34 +198,34 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<Ji?null:`text:${G
197
198
  CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
198
199
  CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
199
200
  CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
200
- `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of ea)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 ea=[["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 we(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 Ar=class{constructor(e){this.db=e;gt(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)
201
- 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,Zi),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?we(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?we(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(we)}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(we)}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,
201
+ `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of ra)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 ra=[["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 we(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 Ir=class{constructor(e){this.db=e;gt(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)
202
+ 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,ta),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?we(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?we(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(we)}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(we)}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,
202
203
  SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
203
204
  SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
204
- 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}},Ir=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=Qi(n,e.title,e.text),i=n.kind??"notice",a=(o?.startsWith("text:")?Math.min(r.repeatWindowHours,Yi):r.repeatWindowHours)*Er,l=r.digestNags&&r.digestAvailable!==!1,d="send";!n.urgent&&o&&this.ledger.lastTold(o,s-a,l)?d="repeat":!n.urgent&&i==="nag"&&l&&(d="digest");let c=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:d==="send"?"sent":d,urgent:n.urgent===!0});return{verdict:d,key:o,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:ta(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*Er)}};function nu(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 ta(t,e=5,n=3){let r=new Map;for(let a of t){let[l,...d]=a.title.split(": "),c=d.join(": ").trim(),u=r.get(l.trim())??{count:0,names:[]};u.count++,c&&!u.names.includes(c)&&u.names.push(c),r.set(l.trim(),u)}let s=[...r.entries()].sort((a,l)=>l[1].count-a[1].count),o=s.slice(0,e).map(([a,{count:l,names:d}])=>{let c=d.length?` (${d.slice(0,n).join(", ")}${d.length>n?", \u2026":""})`:"";return`${a}${l>1?` \xD7${l}`:""}${c}`}),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 na=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,ra=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Tr(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(ra)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],s=sa(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 su(t){if(!t||!t.includes("agentx:ui"))return t;let e=na.exec(t);return e?t.slice(0,e.index).trimEnd():t}function sa(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 iu(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 oa=5*6e4;function N(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var Dr=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(N)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${N(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 l=Date.now(),d=a.filter(c=>c.expiresAt>l);for(let{signal:c}of d)this.deliverTo(s,c);this.pending.delete(i),d.length&&this.log(`flushed ${d.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
205
+ 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}},Tr=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=na(n,e.title,e.text),i=n.kind??"notice",a=(o?.startsWith("text:")?Math.min(r.repeatWindowHours,ea):r.repeatWindowHours)*Ar,l=r.digestNags&&r.digestAvailable!==!1,d="send";!n.urgent&&o&&this.ledger.lastTold(o,s-a,l)?d="repeat":!n.urgent&&i==="nag"&&l&&(d="digest");let c=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:d==="send"?"sent":d,urgent:n.urgent===!0});return{verdict:d,key:o,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:sa(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*Ar)}};function cu(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 sa(t,e=5,n=3){let r=new Map;for(let a of t){let[l,...d]=a.title.split(": "),c=d.join(": ").trim(),u=r.get(l.trim())??{count:0,names:[]};u.count++,c&&!u.names.includes(c)&&u.names.push(c),r.set(l.trim(),u)}let s=[...r.entries()].sort((a,l)=>l[1].count-a[1].count),o=s.slice(0,e).map(([a,{count:l,names:d}])=>{let c=d.length?` (${d.slice(0,n).join(", ")}${d.length>n?", \u2026":""})`:"";return`${a}${l>1?` \xD7${l}`:""}${c}`}),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 oa=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,ia=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Dr(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(ia)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],s=aa(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 uu(t){if(!t||!t.includes("agentx:ui"))return t;let e=oa.exec(t);return e?t.slice(0,e.index).trimEnd():t}function aa(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 gu(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 la=5*6e4;function N(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var Cr=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(N)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${N(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 l=Date.now(),d=a.filter(c=>c.expiresAt>l);for(let{signal:c}of d)this.deliverTo(s,c);this.pending.delete(i),d.length&&this.log(`flushed ${d.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
205
206
  data: ${JSON.stringify(n)}
206
207
 
207
- `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=N(e.to);if(n===N(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&&N(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(N(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+oa),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=N(e.to);for(let s of this.subs)s.callId===e.callId&&N(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 ia,readFileSync as Cr,renameSync as aa,rmSync as la,writeFileSync as ca}from"fs";import{homedir as da}from"os";import{dirname as ua,join as pa}from"path";var Nr=pa(da(),".agentx","call.json");function ga(t=Nr,e=Date.now()){try{let n=JSON.parse(Cr(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 Lr(t=Kt,e=ga){let n=t();return n.active?n:e()}function pu(t,e,n=Nr,r=Date.now()){let s=null;try{s=JSON.parse(Cr(n,"utf-8"))}catch{}if(s&&s.source&&s.source!=="daemon")return;if(!t){s&&la(n,{force:!0});return}ia(ua(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;ca(o,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
208
- `),aa(o,n)}var Or="owner",ke=6e4,Wr=60*ke,fa=24*Wr,ma=7*24*Wr,ha=2*ke,mu={enabled:!1,escalateAfterMinutes:10,ladder:[]};function ba(t){t.exec(`
208
+ `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=N(e.to);if(n===N(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&&N(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(N(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+la),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=N(e.to);for(let s of this.subs)s.callId===e.callId&&N(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 ca,readFileSync as Nr,renameSync as da,rmSync as ua,writeFileSync as pa}from"fs";import{homedir as ga}from"os";import{dirname as fa,join as ma}from"path";var Lr=ma(ga(),".agentx","call.json");function ha(t=Lr,e=Date.now()){try{let n=JSON.parse(Nr(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 Or(t=Kt,e=ha){let n=t();return n.active?n:e()}function wu(t,e,n=Lr,r=Date.now()){let s=null;try{s=JSON.parse(Nr(n,"utf-8"))}catch{}if(s&&s.source&&s.source!=="daemon")return;if(!t){s&&ua(n,{force:!0});return}ca(fa(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;pa(o,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
209
+ `),da(o,n)}var Pr="owner",ke=6e4,qr=60*ke,ba=24*qr,ya=7*24*qr,wa=2*ke,xu={enabled:!1,escalateAfterMinutes:10,ladder:[]};function ka(t){t.exec(`
209
210
  CREATE TABLE IF NOT EXISTS owner_presence (
210
211
  person TEXT NOT NULL,
211
212
  surface TEXT NOT NULL,
212
213
  at INTEGER NOT NULL,
213
214
  PRIMARY KEY (person, surface)
214
215
  );
215
- `)}var Pr=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;ba(e)}written=new Map;touch(e,n=Or){let r=this.now(),s=`${n}
216
+ `)}var Mr=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;ka(e)}written=new Map;touch(e,n=Pr){let r=this.now(),s=`${n}
216
217
  ${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 (?, ?, ?)
217
- ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=Or){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function hu(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var Mr=class{constructor(e,n=Date.now){this.db=e;this.now=n;gt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
218
+ ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=Pr){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function vu(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var Ur=class{constructor(e,n=Date.now){this.db=e;this.now=n;gt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
218
219
  WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
219
- ORDER BY at DESC LIMIT 500`).all(this.now()-ma)}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,l=s.all(o.at-ha,o.at).find(d=>d.title===o.title||i!==o.title&&d.title.startsWith(i));l&&r.push(l.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 = ?
220
- WHERE seen_at IS NULL AND (${Ur(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, ?)
221
- WHERE answered_at IS NULL AND (${Ur(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 Ur(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 bu(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=Z(i);a&&n(a)&&!s.includes(i)&&s.push(i)}return s}function Z(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function ya(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function wa(t){return Z(t)==="push"?["phone","desk"]:[t]}function yu(t,e,n){let r=t.filter(o=>n(Z(o)));if(!r.length)return null;let s=null;for(let o of r){let i=Math.max(-1/0,...e.filter(a=>wa(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 ka(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(Z(o)))??null}var Sa=3;async function wu(t){let{db:e,ledger:n,settings:r,now:s}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let o=r.escalateAfterMinutes*ke,i=e.prepare(`SELECT id FROM owner_told
220
+ ORDER BY at DESC LIMIT 500`).all(this.now()-ya)}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,l=s.all(o.at-wa,o.at).find(d=>d.title===o.title||i!==o.title&&d.title.startsWith(i));l&&r.push(l.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 = ?
221
+ WHERE seen_at IS NULL AND (${Fr(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, ?)
222
+ WHERE answered_at IS NULL AND (${Fr(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 Fr(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 $u(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=Z(i);a&&n(a)&&!s.includes(i)&&s.push(i)}return s}function Z(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function Sa(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function xa(t){return Z(t)==="push"?["phone","desk"]:[t]}function Ru(t,e,n){let r=t.filter(o=>n(Z(o)));if(!r.length)return null;let s=null;for(let o of r){let i=Math.max(-1/0,...e.filter(a=>xa(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 va(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(Z(o)))??null}var $a=3;async function _u(t){let{db:e,ledger:n,settings:r,now:s}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let o=r.escalateAfterMinutes*ke,i=e.prepare(`SELECT id FROM owner_told
222
223
  WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
223
224
  AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
224
225
  AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
225
- ORDER BY at LIMIT 20`).all(Math.max(s-Sa*o,s-fa),s-o),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),l=0;for(let{id:d}of i){if(a.run(s,d).changes!==1)continue;let c=n.get(d);if(!c)continue;let u=`${c.channel}:${c.chatId}`,p=ka(t.stops,u,t.up);if(!p){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${u}; no other address to try`);continue}let g=Math.round((s-c.at)/ke),f=c.outcome==="failed"?`it could not be sent on ${c.channel}`:`not seen on ${c.channel} for ${g} min`,m=`${c.text?`${c.text}
226
+ ORDER BY at LIMIT 20`).all(Math.max(s-$a*o,s-ba),s-o),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),l=0;for(let{id:d}of i){if(a.run(s,d).changes!==1)continue;let c=n.get(d);if(!c)continue;let u=`${c.channel}:${c.chatId}`,p=va(t.stops,u,t.up);if(!p){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${u}; no other address to try`);continue}let g=Math.round((s-c.at)/ke),f=c.outcome==="failed"?`it could not be sent on ${c.channel}`:`not seen on ${c.channel} for ${g} min`,m=`${c.text?`${c.text}
226
227
 
227
- `:""}(Sent again here: ${f}.)`,b=n.add({at:s,key:c.key,requestId:c.requestId,kind:c.kind,channel:Z(p),chatId:ya(p),from:c.from,title:c.title,text:m,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(p,c,m),l++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch(x){n.setOutcome(b,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${p} failed: ${x?.message??x}`)}}return l}var Fr=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 xa={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},qr=class{constructor(e=xa,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)}},va="That code didn't work. Check it, or run agentx app pair for a new one.",$a=400;async function xu(t,e){let n=Date.now(),r=e.log??(d=>console.log(d)),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 un(t,1024)).code}catch{}let a=e.codes.redeem(i),l=a?e.verify(a.token):null;return await Ra(n,e.minMs??$a),!a||!l?(e.limiter.fail(s),r(`[app] pair-code failed from ${s}`),{status:401,body:{error:va}}):(e.limiter.succeed(s),r(`[app] pair-code paired ${a.tokenId} (${l}) from ${s}`),{status:200,body:{device:l},token:a.token})}async function Ra(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as ja}from"child_process";import{mkdtempSync as Oa,rmSync as Pa,writeFileSync as Ma}from"fs";import{tmpdir as Ua}from"os";import{join as zr}from"path";import{randomBytes as _a}from"crypto";var D={top:8,side:32,bottom:60},ft={height:56,keep:52},jr=`
228
+ `:""}(Sent again here: ${f}.)`,b=n.add({at:s,key:c.key,requestId:c.requestId,kind:c.kind,channel:Z(p),chatId:Sa(p),from:c.from,title:c.title,text:m,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(p,c,m),l++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch(x){n.setOutcome(b,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${p} failed: ${x?.message??x}`)}}return l}var Wr=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 Ra={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},jr=class{constructor(e=Ra,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)}},_a="That code didn't work. Check it, or run agentx app pair for a new one.",Ea=400;async function Iu(t,e){let n=Date.now(),r=e.log??(d=>console.log(d)),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 un(t,1024)).code}catch{}let a=e.codes.redeem(i),l=a?e.verify(a.token):null;return await Aa(n,e.minMs??Ea),!a||!l?(e.limiter.fail(s),r(`[app] pair-code failed from ${s}`),{status:401,body:{error:_a}}):(e.limiter.succeed(s),r(`[app] pair-code paired ${a.tokenId} (${l}) from ${s}`),{status:200,body:{device:l},token:a.token})}async function Aa(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as Ha}from"child_process";import{mkdtempSync as Ua,rmSync as Fa,writeFileSync as Wa}from"fs";import{tmpdir as qa}from"os";import{join as Xr}from"path";import{randomBytes as Ia}from"crypto";var D={top:8,side:32,bottom:60},ft={height:56,keep:52},Vr=`
228
229
  :root {
229
230
  --ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
230
231
  --ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
@@ -353,16 +354,16 @@ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: v
353
354
  button.primary:disabled { opacity: .55; cursor: not-allowed; }
354
355
  kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
355
356
  button.primary kbd { color: inherit; opacity: .7; }
356
- `;var Vr=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Br=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Ea(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Vr(n):Br(n)}`}function Aa(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Br(n)],Vr(n)].join(" ")}function Ia(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 Ta(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var mt=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>`,Da=mt('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),Ca=mt('<path d="m6 15 6-6 6 6"/>'),Na=mt('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Hr(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,s=_a(12).toString("base64"),o=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",l=sn(t),d=o.map((p,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${w(p)}</span>${g===l.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${w(r)} recommends</span>`:"",u={choices:o,draft:t.draft??"",placeholder:nn,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:l.index};return`<!doctype html>
357
+ `;var Br=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Hr=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Ta(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Br(n):Hr(n)}`}function Da(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Hr(n)],Br(n)].join(" ")}function Ca(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 Na(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var mt=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>`,La=mt('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),Oa=mt('<path d="m6 15 6-6 6 6"/>'),Pa=mt('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function zr(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,s=Ia(12).toString("base64"),o=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",l=sn(t),d=o.map((p,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${w(p)}</span>${g===l.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${w(r)} recommends</span>`:"",u={choices:o,draft:t.draft??"",placeholder:nn,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:l.index};return`<!doctype html>
357
358
  <html lang="en"><head><meta charset="utf-8">
358
359
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${s}'">
359
360
  <title>AgentX</title>
360
- <style>${jr}</style></head>
361
+ <style>${Vr}</style></head>
361
362
  <body><div class="wrap"><main class="card${e.still?" still":""}">
362
- <div class="head" title="Drag to move"><span class="avatar">${w(Ia(r))}</span>
363
- <div class="who"><b>${w(r)}</b><span>${w(Ea(t.created_at,n))}</span></div>
363
+ <div class="head" title="Drag to move"><span class="avatar">${w(Ca(r))}</span>
364
+ <div class="who"><b>${w(r)}</b><span>${w(Ta(t.created_at,n))}</span></div>
364
365
  <span class="kind${i?"":" decision"}">${i?"Reminder":a?"Request":"Decision"}</span>
365
- <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${Ca}</button></div>
366
+ <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${Oa}</button></div>
366
367
  <div class="body"><h1 dir="auto">${w(t.title)}</h1>
367
368
  ${t.context?`<p class="context" dir="auto">${w(t.context)}</p>`:""}
368
369
  <p class="ask" dir="auto">${w(t.ask)}</p>
@@ -371,15 +372,15 @@ ${d?`<div class="options" role="radiogroup">${d}</div>`:""}
371
372
  ${l.why?`<p class="why" dir="auto">${w(l.why)}</p>`:""}
372
373
  ${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>
373
374
  <textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
374
- <div class="notes"><div>${Da}<span>${a?"It stays in Open requests on the Approvals page until you close it.":`If you don't answer by ${w(Aa(t.expires,n))}: ${w(t.if_silent)}.`}</span></div>
375
- <div>${Na}<span>Nothing goes out until you click.</span></div></div>
375
+ <div class="notes"><div>${La}<span>${a?"It stays in Open requests on the Approvals page until you close it.":`If you don't answer by ${w(Da(t.expires,n))}: ${w(t.if_silent)}.`}</span></div>
376
+ <div>${Pa}<span>Nothing goes out until you click.</span></div></div>
376
377
  </div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
377
378
  <button class="btn" id="no">${a?"Drop":"No"}</button>
378
- <button class="btn primary" id="yes">${Ta(t)}<kbd>\u2318\u21A9</kbd></button></div>
379
+ <button class="btn primary" id="yes">${Na(t)}<kbd>\u2318\u21A9</kbd></button></div>
379
380
  </main></div>
380
381
  <script type="application/json" id="data">${JSON.stringify(u).replace(/</g,"\\u003c")}</script>
381
- <script nonce="${s}">${La}</script>
382
- </body></html>`}var La=`
382
+ <script nonce="${s}">${Ma}</script>
383
+ </body></html>`}var Ma=`
383
384
  (function () {
384
385
  var d = JSON.parse(document.getElementById("data").textContent);
385
386
  var root = document.documentElement;
@@ -468,7 +469,7 @@ ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><sp
468
469
  });
469
470
  } catch (e) {}
470
471
  })();
471
- `;var Fa=440,Wa=`
472
+ `;var ja=440,Va=`
472
473
  ObjC.import("Cocoa"); ObjC.import("WebKit")
473
474
  function run(argv) {
474
475
  var path = argv[0], side = ${D.side}, gripTop = ${D.top}, gripEnd = ${D.top+ft.height}, keep = ${ft.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
@@ -543,22 +544,22 @@ function run(argv) {
543
544
  }
544
545
  function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
545
546
  function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
546
- `;function qa(t,e){let n=t.trim().split(`
547
- `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Kr.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,`
548
- `).trim():"",!i||i.length>tn.text)?{action:"dismiss"}:{action:"yes",...o?{choice:o}:{},...i?{text:i}:{}}}async function Xr(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=Oa(zr(Ua(),"agentx-card-"));try{let o=zr(s,"card.html");Ma(o,Hr(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",Wa,o,String(Fa),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?qa(a.stdout,t):null}finally{Pa(s,{recursive:!0,force:!0})}}var Kr=["not now","timed out","closed"],Va=(t,e,n)=>new Promise(r=>{try{ja(t,e,{timeout:n},(s,o)=>r({ok:!s,stdout:String(o??"")}))}catch{r({ok:!1,stdout:""})}}),Gr=160,ht=15e3;function Jr(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Gr?e.slice(0,Gr):e}async function Ba(t,e,n,r,s){let o=e.sound==="chime"?r?"":"Glass":e.sound,i=o?dn(o):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],ht),!!e.speak)if(s){let a;await Promise.race([s(Jr(t)),new Promise(l=>{a=setTimeout(l,ht)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Jr(t)],ht)}}function Qr(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function Ha(t,e,n){return Qr(["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 Yr(t,e,n,r,s){return Qr(["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(`
549
- `),n[n.length-1],String(r),...s!==void 0?[s]:[]])}function Zr(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
547
+ `;function Ba(t,e){let n=t.trim().split(`
548
+ `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Gr.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,`
549
+ `).trim():"",!i||i.length>tn.text)?{action:"dismiss"}:{action:"yes",...o?{choice:o}:{},...i?{text:i}:{}}}async function Kr(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=Ua(Xr(qa(),"agentx-card-"));try{let o=Xr(s,"card.html");Wa(o,zr(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",Va,o,String(ja),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?Ba(a.stdout,t):null}finally{Fa(s,{recursive:!0,force:!0})}}var Gr=["not now","timed out","closed"],za=(t,e,n)=>new Promise(r=>{try{Ha(t,e,{timeout:n},(s,o)=>r({ok:!s,stdout:String(o??"")}))}catch{r({ok:!1,stdout:""})}}),Jr=160,ht=15e3;function Yr(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Jr?e.slice(0,Jr):e}async function Xa(t,e,n,r,s){let o=e.sound==="chime"?r?"":"Glass":e.sound,i=o?dn(o):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],ht),!!e.speak)if(s){let a;await Promise.race([s(Yr(t)),new Promise(l=>{a=setTimeout(l,ht)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Yr(t)],ht)}}function es(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function Ka(t,e,n){return es(["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 Zr(t,e,n,r,s){return es(["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(`
550
+ `),n[n.length-1],String(r),...s!==void 0?[s]:[]])}function Qr(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
550
551
  `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function bt(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
551
552
 
552
- `)}async function es(t,e,n={}){let r=n.run??Va,s=(e.style??"card")==="card",o=Ba(t,e,r,s,n.speak).catch(()=>{});if(s){let i=await Xr(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,za(t,e,r)}async function za(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 d=await n("/usr/bin/osascript",Ha(o,bt(t),t.choices),s);if(i=d.stdout.replace(/\n$/,""),!d.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let d=i?`${i}
553
+ `)}async function ts(t,e,n={}){let r=n.run??za,s=(e.style??"card")==="card",o=Xa(t,e,r,s,n.speak).catch(()=>{});if(s){let i=await Kr(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,Ga(t,e,r)}async function Ga(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 d=await n("/usr/bin/osascript",Ka(o,bt(t),t.choices),s);if(i=d.stdout.replace(/\n$/,""),!d.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let d=i?`${i}
553
554
 
554
555
  Message (edit it if you like):`:`${bt(t)}
555
556
 
556
- Message (edit it if you like):`,u=await n("/usr/bin/osascript",Yr(o,d,i?["Cancel","Send"]:["Not now","No","Send"],r,rn(t.draft,i)),s),p=u.ok?Zr(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",Yr(o,bt(t),["Not now","No","Yes"],r),s),l=a.ok?Zr(a.stdout):null;return l?.button==="Yes"?{action:"yes"}:l?.button==="No"?{action:"no"}:{action:"dismiss"}}var kt=24*36e5,yt=!1,Xa=10*6e4,ts=-1/0;function ns(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s,passAt:o,wanted:i=[]}=v(t.root),a=o?Date.parse(o):NaN,l=W(t.root,"pending").filter(c=>Date.parse(c.expires)>n),d=l.find(c=>i.includes(`card:${c.id}`));if(d)return d;for(let c of l){let u=`card:${c.id}`;if(r[u]||!e(c)||mn(t.root,c.id,n))continue;let p=s[u];if(p&&Date.parse(p)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>kt&&!(g<=a)))return c}return null}function wt(t){try{return P(t)?.listByState("needs_attention")??[]}catch{return[]}}var rs=new Map;function Ka(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s}=v(t.root);return e({})?wt(t).find(o=>{let i=`request:${o.id}`,a=s[i];return rs.get(o.id)===O(o,De.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-o.updatedAt<=kt})??null:null}function Ga(t,e){return{id:t.id,title:O(t,De.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+kt).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Zu(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(yt)return"busy";let s=ns(e,t.reaches)?null:Ka(e,t.reaches),o=s?Ga(s,e.now??Date.now()):ns(e,t.reaches);if(!o)return"none";let i=(t.focus??Lr)();if(i.active)return"held";let a=`${s?"request":"card"}:${o.id}`,l=(v(e.root).wanted??[]).includes(a)?null:pn(o);if(l){if(s)rs.set(s.id,o.title);else{let d=[...W(e.root,"pending").map(c=>`card:${c.id}`),...wt(e).map(c=>`request:${c.id}`)];Oe(e.root,a,d,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${o.raised_by}: ${l}`),t.returnToAuthor?.(o,gn(o,l)),"returned"}yt=!0;try{let d=[...W(e.root,"pending").map(b=>`card:${b.id}`),...wt(e).map(b=>`request:${b.id}`)];Oe(e.root,a,d,e.now),r(`[approvals] popup: showing ${a} from ${o.raised_by}`);let c=e.now??Date.now(),u=!!s&&c-ts<Xa;s&&n.speak&&(ts=c);let p=t.agentName?.(o.raised_by)??(o.node?`${o.raised_by} on ${o.node}`:void 0),g=await(t.show??es)(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"} (${Gt(i)} when shown)`),"shown";if(!(s?P(e)?.get(s.id)?.state==="needs_attention":X(e.root,o.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await Vn(e,a,g.action,{by:"operator (popup)",...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(m.ok?`[approvals] popup: ${m.message}`:`[approvals] popup: ${a} not recorded: ${m.error}`),"shown"}catch(d){return r(`[approvals] popup failed for ${a}: ${d?.message??d}`),"shown"}finally{yt=!1}}function Qu(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:")?X(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Rn(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 Ja,mkdirSync as Ya,readFileSync as Za,renameSync as Qa,writeFileSync as el}from"fs";import{dirname as tl,resolve as nl}from"path";var rl=["all","urgent","off"],sl=24*36e5,ss=24*36e5,ol=30*24*36e5,os=t=>rl.includes(t);function rp(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:os(e)?e:"off",computer:os(n)?n:t.popupEnabled?"all":"off"}}function as(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=sl}function is(t,e,n){return t==="all"||t==="urgent"&&as(e,n)}function ls(t){return nl(t,".agentx","desk-routed.json")}function il(t){let e=ls(t);if(!Ja(e))return null;try{let n=JSON.parse(Za(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function St(t,e){let n=ls(t);Ya(tl(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;el(r,JSON.stringify(e,null,2)),Qa(r,n)}async function sp(t){let{root:e,now:n,list:r,routing:s,log:o}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),l=il(e);if(!l){let u={};for(let p of r.items)u[p.key]={at:a,seen:a};return St(e,{items:u}),i.primed=!0,i}let d=[],c=[];for(let u of r.items){let p=l.items[u.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>ss&&delete p.computerHeld,p.computerHeld&&c.push(u);continue}l.items[u.key]={at:a,seen:a};let g=u.askedAt?Date.parse(u.askedAt):n;n-g<=ss&&d.push(u)}for(let[u,p]of Object.entries(l.items))n-Date.parse(p.seen)>ol&&delete l.items[u];St(e,l);for(let u of d)if(is(s.phone,u,n))try{await t.phone(u,as(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[...c,...d]){let g=l.items[p.key];if(!is(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&&St(e,l)}return(i.phone.length||i.computer.length)&&o(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function op(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
557
- Answer it on the Desk.`}}import{closeSync as Q,createReadStream as al,fstatSync as ll,openSync as cl,realpathSync as cs}from"fs";import{isAbsolute as dl,resolve as ds,sep as us}from"path";var up="/app-files",ul=/^[A-Za-z0-9_.:-]{1,64}$/;function pl(t,e,n=process.cwd()){if(!e||e.length>oe.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 ${Te}/ first`};if(!Ie(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=cs(ds(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let s;try{s=cs(dl(e)?e:ds(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!s.startsWith(r+us))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Te}/ first`};let o=Ie(s);return o?{ok:!0,path:s,...o}:{ok:!1,status:415,error:"this type of file is not served"}}function gl(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 fl(t,e,n){return{"Content-Type":t,"Content-Disposition":gl(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 ml(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 pp(t,e,n,r){let s=(x,F)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(F))};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(!ul.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 l=pl(a,i,r.cwd);if(!l.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${o}: ${l.error}`),s(l.status,{error:l.error});let d;try{d=cl(l.path,"r")}catch{return s(404,{error:"file not found"})}let c;try{let x=ll(d);if(!x.isFile())return Q(d),s(404,{error:"not a file"});c=x.size}catch{return Q(d),s(404,{error:"file not found"})}if(c>oe.bytes)return Q(d),s(413,{error:`the file is larger than ${oe.bytes/1024/1024} MB`});let u=l.path.split(us).pop()||"file",p=fl(l.mime,u,l.kind),g=ml(t.headers.range,c);if(g==="unsatisfiable"){Q(d),e.writeHead(416,{...p,"Content-Range":`bytes */${c}`}),e.end();return}let{start:f,end:m}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(c?m-f+1:0),...g?{"Content-Range":`bytes ${f}-${m}/${c}`}:{}}),t.method==="HEAD"||c===0){Q(d),e.end();return}let b=al("",{fd:d,start:f,end:m,autoClose:!0});b.on("error",()=>e.destroy()),e.on("close",()=>b.destroy()),b.pipe(e)}import{spawn as ee}from"child_process";import{readFileSync as hl,writeFileSync as bl}from"fs";import{tmpdir as yl}from"os";import{join as wl}from"path";Ot();var ps=t=>t&&t!==1?Math.round(175*t):null,Se=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function kl(){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=hl(t,"utf8").trim();if(e)return e}catch{}return null}function Sp(t=kl()){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",...Se(n.voice.rate)?{voice_settings:{speed:Se(n.voice.rate)}}:{}}),signal:r});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text()).slice(0,160)}`);let o=wl(yl(),`agentx-say-${process.pid}-${++e}.mp3`);return bl(o,Buffer.from(await s.arrayBuffer())),o}catch(s){if(r.aborted||!n.voice.fallback)throw s;return M(`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 gs(t,e){let n=t.languages&&se(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Sl=(t,e="")=>{let n=gs(t,e),r=ps(t.rate);return[...n&&!er(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function xl(t,e,n){if(!n)return["say",Sl(t,e)];let r=gs(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function xp(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function vp(t=xt()){if(t)try{ee("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function $p(t=xt()){if(t)try{ee("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function xt(t={},e){if(!He(t))return null;try{return rr(e)}catch(n){return M("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
558
- `)[0]}); Siri voices will not switch`),null}}var Rp=(t,e)=>{if(!t){let[n,r]=xl(e.voice,e.text,xt()),s=ps(e.voice.rate),o=s?{...process.env,AGENTX_SAY_RATE:String(s)}:process.env,i=ee(n,r,{stdio:["pipe","ignore","ignore"],env:o});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?ee("afplay",[t],{stdio:"ignore"}):ee("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as fs}from"child_process";import{accessSync as vl,constants as $l,readFileSync as ms}from"fs";import{homedir as Rl}from"os";import{basename as H,delimiter as hs,dirname as _l,extname as El,join as vt}from"path";var L={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function bs(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)>L.ms+2e3?{status:413,error:Rt()}:null}var Rt=()=>`The recording is longer than ${L.ms/6e4} minutes.`,Al={"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 ys(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Al[e]??null}function ws(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 _t(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 $t(t,e,n=process.env.PATH??""){let r=Rl(),s=[vt(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(hs).filter(Boolean)];for(let o of[e,...s.map(i=>vt(i,t))])if(o)try{return vl(o,$l.X_OK),o}catch{}return null}function Dp(t){return{key:t,mlx:$t("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:$t("whisper",process.env.AGENTX_WHISPER),ffmpeg:Il()}}var Il=()=>$t("ffmpeg",process.env.AGENTX_FFMPEG);async function ks(t,e){return e?Tl(t,e):null}async function Tl(t,e){let n=String(L.ms/1e3+5);try{let s=[...(await Dl(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 Ss(t,e,n,r){let s=new FormData;s.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),s.set("file",new Blob([ms(t)],{type:e}),H(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 xs(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:`${_l(r)}${hs}${process.env.PATH??""}`};await Cl(e,o,12e4,i);try{return ms(vt(s,H(n,El(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Dl(t,e,n){return new Promise((r,s)=>{let o=fs(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{o.kill("SIGKILL"),s(new Error(`${H(t)} took too long`))},n);o.stderr.on("data",l=>{i=(i+l).slice(-8192)}),o.on("error",l=>{clearTimeout(a),s(l)}),o.on("exit",l=>{clearTimeout(a),l===0?r(i):s(new Error(`${H(t)} exited ${l}`))})})}function Cl(t,e,n,r=process.env){return new Promise((s,o)=>{let i=fs(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",l="",d=setTimeout(()=>{i.kill("SIGKILL"),o(new Error(`${H(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{l.length<4096&&(l+=c)}),i.on("error",c=>{clearTimeout(d),o(c)}),i.on("exit",c=>{clearTimeout(d),c===0?s(a):o(new Error(`${H(t)} exited ${c}: ${l.trim().split(`
559
- `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as Nl,rm as Ll,writeFile as Ol}from"fs/promises";import{tmpdir as Pl}from"os";import{join as vs}from"path";Cs();var Ml=64*1024,Ul=2,Et=0;function jp(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Vp(t,e,n,r){return t.method!=="POST"?y(e,405,{error:"POST"}):n==="/voice/transcribe"?Fl(t,e,r):jl(t,e,r)}async function Fl(t,e,n){let r=String(t.headers["content-type"]||""),s=ys(r);if(!s)return y(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let o=bs(t.headers["x-audio-duration-ms"]);if(o)return t.resume(),y(e,o.status,{error:o.error});let i=await $s(t,L.bytes);if(!i)return y(e,413,{error:Hl()});if(!i.length)return y(e,400,{error:"The recording is empty."});if(Et>=Ul)return y(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),l=n.host(),d=ws(a,l);if(!l.ffmpeg&&!n.allowUnmeasured?.()){let u=n.nodeName?`on ${n.nodeName}`:"on this computer",p=d.length?"":" "+_t(a,l);return y(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(!d.length)return y(e,503,{error:"Voice input isn't set up on this computer.",hint:_t(a,l),setup:!1});Et++;let c;try{let u=await Nl(vs(Pl(),"agentx-phone-voice-"));try{c=await Wl(u,`speech.${s}`,i,r,l,d,n)}finally{await Ll(u,{recursive:!0,force:!0}).catch(()=>{})}}finally{Et--}y(e,c[0],c[1])}async function Wl(t,e,n,r,s,o,i){let a=vs(t,e);if(await Ol(a,n,{mode:384}),s.ffmpeg){let d=await(i.measure??ks)(a,s.ffmpeg);if(d==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(d*1e3>L.ms+2e3)return[413,{error:Rt()}]}let l=[];for(let d of o)try{let c=await ql(d,a,r,s,t,i);return i.log(`[voice] phone recording transcribed with ${d} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:d}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:d}]}catch(c){let u=String(c?.message??c).split(`
560
- `)[0].slice(0,200);l.push(`${d}: ${u}`),i.log(`[voice] phone transcription with ${d} failed: ${u}`)}return[502,{error:"Speech to text failed on this computer.",detail:l.join("; ")}]}function ql(t,e,n,r,s,o){let i=o.engines?.[t];if(i)return i(e,n,r,s);if(t==="elevenlabs")return Ss(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return xs(t,a,e,r.ffmpeg,s)}async function jl(t,e,n){let r=await $s(t,Ml);if(!r)return y(e,413,{error:"request too large"});let s;try{s=JSON.parse(r.toString("utf8")||"{}")}catch{return y(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 y(e,400,{error:"agent is required"});let a=Vl(typeof s?.text=="string"?s.text:"",n.spokenMaxChars?.());if(!a)return y(e,422,{error:"Nothing in this answer can be said aloud."});let l=n.pronounce?n.pronounce(a):a,d=n.voiceOf(o,i);if(!d)return y(e,404,{error:`Unknown agent: ${o}`});let c=(p,g=200)=>y(e,g,{fallback:"browser",reason:p,text:l});if(d.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let u=n.elevenLabsKey();if(!u)return c("No ElevenLabs key is set on this computer.");try{let p=await(n.synth??Bl)(u,d,l);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(l.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
561
- `)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function Vl(t,e){let n=Tr(Xt(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Pt(n,e)}async function Bl(t,e,n){let r=Se(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 Hl=()=>`The recording is larger than ${L.bytes/1024/1024} MB, more than ${L.ms/6e4} minutes of speech.`;function Bp(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let s=n.agents??{};return s[t]?tt(Ze(t,s,n.voice)):null}function $s(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 y(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}import{existsSync as _,readFileSync as Dt,writeFileSync as Ct,mkdirSync as xe,readdirSync as Tt,rmSync as zl,statSync as I}from"fs";import{resolve as Rs,relative as Xl,dirname as Nt,join as U,extname as te,basename as Lt}from"path";var S=200*1024,_s=new Set([".md",".markdown",".txt"]),z=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"]),Kl=6,Gl=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function C(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=Rs(t);if(_(n)||xe(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=Rs(n,e);if(Xl(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function Es(t){let e=te(t).toLowerCase();if(!_s.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function At(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Kp(t){let e=C(t,"."),n=[],r=new Set,s=[];try{s=Tt(e)}catch{}for(let a of Gl){let l=U(e,a);if(_(l)&&I(l).isFile()){let d=I(l).size,c=d>0&&d<S?It(l):"";n.push({path:a,title:At(c,a),size:d,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 l=U(e,a);try{let d=I(l);if(!d.isFile()||!_s.has(te(a).toLowerCase()))continue;let c=d.size>0&&d.size<S?It(l):"";n.push({path:a,title:At(c,a),size:d.size,exists:!0})}catch{}}let o=[],i=U(e,".claude","skills");if(_(i))try{for(let a of Tt(i)){let l=U(i,a),d;try{d=I(l)}catch{continue}if(!d.isDirectory())continue;let c=U(l,"SKILL.md");if(!_(c))continue;let u=I(c),p=u.size<S?It(c):"";o.push({slug:a,title:At(p,a),size:u.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return o.sort((a,l)=>a.slug.localeCompare(l.slug)),{identity:n,skills:o,workspace:e}}function It(t){try{return Dt(t,"utf-8")}catch{return""}}function Gp(t,e){let n=C(t,e);if(Es(n),!_(n))return{path:e,content:""};if(I(n).size>S)throw new Error(`File is too large to edit in the admin panel (> ${S/1024} KB).`);return{path:e,content:Dt(n,"utf-8")}}function Jp(t,e,n){let r=C(t,e);Es(r);let s=Buffer.from(n,"utf-8");if(s.length>S)throw new Error(`File too large (${s.length} > ${S} bytes).`);return xe(Nt(r),{recursive:!0}),Ct(r,s),{path:e,bytes:s.length}}function Yp(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=C(t,r);if(_(s))throw new Error(`Skill "${e}" already exists.`);xe(Nt(s),{recursive:!0});let o=n.content?.trim()?n.content:Jl(e,n.title);return Ct(s,o),{slug:e,path:r}}function Zp(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=C(t,`.claude/skills/${e}`);if(!_(n))throw new Error(`Skill "${e}" not found.`);if(!I(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return zl(n,{recursive:!0,force:!0}),{slug:e}}function Qp(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=C(t,`.claude/skills/${e}`);if(!_(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,l){if(a>Kl)return;let d=[];try{d=Tt(o)}catch{return}for(let c of d){if(c==="node_modules"||c===".git")continue;let u=U(o,c),p=i?`${i}/${c}`:c,g;try{g=I(u)}catch{continue}if(g.isDirectory())l.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),s(u,p,a+1,l);else if(g.isFile()){let f=te(c).toLowerCase(),m=z.has(f)||z.has(c.toLowerCase());l.push({path:p,kind:"file",size:g.size,editable:m&&g.size<S})}}}}function eg(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=C(t,`.claude/skills/${e}/${n}`);if(!_(r)||!I(r).isFile())throw new Error(`File not found: ${n}`);let s=te(r).toLowerCase(),o=Lt(r).toLowerCase();if(!z.has(s)&&!z.has(o))throw new Error(`File type not editable: ${n}`);if(I(r).size>S)throw new Error(`File too large to edit (> ${S/1024} KB): ${n}`);return{path:n,content:Dt(r,"utf-8")}}function tg(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=C(t,`.claude/skills/${e}/${n}`),o=te(s).toLowerCase(),i=Lt(s).toLowerCase();if(!z.has(o)&&!z.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>S)throw new Error(`File too large (${a.length} > ${S} bytes).`);return xe(Nt(s),{recursive:!0}),Ct(s,a),{path:n,bytes:a.length}}function ng(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=C(t,`.claude/skills/${e}`);if(!_(n))throw new Error(`Skill "${e}" not found.`);let r=s=>_(U(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 Jl(t,e){return`# ${e?.trim()||t}
557
+ Message (edit it if you like):`,u=await n("/usr/bin/osascript",Zr(o,d,i?["Cancel","Send"]:["Not now","No","Send"],r,rn(t.draft,i)),s),p=u.ok?Qr(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",Zr(o,bt(t),["Not now","No","Yes"],r),s),l=a.ok?Qr(a.stdout):null;return l?.button==="Yes"?{action:"yes"}:l?.button==="No"?{action:"no"}:{action:"dismiss"}}var kt=24*36e5,yt=!1,Ja=10*6e4,ns=-1/0;function rs(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s,passAt:o,wanted:i=[]}=v(t.root),a=o?Date.parse(o):NaN,l=W(t.root,"pending").filter(c=>Date.parse(c.expires)>n),d=l.find(c=>i.includes(`card:${c.id}`));if(d)return d;for(let c of l){let u=`card:${c.id}`;if(r[u]||!e(c)||mn(t.root,c.id,n))continue;let p=s[u];if(p&&Date.parse(p)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>kt&&!(g<=a)))return c}return null}function wt(t){try{return P(t)?.listByState("needs_attention")??[]}catch{return[]}}var ss=new Map;function Ya(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s}=v(t.root);return e({})?wt(t).find(o=>{let i=`request:${o.id}`,a=s[i];return ss.get(o.id)===O(o,De.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-o.updatedAt<=kt})??null:null}function Za(t,e){return{id:t.id,title:O(t,De.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+kt).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function op(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(yt)return"busy";let s=rs(e,t.reaches)?null:Ya(e,t.reaches),o=s?Za(s,e.now??Date.now()):rs(e,t.reaches);if(!o)return"none";let i=(t.focus??Or)();if(i.active)return"held";let a=`${s?"request":"card"}:${o.id}`,l=(v(e.root).wanted??[]).includes(a)?null:pn(o);if(l){if(s)ss.set(s.id,o.title);else{let d=[...W(e.root,"pending").map(c=>`card:${c.id}`),...wt(e).map(c=>`request:${c.id}`)];Oe(e.root,a,d,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${o.raised_by}: ${l}`),t.returnToAuthor?.(o,gn(o,l)),"returned"}yt=!0;try{let d=[...W(e.root,"pending").map(b=>`card:${b.id}`),...wt(e).map(b=>`request:${b.id}`)];Oe(e.root,a,d,e.now),r(`[approvals] popup: showing ${a} from ${o.raised_by}`);let c=e.now??Date.now(),u=!!s&&c-ns<Ja;s&&n.speak&&(ns=c);let p=t.agentName?.(o.raised_by)??(o.node?`${o.raised_by} on ${o.node}`:void 0),g=await(t.show??ts)(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"} (${Gt(i)} when shown)`),"shown";if(!(s?P(e)?.get(s.id)?.state==="needs_attention":X(e.root,o.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await Vn(e,a,g.action,{by:"operator (popup)",...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(m.ok?`[approvals] popup: ${m.message}`:`[approvals] popup: ${a} not recorded: ${m.error}`),"shown"}catch(d){return r(`[approvals] popup failed for ${a}: ${d?.message??d}`),"shown"}finally{yt=!1}}function ip(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:")?X(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Rn(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 Qa,mkdirSync as el,readFileSync as tl,renameSync as nl,writeFileSync as rl}from"fs";import{dirname as sl,resolve as ol}from"path";var il=["all","urgent","off"],al=24*36e5,os=24*36e5,ll=30*24*36e5,is=t=>il.includes(t);function dp(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:is(e)?e:"off",computer:is(n)?n:t.popupEnabled?"all":"off"}}function ls(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=al}function as(t,e,n){return t==="all"||t==="urgent"&&ls(e,n)}function cs(t){return ol(t,".agentx","desk-routed.json")}function cl(t){let e=cs(t);if(!Qa(e))return null;try{let n=JSON.parse(tl(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function St(t,e){let n=cs(t);el(sl(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;rl(r,JSON.stringify(e,null,2)),nl(r,n)}async function up(t){let{root:e,now:n,list:r,routing:s,log:o}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),l=cl(e);if(!l){let u={};for(let p of r.items)u[p.key]={at:a,seen:a};return St(e,{items:u}),i.primed=!0,i}let d=[],c=[];for(let u of r.items){let p=l.items[u.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>os&&delete p.computerHeld,p.computerHeld&&c.push(u);continue}l.items[u.key]={at:a,seen:a};let g=u.askedAt?Date.parse(u.askedAt):n;n-g<=os&&d.push(u)}for(let[u,p]of Object.entries(l.items))n-Date.parse(p.seen)>ll&&delete l.items[u];St(e,l);for(let u of d)if(as(s.phone,u,n))try{await t.phone(u,ls(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[...c,...d]){let g=l.items[p.key];if(!as(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&&St(e,l)}return(i.phone.length||i.computer.length)&&o(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function pp(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
558
+ Answer it on the Desk.`}}import{closeSync as Q,createReadStream as dl,fstatSync as ul,openSync as pl,realpathSync as ds}from"fs";import{isAbsolute as gl,resolve as us,sep as ps}from"path";var yp="/app-files",fl=/^[A-Za-z0-9_.:-]{1,64}$/;function ml(t,e,n=process.cwd()){if(!e||e.length>oe.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 ${Te}/ first`};if(!Ie(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=ds(us(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let s;try{s=ds(gl(e)?e:us(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!s.startsWith(r+ps))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Te}/ first`};let o=Ie(s);return o?{ok:!0,path:s,...o}:{ok:!1,status:415,error:"this type of file is not served"}}function hl(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 bl(t,e,n){return{"Content-Type":t,"Content-Disposition":hl(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 yl(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 wp(t,e,n,r){let s=(x,F)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(F))};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(!fl.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 l=ml(a,i,r.cwd);if(!l.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${o}: ${l.error}`),s(l.status,{error:l.error});let d;try{d=pl(l.path,"r")}catch{return s(404,{error:"file not found"})}let c;try{let x=ul(d);if(!x.isFile())return Q(d),s(404,{error:"not a file"});c=x.size}catch{return Q(d),s(404,{error:"file not found"})}if(c>oe.bytes)return Q(d),s(413,{error:`the file is larger than ${oe.bytes/1024/1024} MB`});let u=l.path.split(ps).pop()||"file",p=bl(l.mime,u,l.kind),g=yl(t.headers.range,c);if(g==="unsatisfiable"){Q(d),e.writeHead(416,{...p,"Content-Range":`bytes */${c}`}),e.end();return}let{start:f,end:m}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(c?m-f+1:0),...g?{"Content-Range":`bytes ${f}-${m}/${c}`}:{}}),t.method==="HEAD"||c===0){Q(d),e.end();return}let b=dl("",{fd:d,start:f,end:m,autoClose:!0});b.on("error",()=>e.destroy()),e.on("close",()=>b.destroy()),b.pipe(e)}import{spawn as ee}from"child_process";import{readFileSync as wl,writeFileSync as kl}from"fs";import{tmpdir as Sl}from"os";import{join as xl}from"path";Ot();var gs=t=>t&&t!==1?Math.round(175*t):null,Se=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function vl(){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=wl(t,"utf8").trim();if(e)return e}catch{}return null}function Ap(t=vl()){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",...Se(n.voice.rate)?{voice_settings:{speed:Se(n.voice.rate)}}:{}}),signal:r});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text()).slice(0,160)}`);let o=xl(Sl(),`agentx-say-${process.pid}-${++e}.mp3`);return kl(o,Buffer.from(await s.arrayBuffer())),o}catch(s){if(r.aborted||!n.voice.fallback)throw s;return M(`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 fs(t,e){let n=t.languages&&se(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var $l=(t,e="")=>{let n=fs(t,e),r=gs(t.rate);return[...n&&!tr(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Rl(t,e,n){if(!n)return["say",$l(t,e)];let r=fs(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function Ip(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function Tp(t=xt()){if(t)try{ee("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Dp(t=xt()){if(t)try{ee("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function xt(t={},e){if(!He(t))return null;try{return sr(e)}catch(n){return M("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
559
+ `)[0]}); Siri voices will not switch`),null}}var Cp=(t,e)=>{if(!t){let[n,r]=Rl(e.voice,e.text,xt()),s=gs(e.voice.rate),o=s?{...process.env,AGENTX_SAY_RATE:String(s)}:process.env,i=ee(n,r,{stdio:["pipe","ignore","ignore"],env:o});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?ee("afplay",[t],{stdio:"ignore"}):ee("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as ms}from"child_process";import{accessSync as _l,constants as El,readFileSync as hs}from"fs";import{homedir as Al}from"os";import{basename as H,delimiter as bs,dirname as Il,extname as Tl,join as vt}from"path";var L={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function ys(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)>L.ms+2e3?{status:413,error:Rt()}:null}var Rt=()=>`The recording is longer than ${L.ms/6e4} minutes.`,Dl={"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 ws(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Dl[e]??null}function ks(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 _t(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 $t(t,e,n=process.env.PATH??""){let r=Al(),s=[vt(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(bs).filter(Boolean)];for(let o of[e,...s.map(i=>vt(i,t))])if(o)try{return _l(o,El.X_OK),o}catch{}return null}function Up(t){return{key:t,mlx:$t("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:$t("whisper",process.env.AGENTX_WHISPER),ffmpeg:Cl()}}var Cl=()=>$t("ffmpeg",process.env.AGENTX_FFMPEG);async function Ss(t,e){return e?Nl(t,e):null}async function Nl(t,e){let n=String(L.ms/1e3+5);try{let s=[...(await Ll(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 xs(t,e,n,r){let s=new FormData;s.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),s.set("file",new Blob([hs(t)],{type:e}),H(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 vs(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:`${Il(r)}${bs}${process.env.PATH??""}`};await Ol(e,o,12e4,i);try{return hs(vt(s,H(n,Tl(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Ll(t,e,n){return new Promise((r,s)=>{let o=ms(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{o.kill("SIGKILL"),s(new Error(`${H(t)} took too long`))},n);o.stderr.on("data",l=>{i=(i+l).slice(-8192)}),o.on("error",l=>{clearTimeout(a),s(l)}),o.on("exit",l=>{clearTimeout(a),l===0?r(i):s(new Error(`${H(t)} exited ${l}`))})})}function Ol(t,e,n,r=process.env){return new Promise((s,o)=>{let i=ms(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",l="",d=setTimeout(()=>{i.kill("SIGKILL"),o(new Error(`${H(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{l.length<4096&&(l+=c)}),i.on("error",c=>{clearTimeout(d),o(c)}),i.on("exit",c=>{clearTimeout(d),c===0?s(a):o(new Error(`${H(t)} exited ${c}: ${l.trim().split(`
560
+ `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as Pl,rm as Ml,writeFile as Ul}from"fs/promises";import{tmpdir as Fl}from"os";import{join as $s}from"path";Ns();var Wl=64*1024,ql=2,Et=0;function Gp(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Jp(t,e,n,r){return t.method!=="POST"?y(e,405,{error:"POST"}):n==="/voice/transcribe"?jl(t,e,r):Hl(t,e,r)}async function jl(t,e,n){let r=String(t.headers["content-type"]||""),s=ws(r);if(!s)return y(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let o=ys(t.headers["x-audio-duration-ms"]);if(o)return t.resume(),y(e,o.status,{error:o.error});let i=await Rs(t,L.bytes);if(!i)return y(e,413,{error:Kl()});if(!i.length)return y(e,400,{error:"The recording is empty."});if(Et>=ql)return y(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),l=n.host(),d=ks(a,l);if(!l.ffmpeg&&!n.allowUnmeasured?.()){let u=n.nodeName?`on ${n.nodeName}`:"on this computer",p=d.length?"":" "+_t(a,l);return y(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(!d.length)return y(e,503,{error:"Voice input isn't set up on this computer.",hint:_t(a,l),setup:!1});Et++;let c;try{let u=await Pl($s(Fl(),"agentx-phone-voice-"));try{c=await Vl(u,`speech.${s}`,i,r,l,d,n)}finally{await Ml(u,{recursive:!0,force:!0}).catch(()=>{})}}finally{Et--}y(e,c[0],c[1])}async function Vl(t,e,n,r,s,o,i){let a=$s(t,e);if(await Ul(a,n,{mode:384}),s.ffmpeg){let d=await(i.measure??Ss)(a,s.ffmpeg);if(d==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(d*1e3>L.ms+2e3)return[413,{error:Rt()}]}let l=[];for(let d of o)try{let c=await Bl(d,a,r,s,t,i);return i.log(`[voice] phone recording transcribed with ${d} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:d}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:d}]}catch(c){let u=String(c?.message??c).split(`
561
+ `)[0].slice(0,200);l.push(`${d}: ${u}`),i.log(`[voice] phone transcription with ${d} failed: ${u}`)}return[502,{error:"Speech to text failed on this computer.",detail:l.join("; ")}]}function Bl(t,e,n,r,s,o){let i=o.engines?.[t];if(i)return i(e,n,r,s);if(t==="elevenlabs")return xs(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return vs(t,a,e,r.ffmpeg,s)}async function Hl(t,e,n){let r=await Rs(t,Wl);if(!r)return y(e,413,{error:"request too large"});let s;try{s=JSON.parse(r.toString("utf8")||"{}")}catch{return y(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 y(e,400,{error:"agent is required"});let a=zl(typeof s?.text=="string"?s.text:"",n.spokenMaxChars?.());if(!a)return y(e,422,{error:"Nothing in this answer can be said aloud."});let l=n.pronounce?n.pronounce(a):a,d=n.voiceOf(o,i);if(!d)return y(e,404,{error:`Unknown agent: ${o}`});let c=(p,g=200)=>y(e,g,{fallback:"browser",reason:p,text:l});if(d.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let u=n.elevenLabsKey();if(!u)return c("No ElevenLabs key is set on this computer.");try{let p=await(n.synth??Xl)(u,d,l);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(l.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
562
+ `)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function zl(t,e){let n=Dr(Xt(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Pt(n,e)}async function Xl(t,e,n){let r=Se(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 Kl=()=>`The recording is larger than ${L.bytes/1024/1024} MB, more than ${L.ms/6e4} minutes of speech.`;function Yp(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let s=n.agents??{};return s[t]?tt(Ze(t,s,n.voice)):null}function Rs(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 y(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}import{existsSync as _,readFileSync as Dt,writeFileSync as Ct,mkdirSync as xe,readdirSync as Tt,rmSync as Gl,statSync as I}from"fs";import{resolve as _s,relative as Jl,dirname as Nt,join as U,extname as te,basename as Lt}from"path";var S=200*1024,Es=new Set([".md",".markdown",".txt"]),z=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"]),Yl=6,Zl=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function C(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=_s(t);if(_(n)||xe(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=_s(n,e);if(Jl(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function As(t){let e=te(t).toLowerCase();if(!Es.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function At(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function tg(t){let e=C(t,"."),n=[],r=new Set,s=[];try{s=Tt(e)}catch{}for(let a of Zl){let l=U(e,a);if(_(l)&&I(l).isFile()){let d=I(l).size,c=d>0&&d<S?It(l):"";n.push({path:a,title:At(c,a),size:d,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 l=U(e,a);try{let d=I(l);if(!d.isFile()||!Es.has(te(a).toLowerCase()))continue;let c=d.size>0&&d.size<S?It(l):"";n.push({path:a,title:At(c,a),size:d.size,exists:!0})}catch{}}let o=[],i=U(e,".claude","skills");if(_(i))try{for(let a of Tt(i)){let l=U(i,a),d;try{d=I(l)}catch{continue}if(!d.isDirectory())continue;let c=U(l,"SKILL.md");if(!_(c))continue;let u=I(c),p=u.size<S?It(c):"";o.push({slug:a,title:At(p,a),size:u.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return o.sort((a,l)=>a.slug.localeCompare(l.slug)),{identity:n,skills:o,workspace:e}}function It(t){try{return Dt(t,"utf-8")}catch{return""}}function ng(t,e){let n=C(t,e);if(As(n),!_(n))return{path:e,content:""};if(I(n).size>S)throw new Error(`File is too large to edit in the admin panel (> ${S/1024} KB).`);return{path:e,content:Dt(n,"utf-8")}}function rg(t,e,n){let r=C(t,e);As(r);let s=Buffer.from(n,"utf-8");if(s.length>S)throw new Error(`File too large (${s.length} > ${S} bytes).`);return xe(Nt(r),{recursive:!0}),Ct(r,s),{path:e,bytes:s.length}}function sg(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=C(t,r);if(_(s))throw new Error(`Skill "${e}" already exists.`);xe(Nt(s),{recursive:!0});let o=n.content?.trim()?n.content:Ql(e,n.title);return Ct(s,o),{slug:e,path:r}}function og(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=C(t,`.claude/skills/${e}`);if(!_(n))throw new Error(`Skill "${e}" not found.`);if(!I(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return Gl(n,{recursive:!0,force:!0}),{slug:e}}function ig(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=C(t,`.claude/skills/${e}`);if(!_(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,l){if(a>Yl)return;let d=[];try{d=Tt(o)}catch{return}for(let c of d){if(c==="node_modules"||c===".git")continue;let u=U(o,c),p=i?`${i}/${c}`:c,g;try{g=I(u)}catch{continue}if(g.isDirectory())l.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),s(u,p,a+1,l);else if(g.isFile()){let f=te(c).toLowerCase(),m=z.has(f)||z.has(c.toLowerCase());l.push({path:p,kind:"file",size:g.size,editable:m&&g.size<S})}}}}function ag(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=C(t,`.claude/skills/${e}/${n}`);if(!_(r)||!I(r).isFile())throw new Error(`File not found: ${n}`);let s=te(r).toLowerCase(),o=Lt(r).toLowerCase();if(!z.has(s)&&!z.has(o))throw new Error(`File type not editable: ${n}`);if(I(r).size>S)throw new Error(`File too large to edit (> ${S/1024} KB): ${n}`);return{path:n,content:Dt(r,"utf-8")}}function lg(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=C(t,`.claude/skills/${e}/${n}`),o=te(s).toLowerCase(),i=Lt(s).toLowerCase();if(!z.has(o)&&!z.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>S)throw new Error(`File too large (${a.length} > ${S} bytes).`);return xe(Nt(s),{recursive:!0}),Ct(s,a),{path:n,bytes:a.length}}function cg(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=C(t,`.claude/skills/${e}`);if(!_(n))throw new Error(`Skill "${e}" not found.`);let r=s=>_(U(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 Ql(t,e){return`# ${e?.trim()||t}
562
563
 
563
564
  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.
564
565
 
@@ -573,5 +574,5 @@ Document the arguments, commands, or files the skill expects. Example:
573
574
  # Example invocation
574
575
  claude-code ${Lt(t)} --arg value
575
576
  \`\`\`
576
- `}Vt();var As={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Is(t){return{...As,...t??{},regions:{...t?.regions??{}},buffer:{...As.buffer,...t?.buffer??{}}}}function og(t){try{return Is(jt(t).screen)}catch{return Is(void 0)}}var Yl=/^[a-z][\w-]*$/,Ts=["window","screen","menubar","notifications"];function ne(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 ve=(t,e)=>ne(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Ds(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 ig(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=ve(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=ve(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=ve(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ne(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ne(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(!Yl.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=Ds(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=ne(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=ne(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=ve(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&&!Ts.includes(r)&&!n.regions?.[r])try{Ds(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Ts,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{hn as a,ec as b,pt as c,Bi as d,Hi as e,Kd as f,Gd as g,Jd as h,Qd as i,eu as j,tu as k,Ar as l,Ir as m,nu as n,Tr as o,su as p,iu as q,N as r,Dr as s,k as t,sc as u,Lr as v,pu as w,mu as x,Pr as y,hu as z,Mr as A,bu as B,Z as C,ya as D,yu as E,wu as F,Fr as G,wc as H,uo as I,Rc as J,Ln as K,v as L,cc as M,dc as N,Ac as O,ce as P,Ic as Q,_n as R,hc as S,P as T,Hc as U,jn as V,Vn as W,Do as X,Co as Y,Kc as Z,Gc as _,Fo as $,Qc as aa,qr as ba,xu as ca,$r as da,rt as ea,Mi as fa,es as ga,Zu as ha,Qu as ia,rl as ja,rp as ka,is as la,sp as ma,op as na,up as oa,fl as pa,pp as qa,td as ra,nd as sa,rd as ta,sd as ua,od as va,id as wa,ld as xa,cd as ya,yd as za,Ke as Aa,wd as Ba,kd as Ca,J as Da,Y as Ea,kl as Fa,Sp as Ga,xp as Ha,vp as Ia,$p as Ja,xt as Ka,Rp as La,Ye as Ma,Ze as Na,he as Oa,ci as Pa,ui as Qa,Rd as Ra,et as Sa,tt as Ta,pi as Ua,gi as Va,gr as Wa,br as Xa,_d as Ya,hi as Za,Ed as _a,$i as $a,Ei as ab,nt as bb,Ii as cb,yr as db,L as eb,bs as fb,ys as gb,ws as hb,Dp as ib,Il as jb,Ss as kb,xs as lb,jp as mb,Vp as nb,Hl as ob,Bp as pb,$s as qb,be as rb,Fd as sb,dt as tb,zd as ub,Kp as vb,Gp as wb,Jp as xb,Yp as yb,Zp as zb,Qp as Ab,eg as Bb,tg as Cb,ng as Db,As as Eb,Is as Fb,og as Gb,Ts as Hb,ig as Ib};
577
- //# sourceMappingURL=chunk-SRUIUZOC.js.map
577
+ `}Vt();var Is={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Ts(t){return{...Is,...t??{},regions:{...t?.regions??{}},buffer:{...Is.buffer,...t?.buffer??{}}}}function pg(t){try{return Ts(jt(t).screen)}catch{return Ts(void 0)}}var ec=/^[a-z][\w-]*$/,Ds=["window","screen","menubar","notifications"];function ne(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 ve=(t,e)=>ne(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Cs(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 gg(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=ve(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=ve(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=ve(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ne(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ne(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(!ec.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=Cs(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=ne(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=ne(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=ve(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&&!Ds.includes(r)&&!n.regions?.[r])try{Cs(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Ds,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{hn as a,rc as b,pt as c,Xi as d,Ki as e,tu as f,nu as g,ru as h,iu as i,au as j,lu as k,Ir as l,Tr as m,cu as n,Dr as o,uu as p,gu as q,N as r,Cr as s,k as t,ac as u,Or as v,wu as w,xu as x,Mr as y,vu as z,Ur as A,$u as B,Z as C,Sa as D,Ru as E,_u as F,Wr as G,xc as H,po as I,Ac as J,Ln as K,v as L,pc as M,gc as N,Dc as O,ce as P,Cc as Q,_n as R,wc as S,P as T,Kc as U,jn as V,Vn as W,Co as X,No as Y,Yc as Z,Zc as _,Wo as $,nd as aa,jr as ba,Iu as ca,od as da,id as ea,Rr as fa,rt as ga,Wi as ha,ts as ia,op as ja,ip as ka,il as la,dp as ma,as as na,up as oa,pp as pa,yp as qa,bl as ra,wp as sa,ld as ta,cd as ua,dd as va,ud as wa,pd as xa,gd as ya,md as za,hd as Aa,Rd as Ba,Ke as Ca,_d as Da,Ed as Ea,J as Fa,Y as Ga,vl as Ha,Ap as Ia,Ip as Ja,Tp as Ka,Dp as La,xt as Ma,Cp as Na,Ye as Oa,Ze as Pa,he as Qa,pi as Ra,fi as Sa,Cd as Ta,et as Ua,tt as Va,mi as Wa,hi as Xa,fr as Ya,yr as Za,Nd as _a,wi as $a,Ld as ab,Ei as bb,Ti as cb,nt as db,Ci as eb,wr as fb,L as gb,ys as hb,ws as ib,ks as jb,Up as kb,Cl as lb,xs as mb,vs as nb,Gp as ob,Jp as pb,Kl as qb,Yp as rb,Rs as sb,be as tb,zd as ub,dt as vb,Qd as wb,tg as xb,ng as yb,rg as zb,sg as Ab,og as Bb,ig as Cb,ag as Db,lg as Eb,cg as Fb,Is as Gb,Ts as Hb,pg as Ib,Ds as Jb,gg as Kb};
578
+ //# sourceMappingURL=chunk-3MSNOHKU.js.map