agentix-cli 0.166.0 → 0.168.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 (184) hide show
  1. package/README.md +2 -2
  2. package/dist/{App-UOZT7MWS.js → App-GK5F6QMB.js} +2 -2
  3. package/dist/{ChatApp-N7REHHH3.js → ChatApp-4HHJB4HM.js} +2 -2
  4. package/dist/absorb-eval-PO7TUGT2.js +2 -0
  5. package/dist/agent-6WKET7JZ.js +2 -0
  6. package/dist/{board-dashboard-4C77NLY5.js → board-dashboard-ESAX2ZFV.js} +436 -403
  7. package/dist/board-dashboard-ESAX2ZFV.js.map +1 -0
  8. package/dist/{chunk-NHWYEIET.js → chunk-5PEXL5LD.js} +6 -6
  9. package/dist/{chunk-L7RPH3T7.js → chunk-5QI7XFTA.js} +2 -2
  10. package/dist/{chunk-TCC56PYX.js → chunk-BAXGL6TY.js} +2 -2
  11. package/dist/{chunk-JMZNI257.js → chunk-BRQKV4FC.js} +2 -2
  12. package/dist/{chunk-B7QHC7N4.js → chunk-CBXPIKPJ.js} +2 -2
  13. package/dist/{chunk-33KKV3YU.js → chunk-COMJ7R5T.js} +2 -2
  14. package/dist/{chunk-6QLRRSKU.js → chunk-DCIYOPJF.js} +15 -15
  15. package/dist/chunk-DCIYOPJF.js.map +1 -0
  16. package/dist/{chunk-7FH2FEFA.js → chunk-DCJHCUEQ.js} +2 -2
  17. package/dist/{chunk-QLJ3OMPL.js → chunk-E67Z6OYF.js} +2 -2
  18. package/dist/chunk-E7Y4G3FK.js +185 -0
  19. package/dist/chunk-E7Y4G3FK.js.map +1 -0
  20. package/dist/{chunk-XQ2EFLQW.js → chunk-EEM433JK.js} +28 -28
  21. package/dist/{chunk-XQ2EFLQW.js.map → chunk-EEM433JK.js.map} +1 -1
  22. package/dist/chunk-FEA3XMVU.js +580 -0
  23. package/dist/chunk-FEA3XMVU.js.map +1 -0
  24. package/dist/chunk-GZIHLADX.js +4 -0
  25. package/dist/chunk-GZIHLADX.js.map +1 -0
  26. package/dist/{chunk-G3T73GGF.js → chunk-HFSPH5WM.js} +2 -2
  27. package/dist/{chunk-XJYGMCAV.js → chunk-HRN4WKSJ.js} +363 -304
  28. package/dist/chunk-HRN4WKSJ.js.map +1 -0
  29. package/dist/{chunk-IJZNM5PS.js → chunk-JKMFMW3E.js} +2 -2
  30. package/dist/chunk-KMPUUH5R.js +137 -0
  31. package/dist/chunk-KMPUUH5R.js.map +1 -0
  32. package/dist/{chunk-YKHK47G5.js → chunk-KWY5IBII.js} +2 -2
  33. package/dist/{chunk-TM2TPQKH.js → chunk-LE3BXIUF.js} +2 -2
  34. package/dist/chunk-LXW7H4D4.js +2 -0
  35. package/dist/chunk-LXW7H4D4.js.map +1 -0
  36. package/dist/chunk-NKCS6EZ7.js +92 -0
  37. package/dist/chunk-NKCS6EZ7.js.map +1 -0
  38. package/dist/{chunk-BQXKTQCX.js → chunk-PIJ6ECBC.js} +2 -2
  39. package/dist/chunk-RX5O5637.js +7 -0
  40. package/dist/chunk-RX5O5637.js.map +1 -0
  41. package/dist/{chunk-LQTTLXZY.js → chunk-S34KFBMJ.js} +3 -3
  42. package/dist/{chunk-XML72AUF.js → chunk-TVGVQABC.js} +2 -2
  43. package/dist/{chunk-7O43PB6O.js → chunk-U4PICSLC.js} +2 -2
  44. package/dist/{chunk-AFLZHY5Y.js → chunk-U5SJLLXH.js} +2 -2
  45. package/dist/{chunk-LM3K7U6H.js → chunk-UF5TWOKL.js} +15 -15
  46. package/dist/chunk-UF5TWOKL.js.map +1 -0
  47. package/dist/chunk-UKKOBMOP.js +8 -0
  48. package/dist/chunk-UKKOBMOP.js.map +1 -0
  49. package/dist/{chunk-BNOGNRAM.js → chunk-VD2P4GWU.js} +2 -2
  50. package/dist/{chunk-64POGFQZ.js → chunk-YQM6VR6U.js} +2 -2
  51. package/dist/{chunk-QGKNDGH5.js → chunk-Z6ZR2ELO.js} +2 -2
  52. package/dist/{chunk-SXKC2LH7.js → chunk-ZTIOHZIL.js} +2 -2
  53. package/dist/cli.js +1 -1
  54. package/dist/client-DOIYODET.js +2 -0
  55. package/dist/{compaction-VN3M5YGZ.js → compaction-26OHHULF.js} +3 -3
  56. package/dist/config-3UBJRE5R.js +2 -0
  57. package/dist/config-mutate-ZRPDYJKN.js +2 -0
  58. package/dist/config-mutator-B5MR3V4B.js +2 -0
  59. package/dist/{context-planner-2XBAPQ3S.js → context-planner-CVCRW5TV.js} +2 -2
  60. package/dist/{contributions-MUCJKT73.js → contributions-2CJFYRZ7.js} +2 -2
  61. package/dist/{doctor-2N2MX5YP.js → doctor-OQZMDL5S.js} +2 -2
  62. package/dist/{follow-up-tool-W64LMQQN.js → follow-up-tool-PQUPXQQT.js} +2 -2
  63. package/dist/{grants-YGA654NI.js → grants-4O2VF2YX.js} +2 -2
  64. package/dist/heal-ZS56MC4A.js +2 -0
  65. package/dist/hub-LOW7KS5N.js +2 -0
  66. package/dist/index.d.ts +563 -3
  67. package/dist/index.js +1 -1
  68. package/dist/index.js.map +1 -1
  69. package/dist/memory-extract-NLVLQE7V.js +2 -0
  70. package/dist/{program-6YMRDLHO.js → program-7W2LJKDN.js} +298 -273
  71. package/dist/program-7W2LJKDN.js.map +1 -0
  72. package/dist/{promote-OUSVJZ64.js → promote-ZWQAL3RE.js} +2 -2
  73. package/dist/{providers-VVT2OBXA.js → providers-F5GDJSYD.js} +2 -2
  74. package/dist/push-bridge-NR7SLHGX.js +1 -1
  75. package/dist/query-N4EJ24LW.js +2 -0
  76. package/dist/{query-settings-2TNLXEL5.js → query-settings-RZV5ELLC.js} +2 -2
  77. package/dist/registry-EBYOZK3P.js +2 -0
  78. package/dist/{request-planner-7HEHLPA3.js → request-planner-KCG6QB6M.js} +2 -2
  79. package/dist/{review-candidates-NJNMSOCX.js → review-candidates-3GHWVJQ3.js} +2 -2
  80. package/dist/routing-XULOU6BI.js +2 -0
  81. package/dist/schedule-tool-ALZXDGGC.js +2 -0
  82. package/dist/scheduler-SCVCNKJC.js +2 -0
  83. package/dist/{seat-CAYDECW2.js → seat-PD7W3KAN.js} +2 -2
  84. package/dist/{select-QUVE6RN2.js → select-Z3YXBGUP.js} +2 -2
  85. package/dist/{set-enabled-BWJN4IVG.js → set-enabled-NJYJWDWH.js} +2 -2
  86. package/dist/sprint-tool-OLHZZAK3.js +7 -0
  87. package/dist/sprint-tool-OLHZZAK3.js.map +1 -0
  88. package/dist/tool-7IKZO33P.js +4 -0
  89. package/dist/tool-7IKZO33P.js.map +1 -0
  90. package/dist/{tool-FZ4UXMON.js → tool-EVQBMGJV.js} +2 -2
  91. package/dist/{tool-UC7OZWIB.js → tool-XH5QN6JM.js} +2 -2
  92. package/dist/wiki-BPOTYAQV.js +2 -0
  93. package/dist/wiki-enrich-JCNGRYQZ.js +2 -0
  94. package/package.json +1 -1
  95. package/dist/absorb-eval-MT3ZDYBM.js +0 -2
  96. package/dist/agent-SUAQ7EBM.js +0 -2
  97. package/dist/board-dashboard-4C77NLY5.js.map +0 -1
  98. package/dist/chunk-2QNT5JDS.js +0 -4
  99. package/dist/chunk-2QNT5JDS.js.map +0 -1
  100. package/dist/chunk-6QLRRSKU.js.map +0 -1
  101. package/dist/chunk-7UIK4S6T.js +0 -128
  102. package/dist/chunk-7UIK4S6T.js.map +0 -1
  103. package/dist/chunk-A2D3PNDA.js +0 -578
  104. package/dist/chunk-A2D3PNDA.js.map +0 -1
  105. package/dist/chunk-AE3U4GR6.js +0 -181
  106. package/dist/chunk-AE3U4GR6.js.map +0 -1
  107. package/dist/chunk-APPTSTL5.js +0 -2
  108. package/dist/chunk-APPTSTL5.js.map +0 -1
  109. package/dist/chunk-B6GVATMI.js +0 -92
  110. package/dist/chunk-B6GVATMI.js.map +0 -1
  111. package/dist/chunk-LM3K7U6H.js.map +0 -1
  112. package/dist/chunk-XJYGMCAV.js.map +0 -1
  113. package/dist/chunk-YQ25AGX6.js +0 -8
  114. package/dist/chunk-YQ25AGX6.js.map +0 -1
  115. package/dist/client-6ZHYSQU6.js +0 -2
  116. package/dist/config-WCEFYQL4.js +0 -2
  117. package/dist/config-mutate-LW366SKL.js +0 -2
  118. package/dist/config-mutator-NRHZ2XH3.js +0 -2
  119. package/dist/heal-KCM6JYUK.js +0 -2
  120. package/dist/hub-4ODFNGHL.js +0 -2
  121. package/dist/memory-extract-4JFORU2K.js +0 -2
  122. package/dist/program-6YMRDLHO.js.map +0 -1
  123. package/dist/query-QVK5EN3P.js +0 -2
  124. package/dist/registry-BYIWNEFL.js +0 -2
  125. package/dist/routing-HCSXNUOY.js +0 -2
  126. package/dist/schedule-tool-LJYBLCLV.js +0 -2
  127. package/dist/scheduler-74MXJLQS.js +0 -2
  128. package/dist/wiki-KNSPJT2O.js +0 -2
  129. package/dist/wiki-enrich-RVRTAQQF.js +0 -2
  130. /package/dist/{App-UOZT7MWS.js.map → App-GK5F6QMB.js.map} +0 -0
  131. /package/dist/{ChatApp-N7REHHH3.js.map → ChatApp-4HHJB4HM.js.map} +0 -0
  132. /package/dist/{absorb-eval-MT3ZDYBM.js.map → absorb-eval-PO7TUGT2.js.map} +0 -0
  133. /package/dist/{agent-SUAQ7EBM.js.map → agent-6WKET7JZ.js.map} +0 -0
  134. /package/dist/{chunk-NHWYEIET.js.map → chunk-5PEXL5LD.js.map} +0 -0
  135. /package/dist/{chunk-L7RPH3T7.js.map → chunk-5QI7XFTA.js.map} +0 -0
  136. /package/dist/{chunk-TCC56PYX.js.map → chunk-BAXGL6TY.js.map} +0 -0
  137. /package/dist/{chunk-JMZNI257.js.map → chunk-BRQKV4FC.js.map} +0 -0
  138. /package/dist/{chunk-B7QHC7N4.js.map → chunk-CBXPIKPJ.js.map} +0 -0
  139. /package/dist/{chunk-33KKV3YU.js.map → chunk-COMJ7R5T.js.map} +0 -0
  140. /package/dist/{chunk-7FH2FEFA.js.map → chunk-DCJHCUEQ.js.map} +0 -0
  141. /package/dist/{chunk-QLJ3OMPL.js.map → chunk-E67Z6OYF.js.map} +0 -0
  142. /package/dist/{chunk-G3T73GGF.js.map → chunk-HFSPH5WM.js.map} +0 -0
  143. /package/dist/{chunk-IJZNM5PS.js.map → chunk-JKMFMW3E.js.map} +0 -0
  144. /package/dist/{chunk-YKHK47G5.js.map → chunk-KWY5IBII.js.map} +0 -0
  145. /package/dist/{chunk-TM2TPQKH.js.map → chunk-LE3BXIUF.js.map} +0 -0
  146. /package/dist/{chunk-BQXKTQCX.js.map → chunk-PIJ6ECBC.js.map} +0 -0
  147. /package/dist/{chunk-LQTTLXZY.js.map → chunk-S34KFBMJ.js.map} +0 -0
  148. /package/dist/{chunk-XML72AUF.js.map → chunk-TVGVQABC.js.map} +0 -0
  149. /package/dist/{chunk-7O43PB6O.js.map → chunk-U4PICSLC.js.map} +0 -0
  150. /package/dist/{chunk-AFLZHY5Y.js.map → chunk-U5SJLLXH.js.map} +0 -0
  151. /package/dist/{chunk-BNOGNRAM.js.map → chunk-VD2P4GWU.js.map} +0 -0
  152. /package/dist/{chunk-64POGFQZ.js.map → chunk-YQM6VR6U.js.map} +0 -0
  153. /package/dist/{chunk-QGKNDGH5.js.map → chunk-Z6ZR2ELO.js.map} +0 -0
  154. /package/dist/{chunk-SXKC2LH7.js.map → chunk-ZTIOHZIL.js.map} +0 -0
  155. /package/dist/{client-6ZHYSQU6.js.map → client-DOIYODET.js.map} +0 -0
  156. /package/dist/{compaction-VN3M5YGZ.js.map → compaction-26OHHULF.js.map} +0 -0
  157. /package/dist/{config-WCEFYQL4.js.map → config-3UBJRE5R.js.map} +0 -0
  158. /package/dist/{config-mutate-LW366SKL.js.map → config-mutate-ZRPDYJKN.js.map} +0 -0
  159. /package/dist/{config-mutator-NRHZ2XH3.js.map → config-mutator-B5MR3V4B.js.map} +0 -0
  160. /package/dist/{context-planner-2XBAPQ3S.js.map → context-planner-CVCRW5TV.js.map} +0 -0
  161. /package/dist/{contributions-MUCJKT73.js.map → contributions-2CJFYRZ7.js.map} +0 -0
  162. /package/dist/{doctor-2N2MX5YP.js.map → doctor-OQZMDL5S.js.map} +0 -0
  163. /package/dist/{follow-up-tool-W64LMQQN.js.map → follow-up-tool-PQUPXQQT.js.map} +0 -0
  164. /package/dist/{grants-YGA654NI.js.map → grants-4O2VF2YX.js.map} +0 -0
  165. /package/dist/{heal-KCM6JYUK.js.map → heal-ZS56MC4A.js.map} +0 -0
  166. /package/dist/{hub-4ODFNGHL.js.map → hub-LOW7KS5N.js.map} +0 -0
  167. /package/dist/{memory-extract-4JFORU2K.js.map → memory-extract-NLVLQE7V.js.map} +0 -0
  168. /package/dist/{promote-OUSVJZ64.js.map → promote-ZWQAL3RE.js.map} +0 -0
  169. /package/dist/{providers-VVT2OBXA.js.map → providers-F5GDJSYD.js.map} +0 -0
  170. /package/dist/{query-QVK5EN3P.js.map → query-N4EJ24LW.js.map} +0 -0
  171. /package/dist/{query-settings-2TNLXEL5.js.map → query-settings-RZV5ELLC.js.map} +0 -0
  172. /package/dist/{registry-BYIWNEFL.js.map → registry-EBYOZK3P.js.map} +0 -0
  173. /package/dist/{request-planner-7HEHLPA3.js.map → request-planner-KCG6QB6M.js.map} +0 -0
  174. /package/dist/{review-candidates-NJNMSOCX.js.map → review-candidates-3GHWVJQ3.js.map} +0 -0
  175. /package/dist/{routing-HCSXNUOY.js.map → routing-XULOU6BI.js.map} +0 -0
  176. /package/dist/{schedule-tool-LJYBLCLV.js.map → schedule-tool-ALZXDGGC.js.map} +0 -0
  177. /package/dist/{scheduler-74MXJLQS.js.map → scheduler-SCVCNKJC.js.map} +0 -0
  178. /package/dist/{seat-CAYDECW2.js.map → seat-PD7W3KAN.js.map} +0 -0
  179. /package/dist/{select-QUVE6RN2.js.map → select-Z3YXBGUP.js.map} +0 -0
  180. /package/dist/{set-enabled-BWJN4IVG.js.map → set-enabled-NJYJWDWH.js.map} +0 -0
  181. /package/dist/{tool-FZ4UXMON.js.map → tool-EVQBMGJV.js.map} +0 -0
  182. /package/dist/{tool-UC7OZWIB.js.map → tool-XH5QN6JM.js.map} +0 -0
  183. /package/dist/{wiki-KNSPJT2O.js.map → wiki-BPOTYAQV.js.map} +0 -0
  184. /package/dist/{wiki-enrich-RVRTAQQF.js.map → wiki-enrich-JCNGRYQZ.js.map} +0 -0
