agentix-cli 0.213.1 → 0.213.2

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 (139) hide show
  1. package/dist/{App-5CLRBC3C.js → App-OUWMH6QG.js} +2 -2
  2. package/dist/{ChatApp-LDNQVD2C.js → ChatApp-EZ5A47FV.js} +2 -2
  3. package/dist/{absorb-eval-JWQPGUJS.js → absorb-eval-WM6JQGYG.js} +2 -2
  4. package/dist/{adapter-AOKK2LFM.js → adapter-W26OC6ET.js} +2 -2
  5. package/dist/{agent-6VEMBVRN.js → agent-2GK32HCI.js} +2 -2
  6. package/dist/{board-dashboard-LDMIS7MM.js → board-dashboard-6JUASBDZ.js} +131 -131
  7. package/dist/{board-dashboard-LDMIS7MM.js.map → board-dashboard-6JUASBDZ.js.map} +1 -1
  8. package/dist/{chunk-D6H4DH32.js → chunk-2CO3NK6Z.js} +2 -2
  9. package/dist/{chunk-DPA3IOMU.js → chunk-35UGFFHA.js} +2 -2
  10. package/dist/{chunk-6PBYRK7J.js → chunk-3JH3HUHX.js} +2 -2
  11. package/dist/{chunk-EE5RZDQE.js → chunk-7T5Y4H2J.js} +2 -2
  12. package/dist/{chunk-WKBGQGVL.js → chunk-ACPGDZOV.js} +2 -2
  13. package/dist/{chunk-NWE3B245.js → chunk-B7HDWFKR.js} +2 -2
  14. package/dist/{chunk-ERKK22QV.js → chunk-CAH6TNC6.js} +2 -2
  15. package/dist/{chunk-2V43GUET.js → chunk-EUJT7JT3.js} +98 -98
  16. package/dist/chunk-EUJT7JT3.js.map +1 -0
  17. package/dist/{chunk-N7IX77SL.js → chunk-FR4DTMCA.js} +2 -2
  18. package/dist/{chunk-CUCIMPFI.js → chunk-H4DWZIU7.js} +2 -2
  19. package/dist/{chunk-DNPPPUDP.js → chunk-HY4PE6R3.js} +2 -2
  20. package/dist/{chunk-4W5KRZTT.js → chunk-IHFOW4JF.js} +2 -2
  21. package/dist/{chunk-VKLTCUD7.js → chunk-J2R47R56.js} +2 -2
  22. package/dist/{chunk-DSUL5L3T.js → chunk-JEBU5JUM.js} +2 -2
  23. package/dist/{chunk-D3FIIEDR.js → chunk-JKMFKNGS.js} +2 -2
  24. package/dist/chunk-KAM4ZWRE.js +133 -0
  25. package/dist/chunk-KAM4ZWRE.js.map +1 -0
  26. package/dist/{chunk-IXV3BPUZ.js → chunk-MIUITI47.js} +2 -2
  27. package/dist/{chunk-G3GFE3GK.js → chunk-N476XZD3.js} +2 -2
  28. package/dist/{chunk-BU6V75KD.js → chunk-PSYHAO57.js} +2 -2
  29. package/dist/{chunk-O4WFPH6H.js → chunk-QR3P5RG7.js} +2 -2
  30. package/dist/{chunk-XBFXSSHA.js → chunk-RMXG5GNW.js} +2 -2
  31. package/dist/{chunk-MOATCFT5.js → chunk-SPXXLPAS.js} +2 -2
  32. package/dist/{chunk-DYH6KS3X.js → chunk-UPWNWSK3.js} +296 -296
  33. package/dist/chunk-UPWNWSK3.js.map +1 -0
  34. package/dist/{chunk-KU3ZF3WO.js → chunk-UUOCCLIL.js} +2 -2
  35. package/dist/{chunk-Z6N7POAU.js → chunk-WAVO3U3I.js} +78 -78
  36. package/dist/chunk-WAVO3U3I.js.map +1 -0
  37. package/dist/{chunk-FCF47R4W.js → chunk-XHON5WB5.js} +3 -3
  38. package/dist/{chunk-I722PWJE.js → chunk-Z7632XS3.js} +2 -2
  39. package/dist/{chunk-BERSMN6Y.js → chunk-ZMGDHLZD.js} +2 -2
  40. package/dist/{chunk-DGCYMSXU.js → chunk-ZRBTLW2B.js} +2 -2
  41. package/dist/cli.js +1 -1
  42. package/dist/{client-2TFSAO3Y.js → client-U3OFNJ5W.js} +2 -2
  43. package/dist/{config-LTXRWDRK.js → config-S522VXLI.js} +2 -2
  44. package/dist/{config-mutate-UFVJUJQO.js → config-mutate-KBZV2T4X.js} +2 -2
  45. package/dist/{config-mutator-RRKU33OL.js → config-mutator-YNNEGRV3.js} +2 -2
  46. package/dist/{contributions-5XUEOSLT.js → contributions-FXUTKU6R.js} +2 -2
  47. package/dist/{doctor-L675OBBF.js → doctor-ABJSFSMM.js} +2 -2
  48. package/dist/{follow-up-tool-2OEZMPPQ.js → follow-up-tool-C4PLLZIT.js} +2 -2
  49. package/dist/{hub-VJZYQXKB.js → hub-PPQGFC35.js} +2 -2
  50. package/dist/index.d.ts +16 -0
  51. package/dist/index.js +1 -1
  52. package/dist/{org-tool-QBLKCMY3.js → org-tool-6PPIGWH2.js} +2 -2
  53. package/dist/{program-3QOBRNT4.js → program-VCNJHSWN.js} +24 -24
  54. package/dist/{promote-Z6KL6GOL.js → promote-CXXMZWWH.js} +2 -2
  55. package/dist/{query-SZA6UMHA.js → query-RPZIRN3X.js} +2 -2
  56. package/dist/{query-settings-BALRO5J4.js → query-settings-EBOBWOAL.js} +2 -2
  57. package/dist/{registry-J3Y3DDFT.js → registry-QTFATS6J.js} +2 -2
  58. package/dist/{request-planner-Y5HG5DQ4.js → request-planner-LNNKTY7K.js} +2 -2
  59. package/dist/{review-candidates-BZJOFMFO.js → review-candidates-HQBKXAJA.js} +2 -2
  60. package/dist/{routing-3JDN3Z6L.js → routing-XXA7GIBA.js} +2 -2
  61. package/dist/schedule-tool-65TFOUWK.js +2 -0
  62. package/dist/{scheduler-JJOO2ODF.js → scheduler-DIPOBJBF.js} +2 -2
  63. package/dist/{seat-5FTOWN5J.js → seat-BSWBTNCP.js} +2 -2
  64. package/dist/{select-BRQQP7OP.js → select-T4F42G6W.js} +2 -2
  65. package/dist/{set-enabled-EZLQFASM.js → set-enabled-UK4TPVC7.js} +2 -2
  66. package/dist/{sprint-tool-YJ4WT3AD.js → sprint-tool-DN3BKLUY.js} +2 -2
  67. package/dist/{tool-RCEOKPES.js → tool-2VRNH43W.js} +2 -2
  68. package/dist/{tool-CXJHLIHJ.js → tool-JJGEGQF3.js} +2 -2
  69. package/dist/{tool-MT5YQ7F3.js → tool-Z2YLBCN7.js} +2 -2
  70. package/dist/{tool-BFKCGAD6.js → tool-ZVYUWVJQ.js} +2 -2
  71. package/dist/{wiki-F3LZSBN3.js → wiki-FP4JMCYP.js} +2 -2
  72. package/dist/wiki-enrich-3SPIVYSG.js +2 -0
  73. package/package.json +1 -1
  74. package/dist/chunk-2V43GUET.js.map +0 -1
  75. package/dist/chunk-DYH6KS3X.js.map +0 -1
  76. package/dist/chunk-UWDDVDU6.js +0 -133
  77. package/dist/chunk-UWDDVDU6.js.map +0 -1
  78. package/dist/chunk-Z6N7POAU.js.map +0 -1
  79. package/dist/schedule-tool-VM5OJ7XB.js +0 -2
  80. package/dist/wiki-enrich-KIONW7SB.js +0 -2
  81. /package/dist/{App-5CLRBC3C.js.map → App-OUWMH6QG.js.map} +0 -0
  82. /package/dist/{ChatApp-LDNQVD2C.js.map → ChatApp-EZ5A47FV.js.map} +0 -0
  83. /package/dist/{absorb-eval-JWQPGUJS.js.map → absorb-eval-WM6JQGYG.js.map} +0 -0
  84. /package/dist/{adapter-AOKK2LFM.js.map → adapter-W26OC6ET.js.map} +0 -0
  85. /package/dist/{agent-6VEMBVRN.js.map → agent-2GK32HCI.js.map} +0 -0
  86. /package/dist/{chunk-D6H4DH32.js.map → chunk-2CO3NK6Z.js.map} +0 -0
  87. /package/dist/{chunk-DPA3IOMU.js.map → chunk-35UGFFHA.js.map} +0 -0
  88. /package/dist/{chunk-6PBYRK7J.js.map → chunk-3JH3HUHX.js.map} +0 -0
  89. /package/dist/{chunk-EE5RZDQE.js.map → chunk-7T5Y4H2J.js.map} +0 -0
  90. /package/dist/{chunk-WKBGQGVL.js.map → chunk-ACPGDZOV.js.map} +0 -0
  91. /package/dist/{chunk-NWE3B245.js.map → chunk-B7HDWFKR.js.map} +0 -0
  92. /package/dist/{chunk-ERKK22QV.js.map → chunk-CAH6TNC6.js.map} +0 -0
  93. /package/dist/{chunk-N7IX77SL.js.map → chunk-FR4DTMCA.js.map} +0 -0
  94. /package/dist/{chunk-CUCIMPFI.js.map → chunk-H4DWZIU7.js.map} +0 -0
  95. /package/dist/{chunk-DNPPPUDP.js.map → chunk-HY4PE6R3.js.map} +0 -0
  96. /package/dist/{chunk-4W5KRZTT.js.map → chunk-IHFOW4JF.js.map} +0 -0
  97. /package/dist/{chunk-VKLTCUD7.js.map → chunk-J2R47R56.js.map} +0 -0
  98. /package/dist/{chunk-DSUL5L3T.js.map → chunk-JEBU5JUM.js.map} +0 -0
  99. /package/dist/{chunk-D3FIIEDR.js.map → chunk-JKMFKNGS.js.map} +0 -0
  100. /package/dist/{chunk-IXV3BPUZ.js.map → chunk-MIUITI47.js.map} +0 -0
  101. /package/dist/{chunk-G3GFE3GK.js.map → chunk-N476XZD3.js.map} +0 -0
  102. /package/dist/{chunk-BU6V75KD.js.map → chunk-PSYHAO57.js.map} +0 -0
  103. /package/dist/{chunk-O4WFPH6H.js.map → chunk-QR3P5RG7.js.map} +0 -0
  104. /package/dist/{chunk-XBFXSSHA.js.map → chunk-RMXG5GNW.js.map} +0 -0
  105. /package/dist/{chunk-MOATCFT5.js.map → chunk-SPXXLPAS.js.map} +0 -0
  106. /package/dist/{chunk-KU3ZF3WO.js.map → chunk-UUOCCLIL.js.map} +0 -0
  107. /package/dist/{chunk-FCF47R4W.js.map → chunk-XHON5WB5.js.map} +0 -0
  108. /package/dist/{chunk-I722PWJE.js.map → chunk-Z7632XS3.js.map} +0 -0
  109. /package/dist/{chunk-BERSMN6Y.js.map → chunk-ZMGDHLZD.js.map} +0 -0
  110. /package/dist/{chunk-DGCYMSXU.js.map → chunk-ZRBTLW2B.js.map} +0 -0
  111. /package/dist/{client-2TFSAO3Y.js.map → client-U3OFNJ5W.js.map} +0 -0
  112. /package/dist/{config-LTXRWDRK.js.map → config-S522VXLI.js.map} +0 -0
  113. /package/dist/{config-mutate-UFVJUJQO.js.map → config-mutate-KBZV2T4X.js.map} +0 -0
  114. /package/dist/{config-mutator-RRKU33OL.js.map → config-mutator-YNNEGRV3.js.map} +0 -0
  115. /package/dist/{contributions-5XUEOSLT.js.map → contributions-FXUTKU6R.js.map} +0 -0
  116. /package/dist/{doctor-L675OBBF.js.map → doctor-ABJSFSMM.js.map} +0 -0
  117. /package/dist/{follow-up-tool-2OEZMPPQ.js.map → follow-up-tool-C4PLLZIT.js.map} +0 -0
  118. /package/dist/{hub-VJZYQXKB.js.map → hub-PPQGFC35.js.map} +0 -0
  119. /package/dist/{org-tool-QBLKCMY3.js.map → org-tool-6PPIGWH2.js.map} +0 -0
  120. /package/dist/{program-3QOBRNT4.js.map → program-VCNJHSWN.js.map} +0 -0
  121. /package/dist/{promote-Z6KL6GOL.js.map → promote-CXXMZWWH.js.map} +0 -0
  122. /package/dist/{query-SZA6UMHA.js.map → query-RPZIRN3X.js.map} +0 -0
  123. /package/dist/{query-settings-BALRO5J4.js.map → query-settings-EBOBWOAL.js.map} +0 -0
  124. /package/dist/{registry-J3Y3DDFT.js.map → registry-QTFATS6J.js.map} +0 -0
  125. /package/dist/{request-planner-Y5HG5DQ4.js.map → request-planner-LNNKTY7K.js.map} +0 -0
  126. /package/dist/{review-candidates-BZJOFMFO.js.map → review-candidates-HQBKXAJA.js.map} +0 -0
  127. /package/dist/{routing-3JDN3Z6L.js.map → routing-XXA7GIBA.js.map} +0 -0
  128. /package/dist/{schedule-tool-VM5OJ7XB.js.map → schedule-tool-65TFOUWK.js.map} +0 -0
  129. /package/dist/{scheduler-JJOO2ODF.js.map → scheduler-DIPOBJBF.js.map} +0 -0
  130. /package/dist/{seat-5FTOWN5J.js.map → seat-BSWBTNCP.js.map} +0 -0
  131. /package/dist/{select-BRQQP7OP.js.map → select-T4F42G6W.js.map} +0 -0
  132. /package/dist/{set-enabled-EZLQFASM.js.map → set-enabled-UK4TPVC7.js.map} +0 -0
  133. /package/dist/{sprint-tool-YJ4WT3AD.js.map → sprint-tool-DN3BKLUY.js.map} +0 -0
  134. /package/dist/{tool-RCEOKPES.js.map → tool-2VRNH43W.js.map} +0 -0
  135. /package/dist/{tool-CXJHLIHJ.js.map → tool-JJGEGQF3.js.map} +0 -0
  136. /package/dist/{tool-MT5YQ7F3.js.map → tool-Z2YLBCN7.js.map} +0 -0
  137. /package/dist/{tool-BFKCGAD6.js.map → tool-ZVYUWVJQ.js.map} +0 -0
  138. /package/dist/{wiki-F3LZSBN3.js.map → wiki-FP4JMCYP.js.map} +0 -0
  139. /package/dist/{wiki-enrich-KIONW7SB.js.map → wiki-enrich-3SPIVYSG.js.map} +0 -0
@@ -1,10 +1,10 @@
1
- import{a as ft}from"./chunk-GTJIKXDB.js";import{H as Er,O as Ir,k as K}from"./chunk-EE5RZDQE.js";import{f as $r,g as Tr,h as Ar,l as Rr}from"./chunk-BU6V75KD.js";import{b as _r}from"./chunk-2VDO2HEK.js";import{t as vr,u as Sr}from"./chunk-DSUL5L3T.js";import{d as xr,e as kr}from"./chunk-AQASR6KR.js";import{h as pe,j as dr,l as ur,m as pr,n as gr}from"./chunk-RX5O5637.js";import{a as mr,c as fr,e as hr,f as ut,h as br,j as yr,k as wr,l as pt,m as gt,n as mt}from"./chunk-5ELIX7BQ.js";import{a as rr,c as or}from"./chunk-KP7KDLZ2.js";import{Aa as ue,Ca as dt,b as at,f as Gn,s as lt,u as ct,xa as Ae,ya as er,za as W}from"./chunk-N7IX77SL.js";import{a as $e,b as de,e as Yn}from"./chunk-7AB3QUGH.js";import{h as sr,i as ir,j as ar,l as lr,m as cr}from"./chunk-CUCIMPFI.js";import{s as Zn}from"./chunk-ERKK22QV.js";import{a as Jn,b as Te,e as Qn}from"./chunk-G3GFE3GK.js";import{c as Re,d as tr,e as nr}from"./chunk-XVV7ZZ77.js";import{b as ee}from"./chunk-5ONH4ITT.js";import{a as Kn,c as it}from"./chunk-ILEC3IAV.js";import{a as Wn,i as Vn,l as Xn,n as ot,o as st,r as ce,s as Z,u as zn}from"./chunk-XL7UWG36.js";import{a as jn,b as Bn,d as qn,e as Hn}from"./chunk-MNG2AMKZ.js";import{a as Un}from"./chunk-7IW25T4K.js";import{a as Fn}from"./chunk-QUFIUXMQ.js";import{Ba as Dn,Ca as Cn,E as _e,Ea as Nn,F as $n,Fa as On,Fb as rt,G as Tn,H as vi,Pb as Ln,Qb as Pn,_b as Mn,f as Ze,g as C,i as Ee,j as E,k as le,l as En,o as _n,p as et,va as In}from"./chunk-UWDDVDU6.js";import{a as tt,h as Si}from"./chunk-KEUW6YLL.js";import{j as nt,q as An,r as Rn}from"./chunk-N47Y5ADQ.js";import{existsSync as Ei,readdirSync as _i,readFileSync as $i,statSync as Ti}from"fs";import{resolve as Ai}from"path";function Dr(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],d=a.filter(m=>n-m.at<=o),l=a.filter(m=>n-m.at>o&&n-m.at<=o*2),c=d.filter(m=>m.status==="failed").length,p=a.filter(m=>m.status==="paused").length,u=a.length?Math.max(...a.map(m=>m.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var Ie=new Map;function Cu(t,e=1e3){if(!Ei(t))return[];let n=_i(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ai(t,s);return{path:i,mtime:Ti(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of Ie.keys())r.has(s)||Ie.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=Ie.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Ri(s,i);Ie.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Ri(t,e){try{let n=$i(t,"utf-8").split(`
2
- `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Cr=7,Ii={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},A={routines:200,summary:160,filters:6,filterValue:60,text:120},Di=(t,e,n)=>{try{return Zn(t,e,n)}catch{return null}},Nr=864e5;function Pu(t){let e=t.now??Date.now(),n={...Ii,...t.thresholds},r=t.nextFire??Di,o=[];for(let a of t.crons){let d=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",c=d.map(g=>({at:Date.parse(g.startedAt),status:g.status})),p=d[0],u={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:F(a.id,A.text),trigger:{schedule:F(a.schedule,A.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?ht(a.nextRun)??ht(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:Mi(p.status==="success"?void 0:p.errorSummary,A.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Or(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Cr).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Lr(u,c,a.schedule,l,null,e,n,r),o.push(Pr(u))}let s=new Map(Dr(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 d=i.get(a.workflowId);d?d.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let d=a.nodes.find(k=>k.type.startsWith("trigger."));if(!d||d.type!=="trigger.cron"&&d.type!=="trigger.hook")continue;let l=d.config??{},c=a.state||"active",p=c==="active",u=(i.get(a.id)??[]).slice().sort((k,D)=>D.at-k.at),g=u.map(k=>({at:k.at,status:Oi(k.status)})),m=g[0],f=d.type==="trigger.cron",w=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",b={id:`workflow:${a.id}`,source:"workflow",kind:f?"schedule":"event",name:F(a.title||a.id,A.text),trigger:f?{schedule:F(w,A.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",A.text),filters:Pi(l.filter,a)},agent:Li(a),enabled:p,state:c,nextRunAt:f&&p&&w?ht(r(w,new Date(e),x)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let k=g.find(D=>D.status==="success");return k?new Date(k.at).toISOString():null})(),consecutiveFailures:Or(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Cr).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=f?Lr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):Ci(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Pr(b))}return o.sort(Ni).slice(0,A.routines)}function Or(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 Lr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=Fr(l,o,s,i);return u&&d.push(u),d}if(t.consecutiveFailures>=i.failStreak&&d.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return d.push({reason:"never-ran",detail:"No persisted attempt"}),d;let c=new Date(l),p=null;for(let u=0;u<i.missedFires&&(p=a(n,c,r),!!p);u++)c=p;return p&&s>p.getTime()+i.graceMs&&d.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),d}function Ci(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Fr(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function Fr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Nr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Nr)} days`:"Disabled and never ran"}}function Pr(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 Mr={critical:0,warning:1,info:2};function Ni(t,e){let n=t.attention?Mr[t.attention]:3,r=e.attention?Mr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Oi(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 Li(t){if(t.ownerAgent)return F(t.ownerAgent,A.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?F(String(e.config.agentId),A.text):null}function Pi(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,A.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(F(`${o}=${i.join(",")}`,A.filterValue))}return n.slice(0,A.filters)}function ht(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function F(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Mi(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as Fi,readFileSync as Ui,renameSync as Wi,writeFileSync as ji}from"fs";import{resolve as Bi}from"path";function Ur(t){return Bi(st(t),"_state.json")}function N(t){try{let e=JSON.parse(Ui(Ur(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 ge(t,e){Fi(st(t),{recursive:!0});let n=Ur(t),r=`${n}.${process.pid}.tmp`;ji(r,JSON.stringify(e,null,2)+`
3
- `),Wi(r,n)}function Wr(t,e,n,r=Date.now()){let o=N(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),ge(t,{...o,snoozed:s})}function ju(t,e){ge(t,{...N(t),lastDigest:e})}function bt(t,e,n,r=Date.now()){let o=N(t),s=new Set(n),i={};for(let[d,l]of Object.entries(o.popped??{}))s.has(d)&&(i[d]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(d=>d!==e&&s.has(d));ge(t,{...o,popped:i,wanted:a})}function jr(t,e){let n=N(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Bu(t,e=Date.now()){ge(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as qi,readFileSync as Hi}from"fs";Mn();Si();function Br(t){let e=Jn(t),n={};if(qi(e))try{n=Ln(JSON.parse(Hi(e,"utf-8")))}catch{n={}}let r=rt.safeParse(n?.requests);return r.success?r.data:rt.parse(void 0)}async function Ku(t,e={}){let n=(t.channels??[]).filter(r=>!tt.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...tt].join(", ")}`}:Te(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as H,readdirSync as ua,readFileSync as kt,statSync as pa}from"fs";import{dirname as lo,resolve as T}from"path";import{randomBytes as Vr}from"crypto";import{existsSync as Xi,mkdirSync as zi,readdirSync as Ki,readFileSync as Gi,renameSync as Xr,unlinkSync as Yi,writeFileSync as Ji}from"fs";import{resolve as zr}from"path";function qr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Vi=t=>t.trim().split(`
4
- `).pop()?.slice(0,300)||"no output";async function Hr(t,e,n,r=ft){let o=await r(t.bin,[...qr(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Vi(o.stderr||o.stdout)}`}}async function Ju(t,e,n,r,o=ft){return(await o(t.bin,[...qr(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Qi=2e3,Zi=t=>Hr(t.wacli,t.to,t.text);function yt(t){return zr(t,".agentx","whatsapp-triage","drafts")}var ea=t=>/^[a-z0-9-]{8,64}$/.test(t),De=(t,e)=>zr(yt(t),`${e}.json`);function Kr(t,e){zi(yt(t),{recursive:!0});let n=De(t,e.id),r=`${n}.${process.pid}.tmp`;Ji(r,JSON.stringify(e,null,2)+`
5
- `,{mode:384}),Xr(r,n)}function rp(t,e,n=Date.now()){let r=e.text.trim().slice(0,Qi);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${Vr(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Kr(t,o),o}function Ce(t,e){if(!ea(e))return null;try{return JSON.parse(Gi(De(t,e),"utf-8"))}catch{return null}}function Gr(t,e){let n=yt(t);return Xi(n)?Ki(n).filter(r=>r.endsWith(".json")).map(r=>Ce(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function Yr(t,e,n,r={}){let o=Ce(t,e);if(!o||o.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${De(t,e)}.${process.pid}.${Vr(3).toString("hex")}.claim`;try{Xr(De(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...o,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??Zi)(o).catch(d=>({ok:!1,error:String(d?.message??d)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Kr(t,i);try{Yi(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as ta,writeFileSync as na}from"fs";import{resolve as Qr}from"path";var Zr="ready",ra="202510";function oa(t){let e=t.date??t.created_at.slice(0,10);return Qr(t.workspace,Zr,`${e}-${t.platform}-${t.id}.txt`)}function Jr(t){let e=oa(t);return ta(Qr(t.workspace,Zr),{recursive:!0}),na(e,t.text.endsWith(`
1
+ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as _r,O as Dr,k as K}from"./chunk-7T5Y4H2J.js";import{f as Tr,g as Ar,h as Rr,l as Ir}from"./chunk-PSYHAO57.js";import{b as $r}from"./chunk-2VDO2HEK.js";import{t as Sr,u as Er}from"./chunk-JEBU5JUM.js";import{d as kr,e as vr}from"./chunk-AQASR6KR.js";import{h as pe,j as ur,l as pr,m as gr,n as mr}from"./chunk-RX5O5637.js";import{a as fr,c as hr,e as br,f as ut,h as yr,j as wr,k as xr,l as pt,m as gt,n as mt}from"./chunk-5ELIX7BQ.js";import{a as or,c as sr}from"./chunk-KP7KDLZ2.js";import{Aa as ue,Ca as dt,b as at,f as Yn,s as lt,u as ct,xa as Re,ya as tr,za as W}from"./chunk-FR4DTMCA.js";import{a as Te,b as de,e as Jn}from"./chunk-7AB3QUGH.js";import{h as ir,i as ar,j as lr,l as cr,m as dr}from"./chunk-H4DWZIU7.js";import{s as er}from"./chunk-CAH6TNC6.js";import{a as Qn,b as Ae,e as Zn}from"./chunk-N476XZD3.js";import{c as Ie,d as nr,e as rr}from"./chunk-XVV7ZZ77.js";import{b as ee}from"./chunk-5ONH4ITT.js";import{a as Gn,c as it}from"./chunk-ILEC3IAV.js";import{a as jn,i as Xn,l as zn,n as ot,o as st,r as ce,s as Z,u as Kn}from"./chunk-XL7UWG36.js";import{a as Bn,b as Hn,d as qn,e as Vn}from"./chunk-MNG2AMKZ.js";import{a as Wn}from"./chunk-7IW25T4K.js";import{a as Un}from"./chunk-QUFIUXMQ.js";import{E as _e,Ea as Cn,F as $n,Fa as Nn,G as Tn,H as Si,Ha as On,Ia as Ln,Ib as rt,Sb as Pn,Tb as Mn,bc as Fn,ca as $e,ea as An,f as Ze,g as C,i as Ee,j as E,k as le,l as En,o as _n,p as et,ya as Dn}from"./chunk-KAM4ZWRE.js";import{a as tt,h as Ei}from"./chunk-KEUW6YLL.js";import{j as nt,q as Rn,r as In}from"./chunk-N47Y5ADQ.js";import{existsSync as _i,readdirSync as $i,readFileSync as Ti,statSync as Ai}from"fs";import{resolve as Ri}from"path";function Cr(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],d=a.filter(m=>n-m.at<=o),l=a.filter(m=>n-m.at>o&&n-m.at<=o*2),c=d.filter(m=>m.status==="failed").length,p=a.filter(m=>m.status==="paused").length,u=a.length?Math.max(...a.map(m=>m.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var De=new Map;function Iu(t,e=1e3){if(!_i(t))return[];let n=$i(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ri(t,s);return{path:i,mtime:Ai(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of De.keys())r.has(s)||De.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=De.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Ii(s,i);De.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Ii(t,e){try{let n=Ti(t,"utf-8").split(`
2
+ `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Nr=7,Di={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},A={routines:200,summary:160,filters:6,filterValue:60,text:120},Ci=(t,e,n)=>{try{return er(t,e,n)}catch{return null}},Or=864e5;function Ou(t){let e=t.now??Date.now(),n={...Di,...t.thresholds},r=t.nextFire??Ci,o=[];for(let a of t.crons){let d=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",c=d.map(g=>({at:Date.parse(g.startedAt),status:g.status})),p=d[0],u={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:F(a.id,A.text),trigger:{schedule:F(a.schedule,A.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?ht(a.nextRun)??ht(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:Fi(p.status==="success"?void 0:p.errorSummary,A.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Lr(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Nr).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Pr(u,c,a.schedule,l,null,e,n,r),o.push(Mr(u))}let s=new Map(Cr(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 d=i.get(a.workflowId);d?d.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let d=a.nodes.find(k=>k.type.startsWith("trigger."));if(!d||d.type!=="trigger.cron"&&d.type!=="trigger.hook")continue;let l=d.config??{},c=a.state||"active",p=c==="active",u=(i.get(a.id)??[]).slice().sort((k,D)=>D.at-k.at),g=u.map(k=>({at:k.at,status:Li(k.status)})),m=g[0],f=d.type==="trigger.cron",w=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",b={id:`workflow:${a.id}`,source:"workflow",kind:f?"schedule":"event",name:F(a.title||a.id,A.text),trigger:f?{schedule:F(w,A.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",A.text),filters:Mi(l.filter,a)},agent:Pi(a),enabled:p,state:c,nextRunAt:f&&p&&w?ht(r(w,new Date(e),x)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let k=g.find(D=>D.status==="success");return k?new Date(k.at).toISOString():null})(),consecutiveFailures:Lr(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Nr).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=f?Pr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):Ni(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Mr(b))}return o.sort(Oi).slice(0,A.routines)}function Lr(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 Pr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=Ur(l,o,s,i);return u&&d.push(u),d}if(t.consecutiveFailures>=i.failStreak&&d.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return d.push({reason:"never-ran",detail:"No persisted attempt"}),d;let c=new Date(l),p=null;for(let u=0;u<i.missedFires&&(p=a(n,c,r),!!p);u++)c=p;return p&&s>p.getTime()+i.graceMs&&d.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),d}function Ni(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Ur(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function Ur(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Or?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Or)} days`:"Disabled and never ran"}}function Mr(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 Fr={critical:0,warning:1,info:2};function Oi(t,e){let n=t.attention?Fr[t.attention]:3,r=e.attention?Fr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Li(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Pi(t){if(t.ownerAgent)return F(t.ownerAgent,A.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?F(String(e.config.agentId),A.text):null}function Mi(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,A.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(F(`${o}=${i.join(",")}`,A.filterValue))}return n.slice(0,A.filters)}function ht(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function F(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Fi(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as Ui,readFileSync as Wi,renameSync as ji,writeFileSync as Bi}from"fs";import{resolve as Hi}from"path";function Wr(t){return Hi(st(t),"_state.json")}function N(t){try{let e=JSON.parse(Wi(Wr(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 ge(t,e){Ui(st(t),{recursive:!0});let n=Wr(t),r=`${n}.${process.pid}.tmp`;Bi(r,JSON.stringify(e,null,2)+`
3
+ `),ji(r,n)}function jr(t,e,n,r=Date.now()){let o=N(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),ge(t,{...o,snoozed:s})}function Uu(t,e){ge(t,{...N(t),lastDigest:e})}function bt(t,e,n,r=Date.now()){let o=N(t),s=new Set(n),i={};for(let[d,l]of Object.entries(o.popped??{}))s.has(d)&&(i[d]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(d=>d!==e&&s.has(d));ge(t,{...o,popped:i,wanted:a})}function Br(t,e){let n=N(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Wu(t,e=Date.now()){ge(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as qi,readFileSync as Vi}from"fs";Fn();Ei();function Hr(t){let e=Qn(t),n={};if(qi(e))try{n=Pn(JSON.parse(Vi(e,"utf-8")))}catch{n={}}let r=rt.safeParse(n?.requests);return r.success?r.data:rt.parse(void 0)}async function Xu(t,e={}){let n=(t.channels??[]).filter(r=>!tt.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...tt].join(", ")}`}:Ae(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as q,readdirSync as pa,readFileSync as kt,statSync as ga}from"fs";import{dirname as co,resolve as T}from"path";import{randomBytes as Xr}from"crypto";import{existsSync as zi,mkdirSync as Ki,readdirSync as Gi,readFileSync as Yi,renameSync as zr,unlinkSync as Ji,writeFileSync as Qi}from"fs";import{resolve as Kr}from"path";function qr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Xi=t=>t.trim().split(`
4
+ `).pop()?.slice(0,300)||"no output";async function Vr(t,e,n,r=ft){let o=await r(t.bin,[...qr(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Xi(o.stderr||o.stdout)}`}}async function Gu(t,e,n,r,o=ft){return(await o(t.bin,[...qr(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Zi=2e3,ea=t=>Vr(t.wacli,t.to,t.text);function yt(t){return Kr(t,".agentx","whatsapp-triage","drafts")}var ta=t=>/^[a-z0-9-]{8,64}$/.test(t),Ce=(t,e)=>Kr(yt(t),`${e}.json`);function Gr(t,e){Ki(yt(t),{recursive:!0});let n=Ce(t,e.id),r=`${n}.${process.pid}.tmp`;Qi(r,JSON.stringify(e,null,2)+`
5
+ `,{mode:384}),zr(r,n)}function tp(t,e,n=Date.now()){let r=e.text.trim().slice(0,Zi);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${Xr(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Gr(t,o),o}function Ne(t,e){if(!ta(e))return null;try{return JSON.parse(Yi(Ce(t,e),"utf-8"))}catch{return null}}function Yr(t,e){let n=yt(t);return zi(n)?Gi(n).filter(r=>r.endsWith(".json")).map(r=>Ne(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function Jr(t,e,n,r={}){let o=Ne(t,e);if(!o||o.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${Ce(t,e)}.${process.pid}.${Xr(3).toString("hex")}.claim`;try{zr(Ce(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...o,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??ea)(o).catch(d=>({ok:!1,error:String(d?.message??d)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Gr(t,i);try{Ji(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as na,writeFileSync as ra}from"fs";import{resolve as Zr}from"path";var eo="ready",oa="202510";function sa(t){let e=t.date??t.created_at.slice(0,10);return Zr(t.workspace,eo,`${e}-${t.platform}-${t.id}.txt`)}function Qr(t){let e=sa(t);return na(Zr(t.workspace,eo),{recursive:!0}),ra(e,t.text.endsWith(`
6
6
  `)?t.text:`${t.text}
7
- `),e}function eo(t,e,n){let r=Un(t.config,e,n);if(!r)return null;let o=t.env??process.env,s=r.integration.credentials?.tokenEnv,i=s?o[s]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function to(t,e,n){return eo(t,e,n)!==null}async function sa(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 o=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??ra),"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(!o.ok)throw new Error(`LinkedIn said ${o.status}: ${(await o.text().catch(()=>"")).slice(0,200)}`);let s=o.headers.get("x-restli-id");return s?{url:`https://www.linkedin.com/feed/update/${s}/`}:{}}async function ia(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 o=await r.json().catch(()=>({}));return o.data?.id?{url:`https://x.com/i/web/status/${o.data.id}`}:{}}async function aa(t,e){let n=eo(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Jr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await sa(t.text,n,r):await ia(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Jr(t);return{ok:!1,error:`not posted on ${pe[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function no(t){return e=>aa(e,t)}Rn();On();On();Rn();var pp=["done","skipped"],la=1e3;function ca(t){t.exec(`
7
+ `),e}function to(t,e,n){let r=Wn(t.config,e,n);if(!r)return null;let o=t.env??process.env,s=r.integration.credentials?.tokenEnv,i=s?o[s]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function no(t,e,n){return to(t,e,n)!==null}async function ia(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 o=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??oa),"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(!o.ok)throw new Error(`LinkedIn said ${o.status}: ${(await o.text().catch(()=>"")).slice(0,200)}`);let s=o.headers.get("x-restli-id");return s?{url:`https://www.linkedin.com/feed/update/${s}/`}:{}}async function aa(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 o=await r.json().catch(()=>({}));return o.data?.id?{url:`https://x.com/i/web/status/${o.data.id}`}:{}}async function la(t,e){let n=to(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Qr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await ia(t.text,n,r):await aa(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Qr(t);return{ok:!1,error:`not posted on ${pe[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function ro(t){return e=>la(e,t)}In();Ln();Ln();In();var dp=["done","skipped"],ca=1e3;function da(t){t.exec(`
8
8
  CREATE TABLE IF NOT EXISTS request_plans (
9
9
  request_id TEXT PRIMARY KEY,
10
10
  created_by TEXT NOT NULL,
@@ -60,17 +60,17 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as Er,O as Ir,k as K}from"./ch
60
60
  told_at INTEGER,
61
61
  PRIMARY KEY (goal_key, day)
62
62
  );
63
- `),An(t,"request_plan_steps",[["check_count","TEXT"],["last_count","INTEGER"],["last_count_at","INTEGER"]])}function oo(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function wt(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 ro(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,checkCount:t.check_count??null,lastCount:t.last_count??null,lastCountAt:t.last_count_at??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var da={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at",lastCount:"last_count",lastCountAt:"last_count_at"},Ne=class{constructor(e){this.db=e;ca(e)}create(e,n,r,o){let s=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
63
+ `),Rn(t,"request_plan_steps",[["check_count","TEXT"],["last_count","INTEGER"],["last_count_at","INTEGER"]])}function so(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function wt(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 oo(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,checkCount:t.check_count??null,lastCount:t.last_count??null,lastCountAt:t.last_count_at??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var ua={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at",lastCount:"last_count",lastCountAt:"last_count_at"},Oe=class{constructor(e){this.db=e;da(e)}create(e,n,r,o){let s=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
64
64
  to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)
65
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,d)=>{let l=d===0,c=l&&a.agentId===n&&a.kind!=="message";i.run(e,d+1,a.name,a.kind,a.agentId,a.doneWhen,l?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,c?o:null,o,a.checkCount??null)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,o)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?wt(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(ro)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?ro(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(wt)}updateStep(e,n,r){let o=[],s=[];for(let[i,a]of Object.entries(r)){let d=da[i];!d||a===void 0||(o.push(`${d} = ?`),s.push(typeof a=="boolean"?a?1:0:a))}o.length&&this.db.prepare(`UPDATE request_plan_steps SET ${o.join(", ")} WHERE request_id = ? AND idx = ?`).run(...s,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(wt)}event(e,n,r,o,s){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,s,r,o.replace(/\s+/g," ").trim().slice(0,la))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
65
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,d)=>{let l=d===0,c=l&&a.agentId===n&&a.kind!=="message";i.run(e,d+1,a.name,a.kind,a.agentId,a.doneWhen,l?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,c?o:null,o,a.checkCount??null)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,o)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?wt(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(oo)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?oo(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(wt)}updateStep(e,n,r){let o=[],s=[];for(let[i,a]of Object.entries(r)){let d=ua[i];!d||a===void 0||(o.push(`${d} = ?`),s.push(typeof a=="boolean"?a?1:0:a))}o.length&&this.db.prepare(`UPDATE request_plan_steps SET ${o.join(", ")} WHERE request_id = ? AND idx = ?`).run(...s,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(wt)}event(e,n,r,o,s){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,s,r,o.replace(/\s+/g," ").trim().slice(0,ca))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
66
66
  ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,
67
- told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},gp=Dn;var co=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],ga=280;function O(t,e=ga){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function te(t){if(t.configPath)return T(t.configPath);let e=[T(t.root,"agentx.json"),T(t.root,".agentx","config.json")];return e.find(n=>H(n))??e[0]}function V(t){return t.wikiDir?T(t.wikiDir):T(t.root,".agentx","wiki")}function ma(t){return Z(t.root,"pending").map(fa)}function fa(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:O([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function ha(t){let e=te(t);if(!H(e))return[];let n;try{n=JSON.parse(kt(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),o=[];for(let[s,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let d=i.timezone||"UTC",l=i.schedule?sr(i.schedule):"",c=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",p=String(i.prompt??i.command??""),u=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:u?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:u?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${s}" (${c})?`,yes:u?"enable it":"remove it",no:u?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:O(`${p}${u&&i.schedule?` \xB7 first run ${ar(ir(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function uo(t){let e=T(t,".agentx","memory");return H(e)?ua(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ba(t){let e=uo(t.root);if(e.length===0)return[];let n=new at(t.root),r=[];for(let o of e)for(let s of n.held(o))r.push({key:`memory:${o}/${s.id}`,kind:"memory",title:`Fact ${o} learned from ${s.source.channel}`,ask:`Let ${o} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:o,created_at:s.createdAt,detail:O(s.content),more:`agentx memory facts held --agent ${o}`});return r}function ya(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 wa(t){return kr(V(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:O(`${ya(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var so=new Map;function po(t,e){let n=pa(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=so.get(t);if(o?.version===r)return o.value;let s=e();return so.set(t,{version:r,value:s}),s}function xa(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${O(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:O(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function ka(t,e){let n=V(t);if(!H(T(n,"_facts.json")))return;let r=Re(new ee(n),"pending").find(o=>o.id===e);return r?xa(r):void 0}function va(t){let e=T(V(t),"_facts.json");if(!H(e))return;let n=po(e,()=>Re(new ee(lo(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function Sa(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function go(t){let e=V(t),n=new it(e);if(!H(n.path))return[];let r=po(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ee(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:Sa(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function Ea(t){return Gr(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:O(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function _a(t){return Tr(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:O(`Last try not sent: ${e.error}`)}:{}}))}function $a(t){let e=Object.entries(lt(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Oe(t).agents??{};return e.map(([r,o])=>{let s=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${s.name||r}", created by ${o.by}`,ask:`Let ${s.name||r} (${s.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:o.by,created_at:o.at,detail:O(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Oe(t){try{return JSON.parse(kt(te(t),"utf-8"))}catch{return{}}}function xt(t){let e={};try{e=Object.fromEntries(Fn(kt(T(lo(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function Ta(t){let e=pr(t.root,"pending");if(e.length===0)return[];let n=Oe(t),r=xt(t);return e.map(o=>{let s=pe[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:to({config:n,env:r},o.agent,o.platform)?`post it on ${s}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:o.agent,created_at:o.created_at,detail:O(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:dr(o.text)}})}function G(t){if(t.requests)return t.requests;if(T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=nt({quiet:!0});if(!e)return null;let n=io.get(e);return!n&&!Cn(e)?null:(n||io.set(e,n=new Nn(e)),n)}var io=new WeakMap;function jp(t){if(t.plans)return t.plans;if(t.requests||T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=nt({quiet:!0});if(!e||!oo(e))return null;let n=ao.get(e);return n||ao.set(e,n=new Ne(e)),n}var ao=new WeakMap;function Aa(t){let e=G(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:K(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:O(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var mo={card:ma,schedule:ha,agent:$a,memory:ba,wiki:wa,fact:()=>[],question:go,whatsapp:Ea,email:_a,content:Ta,request:Aa};function Ra(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 fo(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??co){if(d==="fact"){try{let c=va(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=mo[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Ra),{items:o,snoozed:a,errors:s,backlog:i}}function ho(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!co.includes(n)||!r?null:{kind:n,ref:r}}function Ia(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return xr(V(t),n)?.status==="pending";case"whatsapp":return Ce(t.root,n)?.status==="pending";case"email":return $r(t.root,n)?.status==="pending";case"content":return ur(t.root,n)?.status==="pending";default:return!!bo(t,e,n)}}function bo(t,e,n){return e==="fact"?ka(t,n):mo[e](t).find(r=>r.key===`${e}:${n}`)}async function yo(t,e,n,r={}){let o=n==="later"?null:ho(e),s;if(o)try{s=bo(t,o.kind,o.ref)}catch{s=void 0}let i=await Da(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;Wn(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Da(t,e,n,r){let o=ho(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),d=r.by??"operator";if(n==="later"){if(!Ia(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return Wr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=zn(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text,popup:r.popup});return c.ok?{ok:!0,message:`${e}: ${c.card.raised_by} will be told ${l?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(l?lr:cr)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(lt(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return ct(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let c=[],p=await Te(u=>{Qn(u,`agents.${i}`);for(let[g,m]of Object.entries(u.crons??{}))m?.agent===i&&(delete u.crons[g],c.push(g))},{configPath:te(t),reload:t.reload});return p.success?(ct(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${c.length?`, with its schedules ${c.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:p.error||"could not remove it from agentx.json"}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let p=i.slice(0,c),u=i.slice(c+1);if(!uo(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new at(t.root);return g.held(p).some(m=>m.id===u)?(g.review(p,u,l?"approved":"rejected",d),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${u}" isn't waiting for review`}}case"wiki":{let c=V(t),p=l?vr(c,i,{by:d,force:r.force,now:a}):Sr(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Ca(t,e,i,l,d,r);case"question":return Oa(t,e,i,l,d,r);case"whatsapp":{let c=await Yr(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Rr(Oe(t),xt(t)),p=await Ar(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,send:c});return p.ok?{ok:!0,message:l?`${e}: sent to ${p.draft.to}${p.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:p}case"content":{let c=t.publishContent??no({config:Oe(t),env:xt(t)}),p=await gr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=pe[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Br(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.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 ${d}`,a,null,d==="operator"?In:d),{ok:!0,message:`${e}: dropped`})}}}function Ca(t,e,n,r,o,s){let i=new ee(V(t));try{let a=Re(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return nr(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=tr(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function Na(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function Oa(t,e,n,r,o,s){let i=V(t),a=new it(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Kn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=go(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=Na(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,m)=>`${m+1}. ${g}`).join(", ")}`};let p=new ee(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var La=3,Pa=7,Ma=50,St=120,Fa=280,vt=600,xo=36e5,Ua=24*xo;function Hp(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 ne(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Le=t=>new Date(t).toISOString();function Wa(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:ne(e.title,St),...e.ask?{ask:ne(e.ask,vt)}:{},...e.detail?{facts:ne(e.detail,Fa)}:{},...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 ja={done:"Done",declined:"Declined",dropped:"Dropped"};function ko(t,e,n){let{record:r,links:o}=e,s=K(r,St),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:ne(s.said,vt)}:{},agent:r.agentId,askedAt:Le(r.createdAt),changedAt:Le(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return o.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:ne(r.question,vt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),d=t.now-r.updatedAt<(t.quietHours??La)*xo;return{...i,column:a||d?"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:Le(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:ja[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Ba(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 qa(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:ne(e.title,St),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Ba(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,wo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function Et(t){let e=[],n=[];for(let o of t.inbox){o.error&&n.push(`What waits on ${o.nodeName} could not be read: ${o.error}`);for(let s of o.items)e.push(Wa(o,s,o.node===t.node))}let r=vo(t,e);for(let o of t.requests??[]){let s=ko(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function vo(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Vp(t){let e=Et(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,o=vo(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=ko(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??Pa)*Ua;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(qa(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,Ma),c=wo(n,"askedAt"),p=wo(i,"changedAt");return{ts:Le(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...p?{oldest:p}:{}},done:{count:l.length}},errors:r}}function Ha(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function Va(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function Gp(t,e){let n=t.now??Date.now(),r=[],o=fo(t,{includeSnoozed:!0});for(let c of o.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let s=o.items.filter(c=>!c.snoozed_until),i=new Set(o.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=G(t);c&&(a=c.listByState("waiting_owner").map(p=>({record:p,links:c.links(p.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:d,errors:l}=Et({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Ha)}],requests:a,deferred:i});return Va(d,i.size,[...r,...l])}import{readFileSync as Xa}from"fs";var za=1e4,So=/^[0-9a-f]{7,64}$/i;function Qp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&So.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(za)})}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 o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&So.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Zp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Xa(n.tokenFile,"utf-8").trim().split(`
68
- `)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var Pe=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function tg(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/assistant"||t.startsWith("/api/assistant/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/api/org"||t.startsWith("/api/org/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"||t==="/lookup"}function ng(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/events"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/channels\/[^/]+\/switch$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"||t==="/api/signals/stop-all"||t==="/api/signals/stop-all/report"||t==="/api/review-gate/replay"}function rg(t){return Pe.has(t)}function og(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Pe.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 sg(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.chatSecret&&n===t.chatSecret?!0:t.foreignBrowser?!1:n&&t.acceptedTokens.has(n)?!0:!t.chatSecret&&Pe.has(t.remoteAddress)}function ig(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return t.chatSecret?n===t.chatSecret:Pe.has(t.remoteAddress)||!!n&&t.acceptedTokens.has(n)}function ag(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 lg(t,e,n=process.env){let r=s=>s.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(s=>r(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function Me(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Ka(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ga(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function dg(t,e=Ga()){let n=Me(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=Ka(n),s=[Me(t.host),Me(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=Me(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function ug(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var _t="/api/admin/pictures",Ya=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Ja=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function _(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function Qa(t){let e={agent:{},person:{}};for(let n of mr)for(let[r,o]of Object.entries(br(t,n)))e[n][r]=yr(n,r,o);return e}function mg(t,e,n,r,o){let s=n.match(Ya);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return _(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=wr(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":fr,"Content-Length":String(a.length),"Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'"}),e.end(a),!0):(_(e,404,{error:"no such picture"}),!0)}async function fg(t,e,n,r){if(n!==_t&&!n.startsWith(`${_t}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===_t)return o!=="GET"?(_(e,405,{error:"GET only"}),!0):(_(e,200,{...Qa(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Ja);if(!s)return _(e,404,{error:"not found"}),!0;if(o!=="PUT"&&o!=="DELETE")return _(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return _(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=s[1],d=decodeURIComponent(s[2]),l=a==="agent"?r.agentIds():r.personIds();if(!hr.test(d)||!l.includes(d))return _(e,404,{error:a==="agent"?`no agent "${d}" in agentx.json`:`no person "${d}" in agentx.json`}),!0;if(o==="DELETE"){let c=gt(r.root,a,d);return _(e,200,{ok:!0,removed:c}),!0}try{let c=await mt(t),p=await pt(r.root,a,d,c);_(e,200,{ok:!0,url:p.url})}catch(c){if(c instanceof ut)return _(e,c.status,{error:c.message}),!0;throw c}return!0}async function hg(t,e,n,r){let o=(t.method||"GET").toUpperCase();if(o!=="PUT"&&o!=="DELETE"){_(e,405,{error:"PUT or DELETE only"});return}let s=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(s);if(!i){_(e,403,{error:"Only an agent sets its own picture, from its own run: send X-AgentX-Task (or X-AgentX-Channel and X-AgentX-Chat) of a running turn. The owner sets pictures in Settings."});return}if(s&&s!==i){_(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${s}".`});return}if(o==="DELETE"){_(e,200,{ok:!0,agent:i,removed:gt(r.root,"agent",i)});return}try{let a=await pt(r.root,"agent",i,await mt(t));_(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof ut){_(e,a.status,{error:a.message});return}throw a}}var Eo={};function wg(t){Eo=t}function xg(){return Eo}var kg=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
67
+ told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},up=Cn;var uo=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],ma=280;function O(t,e=ma){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function te(t){if(t.configPath)return T(t.configPath);let e=[T(t.root,"agentx.json"),T(t.root,".agentx","config.json")];return e.find(n=>q(n))??e[0]}function V(t){return t.wikiDir?T(t.wikiDir):T(t.root,".agentx","wiki")}function fa(t){return Z(t.root,"pending").map(ha)}function ha(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:O([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function ba(t){let e=te(t);if(!q(e))return[];let n;try{n=JSON.parse(kt(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),o=[];for(let[s,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let d=i.timezone||"UTC",l=i.schedule?ir(i.schedule):"",c=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",p=String(i.prompt??i.command??""),u=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:u?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:u?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${s}" (${c})?`,yes:u?"enable it":"remove it",no:u?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:O(`${p}${u&&i.schedule?` \xB7 first run ${lr(ar(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function po(t){let e=T(t,".agentx","memory");return q(e)?pa(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ya(t){let e=po(t.root);if(e.length===0)return[];let n=new at(t.root),r=[];for(let o of e)for(let s of n.held(o))r.push({key:`memory:${o}/${s.id}`,kind:"memory",title:`Fact ${o} learned from ${s.source.channel}`,ask:`Let ${o} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:o,created_at:s.createdAt,detail:O(s.content),more:`agentx memory facts held --agent ${o}`});return r}function wa(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 xa(t){return vr(V(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:O(`${wa(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var io=new Map;function go(t,e){let n=ga(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=io.get(t);if(o?.version===r)return o.value;let s=e();return io.set(t,{version:r,value:s}),s}function ka(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${O(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:O(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function va(t,e){let n=V(t);if(!q(T(n,"_facts.json")))return;let r=Ie(new ee(n),"pending").find(o=>o.id===e);return r?ka(r):void 0}function Sa(t){let e=T(V(t),"_facts.json");if(!q(e))return;let n=go(e,()=>Ie(new ee(co(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function Ea(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function mo(t){let e=V(t),n=new it(e);if(!q(n.path))return[];let r=go(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ee(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:Ea(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function _a(t){return Yr(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:O(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function $a(t){return Ar(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:O(`Last try not sent: ${e.error}`)}:{}}))}function Ta(t){let e=Object.entries(lt(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Le(t).agents??{};return e.map(([r,o])=>{let s=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${s.name||r}", created by ${o.by}`,ask:`Let ${s.name||r} (${s.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:o.by,created_at:o.at,detail:O(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Le(t){try{return JSON.parse(kt(te(t),"utf-8"))}catch{return{}}}function xt(t){let e={};try{e=Object.fromEntries(Un(kt(T(co(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function Aa(t){let e=gr(t.root,"pending");if(e.length===0)return[];let n=Le(t),r=xt(t);return e.map(o=>{let s=pe[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:no({config:n,env:r},o.agent,o.platform)?`post it on ${s}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:o.agent,created_at:o.created_at,detail:O(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:ur(o.text)}})}function G(t){if(t.requests)return t.requests;if(T(t.root)!==process.cwd()||!q(T(t.root,".agentx","db.sqlite")))return null;let e=nt({quiet:!0});if(!e)return null;let n=ao.get(e);return!n&&!Nn(e)?null:(n||ao.set(e,n=new On(e)),n)}var ao=new WeakMap;function Up(t){if(t.plans)return t.plans;if(t.requests||T(t.root)!==process.cwd()||!q(T(t.root,".agentx","db.sqlite")))return null;let e=nt({quiet:!0});if(!e||!so(e))return null;let n=lo.get(e);return n||lo.set(e,n=new Oe(e)),n}var lo=new WeakMap;function Ra(t){let e=G(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:K(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:O(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var fo={card:fa,schedule:ba,agent:Ta,memory:ya,wiki:xa,fact:()=>[],question:mo,whatsapp:_a,email:$a,content:Aa,request:Ra};function Ia(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function ho(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??uo){if(d==="fact"){try{let c=Sa(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=fo[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Ia),{items:o,snoozed:a,errors:s,backlog:i}}function bo(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!uo.includes(n)||!r?null:{kind:n,ref:r}}function Da(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return kr(V(t),n)?.status==="pending";case"whatsapp":return Ne(t.root,n)?.status==="pending";case"email":return Tr(t.root,n)?.status==="pending";case"content":return pr(t.root,n)?.status==="pending";default:return!!yo(t,e,n)}}function yo(t,e,n){return e==="fact"?va(t,n):fo[e](t).find(r=>r.key===`${e}:${n}`)}async function wo(t,e,n,r={}){let o=n==="later"?null:bo(e),s;if(o)try{s=yo(t,o.kind,o.ref)}catch{s=void 0}let i=await Ca(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;jn(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ca(t,e,n,r){let o=bo(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),d=r.by??"operator";if(n==="later"){if(!Da(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return jr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=Kn(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text,popup:r.popup});return c.ok?{ok:!0,message:`${e}: ${c.card.raised_by} will be told ${l?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(l?cr:dr)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(lt(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return ct(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let c=[],p=await Ae(u=>{Zn(u,`agents.${i}`);for(let[g,m]of Object.entries(u.crons??{}))m?.agent===i&&(delete u.crons[g],c.push(g))},{configPath:te(t),reload:t.reload});return p.success?(ct(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${c.length?`, with its schedules ${c.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:p.error||"could not remove it from agentx.json"}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let p=i.slice(0,c),u=i.slice(c+1);if(!po(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new at(t.root);return g.held(p).some(m=>m.id===u)?(g.review(p,u,l?"approved":"rejected",d),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${u}" isn't waiting for review`}}case"wiki":{let c=V(t),p=l?Sr(c,i,{by:d,force:r.force,now:a}):Er(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Na(t,e,i,l,d,r);case"question":return La(t,e,i,l,d,r);case"whatsapp":{let c=await Jr(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Ir(Le(t),xt(t)),p=await Rr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,send:c});return p.ok?{ok:!0,message:l?`${e}: sent to ${p.draft.to}${p.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:p}case"content":{let c=t.publishContent??ro({config:Le(t),env:xt(t)}),p=await mr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=pe[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Hr(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.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 ${d}`,a,null,d==="operator"?Dn:d),{ok:!0,message:`${e}: dropped`})}}}function Na(t,e,n,r,o,s){let i=new ee(V(t));try{let a=Ie(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return rr(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=nr(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function Oa(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function La(t,e,n,r,o,s){let i=V(t),a=new it(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Gn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=mo(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=Oa(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,m)=>`${m+1}. ${g}`).join(", ")}`};let p=new ee(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var Pa=3,Ma=7,Fa=50,St=120,Ua=280,vt=600,ko=36e5,Wa=24*ko;function Bp(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 ne(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 ja(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:ne(e.title,St),...e.ask?{ask:ne(e.ask,vt)}:{},...e.detail?{facts:ne(e.detail,Ua)}:{},...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 Ba={done:"Done",declined:"Declined",dropped:"Dropped"};function vo(t,e,n){let{record:r,links:o}=e,s=K(r,St),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:ne(s.said,vt)}:{},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 o.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:ne(r.question,vt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),d=t.now-r.updatedAt<(t.quietHours??Pa)*ko;return{...i,column:a||d?"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:Ba[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Ha(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 qa(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:ne(e.title,St),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Ha(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,xo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function Et(t){let e=[],n=[];for(let o of t.inbox){o.error&&n.push(`What waits on ${o.nodeName} could not be read: ${o.error}`);for(let s of o.items)e.push(ja(o,s,o.node===t.node))}let r=So(t,e);for(let o of t.requests??[]){let s=vo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function So(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Hp(t){let e=Et(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,o=So(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=vo(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??Ma)*Wa;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(qa(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,Fa),c=xo(n,"askedAt"),p=xo(i,"changedAt");return{ts:Pe(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...p?{oldest:p}:{}},done:{count:l.length}},errors:r}}function Va(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function Xa(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function zp(t,e){let n=t.now??Date.now(),r=[],o=ho(t,{includeSnoozed:!0});for(let c of o.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let s=o.items.filter(c=>!c.snoozed_until),i=new Set(o.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=G(t);c&&(a=c.listByState("waiting_owner").map(p=>({record:p,links:c.links(p.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:d,errors:l}=Et({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Va)}],requests:a,deferred:i});return Xa(d,i.size,[...r,...l])}import{readFileSync as za}from"fs";var Ka=1e4,Eo=/^[0-9a-f]{7,64}$/i;function Yp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&Eo.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(Ka)})}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 o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&Eo.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Jp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=za(n.tokenFile,"utf-8").trim().split(`
68
+ `)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var Me=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function Zp(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/assistant"||t.startsWith("/api/assistant/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/api/org"||t.startsWith("/api/org/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"||t==="/lookup"}function eg(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/events"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/channels\/[^/]+\/switch$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"||t==="/api/signals/stop-all"||t==="/api/signals/stop-all/report"||t==="/api/review-gate/replay"}function tg(t){return Me.has(t)}function ng(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Me.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 rg(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.chatSecret&&n===t.chatSecret?!0:t.foreignBrowser?!1:n&&t.acceptedTokens.has(n)?!0:!t.chatSecret&&Me.has(t.remoteAddress)}function og(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return t.chatSecret?n===t.chatSecret:Me.has(t.remoteAddress)||!!n&&t.acceptedTokens.has(n)}function sg(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 ig(t,e,n=process.env){let r=s=>s.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(s=>r(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function Fe(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Ga(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ya(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function lg(t,e=Ya()){let n=Fe(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=Ga(n),s=[Fe(t.host),Fe(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=Fe(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function cg(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var _t="/api/admin/pictures",Ja=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Qa=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function _(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function Za(t){let e={agent:{},person:{}};for(let n of fr)for(let[r,o]of Object.entries(yr(t,n)))e[n][r]=wr(n,r,o);return e}function pg(t,e,n,r,o){let s=n.match(Ja);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return _(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=xr(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":hr,"Content-Length":String(a.length),"Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'"}),e.end(a),!0):(_(e,404,{error:"no such picture"}),!0)}async function gg(t,e,n,r){if(n!==_t&&!n.startsWith(`${_t}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===_t)return o!=="GET"?(_(e,405,{error:"GET only"}),!0):(_(e,200,{...Za(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Qa);if(!s)return _(e,404,{error:"not found"}),!0;if(o!=="PUT"&&o!=="DELETE")return _(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return _(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=s[1],d=decodeURIComponent(s[2]),l=a==="agent"?r.agentIds():r.personIds();if(!br.test(d)||!l.includes(d))return _(e,404,{error:a==="agent"?`no agent "${d}" in agentx.json`:`no person "${d}" in agentx.json`}),!0;if(o==="DELETE"){let c=gt(r.root,a,d);return _(e,200,{ok:!0,removed:c}),!0}try{let c=await mt(t),p=await pt(r.root,a,d,c);_(e,200,{ok:!0,url:p.url})}catch(c){if(c instanceof ut)return _(e,c.status,{error:c.message}),!0;throw c}return!0}async function mg(t,e,n,r){let o=(t.method||"GET").toUpperCase();if(o!=="PUT"&&o!=="DELETE"){_(e,405,{error:"PUT or DELETE only"});return}let s=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(s);if(!i){_(e,403,{error:"Only an agent sets its own picture, from its own run: send X-AgentX-Task (or X-AgentX-Channel and X-AgentX-Chat) of a running turn. The owner sets pictures in Settings."});return}if(s&&s!==i){_(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${s}".`});return}if(o==="DELETE"){_(e,200,{ok:!0,agent:i,removed:gt(r.root,"agent",i)});return}try{let a=await pt(r.root,"agent",i,await mt(t));_(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof ut){_(e,a.status,{error:a.message});return}throw a}}var _o={};function bg(t){_o=t}function yg(){return _o}var wg=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
69
69
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">
70
70
  <link rel="preconnect" href="https://fonts.googleapis.com">
71
71
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
72
72
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&family=Roboto+Mono:wght@400;500;600&display=swap" rel="stylesheet">
73
- <script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,vg=`
73
+ <script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,xg=`
74
74
  .ax-topbar{display:flex;align-items:center;justify-content:space-between;
75
75
  padding:8px 18px;border-bottom:1px solid var(--ax-border);
76
76
  background:var(--ax-bg-elev);position:sticky;top:0;z-index:20;gap:10px;flex-wrap:nowrap}
@@ -151,7 +151,7 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as Er,O as Ir,k as K}from"./ch
151
151
  background:var(--ax-bg-elev);border-bottom:1px solid var(--ax-border);
152
152
  flex-wrap:wrap}
153
153
  .ax-subheader > * {flex-shrink:0}
154
- .ax-subheader .spacer{flex:1}`,Sg=`<script>
154
+ .ax-subheader .spacer{flex:1}`,kg=`<script>
155
155
  (function(){
156
156
  function wireTheme(){
157
157
  var sw = document.querySelectorAll('[data-theme-opt]');
@@ -346,7 +346,7 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as Er,O as Ir,k as K}from"./ch
346
346
  document.addEventListener('DOMContentLoaded', wire);
347
347
  } else { wire(); }
348
348
  })();
349
- </script>`;function Eg(t){let e=n=>typeof n=="string"&&n?n:null;return{node:e(t?.node?.id),version:e(t?.version),commit:e(t?.commit),startedAt:e(t?.startedAt),diskNewer:t?.build?.newer===!0}}var Za='<span class="ax-build" hidden></span>';function _g(t){let e=t.peers&&t.peers.length>0?t.peers:[{id:"local",name:"this daemon",dashboardUrl:"",primary:!0}],n=t.currentPeerId||e.find(l=>l.primary)?.id||e[0].id,r=e.find(l=>l.id===n)||e[0],o=e.map(l=>{let c=l.id===n,p=l.primary?' <span style="color:var(--ax-muted);font-size:10px">\xB7 primary</span>':"",u=!!l.tokenScope&&!l.primary,g=u?"#":l.dashboardUrl?`${l.dashboardUrl.replace(/\/+$/,"")}/admin`:"#",m=u?` data-peer-id="${j(l.id)}" data-peer-action="proxy"`:l.primary?' data-peer-id="primary" data-peer-action="proxy"':"",f=u?'<div class="url" style="color:var(--ax-accent)">manage from this dashboard \u2713</div>':l.tokenScope?`<div class="url">${j(l.tokenScope)}</div>`:l.dashboardUrl?'<div class="url" style="color:var(--ax-muted)">(open peer dashboard \u2197)</div>':"";return`<a href="${j(g)}" class="${c?"is-current":""}"${m}>
349
+ </script>`;function vg(t){let e=n=>typeof n=="string"&&n?n:null;return{node:e(t?.node?.id),version:e(t?.version),commit:e(t?.commit),startedAt:e(t?.startedAt),diskNewer:t?.build?.newer===!0}}var el='<span class="ax-build" hidden></span>';function Sg(t){let e=t.peers&&t.peers.length>0?t.peers:[{id:"local",name:"this daemon",dashboardUrl:"",primary:!0}],n=t.currentPeerId||e.find(l=>l.primary)?.id||e[0].id,r=e.find(l=>l.id===n)||e[0],o=e.map(l=>{let c=l.id===n,p=l.primary?' <span style="color:var(--ax-muted);font-size:10px">\xB7 primary</span>':"",u=!!l.tokenScope&&!l.primary,g=u?"#":l.dashboardUrl?`${l.dashboardUrl.replace(/\/+$/,"")}/admin`:"#",m=u?` data-peer-id="${j(l.id)}" data-peer-action="proxy"`:l.primary?' data-peer-id="primary" data-peer-action="proxy"':"",f=u?'<div class="url" style="color:var(--ax-accent)">manage from this dashboard \u2713</div>':l.tokenScope?`<div class="url">${j(l.tokenScope)}</div>`:l.dashboardUrl?'<div class="url" style="color:var(--ax-muted)">(open peer dashboard \u2197)</div>':"";return`<a href="${j(g)}" class="${c?"is-current":""}"${m}>
350
350
  <div class="row"><span class="dot"></span><span>${j(l.name)}${p}</span></div>
351
351
  ${l.dashboardUrl?`<div class="url">${j(l.dashboardUrl)}</div>`:""}
352
352
  ${f}
@@ -355,7 +355,7 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as Er,O as Ir,k as K}from"./ch
355
355
  <span class="name">${j(r.name)}</span>
356
356
  <span class="chev">\u25BE</span>
357
357
  <div class="ax-mesh-menu" role="menu">${o}</div>
358
- </div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:$e,href:de},{id:"live",label:"Live",href:`${de}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:Yn},{id:"people",label:"People",href:`${de}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:`${de}#page=settings`}]}].map(l=>{let c=l.tabs.map(p=>{let u=p.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=p.external?' target="_blank" rel="noopener"':"",m=p.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${p.href}" class="${u}"${g}>${p.label}${m}</a>`}).join("");return`<div class="ax-topbar__group" title="${j(l.name)} tier"><span class="ax-topbar__group-label">${j(l.name)}</span>${c}</div>`}).join("");return`<header class="ax-topbar">
358
+ </div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:Te,href:de},{id:"live",label:"Live",href:`${de}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:Jn},{id:"people",label:"People",href:`${de}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:`${de}#page=settings`}]}].map(l=>{let c=l.tabs.map(p=>{let u=p.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=p.external?' target="_blank" rel="noopener"':"",m=p.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${p.href}" class="${u}"${g}>${p.label}${m}</a>`}).join("");return`<div class="ax-topbar__group" title="${j(l.name)} tier"><span class="ax-topbar__group-label">${j(l.name)}</span>${c}</div>`}).join("");return`<header class="ax-topbar">
359
359
  <div class="ax-topbar__left">
360
360
  <div class="ax-brand">
361
361
  <span class="ax-brand__mark">AX</span>
@@ -366,14 +366,14 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as Er,O as Ir,k as K}from"./ch
366
366
  </div>
367
367
  <div class="ax-topbar__right">
368
368
  ${t.rightExtras||""}
369
- ${Za}
369
+ ${el}
370
370
  ${s}
371
371
  <div class="ax-theme-switch" role="tablist" aria-label="Theme">
372
372
  <button data-theme-opt="dark">Dark</button>
373
373
  <button data-theme-opt="light">Light</button>
374
374
  </div>
375
375
  </div>
376
- </header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function j(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}import{existsSync as Go,mkdirSync as Al,readFileSync as Rl,renameSync as Il,writeFileSync as Dl}from"fs";import{homedir as Cl}from"os";import{dirname as Nl,join as Ol}from"path";import{execFile as dl,execFileSync as ul}from"child_process";import{execFileSync as el}from"child_process";import{existsSync as $o,mkdirSync as tl,readdirSync as nl,readFileSync as To,renameSync as rl,writeFileSync as ol}from"fs";import{homedir as Ao}from"os";import{join as Tt}from"path";var P="siri:",Ro="com.apple.ttsbundle.gryphon-neural_",Io=t=>!!t&&t.startsWith(Ro),sl=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],il=()=>{try{return el("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},$t;function At(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&$t!==void 0)return $t;let{platform:n=process.platform,exists:r=$o,prefDomain:o=il}=t,s=n==="darwin"&&sl.every(i=>r(i))&&o();return e||($t=s),s}var Do=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Co={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"},Rt=t=>Co[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 al=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function ll(t){let e=new Map;for(let n of t)for(let[,r,o,s]of n.matchAll(al)){let i=`${r}-${o}`,a=`${Ro}${s}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:i,quality:"premium",gender:Co[s]??null,siri:!0})}return[...e.values()]}function Ue(t=Do,e={}){if(!At(e))return[];let n=[];for(let r of t){let o;try{o=nl(r)}catch{continue}for(let s of o)try{n.push(To(Tt(r,s,"Info.plist"),"latin1"))}catch{}}return ll(n)}var _o=`#!/bin/sh
376
+ </header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function j(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}import{existsSync as Yo,mkdirSync as Rl,readFileSync as Il,renameSync as Dl,writeFileSync as Cl}from"fs";import{homedir as Nl}from"os";import{dirname as Ol,join as Ll}from"path";import{execFile as ul,execFileSync as pl}from"child_process";import{execFileSync as tl}from"child_process";import{existsSync as To,mkdirSync as nl,readdirSync as rl,readFileSync as Ao,renameSync as ol,writeFileSync as sl}from"fs";import{homedir as Ro}from"os";import{join as Tt}from"path";var P="siri:",Io="com.apple.ttsbundle.gryphon-neural_",Do=t=>!!t&&t.startsWith(Io),il=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],al=()=>{try{return tl("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},$t;function At(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&$t!==void 0)return $t;let{platform:n=process.platform,exists:r=To,prefDomain:o=al}=t,s=n==="darwin"&&il.every(i=>r(i))&&o();return e||($t=s),s}var Co=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],No={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"},Rt=t=>No[t.toLowerCase()]??null;function Ue(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 ll=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function cl(t){let e=new Map;for(let n of t)for(let[,r,o,s]of n.matchAll(ll)){let i=`${r}-${o}`,a=`${Io}${s}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:i,quality:"premium",gender:No[s]??null,siri:!0})}return[...e.values()]}function We(t=Co,e={}){if(!At(e))return[];let n=[];for(let r of t){let o;try{o=rl(r)}catch{continue}for(let s of o)try{n.push(Ao(Tt(r,s,"Info.plist"),"latin1"))}catch{}}return cl(n)}var $o=`#!/bin/sh
377
377
  # Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
378
378
  # siri-say.sh [voice] < text speak one line. A Siri voice id switches
379
379
  # the OS default for it; any other id is
@@ -385,7 +385,7 @@ D=com.apple.Accessibility K=SpokenContentDefaultVoiceSelectionsByLanguage
385
385
  dir="$HOME/.agentx/voice" lock="$HOME/.agentx/voice/siri.lock" saved="$HOME/.agentx/voice/siri-saved.plist"
386
386
  stops="$dir/stop"
387
387
  read_s=\${AGENTX_SAY_READ_S:-5} stale_s=\${AGENTX_SAY_STALE_S:-30} max_s=\${AGENTX_SAY_MAX_S:-300}
388
- assets=\${AGENTX_SIRI_ASSET_DIRS:-"${Do.join(" ")}"}
388
+ assets=\${AGENTX_SIRI_ASSET_DIRS:-"${Co.join(" ")}"}
389
389
  if [ "$1" = --stop ]; then
390
390
  mkdir -p "$dir" || exit 1
391
391
  # Queued lines see this change and drop. The owner's trap stops say,
@@ -478,20 +478,20 @@ wait "$say_pid"
478
478
  status=$?
479
479
  say_pid=
480
480
  finish $status
481
- `,cl=(t=Ao())=>Tt(t,".agentx","voice","siri-say.sh");function No(t=Ao()){let e=cl(t);return $o(e)&&To(e,"utf8")===_o||(tl(Tt(t,".agentx","voice"),{recursive:!0}),ol(`${e}.tmp`,_o,{mode:493}),rl(`${e}.tmp`,e)),e}var Oo=`ObjC.import("AVFoundation")
481
+ `,dl=(t=Ro())=>Tt(t,".agentx","voice","siri-say.sh");function Oo(t=Ro()){let e=dl(t);return To(e)&&Ao(e,"utf8")===$o||(nl(Tt(t,".agentx","voice"),{recursive:!0}),sl(`${e}.tmp`,$o,{mode:493}),ol(`${e}.tmp`,e)),e}var Lo=`ObjC.import("AVFoundation")
482
482
  const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
483
483
  for (let i = 0; i < vs.count; i++) {
484
484
  const v = vs.objectAtIndex(i)
485
485
  out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
486
486
  }
487
- out.join("\\n")`,pl=new Set(["Fred","Kathy","Ralph","Junior"]),gl={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 Lo(t){let e=[];for(let n of t.split(`
488
- `)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!pl.has(o)||e.push({id:r,name:o,locale:s,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":gl[o]??null})}return e}var ml=10*60*1e3,Og=60*1e3,re=null,It=!1;function Dt(t=Date.now(),e=ml){if(process.platform!=="darwin")return[];if(re)t-re.at>e&&!It&&(It=!0,dl("osascript",["-l","JavaScript","-e",Oo],{timeout:1e4},(n,r)=>{It=!1,n||(re={at:Date.now(),voices:[...Lo(String(r)),...Ue()]})}));else try{re={at:t,voices:[...Lo(ul("osascript",["-l","JavaScript","-e",Oo],{encoding:"utf8",timeout:1e4})),...Ue()]}}catch(n){Ct(`[voice] could not list system voices: ${String(n?.message??n).split(`
489
- `)[0]}`),re={at:t,voices:Ue()}}return re.voices}var Ct=t=>process.stderr.write(t+`
490
- `),We=new Set;function Lg(t){Ct=t}function Y(t,e){We.has(t)||(We.add(t),Ct(e))}function Fo(t){for(let e of We)t(e)&&We.delete(e)}var Uo=()=>{};function Pg(t){Uo=t}function Wo(t){try{Uo(t)}catch(e){Y("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var fl={premium:3,enhanced:2,standard:1},hl=new Set(["Grandma","Grandpa"]);function Po(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!hl.has(t.name)?1:0;return fl[t.quality]*10+e}var oe=t=>t.toLowerCase().split(/[-_]/)[0],Mo=t=>t.id.startsWith("com.apple.voice.");function Nt(t,e,n,r=new Set){let o=me(t.filter(a=>!a.siri&&oe(a.locale)===oe(e)),e);if(o.some(Mo)&&(o=o.filter(Mo)),n==="female"||n==="male"){let a=o.filter(d=>d.gender===n);a.length&&(o=a)}if(!o.length)return null;let s=o.filter(a=>a.quality===o[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return s.find(a=>!i.has(a.name.toLowerCase()))??s[0]}function me(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=oe(e),o=t.filter(s=>oe(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>Po(i)-Po(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function fe(t,e,n="en"){let r=t.trim();if(!r)return null;let o=e.find(l=>l.id===r);if(o)return o;if(r.toLowerCase().startsWith(P)){let l=r.slice(P.length).trim().toLowerCase(),c=me(e.filter(u=>u.siri&&u.name.toLowerCase()===l),n)[0];if(c||!l)return c??null;let p=fe(l,e.filter(u=>oe(u.locale)===oe(n)),n);return p&&Y(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${p.name} (${p.locale}) instead.`),p}e=e.filter(l=>!l.siri);let s=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(s?s[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=me(e.filter(l=>l.name.toLowerCase()===i),n);return(s?a.find(l=>l.quality===s[2].toLowerCase()):void 0)??a[0]??null}function jo(t,e,n=new Set){let r=new Map;if(!e.length)return r;let o=new Set([...n].map(i=>i.toLowerCase())),s="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",d=a?i.gender:s,l=e.filter(p=>!o.has(p.name.toLowerCase())),c=l.find(p=>p.gender===d)??(a?e.find(p=>p.gender===d):void 0)??l[0]??e[r.size%e.length];r.set(i.id,c),o.add(c.name.toLowerCase()),a||(s=s==="female"?"male":"female")}return r}$n();var Ot="system",bl=t=>t.trim().toLowerCase()===Ot,yl="21m00Tcm4TlvDq8ikWAM";function Lt(t,e,n={},r=Dt()){let o=e[t],s=o?.name||t,i=o?.voice,a=Mt(e,n,r).get(t)??null,d=vl(t,i?.system,i?.gender,n,r);return{agentId:t,name:s,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?Be(a):null,systemByLanguage:d,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||El(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var Be=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function wl(t,e,n,r){if(!e||!n.length)return null;let o=fe(e,n,r);return o||(Y(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Wo(e)),o}function Vo(t,e){let n=t.trim();if(n.toLowerCase().startsWith(P))return{locale:e,gender:Rt(n.slice(P.length).trim())};let r=Fe(n);return r?{locale:r.locale,gender:Rt(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var Xo=t=>t.toLowerCase().split(/[-_]/)[0],Bo=(t,e)=>typeof t=="string"?t:t?.[Xo(e)];function je(t,e,n,r){if(e!==void 0)return bl(e)?null:wl(t,e,n,r)??void 0}var Pt=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function xl(t,e,n,r=new Set){let o=e.locale??"en",s=new Map,i=[],a=je("voice.system",Bo(e.system,o),n,o),d=()=>new Set([...r,...[...s.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let p=Bo(c.system,o),u=je(c.id,p,n,o),g=u!==void 0?u:p!==void 0&&n.length?kl(c,p,o,a,n,d()):a!==void 0&&Pt(a,c.gender)?a:void 0;g!==void 0?s.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let l=d();for(let[c,p]of jo(i,me(n.filter(u=>!u.siri),o),l))s.set(c,p);return s}function kl(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let d=je(`${t.id}.fallbacks`,a,o,n);if(d!==void 0)return d}if(r!==void 0&&Pt(r,t.gender))return r;let i=Vo(e,n);return Nt(o,i.locale,t.gender??i.gender,s)??void 0}function vl(t,e,n,r,o){if(typeof e=="string")return{};let s={},i=(a,d,l)=>{if(!(!d||typeof d=="string"))for(let[c,p]of Object.entries(d)){let u=je(`${a}.${c}`,p,o,c);u===void 0&&o.length&&(u=Nt(o,c,n??Vo(p,c).gender)??void 0),u!==void 0&&l(u)&&(s[Xo(c)]=u)}};return i("voice.system",r.system,a=>Pt(a,n)),i(t,e,()=>!0),s}function jg(t,e){let n=e?_e(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?Be(r):null}}function Mt(t,e={},n=Dt()){let r=Object.entries(t).map(([o,s])=>({id:o,system:s.voice?.system,gender:s.voice?.gender,fallbacks:s.voice?.fallbacks}));return xl(r,e,n)}function Ft(t,e){let n={provider:t.provider,elevenlabs:Sl(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([o,s])=>[o,s?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function Sl(t,e){return t||e||process.env.AGENTX_VOICE_ID||yl}function El(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let o=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[s,...i]=o.split(/,\s*/),a=i.join(", ");return a&&s.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(o)&&o.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${o}.`:`Hello, this is ${t}, ${o}.`}var _l=8*60*60*1e3,$l=500,qo=class{constructor(e=_l){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(Ho(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=Ho(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>$l&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},Ho=(t,e)=>`${t}\0${e}`;function zo(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 Bg(t,e,n,r={}){let o=e[t],s=Lt(t,e,r),i=(o?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:s.name,voice:Ft(s),persona:i||`You are ${s.name}.`,introLine:zo(s,n)}}var Tl="[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 qg(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=s=>typeof s=="string"?s.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),o={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`${Tl}
491
- ${zo(o,e.voice.introduce===!0&&!!r)}`}var Ll="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Yo=(t=Cl())=>Ol(t,".agentx","voice","health.json");function Pl(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===Ot)return!0;if(r.toLowerCase().startsWith(P)){let o=r.slice(P.length).trim().toLowerCase();return e.some(s=>s.siri&&s.name.toLowerCase()===o)}return fe(r,e,n)!==null}function Ml(t){let e=t.voice?.locale??"en",n=[],r=(o,s)=>{if(typeof s=="string")n.push({owner:o,name:s,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(s??{}))n.push({owner:o,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[o,s]of Object.entries(t.agents))(s.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(o,s.voice?.system);return n}function Fl(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of Ml(t)){if(Pl(s,e,i))continue;r??=Mt(t.agents,t.voice,e);let d=n.get(s)??{voice:s,agents:[],speaksWith:{}};d.agents.includes(o)||d.agents.push(o);let l=r.get(o);o!=="voice.system"&&!a&&(d.speaksWith[o]=l?Be(l):"the OS default voice"),n.set(s,d)}return[...n.values()]}function Ut(t){let e=Fe(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(P)){let n=t.slice(P.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function Ul(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${Ut(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
487
+ out.join("\\n")`,gl=new Set(["Fred","Kathy","Ralph","Junior"]),ml={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 Po(t){let e=[];for(let n of t.split(`
488
+ `)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!gl.has(o)||e.push({id:r,name:o,locale:s,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":ml[o]??null})}return e}var fl=10*60*1e3,Cg=60*1e3,re=null,It=!1;function Dt(t=Date.now(),e=fl){if(process.platform!=="darwin")return[];if(re)t-re.at>e&&!It&&(It=!0,ul("osascript",["-l","JavaScript","-e",Lo],{timeout:1e4},(n,r)=>{It=!1,n||(re={at:Date.now(),voices:[...Po(String(r)),...We()]})}));else try{re={at:t,voices:[...Po(pl("osascript",["-l","JavaScript","-e",Lo],{encoding:"utf8",timeout:1e4})),...We()]}}catch(n){Ct(`[voice] could not list system voices: ${String(n?.message??n).split(`
489
+ `)[0]}`),re={at:t,voices:We()}}return re.voices}var Ct=t=>process.stderr.write(t+`
490
+ `),je=new Set;function Ng(t){Ct=t}function Y(t,e){je.has(t)||(je.add(t),Ct(e))}function Uo(t){for(let e of je)t(e)&&je.delete(e)}var Wo=()=>{};function Og(t){Wo=t}function jo(t){try{Wo(t)}catch(e){Y("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var hl={premium:3,enhanced:2,standard:1},bl=new Set(["Grandma","Grandpa"]);function Mo(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!bl.has(t.name)?1:0;return hl[t.quality]*10+e}var oe=t=>t.toLowerCase().split(/[-_]/)[0],Fo=t=>t.id.startsWith("com.apple.voice.");function Nt(t,e,n,r=new Set){let o=me(t.filter(a=>!a.siri&&oe(a.locale)===oe(e)),e);if(o.some(Fo)&&(o=o.filter(Fo)),n==="female"||n==="male"){let a=o.filter(d=>d.gender===n);a.length&&(o=a)}if(!o.length)return null;let s=o.filter(a=>a.quality===o[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return s.find(a=>!i.has(a.name.toLowerCase()))??s[0]}function me(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=oe(e),o=t.filter(s=>oe(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>Mo(i)-Mo(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function fe(t,e,n="en"){let r=t.trim();if(!r)return null;let o=e.find(l=>l.id===r);if(o)return o;if(r.toLowerCase().startsWith(P)){let l=r.slice(P.length).trim().toLowerCase(),c=me(e.filter(u=>u.siri&&u.name.toLowerCase()===l),n)[0];if(c||!l)return c??null;let p=fe(l,e.filter(u=>oe(u.locale)===oe(n)),n);return p&&Y(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${p.name} (${p.locale}) instead.`),p}e=e.filter(l=>!l.siri);let s=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(s?s[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=me(e.filter(l=>l.name.toLowerCase()===i),n);return(s?a.find(l=>l.quality===s[2].toLowerCase()):void 0)??a[0]??null}function Bo(t,e,n=new Set){let r=new Map;if(!e.length)return r;let o=new Set([...n].map(i=>i.toLowerCase())),s="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",d=a?i.gender:s,l=e.filter(p=>!o.has(p.name.toLowerCase())),c=l.find(p=>p.gender===d)??(a?e.find(p=>p.gender===d):void 0)??l[0]??e[r.size%e.length];r.set(i.id,c),o.add(c.name.toLowerCase()),a||(s=s==="female"?"male":"female")}return r}$n();var Ot="system",yl=t=>t.trim().toLowerCase()===Ot,wl="21m00Tcm4TlvDq8ikWAM";function Lt(t,e,n={},r=Dt()){let o=e[t],s=o?.name||t,i=o?.voice,a=Mt(e,n,r).get(t)??null,d=Sl(t,i?.system,i?.gender,n,r);return{agentId:t,name:s,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?He(a):null,systemByLanguage:d,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||_l(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var He=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function xl(t,e,n,r){if(!e||!n.length)return null;let o=fe(e,n,r);return o||(Y(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),jo(e)),o}function Xo(t,e){let n=t.trim();if(n.toLowerCase().startsWith(P))return{locale:e,gender:Rt(n.slice(P.length).trim())};let r=Ue(n);return r?{locale:r.locale,gender:Rt(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var zo=t=>t.toLowerCase().split(/[-_]/)[0],Ho=(t,e)=>typeof t=="string"?t:t?.[zo(e)];function Be(t,e,n,r){if(e!==void 0)return yl(e)?null:xl(t,e,n,r)??void 0}var Pt=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function kl(t,e,n,r=new Set){let o=e.locale??"en",s=new Map,i=[],a=Be("voice.system",Ho(e.system,o),n,o),d=()=>new Set([...r,...[...s.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let p=Ho(c.system,o),u=Be(c.id,p,n,o),g=u!==void 0?u:p!==void 0&&n.length?vl(c,p,o,a,n,d()):a!==void 0&&Pt(a,c.gender)?a:void 0;g!==void 0?s.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let l=d();for(let[c,p]of Bo(i,me(n.filter(u=>!u.siri),o),l))s.set(c,p);return s}function vl(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let d=Be(`${t.id}.fallbacks`,a,o,n);if(d!==void 0)return d}if(r!==void 0&&Pt(r,t.gender))return r;let i=Xo(e,n);return Nt(o,i.locale,t.gender??i.gender,s)??void 0}function Sl(t,e,n,r,o){if(typeof e=="string")return{};let s={},i=(a,d,l)=>{if(!(!d||typeof d=="string"))for(let[c,p]of Object.entries(d)){let u=Be(`${a}.${c}`,p,o,c);u===void 0&&o.length&&(u=Nt(o,c,n??Xo(p,c).gender)??void 0),u!==void 0&&l(u)&&(s[zo(c)]=u)}};return i("voice.system",r.system,a=>Pt(a,n)),i(t,e,()=>!0),s}function Ug(t,e){let n=e?_e(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?He(r):null}}function Mt(t,e={},n=Dt()){let r=Object.entries(t).map(([o,s])=>({id:o,system:s.voice?.system,gender:s.voice?.gender,fallbacks:s.voice?.fallbacks}));return kl(r,e,n)}function Ft(t,e){let n={provider:t.provider,elevenlabs:El(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([o,s])=>[o,s?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function El(t,e){return t||e||process.env.AGENTX_VOICE_ID||wl}function _l(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let o=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[s,...i]=o.split(/,\s*/),a=i.join(", ");return a&&s.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(o)&&o.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${o}.`:`Hello, this is ${t}, ${o}.`}var $l=8*60*60*1e3,Tl=500,qo=class{constructor(e=$l){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(Vo(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=Vo(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>Tl&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},Vo=(t,e)=>`${t}\0${e}`;function Ko(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 Wg(t,e,n,r={}){let o=e[t],s=Lt(t,e,r),i=(o?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:s.name,voice:Ft(s),persona:i||`You are ${s.name}.`,introLine:Ko(s,n)}}var Al="[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 jg(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=s=>typeof s=="string"?s.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),o={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`${Al}
491
+ ${Ko(o,e.voice.introduce===!0&&!!r)}`}var Pl="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Jo=(t=Nl())=>Ll(t,".agentx","voice","health.json");function Ml(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===Ot)return!0;if(r.toLowerCase().startsWith(P)){let o=r.slice(P.length).trim().toLowerCase();return e.some(s=>s.siri&&s.name.toLowerCase()===o)}return fe(r,e,n)!==null}function Fl(t){let e=t.voice?.locale??"en",n=[],r=(o,s)=>{if(typeof s=="string")n.push({owner:o,name:s,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(s??{}))n.push({owner:o,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[o,s]of Object.entries(t.agents))(s.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(o,s.voice?.system);return n}function Ul(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of Fl(t)){if(Ml(s,e,i))continue;r??=Mt(t.agents,t.voice,e);let d=n.get(s)??{voice:s,agents:[],speaksWith:{}};d.agents.includes(o)||d.agents.push(o);let l=r.get(o);o!=="voice.system"&&!a&&(d.speaksWith[o]=l?He(l):"the OS default voice"),n.set(s,d)}return[...n.values()]}function Ut(t){let e=Ue(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(P)){let n=t.slice(P.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function Wl(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${Ut(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
492
492
  `)}
493
- Reinstall in ${Ll}. Agents switch back on their own once it is installed.`}}function Wl(t=Yo()){if(!Go(t))return null;try{let e=JSON.parse(Rl(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function jl(t,e){Al(Nl(t),{recursive:!0}),Dl(`${t}.tmp`,JSON.stringify(e,null,2)+`
494
- `),Il(`${t}.tmp`,t)}var Ko=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 o=this.deps.file??Yo(),s=new Map((Wl(o)?.missing??[]).map(p=>[p.voice,p])),i=Fl(e,n),a=i.map(p=>({...p,since:s.get(p.voice)?.since??r.toISOString(),...s.get(p.voice)?.notifiedAt?{notifiedAt:s.get(p.voice).notifiedAt}:{}})),d=[...s.keys()].filter(p=>!i.some(u=>u.voice===p));for(let p of d)this.deps.log(`[voice] ${Ut(p)} is installed again; its agents speak with it again`);d.length&&Fo(p=>d.some(u=>p===u||p.endsWith(`:${u}`)));let l=a.filter(p=>!p.notifiedAt);if(l.length){let{title:p,message:u}=Ul(l);try{await this.deps.notify(p,u);for(let g of l)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${l.map(g=>Ut(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(!Go(o)||JSON.stringify(a)!==JSON.stringify([...s.values()]))&&jl(o,c),c}finally{this.running=!1}}};import{randomBytes as Jo}from"crypto";var J={content:32e3,messagesPerConversation:200,conversationsPerDevice:100,toolsPerMessage:50,filesPerMessage:W.perMessage},Bl=/^[a-f0-9]{32}$/,ql=/^c[a-z0-9]{8,32}$/,Hl=/^#[0-9a-fA-F]{6}$/;function Wt(t){return ql.test(t)}var Qo=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS app_chat_conversations (
493
+ Reinstall in ${Pl}. Agents switch back on their own once it is installed.`}}function jl(t=Jo()){if(!Yo(t))return null;try{let e=JSON.parse(Il(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function Bl(t,e){Rl(Ol(t),{recursive:!0}),Cl(`${t}.tmp`,JSON.stringify(e,null,2)+`
494
+ `),Dl(`${t}.tmp`,t)}var Go=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 o=this.deps.file??Jo(),s=new Map((jl(o)?.missing??[]).map(p=>[p.voice,p])),i=Ul(e,n),a=i.map(p=>({...p,since:s.get(p.voice)?.since??r.toISOString(),...s.get(p.voice)?.notifiedAt?{notifiedAt:s.get(p.voice).notifiedAt}:{}})),d=[...s.keys()].filter(p=>!i.some(u=>u.voice===p));for(let p of d)this.deps.log(`[voice] ${Ut(p)} is installed again; its agents speak with it again`);d.length&&Uo(p=>d.some(u=>p===u||p.endsWith(`:${u}`)));let l=a.filter(p=>!p.notifiedAt);if(l.length){let{title:p,message:u}=Wl(l);try{await this.deps.notify(p,u);for(let g of l)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${l.map(g=>Ut(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(!Yo(o)||JSON.stringify(a)!==JSON.stringify([...s.values()]))&&Bl(o,c),c}finally{this.running=!1}}};import{randomBytes as Qo}from"crypto";var J={content:32e3,messagesPerConversation:200,conversationsPerDevice:100,toolsPerMessage:50,filesPerMessage:W.perMessage},Hl=/^[a-f0-9]{32}$/,ql=/^c[a-z0-9]{8,32}$/,Vl=/^#[0-9a-fA-F]{6}$/;function Wt(t){return ql.test(t)}var Zo=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS app_chat_conversations (
495
495
  id TEXT PRIMARY KEY, device_id TEXT NOT NULL, title TEXT NOT NULL,
496
496
  node TEXT NOT NULL, node_name TEXT NOT NULL, agent TEXT NOT NULL, agent_name TEXT,
497
497
  created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
@@ -504,11 +504,11 @@ Reinstall in ${Ll}. Agents switch back on their own once it is installed.`}}func
504
504
  id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, message_id INTEGER NOT NULL,
505
505
  path TEXT NOT NULL, name TEXT NOT NULL, mime TEXT NOT NULL, kind TEXT NOT NULL, created_at INTEGER NOT NULL);
506
506
  CREATE INDEX IF NOT EXISTS app_chat_files_conversation ON app_chat_files(conversation_id);`),e.prepare("PRAGMA table_info(app_chat_messages)").all().some(o=>o.name==="files")||e.exec("ALTER TABLE app_chat_messages ADD COLUMN files TEXT");let r=e.prepare("PRAGMA table_info(app_chat_conversations)").all();r.some(o=>o.name==="read_at")||e.transaction(()=>{e.prepare("PRAGMA table_info(app_chat_conversations)").all().some(s=>s.name==="read_at")||(e.exec("ALTER TABLE app_chat_conversations ADD COLUMN read_at INTEGER"),e.exec("UPDATE app_chat_conversations SET read_at = updated_at"))}).immediate(),r.some(o=>o.name==="color")||e.exec("ALTER TABLE app_chat_conversations ADD COLUMN color TEXT"),e.exec(`CREATE TABLE IF NOT EXISTS app_chat_delivered (
507
- key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return Wt(e)?this.db.prepare("SELECT device_id FROM app_chat_conversations WHERE id = ?").get(e)?.device_id??null:null}appendOnce(e,n,r,o,s=[],i=Date.now()){return!r||r.length>200?null:this.db.transaction(()=>!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e)||this.db.prepare("INSERT OR IGNORE INTO app_chat_delivered (key, conversation_id, at) VALUES (?, ?, ?)").run(r,n,i).changes===0?null:(this.db.prepare("DELETE FROM app_chat_delivered WHERE at < ?").run(i-30*24*60*6e4),this.appendWithFiles(e,n,o,s))).immediate()}create(e,n,r,o=Date.now()){let s=`c${o.toString(36)}${Jo(4).toString("hex")}`,{color:i,...a}=n,d=i&&Hl.test(i)?i:void 0,l={id:s,title:es(r),...a,...d?{color:d}:{},createdAt:o,updatedAt:o,messages:[]};return this.db.prepare(`INSERT INTO app_chat_conversations
508
- (id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,d??null,o,o,o),this.pruneDevice(e),l}get(e,n){if(!Wt(n))return null;let r=this.db.prepare("SELECT * FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e);if(!r)return null;let o=this.db.prepare("SELECT * FROM app_chat_messages WHERE conversation_id = ? ORDER BY id").all(n).map(Vl);return{...Zo(r),messages:o}}list(e,n=J.conversationsPerDevice){return this.db.prepare(`SELECT c.*,
507
+ key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return Wt(e)?this.db.prepare("SELECT device_id FROM app_chat_conversations WHERE id = ?").get(e)?.device_id??null:null}appendOnce(e,n,r,o,s=[],i=Date.now()){return!r||r.length>200?null:this.db.transaction(()=>!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e)||this.db.prepare("INSERT OR IGNORE INTO app_chat_delivered (key, conversation_id, at) VALUES (?, ?, ?)").run(r,n,i).changes===0?null:(this.db.prepare("DELETE FROM app_chat_delivered WHERE at < ?").run(i-30*24*60*6e4),this.appendWithFiles(e,n,o,s))).immediate()}create(e,n,r,o=Date.now()){let s=`c${o.toString(36)}${Qo(4).toString("hex")}`,{color:i,...a}=n,d=i&&Vl.test(i)?i:void 0,l={id:s,title:ts(r),...a,...d?{color:d}:{},createdAt:o,updatedAt:o,messages:[]};return this.db.prepare(`INSERT INTO app_chat_conversations
508
+ (id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,d??null,o,o,o),this.pruneDevice(e),l}get(e,n){if(!Wt(n))return null;let r=this.db.prepare("SELECT * FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e);if(!r)return null;let o=this.db.prepare("SELECT * FROM app_chat_messages WHERE conversation_id = ? ORDER BY id").all(n).map(Xl);return{...es(r),messages:o}}list(e,n=J.conversationsPerDevice){return this.db.prepare(`SELECT c.*,
509
509
  (SELECT COUNT(*) FROM app_chat_messages m WHERE m.conversation_id = c.id) AS n,
510
510
  (SELECT substr(m.content, 1, 240) FROM app_chat_messages m WHERE m.conversation_id = c.id ORDER BY m.id DESC LIMIT 1) AS last
511
- FROM app_chat_conversations c WHERE c.device_id = ? ORDER BY c.updated_at DESC, c.rowid DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>{let s=typeof o.last=="string"?o.last.replace(/\s+/g," ").trim().slice(0,120):"";return{...Zo(o),messages:o.n,...s?{last:s}:{}}})}markRead(e,n,r=Date.now()){Wt(n)&&this.db.prepare("UPDATE app_chat_conversations SET read_at = MAX(COALESCE(read_at, 0), ?) WHERE id = ? AND device_id = ?").run(r,n,e)}latestWith(e,n){let r=this.db.prepare(`SELECT id, device_id FROM app_chat_conversations WHERE node = ? AND agent = ?
511
+ FROM app_chat_conversations c WHERE c.device_id = ? ORDER BY c.updated_at DESC, c.rowid DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>{let s=typeof o.last=="string"?o.last.replace(/\s+/g," ").trim().slice(0,120):"";return{...es(o),messages:o.n,...s?{last:s}:{}}})}markRead(e,n,r=Date.now()){Wt(n)&&this.db.prepare("UPDATE app_chat_conversations SET read_at = MAX(COALESCE(read_at, 0), ?) WHERE id = ? AND device_id = ?").run(r,n,e)}latestWith(e,n){let r=this.db.prepare(`SELECT id, device_id FROM app_chat_conversations WHERE node = ? AND agent = ?
512
512
  ORDER BY updated_at DESC, rowid DESC LIMIT 1`).get(e,n);return r?{id:r.id,deviceId:r.device_id}:null}latestDevice(){return this.db.prepare("SELECT device_id FROM app_chat_conversations ORDER BY updated_at DESC, rowid DESC LIMIT 1").get()?.device_id??null}unread(e,n){return this.db.prepare(`SELECT c.id, c.title, c.agent, c.agent_name, c.color,
513
513
  substr(m.content, 1, 240) AS answer, m.status, m.at
514
514
  FROM app_chat_conversations c
@@ -516,21 +516,21 @@ Reinstall in ${Ll}. Agents switch back on their own once it is installed.`}}func
516
516
  WHERE c.device_id = ? AND m.role = 'assistant' AND m.at > COALESCE(c.read_at, 0)
517
517
  ORDER BY m.at DESC, m.id DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>({id:o.id,title:o.title,agent:o.agent,...o.agent_name?{agentName:o.agent_name}:{},...o.color?{color:o.color}:{},answer:String(o.answer??"").trim(),status:o.status==="error"||o.status==="stopped"?o.status:"done",at:o.at}))}append(e,n,r){return this.appendWithFiles(e,n,r)!==null}appendWithFiles(e,n,r,o=[]){if(!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e))return null;let i=r.content.length>J.content?r.content.slice(0,J.content)+`
518
518
 
519
- [Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,J.toolsPerMessage),d=[];for(let u of o){if(d.length>=J.filesPerMessage)break;let g=u.filename.trim(),m=ue(g);if(!m||!g||g.length>W.pathChars||g.includes("\0"))continue;let f=(g.split(/[\\/]/).pop()||g).slice(0,120);d.push({id:Jo(16).toString("hex"),name:f,mime:m.mime,kind:m.kind,path:g})}let l=d.map(u=>({id:u.id,name:u.name,mime:u.mime,kind:u.kind})),c=this.db.prepare(`INSERT INTO app_chat_messages (conversation_id, role, content, status, error, ui, tools, files, at)
519
+ [Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,J.toolsPerMessage),d=[];for(let u of o){if(d.length>=J.filesPerMessage)break;let g=u.filename.trim(),m=ue(g);if(!m||!g||g.length>W.pathChars||g.includes("\0"))continue;let f=(g.split(/[\\/]/).pop()||g).slice(0,120);d.push({id:Qo(16).toString("hex"),name:f,mime:m.mime,kind:m.kind,path:g})}let l=d.map(u=>({id:u.id,name:u.name,mime:u.mime,kind:u.kind})),c=this.db.prepare(`INSERT INTO app_chat_messages (conversation_id, role, content, status, error, ui, tools, files, at)
520
520
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,r.role,i,r.status??null,r.error?.slice(0,500)??null,r.ui?JSON.stringify(r.ui):null,a?.length?JSON.stringify(a):null,l.length?JSON.stringify(l):null,r.at),p=this.db.prepare(`INSERT INTO app_chat_files (id, conversation_id, message_id, path, name, mime, kind, created_at)
521
521
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let u of d)p.run(u.id,n,Number(c.lastInsertRowid),u.path,u.name,u.mime,u.kind,r.at);return this.db.prepare(`DELETE FROM app_chat_messages WHERE conversation_id = ? AND id NOT IN
522
522
  (SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,J.messagesPerConversation),this.db.prepare(`DELETE FROM app_chat_files WHERE conversation_id = ? AND message_id NOT IN
523
- (SELECT id FROM app_chat_messages WHERE conversation_id = ?)`).run(n,n),this.db.prepare("UPDATE app_chat_conversations SET updated_at = ? WHERE id = ?").run(r.at,n),l}getFile(e,n){if(!Bl.test(n))return null;let r=this.db.prepare(`SELECT f.*, c.node, c.agent FROM app_chat_files f
523
+ (SELECT id FROM app_chat_messages WHERE conversation_id = ?)`).run(n,n),this.db.prepare("UPDATE app_chat_conversations SET updated_at = ? WHERE id = ?").run(r.at,n),l}getFile(e,n){if(!Hl.test(n))return null;let r=this.db.prepare(`SELECT f.*, c.node, c.agent FROM app_chat_files f
524
524
  JOIN app_chat_conversations c ON c.id = f.conversation_id WHERE f.id = ? AND c.device_id = ?`).get(n,e);return r?{id:r.id,name:r.name,mime:r.mime,kind:r.kind,path:r.path,conversationId:r.conversation_id,node:r.node,agent:r.agent}:null}pruneDevice(e){let n=this.db.prepare(`SELECT id FROM app_chat_conversations WHERE device_id = ?
525
- ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,J.conversationsPerDevice);for(let{id:r}of n)this.db.prepare("DELETE FROM app_chat_files WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_messages WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_conversations WHERE id = ?").run(r)}};function Zo(t){return{id:t.id,title:t.title,node:t.node,nodeName:t.node_name,agent:t.agent,...t.agent_name?{agentName:t.agent_name}:{},...t.color?{color:t.color}:{},createdAt:t.created_at,updatedAt:t.updated_at}}function Vl(t){let e=s=>{if(s)try{return JSON.parse(s)}catch{return}},n=e(t.ui),r=e(t.tools),o=e(t.files);return{role:t.role,content:t.content,at:t.at,...t.status?{status:t.status}:{},...t.error?{error:t.error}:{},...n?{ui:n}:{},...r?{tools:r}:{},...o?{files:o}:{}}}function es(t){let e=/^\[Call answered\][^"]*"([^"]+)"/.exec(t);if(e)return es(`Call: ${e[1]}`);let n=t.replace(/\s+/g," ").trim();return(n.length>60?n.slice(0,59)+"\u2026":n)||"Untitled"}import{readFileSync as Bt,writeFileSync as is,existsSync as qt,readdirSync as tc,statSync as nc}from"fs";import{resolve as Ht,join as rc}from"path";import{existsSync as ts,mkdirSync as Xl,readFileSync as zl,writeFileSync as ns}from"fs";import{dirname as Kl,resolve as rs}from"path";import{z as v}from"zod";var Gl=v.object({type:v.enum(["gitlab","github"]),host:v.string().optional(),project:v.string(),iid:v.number().int().positive(),url:v.string()}),Yl=v.object({id:v.string(),title:v.string(),description:v.string().optional(),assignee:v.string().optional(),labels:v.array(v.string()).default([]),milestone:v.string().optional(),status:v.enum(["todo","doing","blocked","done"]).default("todo"),priority:v.number().int().optional(),estimatedSeconds:v.number().int().optional(),source:Gl.optional(),importedAt:v.string().optional(),createdAt:v.string(),updatedAt:v.string(),blocker:v.string().optional(),doneNote:v.string().optional()}),Jl=v.object({version:v.literal(1),items:v.array(Yl).default([])}),qe=class{constructor(e){this.path=e}jsonPath(){return rs(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return rs(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return ts(this.jsonPath())}load(){let e=this.jsonPath();if(!ts(e))return{version:1,items:[]};let n=zl(e,"utf-8");try{return Jl.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Xl(Kl(n),{recursive:!0}),ns(n,JSON.stringify(e,null,2)+`
526
- `),ns(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(s=>s.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),o={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return n.items.push(o),this.save(n),o}addMany(e){let n=this.load(),r=new Set(n.items.map(i=>i.id)),o=new Date().toISOString(),s=[];for(let i of e){if(r.has(i.id))continue;let a={...i,labels:i.labels??[],status:i.status??"todo",createdAt:i.createdAt??o,updatedAt:o};n.items.push(a),s.push(a),r.add(a.id)}return s.length&&this.save(n),s}update(e,n){let r=this.load(),o=r.items.findIndex(i=>i.id===e);if(o<0)throw new Error(`backlog item ${e} not found`);let s={...r.items[o],...n,id:r.items[o].id,createdAt:r.items[o].createdAt,updatedAt:new Date().toISOString()};return r.items[o]=s,this.save(r),s}remove(e){let n=this.load(),r=n.items.length;return n.items=n.items.filter(o=>o.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 s of e.items)r[s.status].push(s);let o=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[s,i]of o)if(r[s].length){n.push(`## ${i}`,"");for(let a of r[s]){let d=s==="done"?"x":" ",l=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",p=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${d}] ${l}${a.title}${c}${p}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
527
- `)}};function om(t){return`${t.type}:${t.project}:${t.iid}`}function os(t,e,n){let r=[];if(e.type==="gitlab"){let o=n.channels.gitlab?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(s)}}else if(e.type==="github"){let o=n.channels.github?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(s)}}return r}async function jt(t,e,n,r=()=>{}){return t.source?Ql(t.source,e,n,r):{ok:!0,attempts:[]}}async function Ql(t,e,n,r=()=>{}){return t.type==="gitlab"?Zl(t,e,n,r):t.type==="github"?ec(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Zl(t,e,n,r){let o=n.channels.gitlab,s=o?.token,i=o?.host||(t.host?`https://${t.host}`:void 0);if(!s||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],d=async(g,m={})=>fetch(`${i}/api/v4${g}`,{...m,headers:{"PRIVATE-TOKEN":s,"Content-Type":"application/json",...m.headers||{}}}),l=encodeURIComponent(t.project),c;e.assigneeUsernames!==void 0&&(c=(await Promise.all(e.assigneeUsernames.map(async m=>{try{let f=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(m)}`,{headers:{"PRIVATE-TOKEN":s}});if(!f.ok)return null;let w=await f.json();return Array.isArray(w)&&w[0]?.id?w[0].id:null}catch{return null}}))).filter(m=>typeof m=="number"));let p;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")p=0;else try{let g=await d(`/projects/${l}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let m=await g.json();Array.isArray(m)&&m[0]?.id&&(p=m[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let u={};if(e.title!==void 0&&(u.title=e.title),e.description!==void 0&&(u.description=e.description),e.labels!==void 0&&(u.labels=e.labels.join(",")),e.addLabels?.length&&(u.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(u.remove_labels=e.removeLabels.join(",")),c!==void 0&&(u.assignee_ids=c),p!==void 0&&(u.milestone_id=p),e.state&&(u.state_event=e.state==="closed"?"close":"reopen"),Object.keys(u).length)try{let g=await d(`/projects/${l}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(u)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let m=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${m.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 d(`/projects/${l}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function ec(t,e,n,r){let s=n.channels.github?.token;if(!s)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(u,g={})=>fetch(`https://api.github.com${u}`,{...g,headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),d=t.project,l;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")l=null;else try{let u=await a(`/repos/${d}/milestones?state=all&per_page=100`);if(u.ok){let g=await u.json(),m=Array.isArray(g)?g.find(f=>f.title===e.milestoneTitle):null;m?.number&&(l=m.number)}}catch(u){r(`[backlog-sync] github milestone lookup failed: ${u.message}`)}let c;if(e.labels!==void 0)c=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let u=await a(`/repos/${d}/issues/${t.iid}`);if(u.ok){let g=await u.json(),m=Array.isArray(g.labels)?g.labels.map(w=>typeof w=="string"?w:w.name):[],f=new Set([...m,...e.addLabels??[]]);for(let w of e.removeLabels??[])f.delete(w);c=[...f]}}catch(u){r(`[backlog-sync] github label fetch failed: ${u.message}`)}if(c===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.body=e.description),c!==void 0&&(p.labels=c),e.assigneeUsernames!==void 0&&(p.assignees=e.assigneeUsernames),l!==void 0&&(p.milestone=l),e.state&&(p.state=e.state),Object.keys(p).length)try{let u=await a(`/repos/${d}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(p)});if(i.push({kind:"PATCH issue",ok:u.ok,status:u.status}),!u.ok){let g=await u.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${u.status}: ${g.slice(0,200)}`,url:t.url}}}catch(u){return i.push({kind:"PATCH issue",ok:!1,error:u.message}),{ok:!1,attempts:i,error:u.message,url:t.url}}if(e.note)try{let u=await a(`/repos/${d}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:u.ok,status:u.status})}catch(u){i.push({kind:"POST comment",ok:!1,error:u.message})}return{ok:i.every(u=>u.ok),attempts:i,url:t.url}}var Vt=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,He=/@([a-z0-9_-]+)/i,ss=/\[time:\s*([0-9hm\s]+)\]/i;function oc(t){let e=t.match(/(\d+)\s*h/i),n=t.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(n?parseInt(n[1],10)*60:0)}var Xt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new qe(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=Ht(process.cwd(),this.path);return qt(e)?Bt(e,"utf-8").split(`
528
- `):[]}writeMd(e){let n=Ht(process.cwd(),this.path);is(n,e.join(`
529
- `))}async listOpen(e){if(this.store.exists())return this.store.list().filter(s=>s.status!=="done"&&(!s.assignee||s.assignee.toLowerCase()===e.toLowerCase())).map(s=>this.toWorkItem(s));let n=this.readMd(),r=[];for(let o=0;o<n.length;o++){let s=n[o].match(Vt);if(!s||s[2].toLowerCase()==="x")continue;let a=s[3],d=a.match(He);if(d&&d[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(ss),c=a.replace(He,"").replace(ss,"").trim();r.push({id:`backlog:${o}`,title:c||`Task at line ${o+1}`,assignee:d?d[1]:void 0,estimatedSeconds:l?oc(l[1]):void 0,priority:o})}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 o=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(o.source&&this.daemon){let s=os([o.assignee||e],o.source,this.daemon);jt(o,{assigneeUsernames:s,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 d=this.store.update(e,a);if(d.source&&this.daemon){let l={};n.status==="done"?(l.addLabels=["Done"],l.removeLabels=["Doing"]):n.status==="blocked"&&(l.addLabels=["Blocked"]),n.note&&(l.note=n.note),Object.keys(l).length&&jt(d,l,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),o=this.readMd(),s=o[r];if(!s)throw new Error(`backlog line ${r} missing`);if(!s.match(Vt))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){o[r]=s.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";o.splice(r+1,0,a)}else n.status==="blocked"?o.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&o.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(o)}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"}}},zt=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(qt(e))for(let r of tc(e)){let o=rc(e,r);nc(o).isDirectory()?this.walk(o,n):r.endsWith(".md")&&n.push(o)}}async listOpen(e){let n=[];this.walk(Ht(process.cwd(),this.root),n);let r=[];for(let o of n){let s=Bt(o,"utf-8").split(`
530
- `);for(let i=0;i<s.length;i++){let a=s[i].match(Vt);if(!a||a[2].toLowerCase()==="x")continue;let d=a[3].match(He);!d||d[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${o}:${i}`,title:a[3].replace(He,"").trim(),assignee:d[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),o=parseInt(r[r.length-1],10),s=r.slice(1,-1).join(":");if(!qt(s))return;let i=Bt(s,"utf-8").split(`
531
- `);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),is(s,i.join(`
532
- `)))}},Kt=class{constructor(e,n,r,o,s){this.host=e;this.token=n;this.projects=r;this.agentUsernames=o;this.log=s}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(o=>o.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,o=[],s;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(s=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),o=s.map(l=>l.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),d=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:d?this.usernameToAgent(d)||d:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:o,labelDetails:s,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=[],o=this.projects.length?this.projects:["__ALL__"];for(let s of n)for(let i of o)try{let a=`assignee_username=${encodeURIComponent(s)}&state=opened&scope=all&per_page=20`,d=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(d);for(let c of l){let p=this.mapIssue(c,i);p.assignee=e,r.push(p)}}catch(a){this.log(`[business] GitLab listOpen failed for ${s} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:o,type:s}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${s==="issue"?"issues":"merge_requests"}/${o}?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:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),d=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/add_spent_time?duration=${encodeURIComponent(d)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?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}/${o}?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}/${o}/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(),o=new URLSearchParams,s=e.state??"opened";o.set("state",s),o.set("updated_after",r),o.set("scope","all"),o.set("per_page","100"),o.set("with_labels_details","true"),o.set("order_by","updated_at"),o.set("sort","desc"),e.labels?.length&&o.set("labels",e.labels.join(",")),e.milestone&&o.set("milestone",e.milestone),e.search&&o.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of i)try{let c=l==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${o.toString()}`,p=await this.api(c);for(let u of p)a.push(this.mapIssue(u,l))}catch(c){this.log(`[business] GitLab listAll failed on ${l}: ${c.message}`)}let d=a;if(e.notLabels?.length){let l=new Set(e.notLabels);d=d.filter(c=>!(c.labels||[]).some(p=>l.has(p)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";d=d.filter(c=>!(c.labels||[]).some(p=>p.startsWith(l)))}return d}async setState(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let o=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(o,n),descriptionHtml:o.description_html||void 0,createdAt:o.created_at,author:o.author?{username:o.author.username,name:o.author.name,avatarUrl:o.author.avatar_url}:void 0,allLabels:Array.isArray(o.labels)?typeof o.labels[0]=="object"?o.labels.map(i=>i.name):o.labels:[]}}catch(o){return this.log(`[board] GitLab getItem failed for ${e}: ${o.message}`),null}}async updateItem(e,n){let{project:r,iid:o}=this.parseId(e),s;n.assigneeUsernames&&(s=(await Promise.all(n.assigneeUsernames.map(async c=>{try{let p=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(p)&&p[0]?.id?p[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 l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),s!==void 0&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let d=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(d,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 o of r)o.username&&!e.has(o.username)&&e.set(o.username,{username:o.username,name:o.name,avatarUrl:o.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 o=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let s of o)s.title&&!e.has(s.title)&&e.set(s.title,{id:s.id,title:s.title,state:s.state,dueDate:s.due_date})}catch(o){this.log(`[board] listMilestones failed for ${r}: ${o.message}`)}let n=[...e.values()];return n.sort((r,o)=>r.state!==o.state?r.state==="active"?-1:1:r.title.localeCompare(o.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,o=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];o.length&&(r=(await Promise.all(o.map(async l=>{try{let c=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${l}: ${c.message}`),null}}))).filter(l=>typeof l=="number"));let s;if(e.milestoneTitle)try{let d=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(s=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${d.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),s!==void 0&&(i.milestone_id=s);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:o,iid:s,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",d=new URLSearchParams;n.length&&d.set("add_labels",n.join(",")),r.length&&d.set("remove_labels",r.join(",")),d.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${d.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),o=r.pop(),s=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:s,iid:o}}};function um(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Xt(r.path,e,n);case"wiki":return new zt(r.path,r.glob);case"gitlab":{let o=e.channels.gitlab;if(!o?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let s={};for(let a of o.agentMappings)a.gitlabUsernames.length&&(s[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:o.routes.map(a=>a.project);return new Kt(o.host,o.token,i,s,n)}}}et();var Gt="unmapped";function Yt(t,e=[]){if(!t)return Gt;let n=e.find(o=>o.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function sc(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of le(t)){let a=C(i.from),d=C(i.to);i.type==="reports-to"&&a.kind==="agent"&&d.kind==="agent"&&o.set(a.id,d.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Yt(i.id,n)));let s=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let d=o.get(i);if(!d)return;let l=s(d,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))s(i);return e}function ic(t,e,n=[]){if(!n.length)return;let r=n.filter(o=>!o.channel||o.channel===t);return r.find(o=>o.chatId&&e.chatId&&o.chatId===e.chatId)??r.find(o=>o.username&&e.username&&o.username===e.username)??r.find(o=>o.senderId&&e.senderId&&o.senderId===e.senderId)??r.find(o=>o.channel&&!o.chatId&&!o.username&&!o.senderId)}function mm(t,e){let n=ic(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Yt(t.project,e.projects);if(t.agentId){let r=sc(e).get(t.agentId);if(r)return r}return Gt}function fm(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,o,...s]=n,i=s.join(":"),a={agentId:e||r,channel:o};return o==="gitlab"||o==="github"?a.project=i.split(":")[0]:o==="cron"||o==="api"||(a.chatId=i.split("@")[0]),a}var ac=t=>t===Gt?"internal":"client";function lc(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??ac(t),respondWithinMinutes:cc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function hm(t){let e=new Set;for(let n of t.projects??[])e.add(Yt(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=>lc(n,t))}function cc(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 dc}from"crypto";var wm={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},uc=40,pc=20,xm=90,gc=2e3,as=36e5;function mc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
533
- ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<uc?null:`text:${dc("sha256").update(r).digest("hex").slice(0,24)}`}function km(t){let e=t.indexOf(`
525
+ ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,J.conversationsPerDevice);for(let{id:r}of n)this.db.prepare("DELETE FROM app_chat_files WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_messages WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_conversations WHERE id = ?").run(r)}};function es(t){return{id:t.id,title:t.title,node:t.node,nodeName:t.node_name,agent:t.agent,...t.agent_name?{agentName:t.agent_name}:{},...t.color?{color:t.color}:{},createdAt:t.created_at,updatedAt:t.updated_at}}function Xl(t){let e=s=>{if(s)try{return JSON.parse(s)}catch{return}},n=e(t.ui),r=e(t.tools),o=e(t.files);return{role:t.role,content:t.content,at:t.at,...t.status?{status:t.status}:{},...t.error?{error:t.error}:{},...n?{ui:n}:{},...r?{tools:r}:{},...o?{files:o}:{}}}function ts(t){let e=/^\[Call answered\][^"]*"([^"]+)"/.exec(t);if(e)return ts(`Call: ${e[1]}`);let n=t.replace(/\s+/g," ").trim();return(n.length>60?n.slice(0,59)+"\u2026":n)||"Untitled"}import{readFileSync as Bt,writeFileSync as as,existsSync as Ht,readdirSync as nc,statSync as rc}from"fs";import{resolve as qt,join as oc}from"path";import{existsSync as ns,mkdirSync as zl,readFileSync as Kl,writeFileSync as rs}from"fs";import{dirname as Gl,resolve as os}from"path";import{z as v}from"zod";var Yl=v.object({type:v.enum(["gitlab","github"]),host:v.string().optional(),project:v.string(),iid:v.number().int().positive(),url:v.string()}),Jl=v.object({id:v.string(),title:v.string(),description:v.string().optional(),assignee:v.string().optional(),labels:v.array(v.string()).default([]),milestone:v.string().optional(),status:v.enum(["todo","doing","blocked","done"]).default("todo"),priority:v.number().int().optional(),estimatedSeconds:v.number().int().optional(),source:Yl.optional(),importedAt:v.string().optional(),createdAt:v.string(),updatedAt:v.string(),blocker:v.string().optional(),doneNote:v.string().optional()}),Ql=v.object({version:v.literal(1),items:v.array(Jl).default([])}),qe=class{constructor(e){this.path=e}jsonPath(){return os(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return os(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return ns(this.jsonPath())}load(){let e=this.jsonPath();if(!ns(e))return{version:1,items:[]};let n=Kl(e,"utf-8");try{return Ql.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();zl(Gl(n),{recursive:!0}),rs(n,JSON.stringify(e,null,2)+`
526
+ `),rs(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(s=>s.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),o={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return n.items.push(o),this.save(n),o}addMany(e){let n=this.load(),r=new Set(n.items.map(i=>i.id)),o=new Date().toISOString(),s=[];for(let i of e){if(r.has(i.id))continue;let a={...i,labels:i.labels??[],status:i.status??"todo",createdAt:i.createdAt??o,updatedAt:o};n.items.push(a),s.push(a),r.add(a.id)}return s.length&&this.save(n),s}update(e,n){let r=this.load(),o=r.items.findIndex(i=>i.id===e);if(o<0)throw new Error(`backlog item ${e} not found`);let s={...r.items[o],...n,id:r.items[o].id,createdAt:r.items[o].createdAt,updatedAt:new Date().toISOString()};return r.items[o]=s,this.save(r),s}remove(e){let n=this.load(),r=n.items.length;return n.items=n.items.filter(o=>o.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 s of e.items)r[s.status].push(s);let o=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[s,i]of o)if(r[s].length){n.push(`## ${i}`,"");for(let a of r[s]){let d=s==="done"?"x":" ",l=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",p=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${d}] ${l}${a.title}${c}${p}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
527
+ `)}};function nm(t){return`${t.type}:${t.project}:${t.iid}`}function ss(t,e,n){let r=[];if(e.type==="gitlab"){let o=n.channels.gitlab?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(s)}}else if(e.type==="github"){let o=n.channels.github?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(s)}}return r}async function jt(t,e,n,r=()=>{}){return t.source?Zl(t.source,e,n,r):{ok:!0,attempts:[]}}async function Zl(t,e,n,r=()=>{}){return t.type==="gitlab"?ec(t,e,n,r):t.type==="github"?tc(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function ec(t,e,n,r){let o=n.channels.gitlab,s=o?.token,i=o?.host||(t.host?`https://${t.host}`:void 0);if(!s||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],d=async(g,m={})=>fetch(`${i}/api/v4${g}`,{...m,headers:{"PRIVATE-TOKEN":s,"Content-Type":"application/json",...m.headers||{}}}),l=encodeURIComponent(t.project),c;e.assigneeUsernames!==void 0&&(c=(await Promise.all(e.assigneeUsernames.map(async m=>{try{let f=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(m)}`,{headers:{"PRIVATE-TOKEN":s}});if(!f.ok)return null;let w=await f.json();return Array.isArray(w)&&w[0]?.id?w[0].id:null}catch{return null}}))).filter(m=>typeof m=="number"));let p;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")p=0;else try{let g=await d(`/projects/${l}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let m=await g.json();Array.isArray(m)&&m[0]?.id&&(p=m[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let u={};if(e.title!==void 0&&(u.title=e.title),e.description!==void 0&&(u.description=e.description),e.labels!==void 0&&(u.labels=e.labels.join(",")),e.addLabels?.length&&(u.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(u.remove_labels=e.removeLabels.join(",")),c!==void 0&&(u.assignee_ids=c),p!==void 0&&(u.milestone_id=p),e.state&&(u.state_event=e.state==="closed"?"close":"reopen"),Object.keys(u).length)try{let g=await d(`/projects/${l}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(u)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let m=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${m.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 d(`/projects/${l}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function tc(t,e,n,r){let s=n.channels.github?.token;if(!s)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(u,g={})=>fetch(`https://api.github.com${u}`,{...g,headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),d=t.project,l;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")l=null;else try{let u=await a(`/repos/${d}/milestones?state=all&per_page=100`);if(u.ok){let g=await u.json(),m=Array.isArray(g)?g.find(f=>f.title===e.milestoneTitle):null;m?.number&&(l=m.number)}}catch(u){r(`[backlog-sync] github milestone lookup failed: ${u.message}`)}let c;if(e.labels!==void 0)c=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let u=await a(`/repos/${d}/issues/${t.iid}`);if(u.ok){let g=await u.json(),m=Array.isArray(g.labels)?g.labels.map(w=>typeof w=="string"?w:w.name):[],f=new Set([...m,...e.addLabels??[]]);for(let w of e.removeLabels??[])f.delete(w);c=[...f]}}catch(u){r(`[backlog-sync] github label fetch failed: ${u.message}`)}if(c===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.body=e.description),c!==void 0&&(p.labels=c),e.assigneeUsernames!==void 0&&(p.assignees=e.assigneeUsernames),l!==void 0&&(p.milestone=l),e.state&&(p.state=e.state),Object.keys(p).length)try{let u=await a(`/repos/${d}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(p)});if(i.push({kind:"PATCH issue",ok:u.ok,status:u.status}),!u.ok){let g=await u.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${u.status}: ${g.slice(0,200)}`,url:t.url}}}catch(u){return i.push({kind:"PATCH issue",ok:!1,error:u.message}),{ok:!1,attempts:i,error:u.message,url:t.url}}if(e.note)try{let u=await a(`/repos/${d}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:u.ok,status:u.status})}catch(u){i.push({kind:"POST comment",ok:!1,error:u.message})}return{ok:i.every(u=>u.ok),attempts:i,url:t.url}}var Vt=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,Ve=/@([a-z0-9_-]+)/i,is=/\[time:\s*([0-9hm\s]+)\]/i;function sc(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 Xt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new qe(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=qt(process.cwd(),this.path);return Ht(e)?Bt(e,"utf-8").split(`
528
+ `):[]}writeMd(e){let n=qt(process.cwd(),this.path);as(n,e.join(`
529
+ `))}async listOpen(e){if(this.store.exists())return this.store.list().filter(s=>s.status!=="done"&&(!s.assignee||s.assignee.toLowerCase()===e.toLowerCase())).map(s=>this.toWorkItem(s));let n=this.readMd(),r=[];for(let o=0;o<n.length;o++){let s=n[o].match(Vt);if(!s||s[2].toLowerCase()==="x")continue;let a=s[3],d=a.match(Ve);if(d&&d[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(is),c=a.replace(Ve,"").replace(is,"").trim();r.push({id:`backlog:${o}`,title:c||`Task at line ${o+1}`,assignee:d?d[1]:void 0,estimatedSeconds:l?sc(l[1]):void 0,priority:o})}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 o=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(o.source&&this.daemon){let s=ss([o.assignee||e],o.source,this.daemon);jt(o,{assigneeUsernames:s,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 d=this.store.update(e,a);if(d.source&&this.daemon){let l={};n.status==="done"?(l.addLabels=["Done"],l.removeLabels=["Doing"]):n.status==="blocked"&&(l.addLabels=["Blocked"]),n.note&&(l.note=n.note),Object.keys(l).length&&jt(d,l,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),o=this.readMd(),s=o[r];if(!s)throw new Error(`backlog line ${r} missing`);if(!s.match(Vt))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){o[r]=s.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";o.splice(r+1,0,a)}else n.status==="blocked"?o.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&o.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(o)}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"}}},zt=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(Ht(e))for(let r of nc(e)){let o=oc(e,r);rc(o).isDirectory()?this.walk(o,n):r.endsWith(".md")&&n.push(o)}}async listOpen(e){let n=[];this.walk(qt(process.cwd(),this.root),n);let r=[];for(let o of n){let s=Bt(o,"utf-8").split(`
530
+ `);for(let i=0;i<s.length;i++){let a=s[i].match(Vt);if(!a||a[2].toLowerCase()==="x")continue;let d=a[3].match(Ve);!d||d[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${o}:${i}`,title:a[3].replace(Ve,"").trim(),assignee:d[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),o=parseInt(r[r.length-1],10),s=r.slice(1,-1).join(":");if(!Ht(s))return;let i=Bt(s,"utf-8").split(`
531
+ `);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),as(s,i.join(`
532
+ `)))}},Kt=class{constructor(e,n,r,o,s){this.host=e;this.token=n;this.projects=r;this.agentUsernames=o;this.log=s}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(o=>o.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,o=[],s;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(s=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),o=s.map(l=>l.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),d=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:d?this.usernameToAgent(d)||d:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:o,labelDetails:s,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=[],o=this.projects.length?this.projects:["__ALL__"];for(let s of n)for(let i of o)try{let a=`assignee_username=${encodeURIComponent(s)}&state=opened&scope=all&per_page=20`,d=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(d);for(let c of l){let p=this.mapIssue(c,i);p.assignee=e,r.push(p)}}catch(a){this.log(`[business] GitLab listOpen failed for ${s} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:o,type:s}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${s==="issue"?"issues":"merge_requests"}/${o}?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:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),d=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/add_spent_time?duration=${encodeURIComponent(d)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?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}/${o}?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}/${o}/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(),o=new URLSearchParams,s=e.state??"opened";o.set("state",s),o.set("updated_after",r),o.set("scope","all"),o.set("per_page","100"),o.set("with_labels_details","true"),o.set("order_by","updated_at"),o.set("sort","desc"),e.labels?.length&&o.set("labels",e.labels.join(",")),e.milestone&&o.set("milestone",e.milestone),e.search&&o.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of i)try{let c=l==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${o.toString()}`,p=await this.api(c);for(let u of p)a.push(this.mapIssue(u,l))}catch(c){this.log(`[business] GitLab listAll failed on ${l}: ${c.message}`)}let d=a;if(e.notLabels?.length){let l=new Set(e.notLabels);d=d.filter(c=>!(c.labels||[]).some(p=>l.has(p)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";d=d.filter(c=>!(c.labels||[]).some(p=>p.startsWith(l)))}return d}async setState(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let o=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(o,n),descriptionHtml:o.description_html||void 0,createdAt:o.created_at,author:o.author?{username:o.author.username,name:o.author.name,avatarUrl:o.author.avatar_url}:void 0,allLabels:Array.isArray(o.labels)?typeof o.labels[0]=="object"?o.labels.map(i=>i.name):o.labels:[]}}catch(o){return this.log(`[board] GitLab getItem failed for ${e}: ${o.message}`),null}}async updateItem(e,n){let{project:r,iid:o}=this.parseId(e),s;n.assigneeUsernames&&(s=(await Promise.all(n.assigneeUsernames.map(async c=>{try{let p=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(p)&&p[0]?.id?p[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 l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),s!==void 0&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let d=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(d,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 o of r)o.username&&!e.has(o.username)&&e.set(o.username,{username:o.username,name:o.name,avatarUrl:o.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 o=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let s of o)s.title&&!e.has(s.title)&&e.set(s.title,{id:s.id,title:s.title,state:s.state,dueDate:s.due_date})}catch(o){this.log(`[board] listMilestones failed for ${r}: ${o.message}`)}let n=[...e.values()];return n.sort((r,o)=>r.state!==o.state?r.state==="active"?-1:1:r.title.localeCompare(o.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,o=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];o.length&&(r=(await Promise.all(o.map(async l=>{try{let c=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${l}: ${c.message}`),null}}))).filter(l=>typeof l=="number"));let s;if(e.milestoneTitle)try{let d=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(s=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${d.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),s!==void 0&&(i.milestone_id=s);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:o,iid:s,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",d=new URLSearchParams;n.length&&d.set("add_labels",n.join(",")),r.length&&d.set("remove_labels",r.join(",")),d.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${d.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),o=r.pop(),s=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:s,iid:o}}};function cm(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Xt(r.path,e,n);case"wiki":return new zt(r.path,r.glob);case"gitlab":{let o=e.channels.gitlab;if(!o?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let s={};for(let a of o.agentMappings)a.gitlabUsernames.length&&(s[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:o.routes.map(a=>a.project);return new Kt(o.host,o.token,i,s,n)}}}et();var Gt="unmapped";function Yt(t,e=[]){if(!t)return Gt;let n=e.find(o=>o.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function ic(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of le(t)){let a=C(i.from),d=C(i.to);i.type==="reports-to"&&a.kind==="agent"&&d.kind==="agent"&&o.set(a.id,d.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Yt(i.id,n)));let s=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let d=o.get(i);if(!d)return;let l=s(d,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))s(i);return e}function ac(t,e,n=[]){if(!n.length)return;let r=n.filter(o=>!o.channel||o.channel===t);return r.find(o=>o.chatId&&e.chatId&&o.chatId===e.chatId)??r.find(o=>o.username&&e.username&&o.username===e.username)??r.find(o=>o.senderId&&e.senderId&&o.senderId===e.senderId)??r.find(o=>o.channel&&!o.chatId&&!o.username&&!o.senderId)}function pm(t,e){let n=ac(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Yt(t.project,e.projects);if(t.agentId){let r=ic(e).get(t.agentId);if(r)return r}return Gt}function gm(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,o,...s]=n,i=s.join(":"),a={agentId:e||r,channel:o};return o==="gitlab"||o==="github"?a.project=i.split(":")[0]:o==="cron"||o==="api"||(a.chatId=i.split("@")[0]),a}var lc=t=>t===Gt?"internal":"client";function cc(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??lc(t),respondWithinMinutes:dc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function mm(t){let e=new Set;for(let n of t.projects??[])e.add(Yt(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=>cc(n,t))}function dc(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 uc}from"crypto";var bm={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},pc=40,gc=20,ym=90,mc=2e3,ls=36e5;function fc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
533
+ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<pc?null:`text:${uc("sha256").update(r).digest("hex").slice(0,24)}`}function wm(t){let e=t.indexOf(`
534
534
  `);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function Jt(t){t.exec(`
535
535
  CREATE TABLE IF NOT EXISTS owner_told (
536
536
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -549,34 +549,34 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<uc?null:`text:${d
549
549
  CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
550
550
  CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
551
551
  CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
552
- `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of fc)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(o){if(!/duplicate column/i.test(String(o?.message)))throw o}}var fc=[["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 Ve(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 ls=class{constructor(e){this.db=e;Jt(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
553
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,gc),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?Ve(n):null}setOutcome(e,n){this.db.prepare("UPDATE owner_told SET outcome = ? WHERE id = ?").run(n,e)}lastTold(e,n,r=!0){let o=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 o?Ve(o):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(Ve)}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 o of e)r.run(n,o)})()}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(Ve)}counts(e){let n={sent:0,held:0,digest:0,repeat:0,failed:0};for(let r of this.db.prepare("SELECT outcome, COUNT(*) AS n FROM owner_told WHERE at >= ? GROUP BY outcome").all(e))n[r.outcome]=r.n;return n}states(e){let n=this.db.prepare(`SELECT SUM(CASE WHEN answered_at IS NULL AND seen_at IS NULL THEN 1 ELSE 0 END) AS sent,
552
+ `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of hc)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(o){if(!/duplicate column/i.test(String(o?.message)))throw o}}var hc=[["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 Xe(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 cs=class{constructor(e){this.db=e;Jt(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
553
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,mc),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?Xe(n):null}setOutcome(e,n){this.db.prepare("UPDATE owner_told SET outcome = ? WHERE id = ?").run(n,e)}lastTold(e,n,r=!0){let o=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 o?Xe(o):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(Xe)}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 o of e)r.run(n,o)})()}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(Xe)}counts(e){let n={sent:0,held:0,digest:0,repeat:0,failed:0};for(let r of this.db.prepare("SELECT outcome, COUNT(*) AS n FROM owner_told WHERE at >= ? GROUP BY outcome").all(e))n[r.outcome]=r.n;return n}states(e){let n=this.db.prepare(`SELECT SUM(CASE WHEN answered_at IS NULL AND seen_at IS NULL THEN 1 ELSE 0 END) AS sent,
554
554
  SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
555
555
  SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
556
- FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},cs=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(),o=this.now(),s=mc(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,pc):r.repeatWindowHours)*as,d=r.digestNags&&r.digestAvailable!==!1,l="send";!n.urgent&&s&&this.ledger.lastTold(s,o-a,d)?l="repeat":!n.urgent&&i==="nag"&&d&&(l="digest");let c=this.ledger.add({at:o,key:s??`once:${o}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:l==="send"?"sent":l,urgent:n.urgent===!0});return{verdict:l,key:s,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:hc(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*as)}};function vm(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,o=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,s=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)}:{},...o?{kind:o}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...s?{from:s}:{}}}function hc(t,e=5,n=3){let r=new Map;for(let a of t){let[d,...l]=a.title.split(": "),c=l.join(": ").trim(),p=r.get(d.trim())??{count:0,names:[]};p.count++,c&&!p.names.includes(c)&&p.names.push(c),r.set(d.trim(),p)}let o=[...r.entries()].sort((a,d)=>d[1].count-a[1].count),s=o.slice(0,e).map(([a,{count:d,names:l}])=>{let c=l.length?` (${l.slice(0,n).join(", ")}${l.length>n?", \u2026":""})`:"";return`${a}${d>1?` \xD7${d}`:""}${c}`}),i=o.length>e?`; ${o.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${s.join("; ")}${i}.`}var bc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,yc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Xe(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(yc)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],o=wc(r);if(!o)return{cleanText:t};let s=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,s)+i+t.slice(s+n[0].length)).trim(),ui:o}}function Em(t){if(!t||!t.includes("agentx:ui"))return t;let e=bc.exec(t);return e?t.slice(0,e.index).trimEnd():t}function wc(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=[],o=[],s=[];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()?o.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&s.push(i.label));r.length&&(n.buttons=r),o.length&&(n.replies=o),s.length&&(n.skippedActions=s)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,o=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(o)&&o.filter(s=>typeof s=="string").length>=2&&(n.poll={question:r,options:o.filter(s=>typeof s=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:o,caption:s}=e.media;["image","document","audio","video"].includes(r)&&typeof o=="string"&&o&&(n.media={type:r,url:o,...typeof s=="string"?{caption:s}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function $m(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 xc=5*6e4;function X(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var ds=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(X)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${X(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let o=r.filter(s=>s.expiresAt>e);o.length===0?this.pending.delete(n):o.length!==r.length&&this.pending.set(n,o)}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 o={callId:e,recipient:n,sink:r};this.subs.add(o);let s=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${s}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let d=Date.now(),l=a.filter(c=>c.expiresAt>d);for(let{signal:c}of l)this.deliverTo(o,c);this.pending.delete(i),l.length&&this.log(`flushed ${l.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(o),this.log(`unsubscribe[${s}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
556
+ FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},ds=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(),o=this.now(),s=fc(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,gc):r.repeatWindowHours)*ls,d=r.digestNags&&r.digestAvailable!==!1,l="send";!n.urgent&&s&&this.ledger.lastTold(s,o-a,d)?l="repeat":!n.urgent&&i==="nag"&&d&&(l="digest");let c=this.ledger.add({at:o,key:s??`once:${o}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:l==="send"?"sent":l,urgent:n.urgent===!0});return{verdict:l,key:s,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:bc(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*ls)}};function xm(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,o=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,s=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)}:{},...o?{kind:o}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...s?{from:s}:{}}}function bc(t,e=5,n=3){let r=new Map;for(let a of t){let[d,...l]=a.title.split(": "),c=l.join(": ").trim(),p=r.get(d.trim())??{count:0,names:[]};p.count++,c&&!p.names.includes(c)&&p.names.push(c),r.set(d.trim(),p)}let o=[...r.entries()].sort((a,d)=>d[1].count-a[1].count),s=o.slice(0,e).map(([a,{count:d,names:l}])=>{let c=l.length?` (${l.slice(0,n).join(", ")}${l.length>n?", \u2026":""})`:"";return`${a}${d>1?` \xD7${d}`:""}${c}`}),i=o.length>e?`; ${o.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${s.join("; ")}${i}.`}function vm(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 yc=5*6e4;function X(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var us=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(X)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${X(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let o=r.filter(s=>s.expiresAt>e);o.length===0?this.pending.delete(n):o.length!==r.length&&this.pending.set(n,o)}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 o={callId:e,recipient:n,sink:r};this.subs.add(o);let s=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${s}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let d=Date.now(),l=a.filter(c=>c.expiresAt>d);for(let{signal:c}of l)this.deliverTo(o,c);this.pending.delete(i),l.length&&this.log(`flushed ${l.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(o),this.log(`unsubscribe[${s}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
557
557
  data: ${JSON.stringify(n)}
558
558
 
559
- `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=X(e.to);if(n===X(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 o=await this.forwarder(e.to,e);return o?{ok:o}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&X(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(X(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(),o=this.recentRings.get(e.callId);if(o&&o>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+xc),this.ringHandler)try{this.ringHandler(e)}catch(s){this.log(`ringHandler threw: ${s.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),o=this.pending.get(r)||[];o.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,o),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${o.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=X(e.to);for(let o of this.subs)o.callId===e.callId&&X(o.recipient)===r&&(this.deliverTo(o,e)?n++:this.subs.delete(o));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 kc,readFileSync as us,renameSync as vc,rmSync as Sc,writeFileSync as Ec}from"fs";import{homedir as _c}from"os";import{dirname as $c,join as Tc}from"path";var ps=Tc(_c(),".agentx","call.json");function Ac(t=ps,e=Date.now()){try{let n=JSON.parse(us(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 gs(t=rr,e=Ac){let n=t();return n.active?n:e()}function Cm(t,e,n=ps,r=Date.now()){let o=null;try{o=JSON.parse(us(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&Sc(n,{force:!0});return}kc($c(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;Ec(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
560
- `),vc(s,n)}var ms="owner",ze=6e4,ws=60*ze,Rc=24*ws,Ic=7*24*ws,Dc=2*ze,Lm={enabled:!1,escalateAfterMinutes:10,ladder:[]};function Cc(t){t.exec(`
559
+ `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=X(e.to);if(n===X(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 o=await this.forwarder(e.to,e);return o?{ok:o}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&X(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(X(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(),o=this.recentRings.get(e.callId);if(o&&o>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+yc),this.ringHandler)try{this.ringHandler(e)}catch(s){this.log(`ringHandler threw: ${s.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),o=this.pending.get(r)||[];o.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,o),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${o.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=X(e.to);for(let o of this.subs)o.callId===e.callId&&X(o.recipient)===r&&(this.deliverTo(o,e)?n++:this.subs.delete(o));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 wc,readFileSync as ps,renameSync as xc,rmSync as kc,writeFileSync as vc}from"fs";import{homedir as Sc}from"os";import{dirname as Ec,join as _c}from"path";var gs=_c(Sc(),".agentx","call.json");function $c(t=gs,e=Date.now()){try{let n=JSON.parse(ps(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 ms(t=or,e=$c){let n=t();return n.active?n:e()}function Am(t,e,n=gs,r=Date.now()){let o=null;try{o=JSON.parse(ps(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&kc(n,{force:!0});return}wc(Ec(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;vc(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
560
+ `),xc(s,n)}var fs="owner",ze=6e4,xs=60*ze,Tc=24*xs,Ac=7*24*xs,Rc=2*ze,Dm={enabled:!1,escalateAfterMinutes:10,ladder:[]};function Ic(t){t.exec(`
561
561
  CREATE TABLE IF NOT EXISTS owner_presence (
562
562
  person TEXT NOT NULL,
563
563
  surface TEXT NOT NULL,
564
564
  at INTEGER NOT NULL,
565
565
  PRIMARY KEY (person, surface)
566
566
  );
567
- `)}var fs=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;Cc(e)}written=new Map;touch(e,n=ms){let r=this.now(),o=`${n}
567
+ `)}var hs=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;Ic(e)}written=new Map;touch(e,n=fs){let r=this.now(),o=`${n}
568
568
  ${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this.db.prepare(`INSERT INTO owner_presence (person, surface, at) VALUES (?, ?, ?)
569
- ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=ms){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function Pm(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var hs=class{constructor(e,n=Date.now){this.db=e;this.now=n;Jt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
569
+ ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=fs){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function Cm(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var bs=class{constructor(e,n=Date.now){this.db=e;this.now=n;Jt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
570
570
  WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
571
- ORDER BY at DESC LIMIT 500`).all(this.now()-Ic)}seenByRequest(e,n){return this.byRequest(e,r=>this.seen(r,n))}answeredByRequest(e,n,r=this.now()){return this.byRequest(e,o=>this.answered(o,n,r),r)}seenPush(e,n="phone"){let r=[],o=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 s of e){let i=s.title.endsWith("\u2026")?s.title.slice(0,-1):s.title,d=o.all(s.at-Dc,s.at).find(l=>l.title===s.title||i!==s.title&&l.title.startsWith(i));d&&r.push(d.id)}return this.seen(r,n)}seen(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET seen_at = ?, seen_via = ?
572
- WHERE seen_at IS NULL AND (${bs(e)})`).run(r,n,...e,...e,...e).changes:0}answered(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET answered_at = ?, answered_via = ?, seen_at = COALESCE(seen_at, ?), seen_via = COALESCE(seen_via, ?)
573
- WHERE answered_at IS NULL AND (${bs(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let o=new Set(e.filter(Boolean));if(!o.size)return 0;let s=this.openRequestRows().filter(i=>o.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(s)}};function bs(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 Mm(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(s=>`${s}:default`),...e.addresses],o=[];for(let s of r){let i=s.trim(),a=he(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function he(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function Nc(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function Oc(t){return he(t)==="push"?["phone","desk"]:[t]}function Fm(t,e,n){let r=t.filter(s=>n(he(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>Oc(s).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!o||i>o.at)&&(o={stop:s,at:i})}return o?.stop??r[0]}function Lc(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(s=>s!==e&&n(he(s)))??null}var Pc=3;async function Um(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*ze,i=e.prepare(`SELECT id FROM owner_told
571
+ ORDER BY at DESC LIMIT 500`).all(this.now()-Ac)}seenByRequest(e,n){return this.byRequest(e,r=>this.seen(r,n))}answeredByRequest(e,n,r=this.now()){return this.byRequest(e,o=>this.answered(o,n,r),r)}seenPush(e,n="phone"){let r=[],o=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 s of e){let i=s.title.endsWith("\u2026")?s.title.slice(0,-1):s.title,d=o.all(s.at-Rc,s.at).find(l=>l.title===s.title||i!==s.title&&l.title.startsWith(i));d&&r.push(d.id)}return this.seen(r,n)}seen(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET seen_at = ?, seen_via = ?
572
+ WHERE seen_at IS NULL AND (${ys(e)})`).run(r,n,...e,...e,...e).changes:0}answered(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET answered_at = ?, answered_via = ?, seen_at = COALESCE(seen_at, ?), seen_via = COALESCE(seen_via, ?)
573
+ WHERE answered_at IS NULL AND (${ys(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let o=new Set(e.filter(Boolean));if(!o.size)return 0;let s=this.openRequestRows().filter(i=>o.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(s)}};function ys(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 Nm(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(s=>`${s}:default`),...e.addresses],o=[];for(let s of r){let i=s.trim(),a=he(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function he(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function Dc(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function Cc(t){return he(t)==="push"?["phone","desk"]:[t]}function Om(t,e,n){let r=t.filter(s=>n(he(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>Cc(s).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!o||i>o.at)&&(o={stop:s,at:i})}return o?.stop??r[0]}function Nc(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(s=>s!==e&&n(he(s)))??null}var Oc=3;async function Lm(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*ze,i=e.prepare(`SELECT id FROM owner_told
574
574
  WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
575
575
  AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
576
576
  AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
577
- ORDER BY at LIMIT 20`).all(Math.max(o-Pc*s,o-Rc),o-s),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),d=0;for(let{id:l}of i){if(a.run(o,l).changes!==1)continue;let c=n.get(l);if(!c)continue;let p=`${c.channel}:${c.chatId}`,u=Lc(t.stops,p,t.up);if(!u){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${p}; no other address to try`);continue}let g=Math.round((o-c.at)/ze),m=c.outcome==="failed"?`it could not be sent on ${c.channel}`:`not seen on ${c.channel} for ${g} min`,f=`${c.text?`${c.text}
577
+ ORDER BY at LIMIT 20`).all(Math.max(o-Oc*s,o-Tc),o-s),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),d=0;for(let{id:l}of i){if(a.run(o,l).changes!==1)continue;let c=n.get(l);if(!c)continue;let p=`${c.channel}:${c.chatId}`,u=Nc(t.stops,p,t.up);if(!u){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${p}; no other address to try`);continue}let g=Math.round((o-c.at)/ze),m=c.outcome==="failed"?`it could not be sent on ${c.channel}`:`not seen on ${c.channel} for ${g} min`,f=`${c.text?`${c.text}
578
578
 
579
- `:""}(Sent again here: ${m}.)`,w=n.add({at:o,key:c.key,requestId:c.requestId,kind:c.kind,channel:he(u),chatId:Nc(u),from:c.from,title:c.title,text:f,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(u,c,f),d++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${m}; sent once to ${u}`)}catch(x){n.setOutcome(w,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${u} failed: ${x?.message??x}`)}}return d}var ys=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,o]of Object.entries(this.opts.read())){let s=this.state.get(r)??{downSince:null,checks:0,told:!1};if(o.up){s.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}s.downSince??=e,s.checks++,s.reason=o.reason,!s.told&&s.checks>=n&&(s.told=!0,this.opts.log(`[reach] channel ${r} is down: ${o.reason??"no reason given"}`),this.opts.notice(r,o.reason??"no reason given")),this.state.set(r,s)}}downSince(e){return this.state.get(e)?.downSince??void 0}};function Mc(t,e){let n={"reports-to":"report to","dotted-line":"have a dotted line to","acts-for":"act for"},r={};for(let l of t.members)r[l.ref]=l;let o=l=>l&&r[l]?r[l].name:String(l||"").replace(/^(agent|person):/,""),s=l=>!!l&&!!r[l]&&r[l].kind==="agent",i=l=>l.length<2?l.join(""):l.slice(0,-1).join(", ")+" and "+l[l.length-1],a=o(e.from),d=o(e.to);if(e.op==="add-relation"&&e.type==="reports-to"){let l=t.relations.find(p=>p.type==="reports-to"&&p.from===e.from),c=s(e.from)?" When "+a+" is stuck, it asks "+d+" first.":"";return l&&l.to!==e.to&&e.from!==e.to?{text:a+" will report to "+d+", not "+o(l.to)+"."+c,steps:[{op:"remove-relation",from:l.from,type:"reports-to",to:l.to},e],undo:[{op:"add-relation",from:l.from,type:"reports-to",to:l.to}]}:{text:a+" will report to "+d+"."+c,steps:[e],undo:[]}}if(e.op==="add-relation")return{text:a+" will "+(n[e.type||""]||e.type)+" "+d+".",steps:[e],undo:[]};if(e.op==="remove-relation"){let l=e.type==="reports-to"&&s(e.from)?" When "+a+" is stuck, it no longer asks "+d+".":"";return{text:a+" will no longer "+(n[e.type||""]||e.type)+" "+d+"."+l,steps:[e],undo:[]}}if(e.op==="remove-member"){let l=t.relations.filter(p=>p.from===e.member||p.to===e.member).length,c=t.relations.filter(p=>p.type==="reports-to"&&p.to===e.member).map(p=>o(p.from));return{text:o(e.member)+" will leave the org chart"+(l?", with "+l+" "+(l===1?"line":"lines"):"")+"."+(c.length?" "+i(c)+" will report to no one.":""),steps:[e],undo:[]}}return null}function jm(t){let e=c=>String(c??"").replace(/[&<>"']/g,p=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[p]),n={"dotted-line":"dotted line to","acts-for":"acts for"};if(!t||!t.members.length)return"";let r={};for(let c of t.members)r[c.ref]=c;let o={};for(let c of t.relations)c.type==="reports-to"&&r[c.to]&&(o[c.from]=c.to);let s=c=>r[c]?r[c].name:c.replace(/^(agent|person):/,""),i={},a=c=>{i[c.ref]=!0;let p=t.relations.filter(g=>g.from===c.ref&&g.type!=="reports-to").map(g=>(n[g.type]||g.type)+" "+s(g.to)),u=t.members.filter(g=>o[g.ref]===c.ref&&!i[g.ref]);return"<li><b>"+e(c.name)+'</b> <span class="org-kind">'+(c.kind==="person"?"Person":"Agent")+(c.title?" \xB7 "+e(c.title):"")+"</span>"+(p.length?" <small>"+e(p.join(", "))+"</small>":"")+(u.length?"<ul>"+u.map(a).join("")+"</ul>":"")+"</li>"};return'<ul class="oe-tree" aria-label="Org chart">'+t.members.filter(c=>!o[c.ref]).map(a).join("")+t.members.filter(c=>!i[c.ref]).map(a).join("")+"</ul>"}function Fc(t,e,n){let r=h=>String(h??"").replace(/[&<>"']/g,S=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[S]),o={"reports-to":"Reports to","dotted-line":"Dotted line to","acts-for":"Acts for"},s={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"},i=(h,S)=>'<option value="'+r(h)+'">'+r(S)+"</option>";if(!t)return'<p class="org-quiet">Loading\u2026</p>';if(!t.canEdit||!t.setup||!t.choices)return"";let a='<p class="oe-msg'+(e.bad?" is-bad":"")+'" role="status">'+r(e.text)+"</p>",d=n?'<div class="oe-confirm" id="oe-confirm" role="group" aria-label="Confirm the change"><p class="oe-confirm-text">'+r(n)+'</p><span class="oe-acts"><button type="button" class="ax-btn ax-btn--primary" id="oe-confirm-save" data-oe="confirm">Save the move</button><button type="button" class="ax-btn" data-oe="cancel">Cancel</button></span></div>':"",l=t.choices,c=t.setup.members,p={};for(let h of c)p[h.ref]=h;let u=h=>p[h]?p[h].name:h.replace(/^(agent|person):/,""),g=h=>h.filter(S=>!p[S.ref]).map(S=>i(S.ref,S.name)).join(""),m=g(l.agents),f=g(l.people),w='<div class="oe-form" role="group" aria-label="Add a member"><label for="oe-add-member">Member <select id="oe-add-member">'+(m||f?(m?'<optgroup label="Agents">'+m+"</optgroup>":"")+(f?'<optgroup label="People">'+f+"</optgroup>":""):'<option value="">Everyone is in the chart</option>')+'</select></label><label for="oe-add-role">Role <input id="oe-add-role" list="oe-roles" maxlength="80" placeholder="Engineer" autocomplete="off"></label><button type="button" class="ax-btn" data-oe="add-member"'+(m||f?"":" disabled")+'>Add</button></div><datalist id="oe-roles">'+l.roles.map(h=>i(h.title,h.key)).join("")+"</datalist>",x=[["mon","Mon","Monday"],["tue","Tue","Tuesday"],["wed","Wed","Wednesday"],["thu","Thu","Thursday"],["fri","Fri","Friday"],["sat","Sat","Saturday"],["sun","Sun","Sunday"]],b=(h,S)=>{if(h.kind!=="agent")return"";let Qe=h.schedule||{start:"",end:"",days:[]};return'<fieldset class="oe-hours"><legend class="org-kind">Working hours of '+r(h.name)+'</legend><label for="oe-start-'+S+'">Start <input type="time" id="oe-start-'+S+'" value="'+r(Qe.start)+'" aria-label="Start time of '+r(h.name)+'"></label><label for="oe-end-'+S+'">End <input type="time" id="oe-end-'+S+'" value="'+r(Qe.end)+'" aria-label="End time of '+r(h.name)+'"></label><span class="oe-days" role="group" aria-label="Working days of '+r(h.name)+'">'+x.map(Se=>'<label class="oe-day"><input type="checkbox" name="oe-days-'+S+'" value="'+Se[0]+'"'+(Qe.days.indexOf(Se[0])>=0?" checked":"")+' aria-label="'+Se[2]+'">'+Se[1]+"</label>").join("")+'</span><button type="button" class="ax-btn" data-oe="set-schedule" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save hours</button></fieldset>'},y=c.length?'<ul class="oe-rows">'+c.map((h,S)=>'<li class="oe-row"><span class="oe-who"><b>'+r(h.name)+'</b><span class="org-kind">'+(h.kind==="person"?"Person":"Agent")+'</span></span><label class="oe-role" for="oe-role-'+S+'"><span class="org-kind">Role</span><input id="oe-role-'+S+'" list="oe-roles" maxlength="80" value="'+r(h.title||"")+'" aria-label="Role of '+r(h.name)+'"></label><span class="oe-acts"><button type="button" class="ax-btn" data-oe="set-role" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save role</button><button type="button" class="ax-btn" data-oe="remove-member" data-oe-member="'+r(h.ref)+'" aria-label="Remove '+r(h.name)+'">Remove</button><a class="ax-btn" href="/hub#page=settings&amp;section=agents&amp;under='+encodeURIComponent(h.ref)+'" aria-label="Add an agent who reports to '+r(h.name)+'">Add agent here</a></span>'+b(h,S)+"</li>").join("")+"</ul>":'<p class="org-quiet">No one in the org chart yet. Add a member above.</p>',k=t.setup.relations,D=k.length?'<ul class="oe-rows">'+k.map(h=>'<li class="oe-row"><span class="oe-who">'+r(u(h.from))+' <span class="org-kind">'+r(s[h.type]||h.type)+"</span> "+r(u(h.to))+'</span><span class="oe-acts"><button type="button" class="ax-btn" data-oe="remove-relation" data-oe-from="'+r(h.from)+'" data-oe-type="'+r(h.type)+'" data-oe-to="'+r(h.to)+'" aria-label="Remove: '+r(u(h.from)+" "+(s[h.type]||h.type)+" "+u(h.to))+'">Remove</button></span></li>').join("")+"</ul>":'<p class="org-quiet">No relations yet.</p>',ae=c.map(h=>i(h.ref,h.name+(h.kind==="person"?" (person)":""))).join(""),ve=c.length>=2?'<div class="oe-form" role="group" aria-label="Add a relation"><label for="oe-rel-from">Member <select id="oe-rel-from">'+ae+'</select></label><label for="oe-rel-type">Relation <select id="oe-rel-type">'+l.types.map(h=>i(h,o[h]||h)).join("")+'</select></label><label for="oe-rel-to">Target <select id="oe-rel-to">'+ae+'</select></label><button type="button" class="ax-btn" data-oe="add-relation">Add relation</button></div>':'<p class="org-quiet">Add two members to link them.</p>';return'<p class="oe-lead">Each change is checked, saved to agentx.json with a backup, and used at once, with no restart. A change to a line, or a removal, asks you first.</p>'+a+d+'<h2 class="org-h2">Add a member</h2>'+w+'<h2 class="org-h2">Members <span class="org-kind">'+c.length+"</span></h2>"+y+'<h2 class="org-h2">Relations <span class="org-kind">'+k.length+"</span></h2>"+D+ve+'<dl class="oe-legend"><dt>Reports to</dt><dd>The line manager, one at most. Work an agent cannot finish goes up this line.</dd><dt>Dotted line to</dt><dd>A second manager for one topic or project.</dd><dt>Acts for</dt><dd>An agent works on behalf of a person.</dd><dt>Working hours</dt><dd>When an agent is on the clock. An empty start or end, or no day ticked, goes back to 09:00 to 17:00, Monday to Friday.</dd></dl>'}function Bm(t){let e={msg:"",bad:!1,pending:null,focus:!1},n=i=>{let a=document.getElementById(i);return a?a.value:""};async function r(i,a,d){d&&(d.disabled=!0);let l=0,c={};try{for(;l<i.length;l++)c=await t.post(i[l]);e.msg=(c.summary||"Saved")+". Saved.",e.bad=!1}catch(p){if(e.msg=p.message,e.bad=!0,l>0)try{for(let u of a)await t.post(u);e.msg+=" Nothing was changed."}catch(u){e.msg+=" Putting the old line back failed too: "+u.message+". Check the chart below."}}await t.reload(),t.paint(),d&&(d.disabled=!1)}function o(i,a){let d=t.org(),l=d&&d.setup?Mc(d.setup,i):null;if(!l){r([i],[],a);return}e.pending=l,e.msg="",e.bad=!1,e.focus=!0,t.paint()}function s(){e.pending=null,e.msg="Cancelled. Nothing changed.",e.bad=!1,t.paint()}return{E:e,html:()=>Fc(t.org(),{text:e.msg,bad:e.bad},e.pending?e.pending.text:""),focus(){if(e.focus){let i=document.getElementById("oe-confirm-save");i&&i.focus()}e.focus=!1},click(i){let a=i&&i.closest?i.closest("[data-oe]"):null;if(!a)return!1;let d=a.getAttribute("data-oe")||"",l=c=>a.getAttribute("data-oe-"+c)||"";if(d==="confirm"){let c=e.pending;if(!c)return!0;e.pending=null,r(c.steps,c.undo,a)}else if(d==="cancel")s();else if(d==="add-member")n("oe-add-member")&&r([{op:d,member:n("oe-add-member"),role:n("oe-add-role")}],[],a);else if(d==="set-role")r([{op:d,member:l("member"),role:n("oe-role-"+l("i"))}],[],a);else if(d==="set-schedule"){let c=[];document.querySelectorAll('input[name="oe-days-'+l("i")+'"]').forEach(p=>{p.checked&&c.push(p.value)}),r([{op:d,member:l("member"),start:n("oe-start-"+l("i")),end:n("oe-end-"+l("i")),days:c}],[],a)}else d==="add-relation"?o({op:d,from:n("oe-rel-from"),type:n("oe-rel-type"),to:n("oe-rel-to")},a):d==="remove-member"?o({op:d,member:l("member")},a):d==="remove-relation"&&o({op:d,from:l("from"),type:l("type"),to:l("to")},a);return!0},key(i){i.key==="Escape"&&e.pending&&(i.preventDefault(),s())}}}var qm=`
579
+ `:""}(Sent again here: ${m}.)`,w=n.add({at:o,key:c.key,requestId:c.requestId,kind:c.kind,channel:he(u),chatId:Dc(u),from:c.from,title:c.title,text:f,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(u,c,f),d++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${m}; sent once to ${u}`)}catch(x){n.setOutcome(w,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${u} failed: ${x?.message??x}`)}}return d}var ws=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,o]of Object.entries(this.opts.read())){let s=this.state.get(r)??{downSince:null,checks:0,told:!1};if(o.up){s.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}s.downSince??=e,s.checks++,s.reason=o.reason,!s.told&&s.checks>=n&&(s.told=!0,this.opts.log(`[reach] channel ${r} is down: ${o.reason??"no reason given"}`),this.opts.notice(r,o.reason??"no reason given")),this.state.set(r,s)}}downSince(e){return this.state.get(e)?.downSince??void 0}};function Lc(t,e){let n={"reports-to":"report to","dotted-line":"have a dotted line to","acts-for":"act for"},r={};for(let l of t.members)r[l.ref]=l;let o=l=>l&&r[l]?r[l].name:String(l||"").replace(/^(agent|person):/,""),s=l=>!!l&&!!r[l]&&r[l].kind==="agent",i=l=>l.length<2?l.join(""):l.slice(0,-1).join(", ")+" and "+l[l.length-1],a=o(e.from),d=o(e.to);if(e.op==="add-relation"&&e.type==="reports-to"){let l=t.relations.find(p=>p.type==="reports-to"&&p.from===e.from),c=s(e.from)?" When "+a+" is stuck, it asks "+d+" first.":"";return l&&l.to!==e.to&&e.from!==e.to?{text:a+" will report to "+d+", not "+o(l.to)+"."+c,steps:[{op:"remove-relation",from:l.from,type:"reports-to",to:l.to},e],undo:[{op:"add-relation",from:l.from,type:"reports-to",to:l.to}]}:{text:a+" will report to "+d+"."+c,steps:[e],undo:[]}}if(e.op==="add-relation")return{text:a+" will "+(n[e.type||""]||e.type)+" "+d+".",steps:[e],undo:[]};if(e.op==="remove-relation"){let l=e.type==="reports-to"&&s(e.from)?" When "+a+" is stuck, it no longer asks "+d+".":"";return{text:a+" will no longer "+(n[e.type||""]||e.type)+" "+d+"."+l,steps:[e],undo:[]}}if(e.op==="remove-member"){let l=t.relations.filter(p=>p.from===e.member||p.to===e.member).length,c=t.relations.filter(p=>p.type==="reports-to"&&p.to===e.member).map(p=>o(p.from));return{text:o(e.member)+" will leave the org chart"+(l?", with "+l+" "+(l===1?"line":"lines"):"")+"."+(c.length?" "+i(c)+" will report to no one.":""),steps:[e],undo:[]}}return null}function Mm(t){let e=c=>String(c??"").replace(/[&<>"']/g,p=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[p]),n={"dotted-line":"dotted line to","acts-for":"acts for"};if(!t||!t.members.length)return"";let r={};for(let c of t.members)r[c.ref]=c;let o={};for(let c of t.relations)c.type==="reports-to"&&r[c.to]&&(o[c.from]=c.to);let s=c=>r[c]?r[c].name:c.replace(/^(agent|person):/,""),i={},a=c=>{i[c.ref]=!0;let p=t.relations.filter(g=>g.from===c.ref&&g.type!=="reports-to").map(g=>(n[g.type]||g.type)+" "+s(g.to)),u=t.members.filter(g=>o[g.ref]===c.ref&&!i[g.ref]);return"<li><b>"+e(c.name)+'</b> <span class="org-kind">'+(c.kind==="person"?"Person":"Agent")+(c.title?" \xB7 "+e(c.title):"")+"</span>"+(p.length?" <small>"+e(p.join(", "))+"</small>":"")+(u.length?"<ul>"+u.map(a).join("")+"</ul>":"")+"</li>"};return'<ul class="oe-tree" aria-label="Org chart">'+t.members.filter(c=>!o[c.ref]).map(a).join("")+t.members.filter(c=>!i[c.ref]).map(a).join("")+"</ul>"}function Pc(t,e,n){let r=h=>String(h??"").replace(/[&<>"']/g,S=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[S]),o={"reports-to":"Reports to","dotted-line":"Dotted line to","acts-for":"Acts for"},s={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"},i=(h,S)=>'<option value="'+r(h)+'">'+r(S)+"</option>";if(!t)return'<p class="org-quiet">Loading\u2026</p>';if(!t.canEdit||!t.setup||!t.choices)return"";let a='<p class="oe-msg'+(e.bad?" is-bad":"")+'" role="status">'+r(e.text)+"</p>",d=n?'<div class="oe-confirm" id="oe-confirm" role="group" aria-label="Confirm the change"><p class="oe-confirm-text">'+r(n)+'</p><span class="oe-acts"><button type="button" class="ax-btn ax-btn--primary" id="oe-confirm-save" data-oe="confirm">Save the move</button><button type="button" class="ax-btn" data-oe="cancel">Cancel</button></span></div>':"",l=t.choices,c=t.setup.members,p={};for(let h of c)p[h.ref]=h;let u=h=>p[h]?p[h].name:h.replace(/^(agent|person):/,""),g=h=>h.filter(S=>!p[S.ref]).map(S=>i(S.ref,S.name)).join(""),m=g(l.agents),f=g(l.people),w='<div class="oe-form" role="group" aria-label="Add a member"><label for="oe-add-member">Member <select id="oe-add-member">'+(m||f?(m?'<optgroup label="Agents">'+m+"</optgroup>":"")+(f?'<optgroup label="People">'+f+"</optgroup>":""):'<option value="">Everyone is in the chart</option>')+'</select></label><label for="oe-add-role">Role <input id="oe-add-role" list="oe-roles" maxlength="80" placeholder="Engineer" autocomplete="off"></label><button type="button" class="ax-btn" data-oe="add-member"'+(m||f?"":" disabled")+'>Add</button></div><datalist id="oe-roles">'+l.roles.map(h=>i(h.title,h.key)).join("")+"</datalist>",x=[["mon","Mon","Monday"],["tue","Tue","Tuesday"],["wed","Wed","Wednesday"],["thu","Thu","Thursday"],["fri","Fri","Friday"],["sat","Sat","Saturday"],["sun","Sun","Sunday"]],b=(h,S)=>{if(h.kind!=="agent")return"";let Qe=h.schedule||{start:"",end:"",days:[]};return'<fieldset class="oe-hours"><legend class="org-kind">Working hours of '+r(h.name)+'</legend><label for="oe-start-'+S+'">Start <input type="time" id="oe-start-'+S+'" value="'+r(Qe.start)+'" aria-label="Start time of '+r(h.name)+'"></label><label for="oe-end-'+S+'">End <input type="time" id="oe-end-'+S+'" value="'+r(Qe.end)+'" aria-label="End time of '+r(h.name)+'"></label><span class="oe-days" role="group" aria-label="Working days of '+r(h.name)+'">'+x.map(Se=>'<label class="oe-day"><input type="checkbox" name="oe-days-'+S+'" value="'+Se[0]+'"'+(Qe.days.indexOf(Se[0])>=0?" checked":"")+' aria-label="'+Se[2]+'">'+Se[1]+"</label>").join("")+'</span><button type="button" class="ax-btn" data-oe="set-schedule" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save hours</button></fieldset>'},y=c.length?'<ul class="oe-rows">'+c.map((h,S)=>'<li class="oe-row"><span class="oe-who"><b>'+r(h.name)+'</b><span class="org-kind">'+(h.kind==="person"?"Person":"Agent")+'</span></span><label class="oe-role" for="oe-role-'+S+'"><span class="org-kind">Role</span><input id="oe-role-'+S+'" list="oe-roles" maxlength="80" value="'+r(h.title||"")+'" aria-label="Role of '+r(h.name)+'"></label><span class="oe-acts"><button type="button" class="ax-btn" data-oe="set-role" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save role</button><button type="button" class="ax-btn" data-oe="remove-member" data-oe-member="'+r(h.ref)+'" aria-label="Remove '+r(h.name)+'">Remove</button><a class="ax-btn" href="/hub#page=settings&amp;section=agents&amp;under='+encodeURIComponent(h.ref)+'" aria-label="Add an agent who reports to '+r(h.name)+'">Add agent here</a></span>'+b(h,S)+"</li>").join("")+"</ul>":'<p class="org-quiet">No one in the org chart yet. Add a member above.</p>',k=t.setup.relations,D=k.length?'<ul class="oe-rows">'+k.map(h=>'<li class="oe-row"><span class="oe-who">'+r(u(h.from))+' <span class="org-kind">'+r(s[h.type]||h.type)+"</span> "+r(u(h.to))+'</span><span class="oe-acts"><button type="button" class="ax-btn" data-oe="remove-relation" data-oe-from="'+r(h.from)+'" data-oe-type="'+r(h.type)+'" data-oe-to="'+r(h.to)+'" aria-label="Remove: '+r(u(h.from)+" "+(s[h.type]||h.type)+" "+u(h.to))+'">Remove</button></span></li>').join("")+"</ul>":'<p class="org-quiet">No relations yet.</p>',ae=c.map(h=>i(h.ref,h.name+(h.kind==="person"?" (person)":""))).join(""),ve=c.length>=2?'<div class="oe-form" role="group" aria-label="Add a relation"><label for="oe-rel-from">Member <select id="oe-rel-from">'+ae+'</select></label><label for="oe-rel-type">Relation <select id="oe-rel-type">'+l.types.map(h=>i(h,o[h]||h)).join("")+'</select></label><label for="oe-rel-to">Target <select id="oe-rel-to">'+ae+'</select></label><button type="button" class="ax-btn" data-oe="add-relation">Add relation</button></div>':'<p class="org-quiet">Add two members to link them.</p>';return'<p class="oe-lead">Each change is checked, saved to agentx.json with a backup, and used at once, with no restart. A change to a line, or a removal, asks you first.</p>'+a+d+'<h2 class="org-h2">Add a member</h2>'+w+'<h2 class="org-h2">Members <span class="org-kind">'+c.length+"</span></h2>"+y+'<h2 class="org-h2">Relations <span class="org-kind">'+k.length+"</span></h2>"+D+ve+'<dl class="oe-legend"><dt>Reports to</dt><dd>The line manager, one at most. Work an agent cannot finish goes up this line.</dd><dt>Dotted line to</dt><dd>A second manager for one topic or project.</dd><dt>Acts for</dt><dd>An agent works on behalf of a person.</dd><dt>Working hours</dt><dd>When an agent is on the clock. An empty start or end, or no day ticked, goes back to 09:00 to 17:00, Monday to Friday.</dd></dl>'}function Fm(t){let e={msg:"",bad:!1,pending:null,focus:!1},n=i=>{let a=document.getElementById(i);return a?a.value:""};async function r(i,a,d){d&&(d.disabled=!0);let l=0,c={};try{for(;l<i.length;l++)c=await t.post(i[l]);e.msg=(c.summary||"Saved")+". Saved.",e.bad=!1}catch(p){if(e.msg=p.message,e.bad=!0,l>0)try{for(let u of a)await t.post(u);e.msg+=" Nothing was changed."}catch(u){e.msg+=" Putting the old line back failed too: "+u.message+". Check the chart below."}}await t.reload(),t.paint(),d&&(d.disabled=!1)}function o(i,a){let d=t.org(),l=d&&d.setup?Lc(d.setup,i):null;if(!l){r([i],[],a);return}e.pending=l,e.msg="",e.bad=!1,e.focus=!0,t.paint()}function s(){e.pending=null,e.msg="Cancelled. Nothing changed.",e.bad=!1,t.paint()}return{E:e,html:()=>Pc(t.org(),{text:e.msg,bad:e.bad},e.pending?e.pending.text:""),focus(){if(e.focus){let i=document.getElementById("oe-confirm-save");i&&i.focus()}e.focus=!1},click(i){let a=i&&i.closest?i.closest("[data-oe]"):null;if(!a)return!1;let d=a.getAttribute("data-oe")||"",l=c=>a.getAttribute("data-oe-"+c)||"";if(d==="confirm"){let c=e.pending;if(!c)return!0;e.pending=null,r(c.steps,c.undo,a)}else if(d==="cancel")s();else if(d==="add-member")n("oe-add-member")&&r([{op:d,member:n("oe-add-member"),role:n("oe-add-role")}],[],a);else if(d==="set-role")r([{op:d,member:l("member"),role:n("oe-role-"+l("i"))}],[],a);else if(d==="set-schedule"){let c=[];document.querySelectorAll('input[name="oe-days-'+l("i")+'"]').forEach(p=>{p.checked&&c.push(p.value)}),r([{op:d,member:l("member"),start:n("oe-start-"+l("i")),end:n("oe-end-"+l("i")),days:c}],[],a)}else d==="add-relation"?o({op:d,from:n("oe-rel-from"),type:n("oe-rel-type"),to:n("oe-rel-to")},a):d==="remove-member"?o({op:d,member:l("member")},a):d==="remove-relation"&&o({op:d,from:l("from"),type:l("type"),to:l("to")},a);return!0},key(i){i.key==="Escape"&&e.pending&&(i.preventDefault(),s())}}}var Um=`
580
580
  .oe-tree, .oe-tree ul { list-style: none; margin: 0; padding: 0; font-size: var(--ax-fs-sm); }
581
581
  .oe-tree ul { margin-left: 10px; padding-left: 12px; border-left: var(--ax-border-w) solid var(--ax-border-2); }
582
582
  .oe-tree li { padding: 3px 0; }
@@ -609,7 +609,7 @@ ${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this
609
609
  .oe-form > *, .oe-role { flex: 1 1 100%; }
610
610
  .oe-legend { grid-template-columns: 1fr; }
611
611
  }
612
- `;et();function Qt(t){let e=n=>[...new Set((n??[]).filter(Boolean).map(E))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:E(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function xs(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&Ee(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=Ee(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let m=s(u);if(m)return`Department ${l.name} cannot list ${m.name}: ${i(m)}`;let f=a.get(u);if(f)return`"${u}" is in both department ${f} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=ks(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=Ee(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function ks(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function Xm(t,e){let n=new Set,r=ks(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}et();var vs=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},Ke=["mon","tue","wed","thu","fri","sat","sun"],Zt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Uc(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",be.start),r=e(t.end,"end",be.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!Ke.includes(a));if(s)throw new Error(`"${s}" is not a day. Use mon, tue, wed, thu, fri, sat or sun.`);let i=o.length?Ke.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Wc(t){let e=Ke.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>Ke.indexOf(r)===e+o))return`${Zt[t[0]]} to ${Zt[t[t.length-1]]}`;let n=t.map(r=>Zt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var en={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function tn(t){let e=Array.isArray(t?.people)?t.people:[],n=new Map;for(let r of e)r?.id&&n.set(String(r.id),String(r.name||r.id));return n}function Ts(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function jc(t){let e=t?.business?.roles??{};return{agents:[...Ts(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...tn(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Ze}}function Bc(t){let e=t?.business??{},n=e.roles??{},r=Ts(t),o=tn(t),s=le(e),i=(c,p,u,g)=>({ref:`${c}:${p}`,kind:c,id:p,name:(c==="agent"?r.get(p):o.get(p))??p,...u?{role:u,title:String(n[u]?.title||u)}:{},...g&&typeof g=="object"?{schedule:{start:String(g.start??""),end:String(g.end??""),days:Array.isArray(g.days)?g.days.map(String):[...be.days]}}:{}}),a=[...Object.entries(e.orgChart??{}).map(([c,p])=>i("agent",c,p?.role,p?.schedule)),...Object.entries(e.orgPeople??{}).map(([c,p])=>i("person",c,p?.role))],d=new Set(a.map(c=>c.ref)),l=[...s.flatMap(c=>[c.from,c.to]),...Qt(e).flatMap(c=>[...c.head?[c.head]:[],...c.members])];for(let c of l){let p=C(c);p.kind==="person"&&!d.has(c)&&(d.add(c),a.push(i("person",p.id,void 0)))}return{members:a,relations:s}}function Ss(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(tn(t).keys()),o=_n(t),s=Array.isArray(t?.people)?t.people:[],i=new Map(s.flatMap(a=>a?.id&&(a.role==="client"||a.role==="guest")?[[String(a.id),{name:String(a.name||a.id),role:a.role}]]:[]));return En(le(e),n,r,o)??xs(Qt(e),n,r,o,i)}function qc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&E(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>E(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>E(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function Es(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function _s(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>vs)throw new Error(`Keep the role under ${vs} characters.`);return e}function Hc(t,e,n){let r=new Set;for(let o=e;o&&!r.has(o);o=t.find(s=>s.type==="reports-to"&&s.from===o)?.to){if(o===n)return!0;r.add(o)}return!1}function $s(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:E(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:E(o.from),to:E(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function Ym(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=Ss(n),s=Bc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=jc(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?E(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:m}=C(u),f=d.get(u);if(!f)throw new Error(g==="agent"?`There is no agent "${m}" on this computer.`:`There is no person "${m}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${f} is already in the org chart.`);let w=_s(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?Es(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[m]={role:x,schedule:{...be},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[m]=x?{role:x}:{}),c=`${f} added to the org chart`;break}case"set-role":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=_s(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?Es(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=m:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=m?{role:m}:{}),c=m?`${u.name} is now ${r.roles[m]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let m=$s(r,w=>w.from===u.ref||w.to===u.ref),f=qc(r,u.ref);u.kind==="agent"?delete r.orgChart[u.id]:r.orgPeople&&(delete r.orgPeople[u.id],Object.keys(r.orgPeople).length===0&&delete r.orgPeople),c=`${u.name} removed from the org chart`+(m?`, with ${m} ${m===1?"line":"lines"}`:"")+(f.length?` and out of ${f.join(", ")}`:"");break}case"add-relation":{let u=String(e.type??"").trim(),g=[String(e.from??"").trim(),String(e.to??"").trim()];if(!g[0]||!g[1]||!u)throw new Error("Pick a member, a kind of relation and a target.");if(!Ze.includes(u))throw new Error(`"${u}" is not a kind of relation. Pick reports to, dotted line or acts for.`);let[m,f]=g.map(E);for(let x of[m,f])if(!i.has(x))throw new Error(`${l(x)} is not in the org chart. Add them first.`);if(m===f)throw new Error(`${l(m)} cannot be linked to themself.`);let w={from:m,to:f,type:u};if(s.relations.some(x=>x.from===m&&x.to===f&&x.type===u))throw new Error(`${l(m)} already ${en[u]} ${l(f)}.`);if(u==="acts-for"&&i.get(m).kind!=="agent")throw new Error(`Only an agent can act for someone: ${l(m)} is a person.`);if(u==="acts-for"&&i.get(f).kind!=="person")throw new Error(`An agent acts for a person: ${l(f)} is an agent.`);if(u==="reports-to"){let x=s.relations.find(b=>b.type==="reports-to"&&b.from===m);if(x)throw new Error(`${l(m)} already reports to ${l(x.to)}. Remove that line first: each member has one boss.`);if(Hc(s.relations,f,m))throw new Error(`${l(m)} cannot report to ${l(f)}: ${l(f)} already reports up to ${l(m)}.`)}if(u==="reports-to"&&i.get(m).kind==="agent"){let x=C(f);r.orgChart[C(m).id].reportsTo=x.kind==="agent"?x.id:f}else r.relations=[...r.relations??[],w];c=`${l(m)} ${en[u]} ${l(f)}`;break}case"remove-relation":{let u={from:E(String(e.from??"")),to:E(String(e.to??"")),type:String(e.type??"")};if(!$s(r,g=>g.from===u.from&&g.to===u.to&&g.type===u.type))throw new Error("That line is not in the org chart any more. Reload the page.");c=`${l(u.from)} no longer ${en[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);if(u.kind!=="agent")throw new Error(`Working hours are for agents: ${u.name} is a person.`);let g=Uc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Wc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=Ss(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}var Vc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},As=class{constructor(e=Vc,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(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},Xc="That code didn't work. Check it, or run agentx app pair for a new one.",zc=400;async function Zm(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await _r(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await Kc(n,e.minMs??zc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Xc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function Kc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as ud}from"child_process";import{mkdtempSync as od,rmSync as sd,writeFileSync as id}from"fs";import{tmpdir as ad}from"os";import{join as Ns}from"path";import{randomBytes as Gc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var B={top:8,side:32,bottom:60},nn={height:56,keep:52},Rs=`
612
+ `;et();function Qt(t){let e=n=>[...new Set((n??[]).filter(Boolean).map(E))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:E(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function ks(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&Ee(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=Ee(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let m=s(u);if(m)return`Department ${l.name} cannot list ${m.name}: ${i(m)}`;let f=a.get(u);if(f)return`"${u}" is in both department ${f} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=vs(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=Ee(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function vs(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function Bm(t,e){let n=new Set,r=vs(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}et();var Ss=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},Ke=["mon","tue","wed","thu","fri","sat","sun"],Zt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Mc(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",be.start),r=e(t.end,"end",be.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!Ke.includes(a));if(s)throw new Error(`"${s}" is not a day. Use mon, tue, wed, thu, fri, sat or sun.`);let i=o.length?Ke.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Fc(t){let e=Ke.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>Ke.indexOf(r)===e+o))return`${Zt[t[0]]} to ${Zt[t[t.length-1]]}`;let n=t.map(r=>Zt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var en={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function tn(t){let e=Array.isArray(t?.people)?t.people:[],n=new Map;for(let r of e)r?.id&&n.set(String(r.id),String(r.name||r.id));return n}function As(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function Uc(t){let e=t?.business?.roles??{};return{agents:[...As(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...tn(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Ze}}function Wc(t){let e=t?.business??{},n=e.roles??{},r=As(t),o=tn(t),s=le(e),i=(c,p,u,g)=>({ref:`${c}:${p}`,kind:c,id:p,name:(c==="agent"?r.get(p):o.get(p))??p,...u?{role:u,title:String(n[u]?.title||u)}:{},...g&&typeof g=="object"?{schedule:{start:String(g.start??""),end:String(g.end??""),days:Array.isArray(g.days)?g.days.map(String):[...be.days]}}:{}}),a=[...Object.entries(e.orgChart??{}).map(([c,p])=>i("agent",c,p?.role,p?.schedule)),...Object.entries(e.orgPeople??{}).map(([c,p])=>i("person",c,p?.role))],d=new Set(a.map(c=>c.ref)),l=[...s.flatMap(c=>[c.from,c.to]),...Qt(e).flatMap(c=>[...c.head?[c.head]:[],...c.members])];for(let c of l){let p=C(c);p.kind==="person"&&!d.has(c)&&(d.add(c),a.push(i("person",p.id,void 0)))}return{members:a,relations:s}}function Es(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(tn(t).keys()),o=_n(t),s=Array.isArray(t?.people)?t.people:[],i=new Map(s.flatMap(a=>a?.id&&(a.role==="client"||a.role==="guest")?[[String(a.id),{name:String(a.name||a.id),role:a.role}]]:[]));return En(le(e),n,r,o)??ks(Qt(e),n,r,o,i)}function jc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&E(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>E(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>E(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function _s(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function $s(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>Ss)throw new Error(`Keep the role under ${Ss} characters.`);return e}function Bc(t,e,n){let r=new Set;for(let o=e;o&&!r.has(o);o=t.find(s=>s.type==="reports-to"&&s.from===o)?.to){if(o===n)return!0;r.add(o)}return!1}function Ts(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:E(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:E(o.from),to:E(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function Xm(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=Es(n),s=Wc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=Uc(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?E(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:m}=C(u),f=d.get(u);if(!f)throw new Error(g==="agent"?`There is no agent "${m}" on this computer.`:`There is no person "${m}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${f} is already in the org chart.`);let w=$s(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?_s(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[m]={role:x,schedule:{...be},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[m]=x?{role:x}:{}),c=`${f} added to the org chart`;break}case"set-role":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=$s(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?_s(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=m:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=m?{role:m}:{}),c=m?`${u.name} is now ${r.roles[m]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let m=Ts(r,w=>w.from===u.ref||w.to===u.ref),f=jc(r,u.ref);u.kind==="agent"?delete r.orgChart[u.id]:r.orgPeople&&(delete r.orgPeople[u.id],Object.keys(r.orgPeople).length===0&&delete r.orgPeople),c=`${u.name} removed from the org chart`+(m?`, with ${m} ${m===1?"line":"lines"}`:"")+(f.length?` and out of ${f.join(", ")}`:"");break}case"add-relation":{let u=String(e.type??"").trim(),g=[String(e.from??"").trim(),String(e.to??"").trim()];if(!g[0]||!g[1]||!u)throw new Error("Pick a member, a kind of relation and a target.");if(!Ze.includes(u))throw new Error(`"${u}" is not a kind of relation. Pick reports to, dotted line or acts for.`);let[m,f]=g.map(E);for(let x of[m,f])if(!i.has(x))throw new Error(`${l(x)} is not in the org chart. Add them first.`);if(m===f)throw new Error(`${l(m)} cannot be linked to themself.`);let w={from:m,to:f,type:u};if(s.relations.some(x=>x.from===m&&x.to===f&&x.type===u))throw new Error(`${l(m)} already ${en[u]} ${l(f)}.`);if(u==="acts-for"&&i.get(m).kind!=="agent")throw new Error(`Only an agent can act for someone: ${l(m)} is a person.`);if(u==="acts-for"&&i.get(f).kind!=="person")throw new Error(`An agent acts for a person: ${l(f)} is an agent.`);if(u==="reports-to"){let x=s.relations.find(b=>b.type==="reports-to"&&b.from===m);if(x)throw new Error(`${l(m)} already reports to ${l(x.to)}. Remove that line first: each member has one boss.`);if(Bc(s.relations,f,m))throw new Error(`${l(m)} cannot report to ${l(f)}: ${l(f)} already reports up to ${l(m)}.`)}if(u==="reports-to"&&i.get(m).kind==="agent"){let x=C(f);r.orgChart[C(m).id].reportsTo=x.kind==="agent"?x.id:f}else r.relations=[...r.relations??[],w];c=`${l(m)} ${en[u]} ${l(f)}`;break}case"remove-relation":{let u={from:E(String(e.from??"")),to:E(String(e.to??"")),type:String(e.type??"")};if(!Ts(r,g=>g.from===u.from&&g.to===u.to&&g.type===u.type))throw new Error("That line is not in the org chart any more. Reload the page.");c=`${l(u.from)} no longer ${en[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);if(u.kind!=="agent")throw new Error(`Working hours are for agents: ${u.name} is a person.`);let g=Mc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Fc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=Es(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}var Hc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Rs=class{constructor(e=Hc,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(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},qc="That code didn't work. Check it, or run agentx app pair for a new one.",Vc=400;async function Gm(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await $r(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await Xc(n,e.minMs??Vc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:qc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function Xc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as cd}from"child_process";import{mkdtempSync as nd,rmSync as rd,writeFileSync as od}from"fs";import{tmpdir as sd}from"os";import{join as Os}from"path";import{randomBytes as zc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var B={top:8,side:32,bottom:60},nn={height:56,keep:52},Is=`
613
613
  :root {
614
614
  --ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
615
615
  --ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
@@ -738,16 +738,16 @@ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: v
738
738
  button.primary:disabled { opacity: .55; cursor: not-allowed; }
739
739
  kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
740
740
  button.primary kbd { color: inherit; opacity: .7; }
741
- `;var Is=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Ds=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Yc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Is(n):Ds(n)}`}function Jc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Ds(n)],Is(n)].join(" ")}function Qc(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 Zc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var rn=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>`,ed=rn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),td=rn('<path d="m6 15 6-6 6 6"/>'),nd=rn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Cs(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Gc(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=Hn(t),l=s.map((u,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${R(u)}</span>${g===d.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${R(r)} recommends</span>`:"",p={choices:s,draft:t.draft??"",placeholder:Bn,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=s.length?e.pick-1:d.index};return`<!doctype html>
741
+ `;var Ds=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Cs=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Kc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Ds(n):Cs(n)}`}function Gc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Cs(n)],Ds(n)].join(" ")}function Yc(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 Jc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var rn=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>`,Qc=rn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),Zc=rn('<path d="m6 15 6-6 6 6"/>'),ed=rn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Ns(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=zc(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=Vn(t),l=s.map((u,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${R(u)}</span>${g===d.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${R(r)} recommends</span>`:"",p={choices:s,draft:t.draft??"",placeholder:Hn,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=s.length?e.pick-1:d.index};return`<!doctype html>
742
742
  <html lang="en"><head><meta charset="utf-8">
743
743
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${o}'">
744
744
  <title>AgentX</title>
745
- <style>${Rs}</style></head>
745
+ <style>${Is}</style></head>
746
746
  <body><div class="wrap"><main class="card${e.still?" still":""}">
747
- <div class="head" title="Drag to move"><span class="avatar">${R(Qc(r))}</span>
748
- <div class="who"><b>${R(r)}</b><span>${R(Yc(t.created_at,n))}</span></div>
747
+ <div class="head" title="Drag to move"><span class="avatar">${R(Yc(r))}</span>
748
+ <div class="who"><b>${R(r)}</b><span>${R(Kc(t.created_at,n))}</span></div>
749
749
  <span class="kind${i?"":" decision"}">${i?"Reminder":a?"Request":"Decision"}</span>
750
- <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${td}</button></div>
750
+ <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${Zc}</button></div>
751
751
  <div class="body"><h1 dir="auto">${R(t.title)}</h1>
752
752
  ${t.context?`<p class="context" dir="auto">${R(t.context)}</p>`:""}
753
753
  <p class="ask" dir="auto">${R(t.ask)}</p>
@@ -756,15 +756,15 @@ ${l?`<div class="options" role="radiogroup">${l}</div>`:""}
756
756
  ${d.why?`<p class="why" dir="auto">${R(d.why)}</p>`:""}
757
757
  ${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>
758
758
  <textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
759
- <div class="notes"><div>${ed}<span>${a?`It stays on the ${$e} until you close it.`:`If you don't answer by ${R(Jc(t.expires,n))}: ${R(t.if_silent)}.`}</span></div>
760
- <div>${nd}<span>Nothing goes out until you click.</span></div></div>
759
+ <div class="notes"><div>${Qc}<span>${a?`It stays on the ${Te} until you close it.`:`If you don't answer by ${R(Gc(t.expires,n))}: ${R(t.if_silent)}.`}</span></div>
760
+ <div>${ed}<span>Nothing goes out until you click.</span></div></div>
761
761
  </div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
762
762
  <button class="btn" id="no">${a?"Drop":"No"}</button>
763
- <button class="btn primary" id="yes">${Zc(t)}<kbd>\u2318\u21A9</kbd></button></div>
763
+ <button class="btn primary" id="yes">${Jc(t)}<kbd>\u2318\u21A9</kbd></button></div>
764
764
  </main></div>
765
765
  <script type="application/json" id="data">${JSON.stringify(p).replace(/</g,"\\u003c")}</script>
766
- <script nonce="${o}">${rd}</script>
767
- </body></html>`}var rd=`
766
+ <script nonce="${o}">${td}</script>
767
+ </body></html>`}var td=`
768
768
  (function () {
769
769
  var d = JSON.parse(document.getElementById("data").textContent);
770
770
  var root = document.documentElement;
@@ -853,7 +853,7 @@ ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><sp
853
853
  });
854
854
  } catch (e) {}
855
855
  })();
856
- `;var ld=440,cd=`
856
+ `;var id=440,ad=`
857
857
  ObjC.import("Cocoa"); ObjC.import("WebKit")
858
858
  function run(argv) {
859
859
  var path = argv[0], side = ${B.side}, gripTop = ${B.top}, gripEnd = ${B.top+nn.height}, keep = ${nn.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
@@ -928,29 +928,29 @@ function run(argv) {
928
928
  }
929
929
  function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
930
930
  function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
931
- `;function dd(t,e){let n=t.trim().split(`
932
- `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Ls.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let o=e.choices??[],s;if(o.length){if(typeof r.choice!="string"||!o.includes(r.choice))return{action:"dismiss"};s=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
933
- `).trim():"",!i||i.length>jn.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Os(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=od(Ns(ad(),"agentx-card-"));try{let s=Ns(o,"card.html");id(s,Cs(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",cd,s,String(ld),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?dd(a.stdout,t):null}finally{sd(o,{recursive:!0,force:!0})}}var Ls=["not now","timed out","closed"],pd=(t,e,n)=>new Promise(r=>{try{ud(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Ps=160,on=15e3;function Ms(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Ps?e.slice(0,Ps):e}async function gd(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?Er(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],on),!!e.speak)if(o){let a;await Promise.race([o(Ms(t)),new Promise(d=>{a=setTimeout(d,on)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Ms(t)],on)}}function Ws(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function md(t,e,n){return Ws(["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,o){return Ws(["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(`
934
- `),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function Us(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
931
+ `;function ld(t,e){let n=t.trim().split(`
932
+ `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Ps.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let o=e.choices??[],s;if(o.length){if(typeof r.choice!="string"||!o.includes(r.choice))return{action:"dismiss"};s=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
933
+ `).trim():"",!i||i.length>Bn.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Ls(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=nd(Os(sd(),"agentx-card-"));try{let s=Os(o,"card.html");od(s,Ns(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",ad,s,String(id),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?ld(a.stdout,t):null}finally{rd(o,{recursive:!0,force:!0})}}var Ps=["not now","timed out","closed"],dd=(t,e,n)=>new Promise(r=>{try{cd(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Ms=160,on=15e3;function Fs(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Ms?e.slice(0,Ms):e}async function ud(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?_r(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],on),!!e.speak)if(o){let a;await Promise.race([o(Fs(t)),new Promise(d=>{a=setTimeout(d,on)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Fs(t)],on)}}function js(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function pd(t,e,n){return js(["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 Us(t,e,n,r,o){return js(["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(`
934
+ `),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function Ws(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
935
935
  `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function sn(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
936
936
 
937
- `)}async function js(t,e,n={}){let r=n.run??pd,o=(e.style??"card")==="card",s=gd(t,e,r,o,n.speak).catch(()=>{});if(o){let i=await Os(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 s,fd(t,e,r)}async function fd(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=(r+5)*1e3,s=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let l=await n("/usr/bin/osascript",md(s,sn(t),t.choices),o);if(i=l.stdout.replace(/\n$/,""),!l.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let l=i?`${i}
937
+ `)}async function Bs(t,e,n={}){let r=n.run??dd,o=(e.style??"card")==="card",s=ud(t,e,r,o,n.speak).catch(()=>{});if(o){let i=await Ls(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 s,gd(t,e,r)}async function gd(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=(r+5)*1e3,s=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let l=await n("/usr/bin/osascript",pd(s,sn(t),t.choices),o);if(i=l.stdout.replace(/\n$/,""),!l.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let l=i?`${i}
938
938
 
939
939
  Message (edit it if you like):`:`${sn(t)}
940
940
 
941
- Message (edit it if you like):`,p=await n("/usr/bin/osascript",Fs(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,qn(t.draft,i)),o),u=p.ok?Us(p.stdout):null;if(u?.button==="Send"){let g=u.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return u?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",Fs(s,sn(t),["Not now","No","Yes"],r),o),d=a.ok?Us(a.stdout):null;return d?.button==="Yes"?{action:"yes"}:d?.button==="No"?{action:"no"}:{action:"dismiss"}}var cn=24*36e5,an=!1,hd=10*6e4,Bs=-1/0;function qs(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o,passAt:s,wanted:i=[]}=N(t.root),a=s?Date.parse(s):NaN,d=Z(t.root,"pending").filter(c=>Date.parse(c.expires)>n),l=d.find(c=>i.includes(`card:${c.id}`));if(l)return l;for(let c of d){let p=`card:${c.id}`;if(r[p]||!e(c)||Ir(t.root,c.id,n))continue;let u=o[p];if(u&&Date.parse(u)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>cn&&!(g<=a)))return c}return null}function ln(t){try{return G(t)?.listByState("needs_attention")??[]}catch{return[]}}var Hs=new Map;function bd(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=N(t.root);return e({})?ln(t).find(s=>{let i=`request:${s.id}`,a=o[i];return Hs.get(s.id)===K(s,ot.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=cn})??null:null}function yd(t,e){return{id:t.id,title:K(t,ot.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+cn).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Cf(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(an)return"busy";let o=qs(e,t.reaches)?null:bd(e,t.reaches),s=o?yd(o,e.now??Date.now()):qs(e,t.reaches);if(!s)return"none";let i=(t.focus??gs)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,d=(N(e.root).wanted??[]).includes(a)?null:Vn(s);if(d){if(o)Hs.set(o.id,s.title);else{let l=[...Z(e.root,"pending").map(c=>`card:${c.id}`),...ln(e).map(c=>`request:${c.id}`)];bt(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${d}`),t.returnToAuthor?.(s,Xn(s,d)),"returned"}an=!0;try{let l=[...Z(e.root,"pending").map(w=>`card:${w.id}`),...ln(e).map(w=>`request:${w.id}`)];bt(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),p=!!o&&c-Bs<hd;o&&n.speak&&(Bs=c);let u=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??js)(s,p?{...n,speak:!1}:n,{from:u,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${or(i)} when shown)`),"shown";if(!(o?G(e)?.get(o.id)?.state==="needs_attention":ce(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let f=await yo(e,a,g.action,{by:"operator (popup)",popup:!0,...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(f.ok?`[approvals] popup: ${f.message}`:`[approvals] popup: ${a} not recorded: ${f.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{an=!1}}function Nf(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:")?ce(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(jr(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 wd,mkdirSync as xd,readFileSync as kd,renameSync as vd,writeFileSync as Sd}from"fs";import{dirname as Ed,resolve as _d}from"path";var $d=["all","urgent","off"],Td=24*36e5,Vs=24*36e5,Ad=30*24*36e5,Xs=t=>$d.includes(t);function Mf(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 Ks(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=Td}function zs(t,e,n){return t==="all"||t==="urgent"&&Ks(e,n)}function Gs(t){return _d(t,".agentx","desk-routed.json")}function Rd(t){let e=Gs(t);if(!wd(e))return null;try{let n=JSON.parse(kd(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function dn(t,e){let n=Gs(t);xd(Ed(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Sd(r,JSON.stringify(e,null,2)),vd(r,n)}async function Ff(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),d=Rd(e);if(!d){let p={};for(let u of r.items)p[u.key]={at:a,seen:a};return dn(e,{items:p}),i.primed=!0,i}let l=[],c=[];for(let p of r.items){let u=d.items[p.key];if(u){u.seen=a,u.computerHeld&&n-Date.parse(u.at)>Vs&&delete u.computerHeld,u.computerHeld&&c.push(p);continue}d.items[p.key]={at:a,seen:a};let g=p.askedAt?Date.parse(p.askedAt):n;n-g<=Vs&&l.push(p)}for(let[p,u]of Object.entries(d.items))n-Date.parse(u.seen)>Ad&&delete d.items[p];dn(e,d);for(let p of l)if(zs(o.phone,p,n))try{await t.phone(p,Ks(p,n)),i.phone.push(p.key)}catch(u){s(`[desk] ${p.key}: not sent to the phone: ${u?.message??u}`)}if(t.computer){let p=!1;for(let u of[...c,...l]){let g=d.items[u.key];if(!zs(o.computer,u,n)){g.computerHeld&&(delete g.computerHeld,p=!0);continue}try{let m=await t.computer(u);m&&i.computer.push(u.key),m&&g.computerHeld&&(delete g.computerHeld,p=!0),!m&&!g.computerHeld&&(g.computerHeld=!0,p=!0)}catch(m){s(`[desk] ${u.key}: not shown on this computer: ${m?.message??m}`),g.computerHeld&&(delete g.computerHeld,p=!0)}}p&&dn(e,d)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Uf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
942
- Answer it on the Desk.`}}import{closeSync as ye,createReadStream as Id,fstatSync as Dd,openSync as Cd,realpathSync as Ys}from"fs";import{isAbsolute as Nd,resolve as Js,sep as Qs}from"path";var Vf="/app-files",Od=/^[A-Za-z0-9_.:-]{1,64}$/;function Ld(t,e,n=process.cwd()){if(!e||e.length>W.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 ${dt}/ first`};if(!ue(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Ys(Js(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=Ys(Nd(e)?e:Js(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Qs))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${dt}/ first`};let s=ue(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function Pd(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 Md(t,e,n){return{"Content-Type":t,"Content-Disposition":Pd(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 Fd(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,o;return n[1]?(r=Number(n[1]),o=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),o=e-1),r>o||r>=e?"unsatisfiable":{start:r,end:o}}function Xf(t,e,n,r){let o=(x,b)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(b))};if(t.method!=="GET"&&t.method!=="HEAD")return o(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!Od.test(s))return o(400,{error:"bad agent id"});let a=r.workspaceOf(s);if(!a)return o(404,{error:`no agent "${s}" on this computer`});let d=Ld(a,i,r.cwd);if(!d.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${d.error}`),o(d.status,{error:d.error});let l;try{l=Cd(d.path,"r")}catch{return o(404,{error:"file not found"})}let c;try{let x=Dd(l);if(!x.isFile())return ye(l),o(404,{error:"not a file"});c=x.size}catch{return ye(l),o(404,{error:"file not found"})}if(c>W.bytes)return ye(l),o(413,{error:`the file is larger than ${W.bytes/1024/1024} MB`});let p=d.path.split(Qs).pop()||"file",u=Md(d.mime,p,d.kind),g=Fd(t.headers.range,c);if(g==="unsatisfiable"){ye(l),e.writeHead(416,{...u,"Content-Range":`bytes */${c}`}),e.end();return}let{start:m,end:f}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...u,"Content-Length":String(c?f-m+1:0),...g?{"Content-Range":`bytes ${m}-${f}/${c}`}:{}}),t.method==="HEAD"||c===0){ye(l),e.end();return}let w=Id("",{fd:l,start:m,end:f,autoClose:!0});w.on("error",()=>e.destroy()),e.on("close",()=>w.destroy()),w.pipe(e)}import{spawn as we}from"child_process";import{readFileSync as Ud,writeFileSync as Wd}from"fs";import{tmpdir as jd}from"os";import{join as Bd}from"path";$n();var Zs=t=>t&&t!==1?Math.round(175*t):null,Ge=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function qd(){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=Ud(t,"utf8").trim();if(e)return e}catch{}return null}function th(t=qd()){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 o=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",...Ge(n.voice.rate)?{voice_settings:{speed:Ge(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=Bd(jd(),`agentx-say-${process.pid}-${++e}.mp3`);return Wd(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return Y(`elevenlabs:${String(o?.message??o).slice(0,40)}`,`[voice] ElevenLabs failed (${String(o?.message??o).slice(0,160)}); speaking with the system voice`),null}}}function ei(t,e){let n=t.languages&&_e(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Hd=(t,e="")=>{let n=ei(t,e),r=Zs(t.rate);return[...n&&!Io(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Vd(t,e,n){if(!n)return["say",Hd(t,e)];let r=ei(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function nh(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function rh(t=un()){if(t)try{we("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function oh(t=un()){if(t)try{we("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function un(t={},e){if(!At(t))return null;try{return No(e)}catch(n){return Y("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
943
- `)[0]}); Siri voices will not switch`),null}}var sh=(t,e)=>{if(!t){let[n,r]=Vd(e.voice,e.text,un()),o=Zs(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=we(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?we("afplay",[t],{stdio:"ignore"}):we("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as ti}from"child_process";import{accessSync as Xd,constants as zd,readFileSync as ni}from"fs";import{homedir as Kd}from"os";import{basename as se,delimiter as ri,dirname as Gd,extname as Yd,join as pn}from"path";var z={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function oi(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)>z.ms+2e3?{status:413,error:mn()}:null}var mn=()=>`The recording is longer than ${z.ms/6e4} minutes.`,Jd={"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 si(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Jd[e]??null}function ii(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 fn(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 gn(t,e,n=process.env.PATH??""){let r=Kd(),o=[pn(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(ri).filter(Boolean)];for(let s of[e,...o.map(i=>pn(i,t))])if(s)try{return Xd(s,zd.X_OK),s}catch{}return null}function uh(t){return{key:t,mlx:gn("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:gn("whisper",process.env.AGENTX_WHISPER),ffmpeg:Qd()}}var Qd=()=>gn("ffmpeg",process.env.AGENTX_FFMPEG);async function ai(t,e){return e?Zd(t,e):null}async function Zd(t,e){let n=String(z.ms/1e3+5);try{let o=[...(await eu(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],s=o[o.length-1];return s?Number(s[1])*3600+Number(s[2])*60+Number(s[3]):null}catch{return null}}async function li(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([ni(t)],{type:e}),se(t));let s=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:o,signal:r??AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);let i=await s.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function ci(t,e,n,r,o){let s=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",o,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",o,"--fp16","False"],i={...process.env,PATH:`${Gd(r)}${ri}${process.env.PATH??""}`};await tu(e,s,12e4,i);try{return ni(pn(o,se(n,Yd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function eu(t,e,n){return new Promise((r,o)=>{let s=ti(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${se(t)} took too long`))},n);s.stderr.on("data",d=>{i=(i+d).slice(-8192)}),s.on("error",d=>{clearTimeout(a),o(d)}),s.on("exit",d=>{clearTimeout(a),d===0?r(i):o(new Error(`${se(t)} exited ${d}`))})})}function tu(t,e,n,r=process.env){return new Promise((o,s)=>{let i=ti(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",d="",l=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${se(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{d.length<4096&&(d+=c)}),i.on("error",c=>{clearTimeout(l),s(c)}),i.on("exit",c=>{clearTimeout(l),c===0?o(a):s(new Error(`${se(t)} exited ${c}: ${d.trim().split(`
944
- `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as nu,rm as ru,writeFile as ou}from"fs/promises";import{tmpdir as su}from"os";import{join as di}from"path";vi();var iu=64*1024,au=2,hn=0;function vh(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Sh(t,e,n,r){return t.method!=="POST"?$(e,405,{error:"POST"}):n==="/voice/transcribe"?lu(t,e,r):uu(t,e,r)}async function lu(t,e,n){let r=String(t.headers["content-type"]||""),o=si(r);if(!o)return $(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=oi(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),$(e,s.status,{error:s.error});let i=await ui(t,z.bytes);if(!i)return $(e,413,{error:mu()});if(!i.length)return $(e,400,{error:"The recording is empty."});if(hn>=au)return $(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),d=n.host(),l=ii(a,d);if(!d.ffmpeg&&!n.allowUnmeasured?.()){let p=n.nodeName?`on ${n.nodeName}`:"on this computer",u=l.length?"":" "+fn(a,d);return $(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${p} for voice input from the phone.${u}`,setup:!1})}if(!l.length)return $(e,503,{error:"Voice input isn't set up on this computer.",hint:fn(a,d),setup:!1});hn++;let c;try{let p=await nu(di(su(),"agentx-phone-voice-"));try{c=await cu(p,`speech.${o}`,i,r,d,l,n)}finally{await ru(p,{recursive:!0,force:!0}).catch(()=>{})}}finally{hn--}$(e,c[0],c[1])}async function cu(t,e,n,r,o,s,i){let a=di(t,e);if(await ou(a,n,{mode:384}),o.ffmpeg){let l=await(i.measure??ai)(a,o.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>z.ms+2e3)return[413,{error:mn()}]}let d=[];for(let l of s)try{let c=await du(l,a,r,o,t,i);return i.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(c){let p=String(c?.message??c).split(`
945
- `)[0].slice(0,200);d.push(`${l}: ${p}`),i.log(`[voice] phone transcription with ${l} failed: ${p}`)}return[502,{error:"Speech to text failed on this computer.",detail:d.join("; ")}]}function du(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return li(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return ci(t,a,e,r.ffmpeg,o)}async function uu(t,e,n){let r=await ui(t,iu);if(!r)return $(e,413,{error:"request too large"});let o;try{o=JSON.parse(r.toString("utf8")||"{}")}catch{return $(e,400,{error:"expected JSON"})}let s=typeof o?.agent=="string"?o.agent:"",i=typeof o?.peer=="string"&&o.peer?o.peer:void 0;if(!s)return $(e,400,{error:"agent is required"});let a=pu(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return $(e,422,{error:"Nothing in this answer can be said aloud."});let d=n.pronounce?n.pronounce(a):a,l=n.voiceOf(s,i);if(!l)return $(e,404,{error:`Unknown agent: ${s}`});let c=(u,g=200)=>$(e,g,{fallback:"browser",reason:u,text:d});if(l.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let p=n.elevenLabsKey();if(!p)return c("No ElevenLabs key is set on this computer.");try{let u=await(n.synth??gu)(p,l,d);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":u.length,"Cache-Control":"no-store","X-Spoken-Chars":String(d.length)}),e.end(u)}catch(u){return n.log(`[voice] phone answer synthesis failed: ${String(u?.message??u).split(`
946
- `)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function pu(t,e){let n=Xe(Ae(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Tn(n,e)}async function gu(t,e,n){let r=Ge(e.rate),o=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(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await o.arrayBuffer())}var mu=()=>`The recording is larger than ${z.bytes/1024/1024} MB, more than ${z.ms/6e4} minutes of speech.`;function Eh(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?Ft(Lt(t,o,n.voice)):null}function ui(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let o=[],s=0;t.on("data",i=>{if(!(s>e)){if(s+=i.length,s>e){o.length=0,n(null);return}o.push(i)}}),t.on("end",()=>{s<=e&&n(Buffer.concat(o))}),t.on("error",r)})}function $(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}var fu="[Live voice call on the owner's watch or headset. Your answer is read aloud to them and they can't see a screen. Answer what they just said, in a few short spoken sentences.]",hu="operator",bu=50,pi=4,gi=500;function yu(t){let e={channel:"app",chatId:t.chatId,sender:hu,...t.spoken?{via:"voice"}:{}},n=t.call==="watch"?`${fu}
941
+ Message (edit it if you like):`,p=await n("/usr/bin/osascript",Us(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,qn(t.draft,i)),o),u=p.ok?Ws(p.stdout):null;if(u?.button==="Send"){let g=u.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return u?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",Us(s,sn(t),["Not now","No","Yes"],r),o),d=a.ok?Ws(a.stdout):null;return d?.button==="Yes"?{action:"yes"}:d?.button==="No"?{action:"no"}:{action:"dismiss"}}var cn=24*36e5,an=!1,md=10*6e4,Hs=-1/0;function qs(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o,passAt:s,wanted:i=[]}=N(t.root),a=s?Date.parse(s):NaN,d=Z(t.root,"pending").filter(c=>Date.parse(c.expires)>n),l=d.find(c=>i.includes(`card:${c.id}`));if(l)return l;for(let c of d){let p=`card:${c.id}`;if(r[p]||!e(c)||Dr(t.root,c.id,n))continue;let u=o[p];if(u&&Date.parse(u)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>cn&&!(g<=a)))return c}return null}function ln(t){try{return G(t)?.listByState("needs_attention")??[]}catch{return[]}}var Vs=new Map;function fd(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=N(t.root);return e({})?ln(t).find(s=>{let i=`request:${s.id}`,a=o[i];return Vs.get(s.id)===K(s,ot.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=cn})??null:null}function hd(t,e){return{id:t.id,title:K(t,ot.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+cn).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Af(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(an)return"busy";let o=qs(e,t.reaches)?null:fd(e,t.reaches),s=o?hd(o,e.now??Date.now()):qs(e,t.reaches);if(!s)return"none";let i=(t.focus??ms)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,d=(N(e.root).wanted??[]).includes(a)?null:Xn(s);if(d){if(o)Vs.set(o.id,s.title);else{let l=[...Z(e.root,"pending").map(c=>`card:${c.id}`),...ln(e).map(c=>`request:${c.id}`)];bt(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${d}`),t.returnToAuthor?.(s,zn(s,d)),"returned"}an=!0;try{let l=[...Z(e.root,"pending").map(w=>`card:${w.id}`),...ln(e).map(w=>`request:${w.id}`)];bt(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),p=!!o&&c-Hs<md;o&&n.speak&&(Hs=c);let u=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??Bs)(s,p?{...n,speak:!1}:n,{from:u,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${sr(i)} when shown)`),"shown";if(!(o?G(e)?.get(o.id)?.state==="needs_attention":ce(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let f=await wo(e,a,g.action,{by:"operator (popup)",popup:!0,...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(f.ok?`[approvals] popup: ${f.message}`:`[approvals] popup: ${a} not recorded: ${f.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{an=!1}}function Rf(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:")?ce(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Br(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 bd,mkdirSync as yd,readFileSync as wd,renameSync as xd,writeFileSync as kd}from"fs";import{dirname as vd,resolve as Sd}from"path";var Ed=["all","urgent","off"],_d=24*36e5,Xs=24*36e5,$d=30*24*36e5,zs=t=>Ed.includes(t);function Nf(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:zs(e)?e:"off",computer:zs(n)?n:t.popupEnabled?"all":"off"}}function Gs(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=_d}function Ks(t,e,n){return t==="all"||t==="urgent"&&Gs(e,n)}function Ys(t){return Sd(t,".agentx","desk-routed.json")}function Td(t){let e=Ys(t);if(!bd(e))return null;try{let n=JSON.parse(wd(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function dn(t,e){let n=Ys(t);yd(vd(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;kd(r,JSON.stringify(e,null,2)),xd(r,n)}async function Of(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),d=Td(e);if(!d){let p={};for(let u of r.items)p[u.key]={at:a,seen:a};return dn(e,{items:p}),i.primed=!0,i}let l=[],c=[];for(let p of r.items){let u=d.items[p.key];if(u){u.seen=a,u.computerHeld&&n-Date.parse(u.at)>Xs&&delete u.computerHeld,u.computerHeld&&c.push(p);continue}d.items[p.key]={at:a,seen:a};let g=p.askedAt?Date.parse(p.askedAt):n;n-g<=Xs&&l.push(p)}for(let[p,u]of Object.entries(d.items))n-Date.parse(u.seen)>$d&&delete d.items[p];dn(e,d);for(let p of l)if(Ks(o.phone,p,n))try{await t.phone(p,Gs(p,n)),i.phone.push(p.key)}catch(u){s(`[desk] ${p.key}: not sent to the phone: ${u?.message??u}`)}if(t.computer){let p=!1;for(let u of[...c,...l]){let g=d.items[u.key];if(!Ks(o.computer,u,n)){g.computerHeld&&(delete g.computerHeld,p=!0);continue}try{let m=await t.computer(u);m&&i.computer.push(u.key),m&&g.computerHeld&&(delete g.computerHeld,p=!0),!m&&!g.computerHeld&&(g.computerHeld=!0,p=!0)}catch(m){s(`[desk] ${u.key}: not shown on this computer: ${m?.message??m}`),g.computerHeld&&(delete g.computerHeld,p=!0)}}p&&dn(e,d)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Lf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
942
+ Answer it on the Desk.`}}import{closeSync as ye,createReadStream as Ad,fstatSync as Rd,openSync as Id,realpathSync as Js}from"fs";import{isAbsolute as Dd,resolve as Qs,sep as Zs}from"path";var jf="/app-files",Cd=/^[A-Za-z0-9_.:-]{1,64}$/;function Nd(t,e,n=process.cwd()){if(!e||e.length>W.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 ${dt}/ first`};if(!ue(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Js(Qs(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=Js(Dd(e)?e:Qs(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Zs))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${dt}/ first`};let s=ue(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function Od(t,e){let n=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\;]/g,"_").slice(0,120)||"file";return`${e==="file"?"attachment":"inline"}; filename="${n}"; filename*=UTF-8''${encodeURIComponent(t.slice(0,120))}`}function Ld(t,e,n){return{"Content-Type":t,"Content-Disposition":Od(e,n),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; img-src 'self'; media-src 'self'; sandbox","Cache-Control":"private, max-age=3600","Accept-Ranges":"bytes"}}function Pd(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,o;return n[1]?(r=Number(n[1]),o=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),o=e-1),r>o||r>=e?"unsatisfiable":{start:r,end:o}}function Bf(t,e,n,r){let o=(x,b)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(b))};if(t.method!=="GET"&&t.method!=="HEAD")return o(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!Cd.test(s))return o(400,{error:"bad agent id"});let a=r.workspaceOf(s);if(!a)return o(404,{error:`no agent "${s}" on this computer`});let d=Nd(a,i,r.cwd);if(!d.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${d.error}`),o(d.status,{error:d.error});let l;try{l=Id(d.path,"r")}catch{return o(404,{error:"file not found"})}let c;try{let x=Rd(l);if(!x.isFile())return ye(l),o(404,{error:"not a file"});c=x.size}catch{return ye(l),o(404,{error:"file not found"})}if(c>W.bytes)return ye(l),o(413,{error:`the file is larger than ${W.bytes/1024/1024} MB`});let p=d.path.split(Zs).pop()||"file",u=Ld(d.mime,p,d.kind),g=Pd(t.headers.range,c);if(g==="unsatisfiable"){ye(l),e.writeHead(416,{...u,"Content-Range":`bytes */${c}`}),e.end();return}let{start:m,end:f}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...u,"Content-Length":String(c?f-m+1:0),...g?{"Content-Range":`bytes ${m}-${f}/${c}`}:{}}),t.method==="HEAD"||c===0){ye(l),e.end();return}let w=Ad("",{fd:l,start:m,end:f,autoClose:!0});w.on("error",()=>e.destroy()),e.on("close",()=>w.destroy()),w.pipe(e)}import{spawn as we}from"child_process";import{readFileSync as Md,writeFileSync as Fd}from"fs";import{tmpdir as Ud}from"os";import{join as Wd}from"path";$n();var ei=t=>t&&t!==1?Math.round(175*t):null,Ge=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function jd(){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=Md(t,"utf8").trim();if(e)return e}catch{}return null}function Jf(t=jd()){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 o=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",...Ge(n.voice.rate)?{voice_settings:{speed:Ge(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=Wd(Ud(),`agentx-say-${process.pid}-${++e}.mp3`);return Fd(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return Y(`elevenlabs:${String(o?.message??o).slice(0,40)}`,`[voice] ElevenLabs failed (${String(o?.message??o).slice(0,160)}); speaking with the system voice`),null}}}function ti(t,e){let n=t.languages&&_e(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Bd=(t,e="")=>{let n=ti(t,e),r=ei(t.rate);return[...n&&!Do(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Hd(t,e,n){if(!n)return["say",Bd(t,e)];let r=ti(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function Qf(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function Zf(t=un()){if(t)try{we("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function eh(t=un()){if(t)try{we("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function un(t={},e){if(!At(t))return null;try{return Oo(e)}catch(n){return Y("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
943
+ `)[0]}); Siri voices will not switch`),null}}var th=(t,e)=>{if(!t){let[n,r]=Hd(e.voice,e.text,un()),o=ei(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=we(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?we("afplay",[t],{stdio:"ignore"}):we("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as ni}from"child_process";import{accessSync as qd,constants as Vd,readFileSync as ri}from"fs";import{homedir as Xd}from"os";import{basename as se,delimiter as oi,dirname as zd,extname as Kd,join as pn}from"path";var z={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function si(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)>z.ms+2e3?{status:413,error:mn()}:null}var mn=()=>`The recording is longer than ${z.ms/6e4} minutes.`,Gd={"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 ii(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Gd[e]??null}function ai(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 fn(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 gn(t,e,n=process.env.PATH??""){let r=Xd(),o=[pn(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(oi).filter(Boolean)];for(let s of[e,...o.map(i=>pn(i,t))])if(s)try{return qd(s,Vd.X_OK),s}catch{}return null}function ah(t){return{key:t,mlx:gn("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:gn("whisper",process.env.AGENTX_WHISPER),ffmpeg:Yd()}}var Yd=()=>gn("ffmpeg",process.env.AGENTX_FFMPEG);async function li(t,e){return e?Jd(t,e):null}async function Jd(t,e){let n=String(z.ms/1e3+5);try{let o=[...(await Qd(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],s=o[o.length-1];return s?Number(s[1])*3600+Number(s[2])*60+Number(s[3]):null}catch{return null}}async function ci(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([ri(t)],{type:e}),se(t));let s=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:o,signal:r??AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);let i=await s.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function di(t,e,n,r,o){let s=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",o,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",o,"--fp16","False"],i={...process.env,PATH:`${zd(r)}${oi}${process.env.PATH??""}`};await Zd(e,s,12e4,i);try{return ri(pn(o,se(n,Kd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Qd(t,e,n){return new Promise((r,o)=>{let s=ni(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${se(t)} took too long`))},n);s.stderr.on("data",d=>{i=(i+d).slice(-8192)}),s.on("error",d=>{clearTimeout(a),o(d)}),s.on("exit",d=>{clearTimeout(a),d===0?r(i):o(new Error(`${se(t)} exited ${d}`))})})}function Zd(t,e,n,r=process.env){return new Promise((o,s)=>{let i=ni(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",d="",l=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${se(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{d.length<4096&&(d+=c)}),i.on("error",c=>{clearTimeout(l),s(c)}),i.on("exit",c=>{clearTimeout(l),c===0?o(a):s(new Error(`${se(t)} exited ${c}: ${d.trim().split(`
944
+ `).pop()?.slice(0,160)??""}`))})})}An();Si();import{mkdtemp as eu,rm as tu,writeFile as nu}from"fs/promises";import{tmpdir as ru}from"os";import{join as ui}from"path";var ou=64*1024,su=2,hn=0;function yh(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function wh(t,e,n,r){return t.method!=="POST"?$(e,405,{error:"POST"}):n==="/voice/transcribe"?iu(t,e,r):cu(t,e,r)}async function iu(t,e,n){let r=String(t.headers["content-type"]||""),o=ii(r);if(!o)return $(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=si(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),$(e,s.status,{error:s.error});let i=await pi(t,z.bytes);if(!i)return $(e,413,{error:pu()});if(!i.length)return $(e,400,{error:"The recording is empty."});if(hn>=su)return $(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),d=n.host(),l=ai(a,d);if(!d.ffmpeg&&!n.allowUnmeasured?.()){let p=n.nodeName?`on ${n.nodeName}`:"on this computer",u=l.length?"":" "+fn(a,d);return $(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${p} for voice input from the phone.${u}`,setup:!1})}if(!l.length)return $(e,503,{error:"Voice input isn't set up on this computer.",hint:fn(a,d),setup:!1});hn++;let c;try{let p=await eu(ui(ru(),"agentx-phone-voice-"));try{c=await au(p,`speech.${o}`,i,r,d,l,n)}finally{await tu(p,{recursive:!0,force:!0}).catch(()=>{})}}finally{hn--}$(e,c[0],c[1])}async function au(t,e,n,r,o,s,i){let a=ui(t,e);if(await nu(a,n,{mode:384}),o.ffmpeg){let l=await(i.measure??li)(a,o.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>z.ms+2e3)return[413,{error:mn()}]}let d=[];for(let l of s)try{let c=await lu(l,a,r,o,t,i);return i.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(c){let p=String(c?.message??c).split(`
945
+ `)[0].slice(0,200);d.push(`${l}: ${p}`),i.log(`[voice] phone transcription with ${l} failed: ${p}`)}return[502,{error:"Speech to text failed on this computer.",detail:d.join("; ")}]}function lu(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return ci(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return di(t,a,e,r.ffmpeg,o)}async function cu(t,e,n){let r=await pi(t,ou);if(!r)return $(e,413,{error:"request too large"});let o;try{o=JSON.parse(r.toString("utf8")||"{}")}catch{return $(e,400,{error:"expected JSON"})}let s=typeof o?.agent=="string"?o.agent:"",i=typeof o?.peer=="string"&&o.peer?o.peer:void 0;if(!s)return $(e,400,{error:"agent is required"});let a=du(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return $(e,422,{error:"Nothing in this answer can be said aloud."});let d=n.pronounce?n.pronounce(a):a,l=n.voiceOf(s,i);if(!l)return $(e,404,{error:`Unknown agent: ${s}`});let c=(u,g=200)=>$(e,g,{fallback:"browser",reason:u,text:d});if(l.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let p=n.elevenLabsKey();if(!p)return c("No ElevenLabs key is set on this computer.");try{let u=await(n.synth??uu)(p,l,d);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":u.length,"Cache-Control":"no-store","X-Spoken-Chars":String(d.length)}),e.end(u)}catch(u){return n.log(`[voice] phone answer synthesis failed: ${String(u?.message??u).split(`
946
+ `)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function du(t,e){let n=$e(Re(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Tn(n,e)}async function uu(t,e,n){let r=Ge(e.rate),o=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(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await o.arrayBuffer())}var pu=()=>`The recording is larger than ${z.bytes/1024/1024} MB, more than ${z.ms/6e4} minutes of speech.`;function xh(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?Ft(Lt(t,o,n.voice)):null}function pi(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let o=[],s=0;t.on("data",i=>{if(!(s>e)){if(s+=i.length,s>e){o.length=0,n(null);return}o.push(i)}}),t.on("end",()=>{s<=e&&n(Buffer.concat(o))}),t.on("error",r)})}function $(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}An();var gu="[Live voice call on the owner's watch or headset. Your answer is read aloud to them and they can't see a screen. Answer what they just said, in a few short spoken sentences.]",mu="operator",fu=50,gi=4,mi=500;function hu(t){let e={channel:"app",chatId:t.chatId,sender:mu,...t.spoken?{via:"voice"}:{}},n=t.call==="watch"?`${gu}
947
947
 
948
- ${t.message}`:t.message;return t.node==="local"?{path:"/task",body:{agent:t.agent,message:n,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:n,stream:!0,context:e}}}async function Rh(t,e,n,r){let{path:o,body:s}=yu(e),i="",a=!1,d=[],l=new Map,c=(p,u,g)=>{let m=p!=="done",f=a?{text:er(u,m),artifacts:[]}:Ae(u,W.perMessage,m),{cleanText:w,ui:x}=p==="done"?Xe(f.text):{cleanText:f.text,ui:void 0},b=a?void 0:xu(x);return{status:p,text:w,tools:d,files:f.artifacts,...b?{ui:b}:{},...g?{error:g}:{}}};try{let p=await fetch(t.url.replace(/\/+$/,"")+o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(s),signal:n});if(!p.ok||!p.body){let u=await p.json().then(g=>g?.error).catch(()=>"");return c("error",i,u||`AgentX answered HTTP ${p.status}.`)}for await(let u of ku(p.body)){r(u.event,u.data);let g=u.data??{};if(u.event==="start")a=g.rich===!1;else if(u.event==="text"&&typeof g.text=="string")i+=g.text;else if(u.event==="tool"&&g.status==="start"&&d.length<bu){let m={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};d.push(m),g.id&&l.set(String(g.id),m)}else if(u.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(u.event==="done")return c("done",typeof g.content=="string"&&g.content?g.content:i);if(u.event==="error")return c("error",i,wu(g.error))}}return n.aborted?c("stopped",i):c("error",i,"The connection to the agent closed before it answered.")}catch(p){return n.aborted?c("stopped",i):c("error",i,`Could not reach AgentX: ${p?.message||p}`)}}function wu(t){let e=String(t||"The agent could not answer.");return Gn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function xu(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let o=(t.quickReplies??[]).slice(0,pi).map(i=>i.slice(0,gi));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,pi).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,gi)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*ku(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=n.decode(s,{stream:!0}).replace(/\r\n/g,`
948
+ ${t.message}`:t.message;return t.node==="local"?{path:"/task",body:{agent:t.agent,message:n,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:n,stream:!0,context:e}}}async function _h(t,e,n,r){let{path:o,body:s}=hu(e),i="",a=!1,d=[],l=new Map,c=(p,u,g)=>{let m=p!=="done",f=a?{text:tr(u,m),artifacts:[]}:Re(u,W.perMessage,m),{cleanText:w,ui:x}=p==="done"?$e(f.text):{cleanText:f.text,ui:void 0},b=a?void 0:yu(x);return{status:p,text:w,tools:d,files:f.artifacts,...b?{ui:b}:{},...g?{error:g}:{}}};try{let p=await fetch(t.url.replace(/\/+$/,"")+o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(s),signal:n});if(!p.ok||!p.body){let u=await p.json().then(g=>g?.error).catch(()=>"");return c("error",i,u||`AgentX answered HTTP ${p.status}.`)}for await(let u of wu(p.body)){r(u.event,u.data);let g=u.data??{};if(u.event==="start")a=g.rich===!1;else if(u.event==="text"&&typeof g.text=="string")i+=g.text;else if(u.event==="tool"&&g.status==="start"&&d.length<fu){let m={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};d.push(m),g.id&&l.set(String(g.id),m)}else if(u.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(u.event==="done")return c("done",typeof g.content=="string"&&g.content?g.content:i);if(u.event==="error")return c("error",i,bu(g.error))}}return n.aborted?c("stopped",i):c("error",i,"The connection to the agent closed before it answered.")}catch(p){return n.aborted?c("stopped",i):c("error",i,`Could not reach AgentX: ${p?.message||p}`)}}function bu(t){let e=String(t||"The agent could not answer.");return Yn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function yu(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let o=(t.quickReplies??[]).slice(0,gi).map(i=>i.slice(0,mi));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,gi).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,mi)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*wu(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=n.decode(s,{stream:!0}).replace(/\r\n/g,`
949
949
  `);let i;for(;(i=r.indexOf(`
950
950
 
951
951
  `))!==-1;){let a=r.slice(0,i);r=r.slice(i+2);let d="message",l=[];for(let c of a.split(`
952
952
  `))c.startsWith("event:")?d=c.slice(6).trim():c.startsWith("data:")&&l.push(c.slice(5).replace(/^ /,""));if(l.length)try{yield{event:d,data:JSON.parse(l.join(`
953
- `))}}catch{}}}}finally{e.releaseLock()}}var mi=["custom","announce"];function Dh(t,e){let n=t.nodeName,r=t.recent().filter(s=>mi.includes(s.kind)).slice(-500),o=(e?.list()??[]).slice(-500).map(s=>({...s,node:n}));return{node:n,events:r,wakes:o}}function Ch(t,e={}){let n=e.now??Date.now(),r=Math.max(1,Math.min(200,Math.floor(e.limit||50))),o=new Map;for(let b of t)for(let y of b.events)mi.includes(y.kind)&&!o.has(y.id)&&o.set(y.id,y);let s=[...o.values()].sort((b,y)=>Date.parse(b.at)-Date.parse(y.at)||b.id.localeCompare(y.id)),i=new Map,a=new Map,d=new Set;for(let b of t)for(let y of b.wakes){let k=y.node||b.node,D=`${k}#${y.agentId}#${y.eventId}`;if(d.has(D))continue;d.add(D);let ae=i.get(y.eventId)??[];if(ae.push(Su(y,k,n)),i.set(y.eventId,ae),y.status!=="skipped"){let ve=`${y.agentId}#${y.rootId}`,h=a.get(ve)??[];h.push({eventId:y.eventId,at:y.decidedAt}),a.set(ve,h)}}for(let b of i.values())b.sort((y,k)=>y.decidedAt-k.decidedAt||y.agentId.localeCompare(k.agentId));let l=new Map,c=[];for(let b of s){let y=vu(b,o,a,c);y&&y!==b.id&&l.set(b.id,y),c.push(b)}let p=b=>{let y=b;for(let k=0;k<50;k++){let D=l.get(y);if(!D)return y;y=D}return y},u=new Map,g=b=>({event:b,wakes:i.get(b.id)??[]});for(let b of s){let y=p(b.id);y===b.id?u.set(b.id,{...g(b),replies:[]}):u.get(y)?.replies.push(g(b))}let m=b=>Math.max(Date.parse(b.event.at),...b.replies.map(y=>Date.parse(y.event.at))),f=[...u.values()].sort((b,y)=>m(y)-m(b)),w=[...i.values()].flat(),x=b=>w.filter(y=>b.includes(y.status)).length;return{threads:f.slice(0,r),total:f.length,counts:{events:s.length,wakes:w.length,ran:x(["ran"]),waiting:x(["waiting","held","running"]),timedOut:x(["timed-out","dropped"]),failed:x(["failed"]),skipped:x(["skipped"])}}}function vu(t,e,n,r){if(t.parentId&&e.has(t.parentId))return t.parentId;let o=Date.parse(t.at);if(t.agentId){let s=(n.get(`${t.agentId}#${t.rootId}`)??[]).filter(i=>i.eventId!==t.id&&e.has(i.eventId)&&Date.parse(e.get(i.eventId).at)<=o).sort((i,a)=>a.at-i.at)[0];if(s)return s.eventId}if(t.rootId!==t.id)for(let s=r.length-1;s>=0;s--){let i=r[s];if(i.rootId===t.rootId&&(i.agentId??i.node)!==(t.agentId??t.node))return i.id}}function Su(t,e,n){let r={agentId:t.agentId,node:e,status:t.status,decidedAt:t.decidedAt,attempts:t.attempts};if(t.reason&&(r.reason=t.reason),t.startedAt&&(r.startedAt=t.startedAt),t.endedAt&&(r.endedAt=t.endedAt),t.taskId&&(r.taskId=t.taskId),t.error&&(r.error=t.error),t.status!=="skipped"){let o=t.startedAt??t.endedAt??n;r.waitedMs=Math.max(0,o-t.decidedAt)}return r}import{existsSync as M,readFileSync as xn,writeFileSync as kn,mkdirSync as Ye,readdirSync as wn,rmSync as Eu,statSync as U}from"fs";import{resolve as fi,relative as _u,dirname as vn,join as Q,extname as xe,basename as Sn}from"path";var I=200*1024,hi=new Set([".md",".markdown",".txt"]),ie=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"]),$u=6,Tu=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function q(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=fi(t);if(M(n)||Ye(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=fi(n,e);if(_u(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function bi(t){let e=xe(t).toLowerCase();if(!hi.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function bn(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Ph(t){let e=q(t,"."),n=[],r=new Set,o=[];try{o=wn(e)}catch{}for(let a of Tu){let d=Q(e,a);if(M(d)&&U(d).isFile()){let l=U(d).size,c=l>0&&l<I?yn(d):"";n.push({path:a,title:bn(c,a),size:l,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of o){if(r.has(a))continue;let d=Q(e,a);try{let l=U(d);if(!l.isFile()||!hi.has(xe(a).toLowerCase()))continue;let c=l.size>0&&l.size<I?yn(d):"";n.push({path:a,title:bn(c,a),size:l.size,exists:!0})}catch{}}let s=[],i=Q(e,".claude","skills");if(M(i))try{for(let a of wn(i)){let d=Q(i,a),l;try{l=U(d)}catch{continue}if(!l.isDirectory())continue;let c=Q(d,"SKILL.md");if(!M(c))continue;let p=U(c),u=p.size<I?yn(c):"";s.push({slug:a,title:bn(u,a),size:p.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return s.sort((a,d)=>a.slug.localeCompare(d.slug)),{identity:n,skills:s,workspace:e}}function yn(t){try{return xn(t,"utf-8")}catch{return""}}function Mh(t,e){let n=q(t,e);if(bi(n),!M(n))return{path:e,content:""};if(U(n).size>I)throw new Error(`File is too large to edit in the admin panel (> ${I/1024} KB).`);return{path:e,content:xn(n,"utf-8")}}function Fh(t,e,n){let r=q(t,e);bi(r);let o=Buffer.from(n,"utf-8");if(o.length>I)throw new Error(`File too large (${o.length} > ${I} bytes).`);return Ye(vn(r),{recursive:!0}),kn(r,o),{path:e,bytes:o.length}}function Uh(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`,o=q(t,r);if(M(o))throw new Error(`Skill "${e}" already exists.`);Ye(vn(o),{recursive:!0});let s=n.content?.trim()?n.content:Au(e,n.title);return kn(o,s),{slug:e,path:r}}function Wh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=q(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);if(!U(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return Eu(n,{recursive:!0,force:!0}),{slug:e}}function jh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=q(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=[];return o(n,"",0,r),r.sort((s,i)=>s.kind!==i.kind?s.kind==="dir"?-1:1:s.path.localeCompare(i.path)),r;function o(s,i,a,d){if(a>$u)return;let l=[];try{l=wn(s)}catch{return}for(let c of l){if(c==="node_modules"||c===".git")continue;let p=Q(s,c),u=i?`${i}/${c}`:c,g;try{g=U(p)}catch{continue}if(g.isDirectory())d.push({path:`${u}/`,kind:"dir",size:0,editable:!1}),o(p,u,a+1,d);else if(g.isFile()){let m=xe(c).toLowerCase(),f=ie.has(m)||ie.has(c.toLowerCase());d.push({path:u,kind:"file",size:g.size,editable:f&&g.size<I})}}}}function Bh(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=q(t,`.claude/skills/${e}/${n}`);if(!M(r)||!U(r).isFile())throw new Error(`File not found: ${n}`);let o=xe(r).toLowerCase(),s=Sn(r).toLowerCase();if(!ie.has(o)&&!ie.has(s))throw new Error(`File type not editable: ${n}`);if(U(r).size>I)throw new Error(`File too large to edit (> ${I/1024} KB): ${n}`);return{path:n,content:xn(r,"utf-8")}}function qh(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 o=q(t,`.claude/skills/${e}/${n}`),s=xe(o).toLowerCase(),i=Sn(o).toLowerCase();if(!ie.has(s)&&!ie.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>I)throw new Error(`File too large (${a.length} > ${I} bytes).`);return Ye(vn(o),{recursive:!0}),kn(o,a),{path:n,bytes:a.length}}function Hh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=q(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=o=>M(Q(n,o));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 Au(t,e){return`# ${e?.trim()||t}
953
+ `))}}catch{}}}}finally{e.releaseLock()}}var fi=["custom","announce"];function Th(t,e){let n=t.nodeName,r=t.recent().filter(s=>fi.includes(s.kind)).slice(-500),o=(e?.list()??[]).slice(-500).map(s=>({...s,node:n}));return{node:n,events:r,wakes:o}}function Ah(t,e={}){let n=e.now??Date.now(),r=Math.max(1,Math.min(200,Math.floor(e.limit||50))),o=new Map;for(let b of t)for(let y of b.events)fi.includes(y.kind)&&!o.has(y.id)&&o.set(y.id,y);let s=[...o.values()].sort((b,y)=>Date.parse(b.at)-Date.parse(y.at)||b.id.localeCompare(y.id)),i=new Map,a=new Map,d=new Set;for(let b of t)for(let y of b.wakes){let k=y.node||b.node,D=`${k}#${y.agentId}#${y.eventId}`;if(d.has(D))continue;d.add(D);let ae=i.get(y.eventId)??[];if(ae.push(ku(y,k,n)),i.set(y.eventId,ae),y.status!=="skipped"){let ve=`${y.agentId}#${y.rootId}`,h=a.get(ve)??[];h.push({eventId:y.eventId,at:y.decidedAt}),a.set(ve,h)}}for(let b of i.values())b.sort((y,k)=>y.decidedAt-k.decidedAt||y.agentId.localeCompare(k.agentId));let l=new Map,c=[];for(let b of s){let y=xu(b,o,a,c);y&&y!==b.id&&l.set(b.id,y),c.push(b)}let p=b=>{let y=b;for(let k=0;k<50;k++){let D=l.get(y);if(!D)return y;y=D}return y},u=new Map,g=b=>({event:b,wakes:i.get(b.id)??[]});for(let b of s){let y=p(b.id);y===b.id?u.set(b.id,{...g(b),replies:[]}):u.get(y)?.replies.push(g(b))}let m=b=>Math.max(Date.parse(b.event.at),...b.replies.map(y=>Date.parse(y.event.at))),f=[...u.values()].sort((b,y)=>m(y)-m(b)),w=[...i.values()].flat(),x=b=>w.filter(y=>b.includes(y.status)).length;return{threads:f.slice(0,r),total:f.length,counts:{events:s.length,wakes:w.length,ran:x(["ran"]),waiting:x(["waiting","held","running"]),timedOut:x(["timed-out","dropped"]),failed:x(["failed"]),skipped:x(["skipped"])}}}function xu(t,e,n,r){if(t.parentId&&e.has(t.parentId))return t.parentId;let o=Date.parse(t.at);if(t.agentId){let s=(n.get(`${t.agentId}#${t.rootId}`)??[]).filter(i=>i.eventId!==t.id&&e.has(i.eventId)&&Date.parse(e.get(i.eventId).at)<=o).sort((i,a)=>a.at-i.at)[0];if(s)return s.eventId}if(t.rootId!==t.id)for(let s=r.length-1;s>=0;s--){let i=r[s];if(i.rootId===t.rootId&&(i.agentId??i.node)!==(t.agentId??t.node))return i.id}}function ku(t,e,n){let r={agentId:t.agentId,node:e,status:t.status,decidedAt:t.decidedAt,attempts:t.attempts};if(t.reason&&(r.reason=t.reason),t.startedAt&&(r.startedAt=t.startedAt),t.endedAt&&(r.endedAt=t.endedAt),t.taskId&&(r.taskId=t.taskId),t.error&&(r.error=t.error),t.status!=="skipped"){let o=t.startedAt??t.endedAt??n;r.waitedMs=Math.max(0,o-t.decidedAt)}return r}import{existsSync as M,readFileSync as xn,writeFileSync as kn,mkdirSync as Ye,readdirSync as wn,rmSync as vu,statSync as U}from"fs";import{resolve as hi,relative as Su,dirname as vn,join as Q,extname as xe,basename as Sn}from"path";var I=200*1024,bi=new Set([".md",".markdown",".txt"]),ie=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"]),Eu=6,_u=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function H(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=hi(t);if(M(n)||Ye(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=hi(n,e);if(Su(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function yi(t){let e=xe(t).toLowerCase();if(!bi.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function bn(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Ch(t){let e=H(t,"."),n=[],r=new Set,o=[];try{o=wn(e)}catch{}for(let a of _u){let d=Q(e,a);if(M(d)&&U(d).isFile()){let l=U(d).size,c=l>0&&l<I?yn(d):"";n.push({path:a,title:bn(c,a),size:l,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of o){if(r.has(a))continue;let d=Q(e,a);try{let l=U(d);if(!l.isFile()||!bi.has(xe(a).toLowerCase()))continue;let c=l.size>0&&l.size<I?yn(d):"";n.push({path:a,title:bn(c,a),size:l.size,exists:!0})}catch{}}let s=[],i=Q(e,".claude","skills");if(M(i))try{for(let a of wn(i)){let d=Q(i,a),l;try{l=U(d)}catch{continue}if(!l.isDirectory())continue;let c=Q(d,"SKILL.md");if(!M(c))continue;let p=U(c),u=p.size<I?yn(c):"";s.push({slug:a,title:bn(u,a),size:p.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return s.sort((a,d)=>a.slug.localeCompare(d.slug)),{identity:n,skills:s,workspace:e}}function yn(t){try{return xn(t,"utf-8")}catch{return""}}function Nh(t,e){let n=H(t,e);if(yi(n),!M(n))return{path:e,content:""};if(U(n).size>I)throw new Error(`File is too large to edit in the admin panel (> ${I/1024} KB).`);return{path:e,content:xn(n,"utf-8")}}function Oh(t,e,n){let r=H(t,e);yi(r);let o=Buffer.from(n,"utf-8");if(o.length>I)throw new Error(`File too large (${o.length} > ${I} bytes).`);return Ye(vn(r),{recursive:!0}),kn(r,o),{path:e,bytes:o.length}}function Lh(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`,o=H(t,r);if(M(o))throw new Error(`Skill "${e}" already exists.`);Ye(vn(o),{recursive:!0});let s=n.content?.trim()?n.content:$u(e,n.title);return kn(o,s),{slug:e,path:r}}function Ph(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=H(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);if(!U(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return vu(n,{recursive:!0,force:!0}),{slug:e}}function Mh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=H(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=[];return o(n,"",0,r),r.sort((s,i)=>s.kind!==i.kind?s.kind==="dir"?-1:1:s.path.localeCompare(i.path)),r;function o(s,i,a,d){if(a>Eu)return;let l=[];try{l=wn(s)}catch{return}for(let c of l){if(c==="node_modules"||c===".git")continue;let p=Q(s,c),u=i?`${i}/${c}`:c,g;try{g=U(p)}catch{continue}if(g.isDirectory())d.push({path:`${u}/`,kind:"dir",size:0,editable:!1}),o(p,u,a+1,d);else if(g.isFile()){let m=xe(c).toLowerCase(),f=ie.has(m)||ie.has(c.toLowerCase());d.push({path:u,kind:"file",size:g.size,editable:f&&g.size<I})}}}}function Fh(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=H(t,`.claude/skills/${e}/${n}`);if(!M(r)||!U(r).isFile())throw new Error(`File not found: ${n}`);let o=xe(r).toLowerCase(),s=Sn(r).toLowerCase();if(!ie.has(o)&&!ie.has(s))throw new Error(`File type not editable: ${n}`);if(U(r).size>I)throw new Error(`File too large to edit (> ${I/1024} KB): ${n}`);return{path:n,content:xn(r,"utf-8")}}function Uh(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 o=H(t,`.claude/skills/${e}/${n}`),s=xe(o).toLowerCase(),i=Sn(o).toLowerCase();if(!ie.has(s)&&!ie.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>I)throw new Error(`File too large (${a.length} > ${I} bytes).`);return Ye(vn(o),{recursive:!0}),kn(o,a),{path:n,bytes:a.length}}function Wh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=H(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=o=>M(Q(n,o));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 $u(t,e){return`# ${e?.trim()||t}
954
954
 
955
955
  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.
956
956
 
@@ -965,5 +965,5 @@ Document the arguments, commands, or files the skill expects. Example:
965
965
  # Example invocation
966
966
  claude-code ${Sn(t)} --arg value
967
967
  \`\`\`
968
- `}Mn();var yi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function wi(t){return{...yi,...t??{},regions:{...t?.regions??{}},buffer:{...yi.buffer,...t?.buffer??{}}}}function zh(t){try{return wi(Pn(t).screen)}catch{return wi(void 0)}}var Ru=/^[a-z][\w-]*$/,xi=["window","screen","menubar","notifications"];function ke(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var Je=(t,e)=>ke(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function ki(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 Kh(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Je(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Je(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Je(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ke(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ke(e.changeThreshold,"changeThreshold",o=>o>=0&&o<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let o={...n.regions??{}};for(let[s,i]of Object.entries(e.regions)){if(!Ru.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=ki(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=ke(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ke(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Je(o.maxPixels,"buffer.maxPixels")),"region"in o&&(s.region=String(o.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!xi.includes(r)&&!n.regions?.[r])try{ki(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...xi,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Dr as a,Cu as b,Yt as c,sc as d,ic as e,mm as f,fm as g,hm as h,wm as i,xm as j,km as k,ls as l,cs as m,vm as n,Xe as o,Em as p,$m as q,X as r,ds as s,A as t,Pu as u,gs as v,Cm as w,Lm as x,fs as y,Pm as z,hs as A,Mm as B,he as C,Nc as D,Fm as E,Um as F,ys as G,Ju as H,Zi as I,rp as J,Yr as K,N as L,ju as M,Bu as N,pp as O,Ne as P,gp as Q,Br as R,Ku as S,G as T,jp as U,fo as V,yo as W,Mc as X,jm as Y,Fc as Z,Bm as _,qm as $,Qt as aa,xs as ba,Xm as ca,en as da,jc as ea,Bc as fa,Ym as ga,Pa as ha,Ma as ia,Hp as ja,Vp as ka,Ha as la,Gp as ma,As as na,Zm as oa,Qp as pa,Zp as qa,os as ra,jt as sa,Ql as ta,R as ua,js as va,Cf as wa,Nf as xa,$d as ya,Mf as za,zs as Aa,Ff as Ba,Uf as Ca,Vf as Da,Ld as Ea,Md as Fa,Xf as Ga,tg as Ha,ng as Ia,rg as Ja,og as Ka,sg as La,ig as Ma,ag as Na,lg as Oa,dg as Pa,ug as Qa,mg as Ra,fg as Sa,hg as Ta,wg as Ua,xg as Va,kg as Wa,vg as Xa,Sg as Ya,Eg as Za,_g as _a,Og as $a,Dt as ab,Lg as bb,Pg as cb,me as db,fe as eb,qd as fb,th as gb,nh as hb,rh as ib,oh as jb,un as kb,sh as lb,Ot as mb,Lt as nb,Be as ob,xl as pb,vl as qb,jg as rb,Mt as sb,Ft as tb,Sl as ub,El as vb,qo as wb,zo as xb,Bg as yb,Tl as zb,qg as Ab,Ll as Bb,Fl as Cb,Ut as Db,Wl as Eb,Ko as Fb,z as Gb,oi as Hb,si as Ib,ii as Jb,gn as Kb,uh as Lb,Qd as Mb,li as Nb,ci as Ob,vh as Pb,Sh as Qb,mu as Rb,Eh as Sb,ui as Tb,Qo as Ub,Rh as Vb,xu as Wb,Dh as Xb,Ch as Yb,qe as Zb,om as _b,Kt as $b,um as ac,Ph as bc,Mh as cc,Fh as dc,Uh as ec,Wh as fc,jh as gc,Bh as hc,qh as ic,Hh as jc,yi as kc,wi as lc,zh as mc,xi as nc,Kh as oc};
969
- //# sourceMappingURL=chunk-Z6N7POAU.js.map
968
+ `}Fn();var wi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function xi(t){return{...wi,...t??{},regions:{...t?.regions??{}},buffer:{...wi.buffer,...t?.buffer??{}}}}function Hh(t){try{return xi(Mn(t).screen)}catch{return xi(void 0)}}var Tu=/^[a-z][\w-]*$/,ki=["window","screen","menubar","notifications"];function ke(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var Je=(t,e)=>ke(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function vi(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 qh(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Je(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Je(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Je(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ke(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ke(e.changeThreshold,"changeThreshold",o=>o>=0&&o<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let o={...n.regions??{}};for(let[s,i]of Object.entries(e.regions)){if(!Tu.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=vi(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=ke(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ke(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Je(o.maxPixels,"buffer.maxPixels")),"region"in o&&(s.region=String(o.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!ki.includes(r)&&!n.regions?.[r])try{vi(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...ki,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Cr as a,Iu as b,Yt as c,ic as d,ac as e,pm as f,gm as g,mm as h,bm as i,ym as j,wm as k,cs as l,ds as m,xm as n,vm as o,X as p,us as q,A as r,Ou as s,ms as t,Am as u,Dm as v,hs as w,Cm as x,bs as y,Nm as z,he as A,Dc as B,Om as C,Lm as D,ws as E,Gu as F,ea as G,tp as H,Jr as I,N as J,Uu as K,Wu as L,dp as M,Oe as N,up as O,Hr as P,Xu as Q,G as R,Up as S,ho as T,wo as U,Lc as V,Mm as W,Pc as X,Fm as Y,Um as Z,Qt as _,ks as $,Bm as aa,en as ba,Uc as ca,Wc as da,Xm as ea,Ma as fa,Fa as ga,Bp as ha,Hp as ia,Va as ja,zp as ka,Rs as la,Gm as ma,Yp as na,Jp as oa,ss as pa,jt as qa,Zl as ra,R as sa,Bs as ta,Af as ua,Rf as va,Ed as wa,Nf as xa,Ks as ya,Of as za,Lf as Aa,jf as Ba,Nd as Ca,Ld as Da,Bf as Ea,Zp as Fa,eg as Ga,tg as Ha,ng as Ia,rg as Ja,og as Ka,sg as La,ig as Ma,lg as Na,cg as Oa,pg as Pa,gg as Qa,mg as Ra,bg as Sa,yg as Ta,wg as Ua,xg as Va,kg as Wa,vg as Xa,Sg as Ya,Cg as Za,Dt as _a,Ng as $a,Og as ab,me as bb,fe as cb,jd as db,Jf as eb,Qf as fb,Zf as gb,eh as hb,un as ib,th as jb,Ot as kb,Lt as lb,He as mb,kl as nb,Sl as ob,Ug as pb,Mt as qb,Ft as rb,El as sb,_l as tb,qo as ub,Ko as vb,Wg as wb,Al as xb,jg as yb,Pl as zb,Ul as Ab,Ut as Bb,jl as Cb,Go as Db,z as Eb,si as Fb,ii as Gb,ai as Hb,gn as Ib,ah as Jb,Yd as Kb,ci as Lb,di as Mb,yh as Nb,wh as Ob,pu as Pb,xh as Qb,pi as Rb,Zo as Sb,_h as Tb,yu as Ub,Th as Vb,Ah as Wb,qe as Xb,nm as Yb,Kt as Zb,cm as _b,Ch as $b,Nh as ac,Oh as bc,Lh as cc,Ph as dc,Mh as ec,Fh as fc,Uh as gc,Wh as hc,wi as ic,xi as jc,Hh as kc,ki as lc,qh as mc};
969
+ //# sourceMappingURL=chunk-WAVO3U3I.js.map