@@ -0,0 +1,580 @@
1
+ import{a as Oe}from"./chunk-GTJIKXDB.js";import{C as yn,J as vn,k as O}from"./chunk-PIJ6ECBC.js";import{a as w}from"./chunk-VUEQ4SL5.js";import{b as wn}from"./chunk-2VDO2HEK.js";import{f as kn,i as Sn,k as Ne,l as Le,n as K,o as q,q as xn}from"./chunk-LQS27HSV.js";import{t as hn,u as bn}from"./chunk-ZTIOHZIL.js";import{d as fn,e as mn}from"./chunk-AQASR6KR.js";import{a as on,b as an,d as ln,e as cn}from"./chunk-MNG2AMKZ.js";import{h as X,j as un,l as dn,m as pn,n as gn}from"./chunk-RX5O5637.js";import{h as en,i as tn,j as nn,l as rn,m as sn}from"./chunk-LXW7H4D4.js";import{a as Zt,c as Qt}from"./chunk-KP7KDLZ2.js";import{b as Te,qa as Yt,sa as ae,ta as De,va as Ce}from"./chunk-EEM433JK.js";import{r as Jt}from"./chunk-KMPUUH5R.js";import{a as Kt,b as Gt}from"./chunk-HFSPH5WM.js";import{a as Xt}from"./chunk-QUFIUXMQ.js";import{ba as Wt,bb as Ie,ca as qt,ea as jt,fa as Vt,kb as Bt,lb as Ht,p as ie,q as Ut,r as Ft,s as Gs,ub as zt}from"./chunk-NKCS6EZ7.js";import{a as _e,h as Js}from"./chunk-BRK6M6LA.js";import{j as Ae,r as Ys}from"./chunk-UEEB3UTU.js";import{existsSync as Zs,readdirSync as Qs,readFileSync as eo,statSync as to}from"fs";import{resolve as no}from"path";function $n(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),u=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?u.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:u.length,failed:c,paused:d}}).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 le=new Map;function Ac(t,e=1e3){if(!Zs(t))return[];let n=Qs(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=no(t,o);return{path:i,mtime:to(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of le.keys())r.has(o)||le.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=le.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=ro(o,i);le.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function ro(t,e){try{let n=eo(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 so={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},oo=(t,e,n)=>{try{return Jt(t,e,n)}catch{return null}},Rn=864e5;function Cc(t){let e=t.now??Date.now(),n={...so,...t.thresholds},r=t.nextFire??oo,s=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],u=a.timezone||"UTC",c=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:A(a.id,k.text),trigger:{schedule:A(a.schedule,k.text),timezone:u},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Pe(a.nextRun)??Pe(r(a.schedule,new Date(e),u)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:po(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:En(c),sampledRuns:l.length,flags:[],attention:null};p.flags=_n(p,c,a.schedule,u,null,e,n,r),s.push(An(p))}let o=new Map($n(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 u=l.config??{},c=a.state||"active",d=c==="active",p=(i.get(a.id)??[]).slice().sort((T,Ee)=>Ee.at-T.at),g=p.map(T=>({at:T.at,status:lo(T.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof u.spec=="string"?u.spec:"",x=typeof u.timezone=="string"?u.timezone:"UTC",W={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:A(a.title||a.id,k.text),trigger:m?{schedule:A(b,k.text),timezone:x}:{event:A(typeof u.event=="string"?u.event:"",k.text),filters:uo(u.filter,a)},agent:co(a),enabled:d,state:c,nextRunAt:m&&d&&b?Pe(r(b,new Date(e),x)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let T=g.find(Ee=>Ee.status==="success");return T?new Date(T.at).toISOString():null})(),consecutiveFailures:En(g),sampledRuns:p.length,flags:[],attention:null},oe=Date.parse(a.updated||a.created||"");W.flags=m?_n(W,g,b,x,Number.isFinite(oe)?oe:null,e,n,r):io(W,o.get(a.id)?.state==="dormant",Number.isFinite(oe)?oe:null,e,n),s.push(An(W))}return s.sort(ao).slice(0,k.routines)}function En(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 _n(t,e,n,r,s,o,i,a){let l=[],u=e.length?e[0].at:null;if(!t.enabled){let p=Tn(u,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`}),u===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let c=new Date(u),d=null;for(let p=0;p<i.missedFires&&(d=a(n,c,r),!!d);p++)c=d;return d&&o>d.getTime()+i.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(u).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function io(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Tn(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 Tn(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*Rn?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/Rn)} days`:"Disabled and never ran"}}function An(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 In={critical:0,warning:1,info:2};function ao(t,e){let n=t.attention?In[t.attention]:3,r=e.attention?In[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function lo(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 co(t){if(t.ownerAgent)return A(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?A(String(e.config.agentId),k.text):null}function uo(t,e){let n=[],r=e?.project;if(r&&n.push(A(`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(A(`${s}=${i.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Pe(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function A(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function po(t,e){return t===void 0?void 0:A(t,e)}import{mkdirSync as go,readFileSync as fo,renameSync as mo,writeFileSync as ho}from"fs";import{resolve as bo}from"path";function Dn(t){return bo(Le(t),"_state.json")}function v(t){try{let e=JSON.parse(fo(Dn(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 G(t,e){go(Le(t),{recursive:!0});let n=Dn(t),r=`${n}.${process.pid}.tmp`;ho(r,JSON.stringify(e,null,2)+`
3
+ `),mo(r,n)}function Cn(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(),G(t,{...s,snoozed:o})}function Mc(t,e){G(t,{...v(t),lastDigest:e})}function Me(t,e,n,r=Date.now()){let s=v(t),o=new Set(n),i={};for(let[l,u]of Object.entries(s.popped??{}))o.has(l)&&(i[l]=u);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(l=>l!==e&&o.has(l));G(t,{...s,popped:i,wanted:a})}function Nn(t,e){let n=v(t);G(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Uc(t,e=Date.now()){G(t,{...v(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as yo,readFileSync as wo}from"fs";zt();Js();function Ln(t){let e=Kt(t),n={};if(yo(e))try{n=Bt(JSON.parse(wo(e,"utf-8")))}catch{n={}}let r=Ie.safeParse(n?.requests);return r.success?r.data:Ie.parse(void 0)}async function Bc(t,e={}){let n=(t.channels??[]).filter(r=>!_e.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[..._e].join(", ")}`}:Gt(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 Y,readdirSync as qo,readFileSync as qe}from"fs";import{dirname as jo,resolve as $}from"path";import{randomBytes as Mn}from"crypto";import{existsSync as So,mkdirSync as xo,readdirSync as vo,readFileSync as $o,renameSync as Un,unlinkSync as Ro,writeFileSync as Eo}from"fs";import{resolve as Fn}from"path";function On(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ko=t=>t.trim().split(`
4
+ `).pop()?.slice(0,300)||"no output";async function Pn(t,e,n,r=Oe){let s=await r(t.bin,[...On(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ko(s.stderr||s.stdout)}`}}async function Xc(t,e,n,r,s=Oe){return(await s(t.bin,[...On(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var _o=2e3,Ao=t=>Pn(t.wacli,t.to,t.text);function Ue(t){return Fn(t,".agentx","whatsapp-triage","drafts")}var Io=t=>/^[a-z0-9-]{8,64}$/.test(t),ce=(t,e)=>Fn(Ue(t),`${e}.json`);function Wn(t,e){xo(Ue(t),{recursive:!0});let n=ce(t,e.id),r=`${n}.${process.pid}.tmp`;Eo(r,JSON.stringify(e,null,2)+`
5
+ `,{mode:384}),Un(r,n)}function Qc(t,e,n=Date.now()){let r=e.text.trim().slice(0,_o);if(!r)throw new Error("empty draft");let s={...e,text:r,id:`${n.toString(36)}-${Mn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Wn(t,s),s}function ue(t,e){if(!Io(e))return null;try{return JSON.parse($o(ce(t,e),"utf-8"))}catch{return null}}function qn(t,e){let n=Ue(t);return So(n)?vo(n).filter(r=>r.endsWith(".json")).map(r=>ue(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,s)=>r.created_at.localeCompare(s.created_at)):[]}async function jn(t,e,n,r={}){let s=ue(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let o=`${ce(t,e)}.${process.pid}.${Mn(3).toString("hex")}.claim`;try{Un(ce(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??Ao)(s).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Wn(t,i);try{Ro(o)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as Do,writeFileSync as Co}from"fs";import{resolve as Bn}from"path";function Fe(t,e,n,r){let s=t.agents?.[e];if(!s)return null;let o=s.integrations;if(!Array.isArray(o))return null;let i=o.find(a=>a.enabled!==!1&&a.kind===n&&(!r||a.label===r));return i?{agentId:e,integration:i}:null}function To(t,e){let r=(t.credentials??{})[e];if(!r)return{status:"no-credential",reason:`integration "${t.label}" has no ${String(e)} configured`};if(e==="auth"&&r==="keyring")return{status:"ok"};if(typeof r=="string"&&/^[A-Z][A-Z0-9_]*$/.test(r)){let s=process.env[r];return s?{status:"ok",value:s,envVar:r}:{status:"env-unset",envVar:r,reason:`env var ${r} is unset (declared by integration "${t.label}")`}}return typeof r=="string"?{status:"ok",value:r}:{status:"no-credential",reason:`unrecognized credential ref shape for ${String(e)}`}}function tu(t,e,n,r,s){let o=Fe(t,e,n,s);return o?To(o.integration,r):{status:"kind-not-found",reason:`agent "${e}" has no integration of kind "${n}"${s?` with label "${s}"`:""}`}}var Hn="ready",No="202510";function Lo(t){let e=t.date??t.created_at.slice(0,10);return Bn(t.workspace,Hn,`${e}-${t.platform}-${t.id}.txt`)}function Vn(t){let e=Lo(t);return Do(Bn(t.workspace,Hn),{recursive:!0}),Co(e,t.text.endsWith(`
6
+ `)?t.text:`${t.text}
7
+ `),e}function zn(t,e,n){let r=Fe(t.config,e,n);if(!r)return null;let s=t.env??process.env,o=r.integration.credentials?.tokenEnv,i=o?s[o]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function Xn(t,e,n){return zn(t,e,n)!==null}async function Oo(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let s=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??No),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!s.ok)throw new Error(`LinkedIn said ${s.status}: ${(await s.text().catch(()=>"")).slice(0,200)}`);let o=s.headers.get("x-restli-id");return o?{url:`https://www.linkedin.com/feed/update/${o}/`}:{}}async function Po(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let s=await r.json().catch(()=>({}));return s.data?.id?{url:`https://x.com/i/web/status/${s.data.id}`}:{}}async function Mo(t,e){let n=zn(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Vn(t)};let r=e.fetch??fetch;try{let s=t.platform==="linkedin"?await Oo(t.text,n,r):await Po(t.text,n,r);return{ok:!0,posted:!0,...s.url?{url:s.url}:{}}}catch(s){let o=Vn(t);return{ok:!1,error:`not posted on ${X[t.platform]}: ${s?.message??s}. Saved to paste by hand: ${o}`,file:o}}}function Kn(t){return e=>Mo(e,t)}Ys();Vt();Vt();var cu=["done","skipped"],Uo=1e3;function Fo(t){t.exec(`
8
+ CREATE TABLE IF NOT EXISTS request_plans (
9
+ request_id TEXT PRIMARY KEY,
10
+ created_by TEXT NOT NULL,
11
+ created_at INTEGER NOT NULL,
12
+ state TEXT NOT NULL,
13
+ finished_at INTEGER,
14
+ notified_at INTEGER,
15
+ FOREIGN KEY (request_id) REFERENCES requests(id) ON DELETE CASCADE
16
+ );
17
+ CREATE INDEX IF NOT EXISTS idx_request_plans_state ON request_plans(state);
18
+ CREATE TABLE IF NOT EXISTS request_plan_steps (
19
+ request_id TEXT NOT NULL,
20
+ idx INTEGER NOT NULL,
21
+ name TEXT NOT NULL,
22
+ kind TEXT NOT NULL,
23
+ agent_id TEXT NOT NULL,
24
+ done_when TEXT NOT NULL,
25
+ state TEXT NOT NULL,
26
+ needs_approval INTEGER NOT NULL DEFAULT 0,
27
+ approval TEXT NOT NULL DEFAULT 'none',
28
+ card_id TEXT,
29
+ message TEXT,
30
+ to_channel TEXT,
31
+ to_chat TEXT,
32
+ to_account TEXT,
33
+ check_url TEXT,
34
+ check_contains TEXT,
35
+ stall_minutes REAL,
36
+ evidence TEXT,
37
+ note TEXT,
38
+ dispatched_at INTEGER,
39
+ updated_at INTEGER NOT NULL,
40
+ nudges INTEGER NOT NULL DEFAULT 0,
41
+ last_nudge_at INTEGER,
42
+ notified_at INTEGER,
43
+ PRIMARY KEY (request_id, idx),
44
+ FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
45
+ );
46
+ CREATE TABLE IF NOT EXISTS request_plan_events (
47
+ request_id TEXT NOT NULL,
48
+ step INTEGER,
49
+ at INTEGER NOT NULL,
50
+ kind TEXT NOT NULL,
51
+ detail TEXT NOT NULL,
52
+ FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
53
+ );
54
+ CREATE INDEX IF NOT EXISTS idx_request_plan_events ON request_plan_events(request_id, at);
55
+ `)}function Jn(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function We(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 Gn(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 Wo={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"},de=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,
56
+ to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at)
57
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{o.run(e,n,s),r.forEach((a,l)=>{let u=l===0,c=u&&a.agentId===n&&a.kind!=="message";i.run(e,l+1,a.name,a.kind,a.agentId,a.doneWhen,u?"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?We(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(Gn)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?Gn(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(We)}updateStep(e,n,r){let s=[],o=[];for(let[i,a]of Object.entries(r)){let l=Wo[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(We)}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,Uo))}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}))}},uu=Wt;var Qn=["card","schedule","memory","wiki","whatsapp","content","request"],Vo=280;function P(t,e=Vo){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function J(t){if(t.configPath)return $(t.configPath);let e=[$(t.root,"agentx.json"),$(t.root,".agentx","config.json")];return e.find(n=>Y(n))??e[0]}function je(t){return t.wikiDir?$(t.wikiDir):$(t.root,".agentx","wiki")}function Bo(t){return q(t.root,"pending").map(Ho)}function Ho(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:P([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function zo(t){let e=J(t);if(!Y(e))return[];let n;try{n=JSON.parse(qe(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",u=i.schedule?en(i.schedule):"",c=i.schedule?`${u.charAt(0).toLowerCase()}${u.slice(1)} (${i.schedule})`:"no schedule",d=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:P(`${d}${p&&i.schedule?` \xB7 first run ${nn(tn(i.schedule,l,r),l)}`:""}`),more:"agentx schedule list"})}return s}function er(t){let e=$(t,".agentx","memory");return Y(e)?qo(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Xo(t){let e=er(t.root);if(e.length===0)return[];let n=new Te(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:P(o.content),more:`agentx memory facts held --agent ${s}`});return r}function Ko(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 Go(t){return mn(je(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:P(`${Ko(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function Jo(t){return qn(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:P(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function tr(t){try{return JSON.parse(qe(J(t),"utf-8"))}catch{return{}}}function nr(t){let e={};try{e=Object.fromEntries(Xt(qe($(jo(J(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function Yo(t){let e=pn(t.root,"pending");if(e.length===0)return[];let n=tr(t),r=nr(t);return e.map(s=>{let o=X[s.platform]??s.platform;return{key:`content:${s.id}`,kind:"content",title:`${o} post${s.topic?`: ${s.topic}`:""}${s.date?` (for ${s.date})`:""}`,ask:`Publish this on ${o}? "${s.text}"`,yes:Xn({config:n,env:r},s.agent,s.platform)?`post it on ${o}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:s.agent,created_at:s.created_at,detail:P(`Follows your past posts: ${s.samples.join(", ")}`),more:`agentx content show ${s.id}`,text_hash:un(s.text)}})}function M(t){if(t.requests)return t.requests;if($(t.root)!==process.cwd()||!Y($(t.root,".agentx","db.sqlite")))return null;let e=Ae({quiet:!0});if(!e)return null;let n=Yn.get(e);return!n&&!qt(e)?null:(n||Yn.set(e,n=new jt(e)),n)}var Yn=new WeakMap;function Iu(t){if(t.plans)return t.plans;if(t.requests||$(t.root)!==process.cwd()||!Y($(t.root,".agentx","db.sqlite")))return null;let e=Ae({quiet:!0});if(!e||!Jn(e))return null;let n=Zn.get(e);return n||Zn.set(e,n=new de(e)),n}var Zn=new WeakMap;function Zo(t){let e=M(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:P(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var rr={card:Bo,schedule:zo,memory:Xo,wiki:Go,whatsapp:Jo,content:Yo,request:Zo};function Qo(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 sr(t,e={}){let n=t.now??Date.now(),{snoozed:r}=v(t.root),s=[],o=[],i=0;for(let a of e.kinds??Qn){let l;try{l=rr[a](t)}catch(u){o.push({kind:a,error:String(u?.message??u).slice(0,200)});continue}for(let u of l){let c=r[u.key];if(c&&Date.parse(c)>n){if(!e.includeSnoozed){i++;continue}u.snoozed_until=c}s.push(u)}}return s.sort(Qo),{items:s,snoozed:i,errors:o}}function ei(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!Qn.includes(n)||!r?null:{kind:n,ref:r}}function ti(t,e,n){switch(e){case"card":return K(t.root,n)?.status==="pending";case"wiki":return fn(je(t),n)?.status==="pending";case"whatsapp":return ue(t.root,n)?.status==="pending";case"content":return dn(t.root,n)?.status==="pending";default:return rr[e](t).some(r=>r.key===`${e}:${n}`)}}async function or(t,e,n,r={}){let s=ei(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(!ti(t,o,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,d=new Date(a+c*36e5);return Cn(t.root,e,d,a),{ok:!0,message:`${e} put off until ${d.toISOString()}`}}let u=n==="yes";switch(o){case"card":{let c=xn(t.root,i,u?"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 ${u?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(u?rn:sn)(i,{configPath:J(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 d=i.slice(0,c),p=i.slice(c+1);if(!er(t.root).includes(d))return{ok:!1,error:`no memory for agent "${d}"`};let g=new Te(t.root);return g.held(d).some(f=>f.id===p)?(g.review(d,p,u?"approved":"rejected",l),{ok:!0,message:`${e} ${u?"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=je(t),d=u?hn(c,i,{by:l,force:r.force,now:a}):bn(c,i,{by:l,reason:r.note,now:a});return d.ok?{ok:!0,message:u?`${d.proposal.article.path} written to the shared wiki`:`${e} rejected`}:d}case"whatsapp":{let c=await jn(t.root,i,u?"yes":"no",{by:l,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:u?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"content":{let c=t.publishContent??Kn({config:tr(t),env:nr(t)}),d=await gn(t.root,i,u?"yes":"no",{by:l,now:a,text:r.text,seen:r.seen,publish:c});if(!d.ok)return d;if(!u)return{ok:!0,message:`${e}: dropped, nothing published`};let p=X[d.draft.platform];return{ok:!0,message:d.draft.status==="posted"?`${e}: posted on ${p}${d.draft.url?` (${d.draft.url})`:""}`:`${e}: no ${p} connector is set, so it is saved ready to paste: ${d.draft.file}`}}case"request":{let c=M(t),d=c?.get(i);return!c||!d||d.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:u?Ln(J(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${d.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 ni=3,ri=7,si=50,Be=120,oi=280,Ve=600,ar=36e5,ii=24*ar;function Cu(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 pe=t=>new Date(t).toISOString();function ai(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,Be),...e.ask?{ask:j(e.ask,Ve)}:{},...e.detail?{facts:j(e.detail,oi)}:{},...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 li={done:"Done",declined:"Declined",dropped:"Dropped"};function lr(t,e,n){let{record:r,links:s}=e,o=O(r,Be),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,Ve)}:{},agent:r.agentId,askedAt:pe(r.createdAt),changedAt:pe(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,Ve)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=s.some(u=>u.kind==="run"&&!!t.liveRuns?.has(u.ref)),l=t.now-r.updatedAt<(t.quietHours??ni)*ar;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:pe(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:li[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function ci(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 ui(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:j(e.title,Be),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:ci(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var R=t=>t&&Date.parse(t)||0,ir=(t,e)=>t.map(n=>n[e]).filter(n=>!!R(n)).sort((n,r)=>R(n)-R(r))[0];function He(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(ai(s,o,s.node===t.node))}let r=cr(t,e);for(let s of t.requests??[]){let o=lr(t,s,r);o?.column==="yours"&&e.push(o)}return{cards:e,errors:n}}function cr(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Nu(t){let e=He(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=cr(t,n),o=[],i=[],a=[];for(let p of t.requests??[]){let g=lr(t,p,s);g&&g.column!=="yours"&&{agent:o,quiet:i,done:a}[g.column].push(g)}let l=t.now-(t.doneDays??ri)*ii;for(let p of t.cards)p.status!=="pending"&&R(p.decided_at)>=l&&a.push(ui(t,p));o.sort((p,g)=>R(g.changedAt)-R(p.changedAt)),i.sort((p,g)=>R(p.changedAt)-R(g.changedAt)),a.sort((p,g)=>R(g.changedAt)-R(p.changedAt));let u=a.filter(p=>R(p.changedAt)>=l).slice(0,si),c=ir(n,"askedAt"),d=ir(i,"changedAt");return{ts:pe(t.now),cards:[...n,...o,...i,...u],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:o.length},quiet:{count:i.length,...d?{oldest:d}:{}},done:{count:u.length}},errors:r}}function di(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 pi(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 Mu(t,e){let n=t.now??Date.now(),r=[],s=sr(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=M(t);c&&(a=c.listByState("waiting_owner").map(d=>({record:d,links:c.links(d.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:l,errors:u}=He({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:o.map(di)}],requests:a,deferred:i});return pi(l,i.size,[...r,...u])}import{readFileSync as gi}from"fs";var fi=1e4,ur=/^[0-9a-f]{7,64}$/i;function Wu(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&ur.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(fi)})}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"&&ur.test(o.trim())?{source:n,commit:o.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function qu(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=gi(n.tokenFile,"utf-8").trim().split(`
58
+ `)[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 dr=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function Vu(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||t==="/content"||t.startsWith("/content/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||/^\/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 Bu(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/events"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/channels\/[^/]+\/switch$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"||t==="/api/signals/stop-all"||t==="/api/review-gate/replay"}function Hu(t){return dr.has(t)}function zu(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(dr.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 Xu(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 Ku(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 ge(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function mi(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function hi(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function Ju(t,e=hi()){let n=ge(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let s=mi(n),o=[ge(t.host),ge(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return s&&o.includes(s)?"same-origin":"foreign"}let r=ge(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function Yu(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{existsSync as Pr,mkdirSync as Hi,readFileSync as zi,renameSync as Xi,writeFileSync as Ki}from"fs";import{homedir as Gi}from"os";import{dirname as Ji,join as Yi}from"path";import{execFile as _i,execFileSync as Ai}from"child_process";import{execFileSync as bi}from"child_process";import{existsSync as gr,mkdirSync as yi,readdirSync as wi,readFileSync as fr,renameSync as ki,writeFileSync as Si}from"fs";import{homedir as mr}from"os";import{join as Xe}from"path";var E="siri:",hr="com.apple.ttsbundle.gryphon-neural_",br=t=>!!t&&t.startsWith(hr),xi=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],vi=()=>{try{return bi("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},ze;function Ke(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&ze!==void 0)return ze;let{platform:n=process.platform,exists:r=gr,prefDomain:s=vi}=t,o=n==="darwin"&&xi.every(i=>r(i))&&s();return e||(ze=o),o}var yr=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],wr={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"},Ge=t=>wr[t.toLowerCase()]??null;function fe(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 $i=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function Ri(t){let e=new Map;for(let n of t)for(let[,r,s,o]of n.matchAll($i)){let i=`${r}-${s}`,a=`${hr}${o}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:o[0].toUpperCase()+o.slice(1),locale:i,quality:"premium",gender:wr[o]??null,siri:!0})}return[...e.values()]}function me(t=yr,e={}){if(!Ke(e))return[];let n=[];for(let r of t){let s;try{s=wi(r)}catch{continue}for(let o of s)try{n.push(fr(Xe(r,o,"Info.plist"),"latin1"))}catch{}}return Ri(n)}var pr=`#!/bin/sh
59
+ # Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
60
+ # siri-say.sh [voice] < text speak one line. A Siri voice id switches
61
+ # the OS default for it; any other id is
62
+ # passed to say -v.
63
+ # siri-say.sh --stop silence the line speaking, drop the queue.
64
+ # siri-say.sh --restore put back a voice a killed line left switched.
65
+ # AGENTX_SAY_RATE=<words a minute> sets the speed; unset, say's own.
66
+ D=com.apple.Accessibility K=SpokenContentDefaultVoiceSelectionsByLanguage
67
+ dir="$HOME/.agentx/voice" lock="$HOME/.agentx/voice/siri.lock" saved="$HOME/.agentx/voice/siri-saved.plist"
68
+ stops="$dir/stop"
69
+ read_s=\${AGENTX_SAY_READ_S:-5} stale_s=\${AGENTX_SAY_STALE_S:-30} max_s=\${AGENTX_SAY_MAX_S:-300}
70
+ assets=\${AGENTX_SIRI_ASSET_DIRS:-"${yr.join(" ")}"}
71
+ if [ "$1" = --stop ]; then
72
+ mkdir -p "$dir" || exit 1
73
+ # Queued lines see this change and drop. The owner's trap stops say,
74
+ # restores the voice, and frees the lock.
75
+ echo "$$ $(date +%s)" > "$stops"
76
+ owner=$(cat "$lock/pid" 2>/dev/null)
77
+ [ -n "$owner" ] && kill "$owner" 2>/dev/null
78
+ exit 0
79
+ fi
80
+ mode=speak
81
+ [ "$1" = --restore ] && { mode=restore; set --; }
82
+ case "$1" in com.apple.ttsbundle.gryphon-neural_*) siri=$1 voice= ;; *) siri= voice=$1 ;; esac
83
+ rate=\${AGENTX_SAY_RATE:-}
84
+ case "$rate" in *[!0-9]*) rate= ;; esac
85
+ case "$siri" in *[!A-Za-z0-9._-]*) echo "bad voice id" >&2; exit 2;; esac
86
+ # Not macOS, or no pref tools: speak as is and never touch a pref.
87
+ if [ "$(uname)" != Darwin ] || ! command -v defaults >/dev/null || ! command -v plutil >/dev/null; then
88
+ [ "$mode" = restore ] && exit 0
89
+ if [ -n "$voice" ]; then exec say \${rate:+-r "$rate"} -v "$voice"; else exec say \${rate:+-r "$rate"}; fi
90
+ fi
91
+ mkdir -p "$dir" || exit 1
92
+ mine=$(cat "$stops" 2>/dev/null)
93
+ stopped() { [ "$(cat "$stops" 2>/dev/null)" != "$mine" ]; }
94
+ txt=$(mktemp "\${TMPDIR:-/tmp}/agentx-say.XXXXXX") || exit 1
95
+ say_pid= dog=
96
+ restore() {
97
+ [ -f "$saved" ] || return 0
98
+ if [ -s "$saved" ]; then defaults write $D $K "$(cat "$saved")"; else defaults delete $D $K 2>/dev/null; fi
99
+ rm -f "$saved"
100
+ }
101
+ finish() {
102
+ [ -n "$say_pid" ] && kill "$say_pid" 2>/dev/null
103
+ [ -n "$dog" ] && { pkill -P "$dog" 2>/dev/null; kill "$dog" 2>/dev/null; }
104
+ restore; rm -rf "$lock"; rm -f "$txt"; exit "$1"
105
+ }
106
+ drop() { rm -f "$txt"; exit 75; }
107
+ # A Siri voice whose asset macOS purged: switching to it makes the OS
108
+ # speak a fallback of its own (Eloquence Flo), so leave the pref alone.
109
+ if [ -n "$siri" ]; then
110
+ s=\${siri#com.apple.ttsbundle.gryphon-neural_} ; name=\${s%%_*} ; s=\${s#*_} ; loc=$(printf %s "\${s%%_*}" | tr - _)
111
+ found=
112
+ for a in $assets; do
113
+ grep -aqs "com.apple.siri.tts.voice.$loc.$name.neural.premium" "$a"/*/Info.plist && { found=1; break; }
114
+ done
115
+ [ -z "$found" ] && { echo "Siri voice $siri is not installed; speaking with the OS default" >&2; siri=; }
116
+ fi
117
+ # The whole text first, before the lock: a writer that never closes stdin
118
+ # must not hold up every other speaker.
119
+ [ "$mode" = restore ] && exec 0</dev/null
120
+ exec 3<&0 0</dev/null
121
+ cat <&3 > "$txt" & cat_pid=$!
122
+ exec 3<&-
123
+ n=0
124
+ while kill -0 "$cat_pid" 2>/dev/null; do
125
+ if [ $n -ge $((read_s * 10)) ]; then
126
+ kill "$cat_pid" 2>/dev/null; echo "stdin never closed; nothing said" >&2; rm -f "$txt"; exit 3
127
+ fi
128
+ sleep 0.1; n=$((n + 1))
129
+ done
130
+ # One speaker at a time. A lock whose owner died is taken over. A line
131
+ # that waits past stale_s, or that a stop overtook, is dropped unsaid.
132
+ n=0
133
+ while ! mkdir "$lock" 2>/dev/null; do
134
+ stopped && drop
135
+ if [ $n -ge $((stale_s * 10)) ]; then echo "waited \${stale_s}s for the speaker; dropped" >&2; drop; fi
136
+ owner=$(cat "$lock/pid" 2>/dev/null)
137
+ if [ -n "$owner" ] && ! kill -0 "$owner" 2>/dev/null; then rm -rf "$lock"
138
+ elif [ -z "$owner" ] && [ -n "$(find "$lock" -maxdepth 0 -mmin +1 2>/dev/null)" ]; then rm -rf "$lock"
139
+ else sleep 0.1; n=$((n + 1)); fi
140
+ done
141
+ echo $$ > "$lock/pid"
142
+ trap 'finish 143' TERM INT HUP
143
+ stopped && finish 75
144
+ [ "$mode" = restore ] && finish 0
145
+ restore
146
+ if [ -n "$siri" ]; then
147
+ lang=$(defaults read -g AppleLanguages 2>/dev/null | sed -n '2s/^[^A-Za-z]*\\([A-Za-z]*\\).*/\\1/p')
148
+ defaults export $D - 2>/dev/null | plutil -extract $K xml1 -o "$saved.tmp" - 2>/dev/null || : > "$saved.tmp"
149
+ mv "$saved.tmp" "$saved"
150
+ defaults write $D $K -array "\${lang:-en}" "{ _type = \\"Speech.VoiceSelection\\"; _version = 0; voiceId = \\"$siri\\"; }"
151
+ fi
152
+ # A watchdog: no line runs past its length's worth of speech (a hung say
153
+ # held the lock for minutes), capped at max_s.
154
+ limit=$((5 + $(wc -w < "$txt") * 6 / 10))
155
+ [ $limit -gt $max_s ] && limit=$max_s
156
+ if [ -n "$voice" ]; then say \${rate:+-r "$rate"} -v "$voice" -f "$txt" & else say \${rate:+-r "$rate"} -f "$txt" & fi
157
+ say_pid=$!
158
+ ( sleep "$limit"; echo "say ran past \${limit}s; stopped" >&2; kill "$say_pid" 2>/dev/null ) & dog=$!
159
+ wait "$say_pid"
160
+ status=$?
161
+ say_pid=
162
+ finish $status
163
+ `,Ei=(t=mr())=>Xe(t,".agentx","voice","siri-say.sh");function kr(t=mr()){let e=Ei(t);return gr(e)&&fr(e,"utf8")===pr||(yi(Xe(t,".agentx","voice"),{recursive:!0}),Si(`${e}.tmp`,pr,{mode:493}),ki(`${e}.tmp`,e)),e}var Sr=`ObjC.import("AVFoundation")
164
+ const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
165
+ for (let i = 0; i < vs.count; i++) {
166
+ const v = vs.objectAtIndex(i)
167
+ out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
168
+ }
169
+ out.join("\\n")`,Ii=new Set(["Fred","Kathy","Ralph","Junior"]),Ti={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 xr(t){let e=[];for(let n of t.split(`
170
+ `)){let[r,s,o,i,a]=n.split(" ");!r||!s||!o||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!Ii.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":Ti[s]??null})}return e}var Di=10*60*1e3,id=60*1e3,V=null,Je=!1;function Ye(t=Date.now(),e=Di){if(process.platform!=="darwin")return[];if(V)t-V.at>e&&!Je&&(Je=!0,_i("osascript",["-l","JavaScript","-e",Sr],{timeout:1e4},(n,r)=>{Je=!1,n||(V={at:Date.now(),voices:[...xr(String(r)),...me()]})}));else try{V={at:t,voices:[...xr(Ai("osascript",["-l","JavaScript","-e",Sr],{encoding:"utf8",timeout:1e4})),...me()]}}catch(n){Ze(`[voice] could not list system voices: ${String(n?.message??n).split(`
171
+ `)[0]}`),V={at:t,voices:me()}}return V.voices}var Ze=t=>process.stderr.write(t+`
172
+ `),he=new Set;function ad(t){Ze=t}function U(t,e){he.has(t)||(he.add(t),Ze(e))}function Rr(t){for(let e of he)t(e)&&he.delete(e)}var Er=()=>{};function ld(t){Er=t}function _r(t){try{Er(t)}catch(e){U("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var Ci={premium:3,enhanced:2,standard:1},Ni=new Set(["Grandma","Grandpa"]);function vr(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!Ni.has(t.name)?1:0;return Ci[t.quality]*10+e}var B=t=>t.toLowerCase().split(/[-_]/)[0],$r=t=>t.id.startsWith("com.apple.voice.");function Qe(t,e,n,r=new Set){let s=Z(t.filter(a=>!a.siri&&B(a.locale)===B(e)),e);if(s.some($r)&&(s=s.filter($r)),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 Z(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)=>vr(i)-vr(o)||+(i.locale.toLowerCase()===n)-+(o.locale.toLowerCase()===n)||o.name.localeCompare(i.name)||o.locale.localeCompare(i.locale))}function Q(t,e,n="en"){let r=t.trim();if(!r)return null;let s=e.find(u=>u.id===r);if(s)return s;if(r.toLowerCase().startsWith(E)){let u=r.slice(E.length).trim().toLowerCase(),c=Z(e.filter(p=>p.siri&&p.name.toLowerCase()===u),n)[0];if(c||!u)return c??null;let d=Q(u,e.filter(p=>B(p.locale)===B(n)),n);return d&&U(`siri:${u}`,`[voice] Siri voice "${u}" is not installed; speaking with ${d.name} (${d.locale}) instead.`),d}e=e.filter(u=>!u.siri);let o=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(o?o[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=Z(e.filter(u=>u.name.toLowerCase()===i),n);return(o?a.find(u=>u.quality===o[2].toLowerCase()):void 0)??a[0]??null}function Ar(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,u=e.filter(d=>!s.has(d.name.toLowerCase())),c=u.find(d=>d.gender===l)??(a?e.find(d=>d.gender===l):void 0)??u[0]??e[r.size%e.length];r.set(i.id,c),s.add(c.name.toLowerCase()),a||(o=o==="female"?"male":"female")}return r}Ut();var et="system",Li=t=>t.trim().toLowerCase()===et,Oi="21m00Tcm4TlvDq8ikWAM";function tt(t,e,n={},r=Ye()){let s=e[t],o=s?.name||t,i=s?.voice,a=rt(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?ye(a):null,systemByLanguage:l,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||qi(o,s?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var ye=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function Pi(t,e,n,r){if(!e||!n.length)return null;let s=Q(e,n,r);return s||(U(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),_r(e)),s}function Cr(t,e){let n=t.trim();if(n.toLowerCase().startsWith(E))return{locale:e,gender:Ge(n.slice(E.length).trim())};let r=fe(n);return r?{locale:r.locale,gender:Ge(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var Nr=t=>t.toLowerCase().split(/[-_]/)[0],Ir=(t,e)=>typeof t=="string"?t:t?.[Nr(e)];function be(t,e,n,r){if(e!==void 0)return Li(e)?null:Pi(t,e,n,r)??void 0}var nt=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function Mi(t,e,n,r=new Set){let s=e.locale??"en",o=new Map,i=[],a=be("voice.system",Ir(e.system,s),n,s),l=()=>new Set([...r,...[...o.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let d=Ir(c.system,s),p=be(c.id,d,n,s),g=p!==void 0?p:d!==void 0&&n.length?Ui(c,d,s,a,n,l()):a!==void 0&&nt(a,c.gender)?a:void 0;g!==void 0?o.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let u=l();for(let[c,d]of Ar(i,Z(n.filter(p=>!p.siri),s),u))o.set(c,d);return o}function Ui(t,e,n,r,s,o){for(let a of t.fallbacks??[]){let l=be(`${t.id}.fallbacks`,a,s,n);if(l!==void 0)return l}if(r!==void 0&&nt(r,t.gender))return r;let i=Cr(e,n);return Qe(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,u)=>{if(!(!l||typeof l=="string"))for(let[c,d]of Object.entries(l)){let p=be(`${a}.${c}`,d,s,c);p===void 0&&s.length&&(p=Qe(s,c,n??Cr(d,c).gender)??void 0),p!==void 0&&u(p)&&(o[Nr(c)]=p)}};return i("voice.system",r.system,a=>nt(a,n)),i(t,e,()=>!0),o}function gd(t,e){let n=e?ie(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?ye(r):null}}function rt(t,e={},n=Ye()){let r=Object.entries(t).map(([s,o])=>({id:s,system:o.voice?.system,gender:o.voice?.gender,fallbacks:o.voice?.fallbacks}));return Mi(r,e,n)}function st(t,e){let n={provider:t.provider,elevenlabs:Wi(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 Wi(t,e){return t||e||process.env.AGENTX_VOICE_ID||Oi}function qi(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 ji=8*60*60*1e3,Vi=500,Tr=class{constructor(e=ji){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let s=this.lastSpoke.get(Dr(e,n));return s===void 0||r-s>this.gapMs}spoke(e,n,r=Date.now()){let s=Dr(e,n);this.lastSpoke.delete(s),this.lastSpoke.set(s,r),this.lastSpoke.size>Vi&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},Dr=(t,e)=>`${t}\0${e}`;function Lr(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 fd(t,e,n,r={}){let s=e[t],o=tt(t,e,r),i=(s?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:o.name,voice:st(o),persona:i||`You are ${o.name}.`,introLine:Lr(o,n)}}var Bi="[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 md(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`${Bi}
173
+ ${Lr(s,e.voice.introduce===!0&&!!r)}`}var Zi="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Mr=(t=Gi())=>Yi(t,".agentx","voice","health.json");function Qi(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===et)return!0;if(r.toLowerCase().startsWith(E)){let s=r.slice(E.length).trim().toLowerCase();return e.some(o=>o.siri&&o.name.toLowerCase()===s)}return Q(r,e,n)!==null}function ea(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 ta(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:s,name:o,locale:i,perLanguage:a}of ea(t)){if(Qi(o,e,i))continue;r??=rt(t.agents,t.voice,e);let l=n.get(o)??{voice:o,agents:[],speaksWith:{}};l.agents.includes(s)||l.agents.push(s);let u=r.get(s);s!=="voice.system"&&!a&&(l.speaksWith[s]=u?ye(u):"the OS default voice"),n.set(o,l)}return[...n.values()]}function ot(t){let e=fe(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(E)){let n=t.slice(E.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function na(t){let e=t.map(n=>{let r=n.agents.map(s=>n.speaksWith[s]?`${s} (now ${n.speaksWith[s]})`:s).join(", ");return`\u2022 ${ot(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
174
+ `)}
175
+ Reinstall in ${Zi}. Agents switch back on their own once it is installed.`}}function ra(t=Mr()){if(!Pr(t))return null;try{let e=JSON.parse(zi(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function sa(t,e){Hi(Ji(t),{recursive:!0}),Ki(`${t}.tmp`,JSON.stringify(e,null,2)+`
176
+ `),Xi(`${t}.tmp`,t)}var Or=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??Mr(),o=new Map((ra(s)?.missing??[]).map(d=>[d.voice,d])),i=ta(e,n),a=i.map(d=>({...d,since:o.get(d.voice)?.since??r.toISOString(),...o.get(d.voice)?.notifiedAt?{notifiedAt:o.get(d.voice).notifiedAt}:{}})),l=[...o.keys()].filter(d=>!i.some(p=>p.voice===d));for(let d of l)this.deps.log(`[voice] ${ot(d)} is installed again; its agents speak with it again`);l.length&&Rr(d=>l.some(p=>d===p||d.endsWith(`:${p}`)));let u=a.filter(d=>!d.notifiedAt);if(u.length){let{title:d,message:p}=na(u);try{await this.deps.notify(d,p);for(let g of u)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${u.map(g=>ot(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(!Pr(s)||JSON.stringify(a)!==JSON.stringify([...o.values()]))&&sa(s,c),c}finally{this.running=!1}}};import{readFileSync as at,writeFileSync as Vr,existsSync as lt,readdirSync as fa,statSync as ma}from"fs";import{resolve as ct,join as ha}from"path";import{existsSync as Ur,mkdirSync as oa,readFileSync as ia,writeFileSync as Fr}from"fs";import{dirname as aa,resolve as Wr}from"path";import{z as h}from"zod";var la=h.object({type:h.enum(["gitlab","github"]),host:h.string().optional(),project:h.string(),iid:h.number().int().positive(),url:h.string()}),ca=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:la.optional(),importedAt:h.string().optional(),createdAt:h.string(),updatedAt:h.string(),blocker:h.string().optional(),doneNote:h.string().optional()}),ua=h.object({version:h.literal(1),items:h.array(ca).default([])}),we=class{constructor(e){this.path=e}jsonPath(){return Wr(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Wr(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return Ur(this.jsonPath())}load(){let e=this.jsonPath();if(!Ur(e))return{version:1,items:[]};let n=ia(e,"utf-8");try{return ua.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();oa(aa(n),{recursive:!0}),Fr(n,JSON.stringify(e,null,2)+`
177
+ `),Fr(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":" ",u=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",d=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${l}] ${u}${a.title}${c}${d}`),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(`
178
+ `)}};function _d(t){return`${t.type}:${t.project}:${t.iid}`}function qr(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 it(t,e,n,r=()=>{}){return t.source?da(t.source,e,n,r):{ok:!0,attempts:[]}}async function da(t,e,n,r=()=>{}){return t.type==="gitlab"?pa(t,e,n,r):t.type==="github"?ga(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function pa(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||{}}}),u=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 d;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")d=0;else try{let g=await l(`/projects/${u}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let f=await g.json();Array.isArray(f)&&f[0]?.id&&(d=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),d!==void 0&&(p.milestone_id=d),e.state&&(p.state_event=e.state==="closed"?"close":"reopen"),Object.keys(p).length)try{let g=await l(`/projects/${u}/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/${u}/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 ga(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,u;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")u=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&&(u=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 d={};if(e.title!==void 0&&(d.title=e.title),e.description!==void 0&&(d.body=e.description),c!==void 0&&(d.labels=c),e.assigneeUsernames!==void 0&&(d.assignees=e.assigneeUsernames),u!==void 0&&(d.milestone=u),e.state&&(d.state=e.state),Object.keys(d).length)try{let p=await a(`/repos/${l}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(d)});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 ut=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,ke=/@([a-z0-9_-]+)/i,jr=/\[time:\s*([0-9hm\s]+)\]/i;function ba(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 dt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new we(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=ct(process.cwd(),this.path);return lt(e)?at(e,"utf-8").split(`
179
+ `):[]}writeMd(e){let n=ct(process.cwd(),this.path);Vr(n,e.join(`
180
+ `))}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(ut);if(!o||o[2].toLowerCase()==="x")continue;let a=o[3],l=a.match(ke);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let u=a.match(jr),c=a.replace(ke,"").replace(jr,"").trim();r.push({id:`backlog:${s}`,title:c||`Task at line ${s+1}`,assignee:l?l[1]:void 0,estimatedSeconds:u?ba(u[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=qr([s.assignee||e],s.source,this.daemon);it(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 u={};n.status==="done"?(u.addLabels=["Done"],u.removeLabels=["Doing"]):n.status==="blocked"&&(u.addLabels=["Blocked"]),n.note&&(u.note=n.note),Object.keys(u).length&&it(l,u,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(ut))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"}}},pt=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(lt(e))for(let r of fa(e)){let s=ha(e,r);ma(s).isDirectory()?this.walk(s,n):r.endsWith(".md")&&n.push(s)}}async listOpen(e){let n=[];this.walk(ct(process.cwd(),this.root),n);let r=[];for(let s of n){let o=at(s,"utf-8").split(`
181
+ `);for(let i=0;i<o.length;i++){let a=o[i].match(ut);if(!a||a[2].toLowerCase()==="x")continue;let l=a[3].match(ke);!l||l[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${s}:${i}`,title:a[3].replace(ke,"").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(!lt(o))return;let i=at(o,"utf-8").split(`
182
+ `);n.status==="done"&&i[s]&&(i[s]=i[s].replace(/- \[ \]/,"- [x]"),Vr(o,i.join(`
183
+ `)))}},gt=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(u=>({name:u.name,color:u.color,text_color:u.text_color})),s=o.map(u=>u.name)):s=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(u=>({username:u.username,name:u.name,avatarUrl:u.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}`,u=await this.api(l);for(let c of u){let d=this.mapIssue(c,i);d.assignee=e,r.push(d)}}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(u){this.log(`[business] add_spent_time failed: ${u.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 u of i)try{let c=u==="__ALL__"?`/issues?${s.toString()}`:`/projects/${encodeURIComponent(u)}/issues?${s.toString()}`,d=await this.api(c);for(let p of d)a.push(this.mapIssue(p,u))}catch(c){this.log(`[business] GitLab listAll failed on ${u}: ${c.message}`)}let l=a;if(e.notLabels?.length){let u=new Set(e.notLabels);l=l.filter(c=>!(c.labels||[]).some(d=>u.has(d)))}if(e.withoutScopedPrefix){let u=e.withoutScopedPrefix+"::";l=l.filter(c=>!(c.labels||[]).some(d=>d.startsWith(u)))}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 d=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(d)&&d[0]?.id?d[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 u=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(u)&&u[0]?.id&&(i=u[0].id)}catch(u){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${u.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 u=>{try{let c=await this.api(`/users?username=${encodeURIComponent(u)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${u}: ${c.message}`),null}}))).filter(u=>typeof u=="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 Ld(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new dt(r.path,e,n);case"wiki":return new pt(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 gt(s.host,s.token,i,o,n)}}}var ft="unmapped";function mt(t,e=[]){if(!t)return ft;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 ya(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,mt(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 wa(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 Pd(t,e){let n=wa(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return mt(t.project,e.projects);if(t.agentId){let r=ya(e).get(t.agentId);if(r)return r}return ft}function Md(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 ka=t=>t===ft?"internal":"client";function Sa(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??ka(t),respondWithinMinutes:xa(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function Ud(t){let e=new Set;for(let n of t.projects??[])e.add(mt(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>Sa(n,t))}function xa(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 va}from"crypto";var qd={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},$a=40,Ra=20,jd=90,Ea=2e3,Br=36e5;function _a(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
184
+ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<$a?null:`text:${va("sha256").update(r).digest("hex").slice(0,24)}`}function Vd(t){let e=t.indexOf(`
185
+ `);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function ht(t){t.exec(`
186
+ CREATE TABLE IF NOT EXISTS owner_told (
187
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
188
+ at INTEGER NOT NULL,
189
+ item_key TEXT NOT NULL,
190
+ request_id TEXT,
191
+ kind TEXT NOT NULL,
192
+ channel TEXT NOT NULL,
193
+ chat_id TEXT NOT NULL,
194
+ sender TEXT,
195
+ title TEXT NOT NULL,
196
+ text TEXT NOT NULL,
197
+ outcome TEXT NOT NULL,
198
+ digested_at INTEGER
199
+ );
200
+ CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
201
+ CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
202
+ CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
203
+ `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of Aa)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 Aa=[["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 Se(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 Hr=class{constructor(e){this.db=e;ht(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)
204
+ 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,Ea),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?Se(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?Se(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(Se)}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(Se)}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,
205
+ SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
206
+ SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
207
+ 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}},zr=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=_a(n,e.title,e.text),i=n.kind??"notice",a=(o?.startsWith("text:")?Math.min(r.repeatWindowHours,Ra):r.repeatWindowHours)*Br,l=r.digestNags&&r.digestAvailable!==!1,u="send";!n.urgent&&o&&this.ledger.lastTold(o,s-a,l)?u="repeat":!n.urgent&&i==="nag"&&l&&(u="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:u==="send"?"sent":u,urgent:n.urgent===!0});return{verdict:u,key:o,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:Ia(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*Br)}};function Bd(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 Ia(t,e=5,n=3){let r=new Map;for(let a of t){let[l,...u]=a.title.split(": "),c=u.join(": ").trim(),d=r.get(l.trim())??{count:0,names:[]};d.count++,c&&!d.names.includes(c)&&d.names.push(c),r.set(l.trim(),d)}let s=[...r.entries()].sort((a,l)=>l[1].count-a[1].count),o=s.slice(0,e).map(([a,{count:l,names:u}])=>{let c=u.length?` (${u.slice(0,n).join(", ")}${u.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 Ta=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,Da=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Xr(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(Da)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],s=Ca(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 zd(t){if(!t||!t.includes("agentx:ui"))return t;let e=Ta.exec(t);return e?t.slice(0,e.index).trimEnd():t}function Ca(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 Kd(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 Na=5*6e4;function N(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var Kr=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(),u=a.filter(c=>c.expiresAt>l);for(let{signal:c}of u)this.deliverTo(s,c);this.pending.delete(i),u.length&&this.log(`flushed ${u.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
208
+ data: ${JSON.stringify(n)}
209
+
210
+ `):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+Na),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 La,readFileSync as Gr,renameSync as Oa,rmSync as Pa,writeFileSync as Ma}from"fs";import{homedir as Ua}from"os";import{dirname as Fa,join as Wa}from"path";var Jr=Wa(Ua(),".agentx","call.json");function qa(t=Jr,e=Date.now()){try{let n=JSON.parse(Gr(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 Yr(t=Zt,e=qa){let n=t();return n.active?n:e()}function ep(t,e,n=Jr,r=Date.now()){let s=null;try{s=JSON.parse(Gr(n,"utf-8"))}catch{}if(s&&s.source&&s.source!=="daemon")return;if(!t){s&&Pa(n,{force:!0});return}La(Fa(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;Ma(o,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
211
+ `),Oa(o,n)}var Zr="owner",xe=6e4,rs=60*xe,ja=24*rs,Va=7*24*rs,Ba=2*xe,rp={enabled:!1,escalateAfterMinutes:10,ladder:[]};function Ha(t){t.exec(`
212
+ CREATE TABLE IF NOT EXISTS owner_presence (
213
+ person TEXT NOT NULL,
214
+ surface TEXT NOT NULL,
215
+ at INTEGER NOT NULL,
216
+ PRIMARY KEY (person, surface)
217
+ );
218
+ `)}var Qr=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;Ha(e)}written=new Map;touch(e,n=Zr){let r=this.now(),s=`${n}
219
+ ${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 (?, ?, ?)
220
+ ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=Zr){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function sp(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var es=class{constructor(e,n=Date.now){this.db=e;this.now=n;ht(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
221
+ WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
222
+ ORDER BY at DESC LIMIT 500`).all(this.now()-Va)}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-Ba,o.at).find(u=>u.title===o.title||i!==o.title&&u.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 = ?
223
+ WHERE seen_at IS NULL AND (${ts(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, ?)
224
+ WHERE answered_at IS NULL AND (${ts(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 ts(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 op(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=ee(i);a&&n(a)&&!s.includes(i)&&s.push(i)}return s}function ee(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function za(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function Xa(t){return ee(t)==="push"?["phone","desk"]:[t]}function ip(t,e,n){let r=t.filter(o=>n(ee(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 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(ee(o)))??null}var Ga=3;async function ap(t){let{db:e,ledger:n,settings:r,now:s}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let o=r.escalateAfterMinutes*xe,i=e.prepare(`SELECT id FROM owner_told
225
+ WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
226
+ AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
227
+ AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
228
+ ORDER BY at LIMIT 20`).all(Math.max(s-Ga*o,s-ja),s-o),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),l=0;for(let{id:u}of i){if(a.run(s,u).changes!==1)continue;let c=n.get(u);if(!c)continue;let d=`${c.channel}:${c.chatId}`,p=Ka(t.stops,d,t.up);if(!p){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${d}; no other address to try`);continue}let g=Math.round((s-c.at)/xe),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}
229
+
230
+ `:""}(Sent again here: ${f}.)`,b=n.add({at:s,key:c.key,requestId:c.requestId,kind:c.kind,channel:ee(p),chatId:za(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 ns=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 Ja={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},ss=class{constructor(e=Ja,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)}},Ya="That code didn't work. Check it, or run agentx app pair for a new one.",Za=400;async function up(t,e){let n=Date.now(),r=e.log??(u=>console.log(u)),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 wn(t,1024)).code}catch{}let a=e.codes.redeem(i),l=a?e.verify(a.token):null;return await Qa(n,e.minMs??Za),!a||!l?(e.limiter.fail(s),r(`[app] pair-code failed from ${s}`),{status:401,body:{error:Ya}}):(e.limiter.succeed(s),r(`[app] pair-code paired ${a.tokenId} (${l}) from ${s}`),{status:200,body:{device:l},token:a.token})}async function Qa(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as hl}from"child_process";import{mkdtempSync as cl,rmSync as ul,writeFileSync as dl}from"fs";import{tmpdir as pl}from"os";import{join as cs}from"path";import{randomBytes as el}from"crypto";var D={top:8,side:32,bottom:60},bt={height:56,keep:52},os=`
231
+ :root {
232
+ --ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
233
+ --ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
234
+ --ac-primary: #1e3a8a; --ac-primary-deep: #172554;
235
+ --ac-blue: #1e3a8a; --ac-blue-2: #1d4ed8;
236
+ --ac-accent: #14b8a6; --ac-accent-deep: #0f766e;
237
+ --ac-rim: rgba(11,20,19,.10);
238
+ --ac-shadow: 0 0 0 .5px rgba(11,20,19,.05), 0 24px 48px -16px rgba(11,20,19,.30), 0 2px 6px rgba(11,20,19,.06);
239
+ --ac-lift: 0 12px 40px rgba(30,58,138,.20), 0 2px 6px rgba(11,20,19,.06);
240
+ --ac-font: "Geist", -apple-system, BlinkMacSystemFont, "Noto Sans Arabic", system-ui, sans-serif;
241
+ --ac-mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;
242
+ color-scheme: light;
243
+ }
244
+ [data-theme="dark"] {
245
+ --ac-paper: #111c1b; --ac-soft: #172322; --ac-edge: #263433;
246
+ --ac-text: #e8eeed; --ac-muted: #a7b3b1; --ac-subtle: #83918f;
247
+ --ac-primary: #2563eb; --ac-primary-deep: #1d4ed8;
248
+ --ac-blue: #93c5fd; --ac-blue-2: #60a5fa;
249
+ --ac-accent-deep: #5eead4;
250
+ --ac-rim: rgba(255,255,255,.09);
251
+ --ac-shadow: 0 0 0 .5px rgba(0,0,0,.6), 0 28px 56px -16px rgba(0,0,0,.65), 0 2px 8px rgba(0,0,0,.3);
252
+ color-scheme: dark;
253
+ }
254
+ * { box-sizing: border-box; }
255
+ html, body { margin: 0; background: transparent; }
256
+ body {
257
+ font: 13.5px/1.5 var(--ac-font); color: var(--ac-text); font-feature-settings: "ss01", "cv11";
258
+ -webkit-font-smoothing: antialiased; -webkit-user-select: none; user-select: none; cursor: default;
259
+ }
260
+ .wrap { padding: ${D.top}px ${D.side}px ${D.bottom}px; }
261
+ .card {
262
+ background: var(--ac-paper); border: 1px solid var(--ac-rim); border-radius: 18px;
263
+ box-shadow: var(--ac-shadow); overflow: hidden; animation: ac-in .26s cubic-bezier(.65,0,.35,1);
264
+ position: relative; display: flex; flex-direction: column; max-height: calc(100vh - ${D.top+D.bottom}px);
265
+ }
266
+ .card::before {
267
+ content: ""; position: absolute; top: 6px; left: 50%; width: 32px; height: 4px; margin-left: -16px;
268
+ border-radius: 2px; background: var(--ac-edge);
269
+ }
270
+ @keyframes ac-in { from { transform: translateY(14px); opacity: 0; } }
271
+ .card.still { animation: none; }
272
+ @media (prefers-reduced-motion: reduce) { .card { animation: none; } }
273
+ .head { flex: none; display: flex; align-items: center; gap: 10px; padding: 18px 20px 0; cursor: grab; }
274
+ .body { padding: 14px 20px 16px; min-height: 0; overflow-y: auto; }
275
+ .fold {
276
+ flex: none; width: 24px; height: 24px; display: grid; place-items: center; padding: 0; border-radius: 6px;
277
+ border: 1px solid var(--ac-edge); background: var(--ac-soft); color: var(--ac-subtle); cursor: pointer;
278
+ }
279
+ .fold:hover { color: var(--ac-text); border-color: var(--ac-subtle); }
280
+ .folded .fold svg { transform: rotate(180deg); }
281
+ .folded .body > :not(h1), .folded .foot { display: none; }
282
+ .avatar {
283
+ flex: none; width: 32px; height: 32px; border-radius: 50%; display: grid; place-items: center;
284
+ font-size: 14px; font-weight: 600; color: #fff;
285
+ background: linear-gradient(135deg, var(--ac-blue-2), var(--ac-accent));
286
+ }
287
+ .who { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }
288
+ .who b { font-size: 13.5px; font-weight: 560; letter-spacing: -.008em; line-height: 1.25; }
289
+ .who span { font-size: 12px; line-height: 1.3; color: var(--ac-subtle); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
290
+ .label, .kind, .edited { font-family: var(--ac-mono); font-size: 10.5px; letter-spacing: .06em; text-transform: uppercase; }
291
+ .kind {
292
+ padding: 3px 8px; border-radius: 999px; white-space: nowrap;
293
+ color: var(--ac-muted); background: var(--ac-soft); border: 1px solid var(--ac-edge);
294
+ }
295
+ .kind.decision {
296
+ color: var(--ac-blue); background: color-mix(in oklab, var(--ac-blue-2) 10%, var(--ac-paper));
297
+ border-color: color-mix(in oklab, var(--ac-blue-2) 22%, var(--ac-edge));
298
+ }
299
+ h1 { margin: 0; font-size: 18.5px; line-height: 1.3; font-weight: 540; letter-spacing: -.018em; text-wrap: balance; }
300
+ h1:dir(rtl) { letter-spacing: 0; }
301
+ .context { margin: 6px 0 0; color: var(--ac-muted); white-space: pre-wrap; unicode-bidi: plaintext; text-wrap: pretty; }
302
+ .ask { margin: 10px 0 0; font-weight: 500; unicode-bidi: plaintext; }
303
+ .label-row { margin-top: 16px; display: flex; align-items: center; gap: 8px; min-height: 18px; }
304
+ .label { color: var(--ac-subtle); margin-inline-end: auto; }
305
+ .dot { flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--ac-accent); }
306
+ .rec { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--ac-subtle); }
307
+ .why { margin: 8px 0 0; font-size: 12px; line-height: 1.4; color: var(--ac-subtle); unicode-bidi: plaintext; }
308
+ .options { margin-top: 8px; display: flex; flex-wrap: wrap; gap: 6px; }
309
+ .opt {
310
+ display: inline-flex; align-items: center; gap: 8px; padding: 5px 12px 5px 5px; padding-inline: 5px 12px;
311
+ border-radius: 999px; border: 1px solid var(--ac-edge); background: var(--ac-paper); color: var(--ac-text);
312
+ font: inherit; font-size: 13px; line-height: 1.35; text-align: start; cursor: pointer;
313
+ transition: background .15s ease, border-color .15s ease, transform .15s ease;
314
+ }
315
+ .opt:hover { transform: translateY(-1px); }
316
+ .opt .n {
317
+ flex: none; width: 20px; height: 20px; display: grid; place-items: center; border-radius: 6px;
318
+ border: 1px solid var(--ac-edge); border-bottom-width: 2px; background: var(--ac-soft); color: var(--ac-subtle);
319
+ font-family: var(--ac-mono); font-size: 10.5px;
320
+ }
321
+ .opt .t { unicode-bidi: plaintext; }
322
+ .opt[aria-checked="true"] { background: var(--ac-primary); border-color: var(--ac-primary); color: #fff; }
323
+ .opt[aria-checked="true"] .n { background: rgba(255,255,255,.16); border-color: rgba(255,255,255,.28); color: #fff; }
324
+ .opt[aria-checked="true"] .dot { background: #5eead4; }
325
+ .edited { display: none; align-items: center; gap: 5px; color: var(--ac-accent-deep); }
326
+ .edited .dot { width: 5px; height: 5px; }
327
+ .reset { display: none; border: 0; background: none; padding: 0; font: inherit; font-size: 12px; color: var(--ac-muted); cursor: pointer; }
328
+ .reset:hover { color: var(--ac-text); }
329
+ .touched .edited { display: inline-flex; }
330
+ .touched .reset { display: inline; }
331
+ textarea {
332
+ margin-top: 6px; display: block; width: 100%; min-height: 60px; max-height: 240px; resize: none; overflow-y: auto;
333
+ padding: 10px 12px; border: 1px solid var(--ac-edge); border-radius: 10px; background: var(--ac-soft);
334
+ color: var(--ac-text); font: inherit; line-height: 1.45; outline: none; unicode-bidi: plaintext;
335
+ -webkit-user-select: text; user-select: text; cursor: text; transition: border-color .15s ease, box-shadow .15s ease;
336
+ }
337
+ textarea::placeholder { color: var(--ac-subtle); }
338
+ textarea:focus {
339
+ border-color: var(--ac-accent); background: var(--ac-paper);
340
+ box-shadow: 0 0 0 4px color-mix(in oklab, var(--ac-accent) 18%, transparent);
341
+ }
342
+ .notes { margin-top: 14px; display: flex; flex-direction: column; gap: 5px; font-size: 12px; line-height: 1.4; color: var(--ac-subtle); }
343
+ .notes div { display: flex; gap: 7px; align-items: flex-start; }
344
+ .notes svg { flex: none; margin-top: 1.5px; }
345
+ .foot { flex: none; display: flex; align-items: center; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--ac-edge); background: var(--ac-soft); }
346
+ .foot .later { margin-inline-end: auto; }
347
+ button.btn {
348
+ display: inline-flex; align-items: center; gap: 8px; padding: 9px 14px; border-radius: 999px;
349
+ font: inherit; font-weight: 500; letter-spacing: -.005em; white-space: nowrap; cursor: pointer;
350
+ background: transparent; color: var(--ac-text); border: 1px solid var(--ac-edge);
351
+ transition: transform .15s ease, background .15s ease, box-shadow .15s ease, border-color .15s ease;
352
+ }
353
+ button.btn:hover { background: var(--ac-soft); border-color: var(--ac-subtle); }
354
+ button.primary, button.primary:hover { background: var(--ac-primary); border-color: transparent; color: #fff; }
355
+ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: var(--ac-primary-deep); box-shadow: var(--ac-lift); }
356
+ button.primary:disabled { opacity: .55; cursor: not-allowed; }
357
+ kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
358
+ button.primary kbd { color: inherit; opacity: .7; }
359
+ `;var is=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),as=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function tl(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?is(n):as(n)}`}function nl(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[as(n)],is(n)].join(" ")}function rl(t){let e=t.trim().split(/[\s_-]+/).filter(Boolean);return(e.length>1?e[0][0]+e[1][0]:t.trim().slice(0,1)).toUpperCase()}function sl(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var yt=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>`,ol=yt('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),il=yt('<path d="m6 15 6-6 6 6"/>'),al=yt('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function ls(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,s=el(12).toString("base64"),o=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",l=cn(t),u=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>`:"",d={choices:o,draft:t.draft??"",placeholder:an,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>
360
+ <html lang="en"><head><meta charset="utf-8">
361
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${s}'">
362
+ <title>AgentX</title>
363
+ <style>${os}</style></head>
364
+ <body><div class="wrap"><main class="card${e.still?" still":""}">
365
+ <div class="head" title="Drag to move"><span class="avatar">${w(rl(r))}</span>
366
+ <div class="who"><b>${w(r)}</b><span>${w(tl(t.created_at,n))}</span></div>
367
+ <span class="kind${i?"":" decision"}">${i?"Reminder":a?"Request":"Decision"}</span>
368
+ <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${il}</button></div>
369
+ <div class="body"><h1 dir="auto">${w(t.title)}</h1>
370
+ ${t.context?`<p class="context" dir="auto">${w(t.context)}</p>`:""}
371
+ <p class="ask" dir="auto">${w(t.ask)}</p>
372
+ ${u||c?`<div class="label-row">${u?'<span class="label">Pick one</span>':""}${c}</div>`:""}
373
+ ${u?`<div class="options" role="radiogroup">${u}</div>`:""}
374
+ ${l.why?`<p class="why" dir="auto">${w(l.why)}</p>`:""}
375
+ ${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>
376
+ <textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
377
+ <div class="notes"><div>${ol}<span>${a?"It stays in Open requests on the Approvals page until you close it.":`If you don't answer by ${w(nl(t.expires,n))}: ${w(t.if_silent)}.`}</span></div>
378
+ <div>${al}<span>Nothing goes out until you click.</span></div></div>
379
+ </div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
380
+ <button class="btn" id="no">${a?"Drop":"No"}</button>
381
+ <button class="btn primary" id="yes">${sl(t)}<kbd>\u2318\u21A9</kbd></button></div>
382
+ </main></div>
383
+ <script type="application/json" id="data">${JSON.stringify(d).replace(/</g,"\\u003c")}</script>
384
+ <script nonce="${s}">${ll}</script>
385
+ </body></html>`}var ll=`
386
+ (function () {
387
+ var d = JSON.parse(document.getElementById("data").textContent);
388
+ var root = document.documentElement;
389
+ var dark = d.theme === "dark" || (d.theme === "system" && matchMedia("(prefers-color-scheme: dark)").matches);
390
+ if (dark) root.setAttribute("data-theme", "dark");
391
+ var opts = [].slice.call(document.querySelectorAll(".opt"));
392
+ var box = document.getElementById("text");
393
+ var msg = document.getElementById("msg");
394
+ var yes = document.getElementById("yes");
395
+ var card = document.querySelector(".card");
396
+ var body = document.querySelector(".body");
397
+ var fold = document.getElementById("fold");
398
+ var pick = -1, touched = false, done = false;
399
+
400
+ function fill(i) { return d.draft.split(d.placeholder).join(i >= 0 ? d.choices[i] : "").trim(); }
401
+ function send(a) { if (done) return; done = true; window.agentxAnswer = JSON.stringify(a); document.title = "agentx:answer"; }
402
+ // What the card needs, not what it has: in a window too short for it, its middle scrolls.
403
+ function fit() {
404
+ // The title carries the answer signal once sent: a late resize must not write over it.
405
+ if (done) return;
406
+ var wrap = document.querySelector(".wrap"), head = document.querySelector(".head"), foot = document.querySelector(".foot");
407
+ document.title = "agentx:size:" + Math.ceil(wrap.offsetHeight - card.clientHeight + head.offsetHeight + body.scrollHeight + foot.offsetHeight);
408
+ }
409
+ function mark() { touched = box.value.trim() !== fill(pick); msg.classList.toggle("touched", touched); }
410
+ function update() {
411
+ opts.forEach(function (o, i) { o.setAttribute("aria-checked", String(i === pick)); });
412
+ yes.disabled = (d.choices.length > 0 && pick < 0) || (box && !box.value.trim());
413
+ }
414
+ function grow() { if (!box) return; box.style.height = "auto"; box.style.height = box.scrollHeight + 4 + "px"; }
415
+ // quiet: the pick made on open. The box is not focused, so the number keys still pick.
416
+ function choose(i, quiet) {
417
+ // An edited message keeps the edits, with the old pick swapped for the new one.
418
+ if (box && touched && pick >= 0) box.value = box.value.split(d.choices[pick]).join(d.choices[i]);
419
+ else if (box) box.value = fill(i);
420
+ pick = i;
421
+ if (box) { grow(); mark(); }
422
+ update();
423
+ if (box && !quiet) box.focus();
424
+ }
425
+ opts.forEach(function (o, i) { o.addEventListener("click", function () { choose(i); }); });
426
+ if (box) {
427
+ box.value = d.choices.length ? "" : fill(-1);
428
+ box.placeholder = d.choices.length ? "Pick an option above" : "";
429
+ grow();
430
+ box.addEventListener("input", function () { grow(); mark(); update(); });
431
+ document.getElementById("reset").addEventListener("click", function () { box.value = fill(pick); grow(); mark(); update(); box.focus(); });
432
+ }
433
+ yes.addEventListener("click", function () {
434
+ if (yes.disabled) return;
435
+ var a = { action: "yes" };
436
+ if (pick >= 0) a.choice = d.choices[pick];
437
+ if (box) a.text = box.value.trim();
438
+ send(a);
439
+ });
440
+ document.getElementById("no").addEventListener("click", function () { send({ action: "no" }); });
441
+ document.getElementById("later").addEventListener("click", function () { send({ action: "dismiss", why: "not now" }); });
442
+ fold.addEventListener("click", function () {
443
+ var shrunk = card.classList.toggle("folded");
444
+ fold.setAttribute("aria-expanded", String(!shrunk));
445
+ fold.title = shrunk ? "Show all" : "Shrink";
446
+ fit();
447
+ });
448
+ document.addEventListener("keydown", function (e) {
449
+ if (e.key === "Escape") return send({ action: "dismiss", why: "not now" });
450
+ // A shrunk card hides its buttons: no answer by key while they can't be seen.
451
+ if (card.classList.contains("folded")) return;
452
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); return yes.click(); }
453
+ // preventDefault: choose() focuses the box, and the digit must not be typed into it.
454
+ if (document.activeElement !== box && /^[1-9]$/.test(e.key) && opts[+e.key - 1]) { e.preventDefault(); choose(+e.key - 1); }
455
+ });
456
+ if (d.pick >= 0) choose(d.pick, true); else update();
457
+ requestAnimationFrame(fit);
458
+ if (box) new ResizeObserver(fit).observe(box);
459
+
460
+ if (d.chime) try {
461
+ var ac = new AudioContext(), t = ac.currentTime + 0.05;
462
+ [[783.99, 0], [1046.5, 0.14]].forEach(function (n) {
463
+ [1, 2].forEach(function (h) {
464
+ var o = ac.createOscillator(), g = ac.createGain();
465
+ o.type = "sine"; o.frequency.value = n[0] * h;
466
+ g.gain.setValueAtTime(0, t + n[1]);
467
+ g.gain.linearRampToValueAtTime(d.volume * (h === 1 ? 0.5 : 0.12), t + n[1] + 0.012);
468
+ g.gain.exponentialRampToValueAtTime(0.0001, t + n[1] + 1.4);
469
+ o.connect(g).connect(ac.destination); o.start(t + n[1]); o.stop(t + n[1] + 1.5);
470
+ });
471
+ });
472
+ } catch (e) {}
473
+ })();
474
+ `;var gl=440,fl=`
475
+ ObjC.import("Cocoa"); ObjC.import("WebKit")
476
+ function run(argv) {
477
+ var path = argv[0], side = ${D.side}, gripTop = ${D.top}, gripEnd = ${D.top+bt.height}, keep = ${bt.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
478
+ var app = $.NSApplication.sharedApplication
479
+ app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
480
+ ObjC.registerSubclass({ name: "AgentXCardView", superclass: "WKWebView", methods: {
481
+ "acceptsFirstMouse:": { types: ["bool", ["id"]], implementation: function () { return true } },
482
+ } })
483
+ var vis = $.NSScreen.mainScreen.visibleFrame
484
+ var top = vis.origin.y + vis.size.height - 4, right = vis.origin.x + vis.size.width - 14 + side
485
+ var mask = $.NSWindowStyleMaskTitled | $.NSWindowStyleMaskClosable | $.NSWindowStyleMaskFullSizeContentView | $.NSWindowStyleMaskNonactivatingPanel
486
+ var win = $.NSPanel.alloc.initWithContentRectStyleMaskBackingDefer($.NSMakeRect(right - w, top - h, w, h), mask, $.NSBackingStoreBuffered, false)
487
+ win.titlebarAppearsTransparent = true
488
+ win.titleVisibility = $.NSWindowTitleHidden
489
+ win.movableByWindowBackground = true
490
+ win.level = $.NSFloatingWindowLevel
491
+ win.releasedWhenClosed = false
492
+ win.hidesOnDeactivate = false
493
+ win.collectionBehavior = $.NSWindowCollectionBehaviorCanJoinAllSpaces
494
+ win.opaque = false
495
+ win.backgroundColor = $.NSColor.clearColor
496
+ win.hasShadow = false
497
+ ;[$.NSWindowCloseButton, $.NSWindowMiniaturizeButton, $.NSWindowZoomButton].forEach(function (b) { win.standardWindowButton(b).hidden = true })
498
+ var cfg = $.WKWebViewConfiguration.alloc.init
499
+ cfg.mediaTypesRequiringUserActionForPlayback = 0
500
+ var web = $.AgentXCardView.alloc.initWithFrameConfiguration($.NSMakeRect(0, 0, w, h), cfg)
501
+ web.autoresizingMask = $.NSViewWidthSizable | $.NSViewHeightSizable
502
+ web.setValueForKey(false, "drawsBackground")
503
+ win.contentView = web
504
+ var url = $.NSURL.fileURLWithPath(path)
505
+ web.loadFileURLAllowingReadAccessToURL(url, url.URLByDeletingLastPathComponent)
506
+ // No focus taken (#394): shown over the app in use, which keeps the keyboard.
507
+ // A click on the card still lands (acceptsFirstMouse); a click in its text
508
+ // box makes the panel key without bringing anything else forward.
509
+ win.orderFrontRegardless
510
+ var end = Date.now() + secs * 1000, sized = 0, shot = false, seen = "", asked = false, answer = null
511
+ // Every kind of event, as a number. JXA hands the AppKit constant for it over as text, and a
512
+ // loop asking with that gets no event at all: no click, no drag, no key.
513
+ var anyEvent = Number.MAX_SAFE_INTEGER
514
+ while (Date.now() < end) {
515
+ var ev = app.nextEventMatchingMaskUntilDateInModeDequeue(anyEvent, $.NSDate.dateWithTimeIntervalSinceNow(0.05), $.NSDefaultRunLoopMode, true)
516
+ if (ev && !ev.isNil()) {
517
+ if (onGrip(ev)) win.performWindowDragWithEvent(ev); else app.sendEvent(ev)
518
+ }
519
+ if (answer !== null) { win.close; return answer }
520
+ if (!win.isVisible) return gone("closed")
521
+ var t = web.title.js || ""
522
+ if (t === "agentx:answer" && !asked) {
523
+ asked = true
524
+ web.evaluateJavaScriptCompletionHandler("window.agentxAnswer", function (r) { answer = String(ObjC.unwrap(r) || "") })
525
+ }
526
+ if (t !== seen && t.indexOf("agentx:size:") === 0) {
527
+ seen = t
528
+ var want = Math.min(Number(t.slice(12)), vis.size.height - 8)
529
+ var f = win.frame
530
+ if (want > 80) { win.setFrameDisplayAnimate($.NSMakeRect(f.origin.x, f.origin.y + f.size.height - want, w, want), true, true); sized = Date.now() }
531
+ }
532
+ if (capture && !shot && sized && Date.now() - sized > 900) {
533
+ shot = true
534
+ var sa = Application.currentApplication(); sa.includeStandardAdditions = true
535
+ sa.doShellScript("/usr/sbin/screencapture -x -o -l " + win.windowNumber + " " + quoted(capture))
536
+ end = Math.min(end, Date.now() + 300)
537
+ }
538
+ }
539
+ win.close
540
+ return gone("timed out")
541
+ function onGrip(ev) {
542
+ if (ev.type != $.NSEventTypeLeftMouseDown || ev.windowNumber != win.windowNumber) return false
543
+ var p = ev.locationInWindow, down = win.frame.size.height - p.y
544
+ return down >= gripTop && down <= gripEnd && p.x >= side && p.x <= w - side - keep
545
+ }
546
+ }
547
+ function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
548
+ function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
549
+ `;function ml(t,e){let n=t.trim().split(`
550
+ `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&ds.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,`
551
+ `).trim():"",!i||i.length>on.text)?{action:"dismiss"}:{action:"yes",...o?{choice:o}:{},...i?{text:i}:{}}}async function us(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=cl(cs(pl(),"agentx-card-"));try{let o=cs(s,"card.html");dl(o,ls(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",fl,o,String(gl),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?ml(a.stdout,t):null}finally{ul(s,{recursive:!0,force:!0})}}var ds=["not now","timed out","closed"],bl=(t,e,n)=>new Promise(r=>{try{hl(t,e,{timeout:n},(s,o)=>r({ok:!s,stdout:String(o??"")}))}catch{r({ok:!1,stdout:""})}}),ps=160,wt=15e3;function gs(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>ps?e.slice(0,ps):e}async function yl(t,e,n,r,s){let o=e.sound==="chime"?r?"":"Glass":e.sound,i=o?yn(o):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],wt),!!e.speak)if(s){let a;await Promise.race([s(gs(t)),new Promise(l=>{a=setTimeout(l,wt)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",gs(t)],wt)}}function hs(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function wl(t,e,n){return hs(["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 fs(t,e,n,r,s){return hs(["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(`
552
+ `),n[n.length-1],String(r),...s!==void 0?[s]:[]])}function ms(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
553
+ `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function kt(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
554
+
555
+ `)}async function bs(t,e,n={}){let r=n.run??bl,s=(e.style??"card")==="card",o=yl(t,e,r,s,n.speak).catch(()=>{});if(s){let i=await us(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,kl(t,e,r)}async function kl(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 u=await n("/usr/bin/osascript",wl(o,kt(t),t.choices),s);if(i=u.stdout.replace(/\n$/,""),!u.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let u=i?`${i}
556
+
557
+ Message (edit it if you like):`:`${kt(t)}
558
+
559
+ Message (edit it if you like):`,d=await n("/usr/bin/osascript",fs(o,u,i?["Cancel","Send"]:["Not now","No","Send"],r,ln(t.draft,i)),s),p=d.ok?ms(d.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",fs(o,kt(t),["Not now","No","Yes"],r),s),l=a.ok?ms(a.stdout):null;return l?.button==="Yes"?{action:"yes"}:l?.button==="No"?{action:"no"}:{action:"dismiss"}}var vt=24*36e5,St=!1,Sl=10*6e4,ys=-1/0;function ws(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=q(t.root,"pending").filter(c=>Date.parse(c.expires)>n),u=l.find(c=>i.includes(`card:${c.id}`));if(u)return u;for(let c of l){let d=`card:${c.id}`;if(r[d]||!e(c)||vn(t.root,c.id,n))continue;let p=s[d];if(p&&Date.parse(p)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>vt&&!(g<=a)))return c}return null}function xt(t){try{return M(t)?.listByState("needs_attention")??[]}catch{return[]}}var ks=new Map;function xl(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s}=v(t.root);return e({})?xt(t).find(o=>{let i=`request:${o.id}`,a=s[i];return ks.get(o.id)===O(o,Ne.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-o.updatedAt<=vt})??null:null}function vl(t,e){return{id:t.id,title:O(t,Ne.title).headline,context:t.attentionReason??"It is not finished and nothing is retrying it.",ask:`Hand it back to ${t.agentId}, or drop it?`,say:"A request you made is not finished.",recommend:"",if_silent:"keep",expires:new Date(e+vt).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Wp(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(St)return"busy";let s=ws(e,t.reaches)?null:xl(e,t.reaches),o=s?vl(s,e.now??Date.now()):ws(e,t.reaches);if(!o)return"none";let i=(t.focus??Yr)();if(i.active)return"held";let a=`${s?"request":"card"}:${o.id}`,l=(v(e.root).wanted??[]).includes(a)?null:kn(o);if(l){if(s)ks.set(s.id,o.title);else{let u=[...q(e.root,"pending").map(c=>`card:${c.id}`),...xt(e).map(c=>`request:${c.id}`)];Me(e.root,a,u,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${o.raised_by}: ${l}`),t.returnToAuthor?.(o,Sn(o,l)),"returned"}St=!0;try{let u=[...q(e.root,"pending").map(b=>`card:${b.id}`),...xt(e).map(b=>`request:${b.id}`)];Me(e.root,a,u,e.now),r(`[approvals] popup: showing ${a} from ${o.raised_by}`);let c=e.now??Date.now(),d=!!s&&c-ys<Sl;s&&n.speak&&(ys=c);let p=t.agentName?.(o.raised_by)??(o.node?`${o.raised_by} on ${o.node}`:void 0),g=await(t.show??bs)(o,d?{...n,speak:!1}:n,{from:p,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${Qt(i)} when shown)`),"shown";if(!(s?M(e)?.get(s.id)?.state==="needs_attention":K(e.root,o.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await or(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(u){return r(`[approvals] popup failed for ${a}: ${u?.message??u}`),"shown"}finally{St=!1}}function qp(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:")?K(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Nn(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 $l,mkdirSync as Rl,readFileSync as El,renameSync as _l,writeFileSync as Al}from"fs";import{dirname as Il,resolve as Tl}from"path";var Dl=["all","urgent","off"],Cl=24*36e5,Ss=24*36e5,Nl=30*24*36e5,xs=t=>Dl.includes(t);function Hp(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:xs(e)?e:"off",computer:xs(n)?n:t.popupEnabled?"all":"off"}}function $s(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=Cl}function vs(t,e,n){return t==="all"||t==="urgent"&&$s(e,n)}function Rs(t){return Tl(t,".agentx","desk-routed.json")}function Ll(t){let e=Rs(t);if(!$l(e))return null;try{let n=JSON.parse(El(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function $t(t,e){let n=Rs(t);Rl(Il(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Al(r,JSON.stringify(e,null,2)),_l(r,n)}async function zp(t){let{root:e,now:n,list:r,routing:s,log:o}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),l=Ll(e);if(!l){let d={};for(let p of r.items)d[p.key]={at:a,seen:a};return $t(e,{items:d}),i.primed=!0,i}let u=[],c=[];for(let d of r.items){let p=l.items[d.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>Ss&&delete p.computerHeld,p.computerHeld&&c.push(d);continue}l.items[d.key]={at:a,seen:a};let g=d.askedAt?Date.parse(d.askedAt):n;n-g<=Ss&&u.push(d)}for(let[d,p]of Object.entries(l.items))n-Date.parse(p.seen)>Nl&&delete l.items[d];$t(e,l);for(let d of u)if(vs(s.phone,d,n))try{await t.phone(d,$s(d,n)),i.phone.push(d.key)}catch(p){o(`[desk] ${d.key}: not sent to the phone: ${p?.message??p}`)}if(t.computer){let d=!1;for(let p of[...c,...u]){let g=l.items[p.key];if(!vs(s.computer,p,n)){g.computerHeld&&(delete g.computerHeld,d=!0);continue}try{let f=await t.computer(p);f&&i.computer.push(p.key),f&&g.computerHeld&&(delete g.computerHeld,d=!0),!f&&!g.computerHeld&&(g.computerHeld=!0,d=!0)}catch(f){o(`[desk] ${p.key}: not shown on this computer: ${f?.message??f}`),g.computerHeld&&(delete g.computerHeld,d=!0)}}d&&$t(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 Xp(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
560
+ Answer it on the Desk.`}}import{closeSync as te,createReadStream as Ol,fstatSync as Pl,openSync as Ml,realpathSync as Es}from"fs";import{isAbsolute as Ul,resolve as _s,sep as As}from"path";var Qp="/app-files",Fl=/^[A-Za-z0-9_.:-]{1,64}$/;function Wl(t,e,n=process.cwd()){if(!e||e.length>ae.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 ${Ce}/ first`};if(!De(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Es(_s(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let s;try{s=Es(Ul(e)?e:_s(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!s.startsWith(r+As))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Ce}/ first`};let o=De(s);return o?{ok:!0,path:s,...o}:{ok:!1,status:415,error:"this type of file is not served"}}function ql(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 jl(t,e,n){return{"Content-Type":t,"Content-Disposition":ql(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 Vl(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 eg(t,e,n,r){let s=(x,W)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(W))};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=Wl(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 u;try{u=Ml(l.path,"r")}catch{return s(404,{error:"file not found"})}let c;try{let x=Pl(u);if(!x.isFile())return te(u),s(404,{error:"not a file"});c=x.size}catch{return te(u),s(404,{error:"file not found"})}if(c>ae.bytes)return te(u),s(413,{error:`the file is larger than ${ae.bytes/1024/1024} MB`});let d=l.path.split(As).pop()||"file",p=jl(l.mime,d,l.kind),g=Vl(t.headers.range,c);if(g==="unsatisfiable"){te(u),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){te(u),e.end();return}let b=Ol("",{fd:u,start:f,end:m,autoClose:!0});b.on("error",()=>e.destroy()),e.on("close",()=>b.destroy()),b.pipe(e)}import{spawn as ne}from"child_process";import{readFileSync as Bl,writeFileSync as Hl}from"fs";import{tmpdir as zl}from"os";import{join as Xl}from"path";Ut();var Is=t=>t&&t!==1?Math.round(175*t):null,ve=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=Bl(t,"utf8").trim();if(e)return e}catch{}return null}function cg(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",...ve(n.voice.rate)?{voice_settings:{speed:ve(n.voice.rate)}}:{}}),signal:r});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text()).slice(0,160)}`);let o=Xl(zl(),`agentx-say-${process.pid}-${++e}.mp3`);return Hl(o,Buffer.from(await s.arrayBuffer())),o}catch(s){if(r.aborted||!n.voice.fallback)throw s;return U(`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 Ts(t,e){let n=t.languages&&ie(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Gl=(t,e="")=>{let n=Ts(t,e),r=Is(t.rate);return[...n&&!br(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Jl(t,e,n){if(!n)return["say",Gl(t,e)];let r=Ts(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function ug(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function dg(t=Rt()){if(t)try{ne("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function pg(t=Rt()){if(t)try{ne("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Rt(t={},e){if(!Ke(t))return null;try{return kr(e)}catch(n){return U("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
561
+ `)[0]}); Siri voices will not switch`),null}}var gg=(t,e)=>{if(!t){let[n,r]=Jl(e.voice,e.text,Rt()),s=Is(e.voice.rate),o=s?{...process.env,AGENTX_SAY_RATE:String(s)}:process.env,i=ne(n,r,{stdio:["pipe","ignore","ignore"],env:o});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?ne("afplay",[t],{stdio:"ignore"}):ne("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Ds}from"child_process";import{accessSync as Yl,constants as Zl,readFileSync as Cs}from"fs";import{homedir as Ql}from"os";import{basename as H,delimiter as Ns,dirname as ec,extname as tc,join as Et}from"path";var L={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function Ls(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:At()}:null}var At=()=>`The recording is longer than ${L.ms/6e4} minutes.`,nc={"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 Os(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return nc[e]??null}function Ps(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 It(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=Ql(),s=[Et(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(Ns).filter(Boolean)];for(let o of[e,...s.map(i=>Et(i,t))])if(o)try{return Yl(o,Zl.X_OK),o}catch{}return null}function wg(t){return{key:t,mlx:_t("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:_t("whisper",process.env.AGENTX_WHISPER),ffmpeg:rc()}}var rc=()=>_t("ffmpeg",process.env.AGENTX_FFMPEG);async function Ms(t,e){return e?sc(t,e):null}async function sc(t,e){let n=String(L.ms/1e3+5);try{let s=[...(await oc(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 Us(t,e,n,r){let s=new FormData;s.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),s.set("file",new Blob([Cs(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 Fs(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:`${ec(r)}${Ns}${process.env.PATH??""}`};await ic(e,o,12e4,i);try{return Cs(Et(s,H(n,tc(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function oc(t,e,n){return new Promise((r,s)=>{let o=Ds(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 ic(t,e,n,r=process.env){return new Promise((s,o)=>{let i=Ds(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",l="",u=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(u),o(c)}),i.on("exit",c=>{clearTimeout(u),c===0?s(a):o(new Error(`${H(t)} exited ${c}: ${l.trim().split(`
562
+ `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as ac,rm as lc,writeFile as cc}from"fs/promises";import{tmpdir as uc}from"os";import{join as Ws}from"path";Gs();var dc=64*1024,pc=2,Tt=0;function Tg(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Dg(t,e,n,r){return t.method!=="POST"?y(e,405,{error:"POST"}):n==="/voice/transcribe"?gc(t,e,r):hc(t,e,r)}async function gc(t,e,n){let r=String(t.headers["content-type"]||""),s=Os(r);if(!s)return y(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let o=Ls(t.headers["x-audio-duration-ms"]);if(o)return t.resume(),y(e,o.status,{error:o.error});let i=await qs(t,L.bytes);if(!i)return y(e,413,{error:wc()});if(!i.length)return y(e,400,{error:"The recording is empty."});if(Tt>=pc)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(),u=Ps(a,l);if(!l.ffmpeg&&!n.allowUnmeasured?.()){let d=n.nodeName?`on ${n.nodeName}`:"on this computer",p=u.length?"":" "+It(a,l);return y(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${d} for voice input from the phone.${p}`,setup:!1})}if(!u.length)return y(e,503,{error:"Voice input isn't set up on this computer.",hint:It(a,l),setup:!1});Tt++;let c;try{let d=await ac(Ws(uc(),"agentx-phone-voice-"));try{c=await fc(d,`speech.${s}`,i,r,l,u,n)}finally{await lc(d,{recursive:!0,force:!0}).catch(()=>{})}}finally{Tt--}y(e,c[0],c[1])}async function fc(t,e,n,r,s,o,i){let a=Ws(t,e);if(await cc(a,n,{mode:384}),s.ffmpeg){let u=await(i.measure??Ms)(a,s.ffmpeg);if(u==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(u*1e3>L.ms+2e3)return[413,{error:At()}]}let l=[];for(let u of o)try{let c=await mc(u,a,r,s,t,i);return i.log(`[voice] phone recording transcribed with ${u} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:u}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:u}]}catch(c){let d=String(c?.message??c).split(`
563
+ `)[0].slice(0,200);l.push(`${u}: ${d}`),i.log(`[voice] phone transcription with ${u} failed: ${d}`)}return[502,{error:"Speech to text failed on this computer.",detail:l.join("; ")}]}function mc(t,e,n,r,s,o){let i=o.engines?.[t];if(i)return i(e,n,r,s);if(t==="elevenlabs")return Us(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return Fs(t,a,e,r.ffmpeg,s)}async function hc(t,e,n){let r=await qs(t,dc);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=bc(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,u=n.voiceOf(o,i);if(!u)return y(e,404,{error:`Unknown agent: ${o}`});let c=(p,g=200)=>y(e,g,{fallback:"browser",reason:p,text:l});if(u.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let d=n.elevenLabsKey();if(!d)return c("No ElevenLabs key is set on this computer.");try{let p=await(n.synth??yc)(d,u,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(`
564
+ `)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function bc(t,e){let n=Xr(Yt(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Ft(n,e)}async function yc(t,e,n){let r=ve(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 wc=()=>`The recording is larger than ${L.bytes/1024/1024} MB, more than ${L.ms/6e4} minutes of speech.`;function Cg(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let s=n.agents??{};return s[t]?st(tt(t,s,n.voice)):null}function qs(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 Lt,writeFileSync as Ot,mkdirSync as $e,readdirSync as Nt,rmSync as kc,statSync as I}from"fs";import{resolve as js,relative as Sc,dirname as Pt,join as F,extname as re,basename as Mt}from"path";var S=200*1024,Vs=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"]),xc=6,vc=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=js(t);if(_(n)||$e(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=js(n,e);if(Sc(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function Bs(t){let e=re(t).toLowerCase();if(!Vs.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Dt(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Pg(t){let e=C(t,"."),n=[],r=new Set,s=[];try{s=Nt(e)}catch{}for(let a of vc){let l=F(e,a);if(_(l)&&I(l).isFile()){let u=I(l).size,c=u>0&&u<S?Ct(l):"";n.push({path:a,title:Dt(c,a),size:u,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=F(e,a);try{let u=I(l);if(!u.isFile()||!Vs.has(re(a).toLowerCase()))continue;let c=u.size>0&&u.size<S?Ct(l):"";n.push({path:a,title:Dt(c,a),size:u.size,exists:!0})}catch{}}let o=[],i=F(e,".claude","skills");if(_(i))try{for(let a of Nt(i)){let l=F(i,a),u;try{u=I(l)}catch{continue}if(!u.isDirectory())continue;let c=F(l,"SKILL.md");if(!_(c))continue;let d=I(c),p=d.size<S?Ct(c):"";o.push({slug:a,title:Dt(p,a),size:d.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 Ct(t){try{return Lt(t,"utf-8")}catch{return""}}function Mg(t,e){let n=C(t,e);if(Bs(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:Lt(n,"utf-8")}}function Ug(t,e,n){let r=C(t,e);Bs(r);let s=Buffer.from(n,"utf-8");if(s.length>S)throw new Error(`File too large (${s.length} > ${S} bytes).`);return $e(Pt(r),{recursive:!0}),Ot(r,s),{path:e,bytes:s.length}}function Fg(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.`);$e(Pt(s),{recursive:!0});let o=n.content?.trim()?n.content:$c(e,n.title);return Ot(s,o),{slug:e,path:r}}function Wg(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 kc(n,{recursive:!0,force:!0}),{slug:e}}function qg(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>xc)return;let u=[];try{u=Nt(o)}catch{return}for(let c of u){if(c==="node_modules"||c===".git")continue;let d=F(o,c),p=i?`${i}/${c}`:c,g;try{g=I(d)}catch{continue}if(g.isDirectory())l.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),s(d,p,a+1,l);else if(g.isFile()){let f=re(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 jg(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=re(r).toLowerCase(),o=Mt(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:Lt(r,"utf-8")}}function Vg(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=re(s).toLowerCase(),i=Mt(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 $e(Pt(s),{recursive:!0}),Ot(s,a),{path:n,bytes:a.length}}function Bg(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=>_(F(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 $c(t,e){return`# ${e?.trim()||t}
565
+
566
+ 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.
567
+
568
+ ## When to use
569
+ - Trigger condition 1
570
+ - Trigger condition 2
571
+
572
+ ## How to use
573
+ Document the arguments, commands, or files the skill expects. Example:
574
+
575
+ \`\`\`bash
576
+ # Example invocation
577
+ claude-code ${Mt(t)} --arg value
578
+ \`\`\`
579
+ `}zt();var Hs={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function zs(t){return{...Hs,...t??{},regions:{...t?.regions??{}},buffer:{...Hs.buffer,...t?.buffer??{}}}}function Xg(t){try{return zs(Ht(t).screen)}catch{return zs(void 0)}}var Rc=/^[a-z][\w-]*$/,Xs=["window","screen","menubar","notifications"];function se(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 Re=(t,e)=>se(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Ks(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 Kg(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Re(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Re(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Re(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=se(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=se(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(!Rc.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=Ks(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=se(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=se(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=Re(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&&!Xs.includes(r)&&!n.regions?.[r])try{Ks(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Xs,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{$n as a,Ac as b,mt as c,ya as d,wa as e,Pd as f,Md as g,Ud as h,qd as i,jd as j,Vd as k,Hr as l,zr as m,Bd as n,Xr as o,zd as p,Kd as q,N as r,Kr as s,k as t,Cc as u,Yr as v,ep as w,rp as x,Qr as y,sp as z,es as A,op as B,ee as C,za as D,ip as E,ap as F,ns as G,Xc as H,Ao as I,Qc as J,jn as K,tu as L,v as M,Mc as N,Uc as O,cu as P,de as Q,uu as R,Ln as S,Bc as T,M as U,Iu as V,sr as W,or as X,ri as Y,si as Z,Cu as _,Nu as $,di as aa,Mu as ba,ss as ca,up as da,Wu as ea,qu as fa,qr as ga,it as ha,da as ia,bs as ja,Wp as ka,qp as la,Dl as ma,Hp as na,vs as oa,zp as pa,Xp as qa,Qp as ra,jl as sa,eg as ta,Vu as ua,Bu as va,Hu as wa,zu as xa,Xu as ya,Ku as za,Ju as Aa,Yu as Ba,id as Ca,Ye as Da,ad as Ea,ld as Fa,Z as Ga,Q as Ha,Kl as Ia,cg as Ja,ug as Ka,dg as La,pg as Ma,Rt as Na,gg as Oa,et as Pa,tt as Qa,ye as Ra,Mi as Sa,Fi as Ta,gd as Ua,rt as Va,st as Wa,Wi as Xa,qi as Ya,Tr as Za,Lr as _a,fd as $a,Bi as ab,md as bb,Zi as cb,ta as db,ot as eb,ra as fb,Or as gb,L as hb,Ls as ib,Os as jb,Ps as kb,_t as lb,wg as mb,rc as nb,Us as ob,Fs as pb,Tg as qb,Dg as rb,wc as sb,Cg as tb,qs as ub,we as vb,_d as wb,gt as xb,Ld as yb,Pg as zb,Mg as Ab,Ug as Bb,Fg as Cb,Wg as Db,qg as Eb,jg as Fb,Vg as Gb,Bg as Hb,Hs as Ib,zs as Jb,Xg as Kb,Xs as Lb,Kg as Mb};
580
+ //# sourceMappingURL=chunk-FEA3XMVU.js.map