agentix-cli 0.181.1 → 0.182.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +2 -2
  2. package/apps/mac-voice/Sources/AgentXVoice/Config.swift +9 -0
  3. package/apps/mac-voice/Sources/AgentXVoice/MiniOrbs.swift +19 -6
  4. package/apps/mac-voice/Sources/AgentXVoice/OpenRequests.swift +260 -0
  5. package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +72 -5
  6. package/apps/mac-voice/Sources/AgentXVoice/PillBusy.swift +22 -4
  7. package/apps/mac-voice/Sources/AgentXVoice/PillPlacement.swift +24 -0
  8. package/apps/mac-voice/Sources/AgentXVoice/RequestsWindow.swift +401 -0
  9. package/apps/mac-voice/Sources/AgentXVoice/SettingsWindow.swift +1 -0
  10. package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +22 -1
  11. package/apps/mac-voice/Sources/AgentXVoice/main.swift +263 -4
  12. package/dist/{App-UXX5TGFF.js → App-XWSSUYKF.js} +2 -2
  13. package/dist/{ChatApp-X635NOAE.js → ChatApp-UT2BRHYE.js} +2 -2
  14. package/dist/{absorb-eval-4ZPDWNBA.js → absorb-eval-SFGUURBD.js} +2 -2
  15. package/dist/{adapter-Z23K544D.js → adapter-UHR7FVM7.js} +2 -2
  16. package/dist/{agent-OBRH5BJZ.js → agent-5NTFSCEO.js} +2 -2
  17. package/dist/{board-dashboard-SFXVOICJ.js → board-dashboard-7HIME2W4.js} +2090 -2248
  18. package/dist/board-dashboard-7HIME2W4.js.map +1 -0
  19. package/dist/{chunk-SDINSYTN.js → chunk-343MPMLD.js} +2 -2
  20. package/dist/{chunk-WKU7YFDV.js → chunk-4KNHLHE3.js} +2 -2
  21. package/dist/{chunk-WZUY7VGL.js → chunk-4WSJKKSA.js} +2 -2
  22. package/dist/{chunk-ZSY6PFHD.js → chunk-5NGQQOVK.js} +2 -2
  23. package/dist/{chunk-FRVFRWFN.js → chunk-5YG2ZQQW.js} +2 -2
  24. package/dist/{chunk-N6VBEITO.js → chunk-7PQQZC6B.js} +2 -2
  25. package/dist/{chunk-N6VBEITO.js.map → chunk-7PQQZC6B.js.map} +1 -1
  26. package/dist/{chunk-7RVJWLIP.js → chunk-7WGJZLVJ.js} +2 -2
  27. package/dist/{chunk-CF7CPE7K.js → chunk-BY3AUZYM.js} +2 -2
  28. package/dist/{chunk-IRZYRLXQ.js → chunk-FDX4IGLK.js} +2 -2
  29. package/dist/{chunk-SD6UDSXV.js → chunk-FYFJ7IQJ.js} +2 -2
  30. package/dist/{chunk-HBQRVCLU.js → chunk-GEFZMDDX.js} +2 -2
  31. package/dist/{chunk-TZ7GB7FI.js → chunk-H2KOXGDX.js} +2 -2
  32. package/dist/{chunk-UFUQQ5J5.js → chunk-IFHVAHQM.js} +2 -2
  33. package/dist/{chunk-LZY6YN2J.js → chunk-IGBW4VVM.js} +2 -2
  34. package/dist/{chunk-OYCMFCME.js → chunk-JNWXHOJE.js} +2 -2
  35. package/dist/{chunk-KOY3EOPH.js → chunk-MD2HCGSC.js} +36 -36
  36. package/dist/chunk-MD2HCGSC.js.map +1 -0
  37. package/dist/{chunk-PCWXHXTM.js → chunk-NIPMVM3G.js} +2 -2
  38. package/dist/{chunk-DOBTHQ32.js → chunk-NRUUT5TL.js} +2 -2
  39. package/dist/{chunk-Z2UDWVZZ.js → chunk-OKADR5QO.js} +4 -4
  40. package/dist/chunk-OKADR5QO.js.map +1 -0
  41. package/dist/{chunk-IYITREE5.js → chunk-QB6UPODO.js} +2 -2
  42. package/dist/{chunk-VK3M3TVL.js → chunk-QGNV2HA4.js} +3 -3
  43. package/dist/chunk-QGNV2HA4.js.map +1 -0
  44. package/dist/{chunk-KVAWRQBA.js → chunk-R3CDFSNF.js} +67 -67
  45. package/dist/chunk-R3CDFSNF.js.map +1 -0
  46. package/dist/{chunk-HMEFQL5P.js → chunk-RDWDDPBI.js} +4 -3
  47. package/dist/chunk-RDWDDPBI.js.map +1 -0
  48. package/dist/{chunk-QJXGJMHM.js → chunk-XHJ5SVO5.js} +234 -234
  49. package/dist/chunk-XHJ5SVO5.js.map +1 -0
  50. package/dist/chunk-XI2HH5NR.js +36 -0
  51. package/dist/chunk-XI2HH5NR.js.map +1 -0
  52. package/dist/{chunk-J56YGKUO.js → chunk-Y4TVCWWF.js} +2 -2
  53. package/dist/{chunk-33DLG4I2.js → chunk-Y5TBOMHY.js} +5 -5
  54. package/dist/{chunk-UHTIZCKU.js → chunk-YSPBVLTZ.js} +2 -2
  55. package/dist/{chunk-NI2XD6P3.js → chunk-YX4R2VGD.js} +2 -2
  56. package/dist/{chunk-U5S6IP7Z.js → chunk-Z4XVPGPZ.js} +3 -3
  57. package/dist/{chunk-DMCMV4UJ.js → chunk-ZRALOFEG.js} +2 -2
  58. package/dist/cli.js +1 -1
  59. package/dist/{client-ILPJFCTF.js → client-SQMU25PS.js} +2 -2
  60. package/dist/{config-JVWOL233.js → config-56NBA4SF.js} +2 -2
  61. package/dist/{config-mutate-WYCHP6VK.js → config-mutate-PD4O3HZ7.js} +2 -2
  62. package/dist/config-mutator-ITL64FBW.js +2 -0
  63. package/dist/{contributions-XD66HYWE.js → contributions-DKTJ623L.js} +2 -2
  64. package/dist/{doctor-DYTYJQYC.js → doctor-OI6GJZR5.js} +2 -2
  65. package/dist/{follow-up-tool-HPET6LZW.js → follow-up-tool-DYSLS6ZI.js} +2 -2
  66. package/dist/{hub-L5FFJPS3.js → hub-4HDMTSR7.js} +2 -2
  67. package/dist/index.d.ts +317 -216
  68. package/dist/index.js +1 -1
  69. package/dist/processes-M7YPWX7H.js +2 -0
  70. package/dist/{program-24C3VBSD.js → program-4GDIWCDM.js} +259 -259
  71. package/dist/program-4GDIWCDM.js.map +1 -0
  72. package/dist/{promote-XI6W27JK.js → promote-3272TZNI.js} +2 -2
  73. package/dist/{query-MGG5QKNC.js → query-7XM6V4QG.js} +2 -2
  74. package/dist/{query-settings-CALZYYWD.js → query-settings-HHVBIIVQ.js} +2 -2
  75. package/dist/{registry-XJWSLJ4O.js → registry-QL3AM3UH.js} +2 -2
  76. package/dist/{request-planner-JCRGGJUO.js → request-planner-WNEDEA7X.js} +2 -2
  77. package/dist/{review-candidates-OEBEEAEZ.js → review-candidates-TGPDJMWJ.js} +2 -2
  78. package/dist/{routing-CGH54RYG.js → routing-ALXY25NE.js} +2 -2
  79. package/dist/schedule-tool-22UBZXCG.js +2 -0
  80. package/dist/{scheduler-2K5YEV2U.js → scheduler-5PHNW243.js} +2 -2
  81. package/dist/{seat-DEL5YUOS.js → seat-ZYVVEILY.js} +2 -2
  82. package/dist/{select-MRTWSI7U.js → select-6QLEV6AC.js} +2 -2
  83. package/dist/{set-enabled-XTDCFCZY.js → set-enabled-SYYTKJPC.js} +2 -2
  84. package/dist/{sprint-tool-N7WPDX5J.js → sprint-tool-PYVHPHR2.js} +2 -2
  85. package/dist/{tool-BQEJOTF3.js → tool-GIYOYXXM.js} +2 -2
  86. package/dist/{tool-NZTJZDSB.js → tool-TDOUM3BJ.js} +2 -2
  87. package/dist/{tool-KZHWJ7BC.js → tool-ZKZ4KYJT.js} +2 -2
  88. package/dist/{wiki-YERCKD3E.js → wiki-ZRGLGMII.js} +2 -2
  89. package/dist/wiki-enrich-CTID7JQW.js +2 -0
  90. package/package.json +1 -1
  91. package/dist/board-dashboard-SFXVOICJ.js.map +0 -1
  92. package/dist/chunk-G6ZRPC6E.js +0 -36
  93. package/dist/chunk-G6ZRPC6E.js.map +0 -1
  94. package/dist/chunk-HMEFQL5P.js.map +0 -1
  95. package/dist/chunk-KOY3EOPH.js.map +0 -1
  96. package/dist/chunk-KVAWRQBA.js.map +0 -1
  97. package/dist/chunk-QJXGJMHM.js.map +0 -1
  98. package/dist/chunk-VK3M3TVL.js.map +0 -1
  99. package/dist/chunk-Z2UDWVZZ.js.map +0 -1
  100. package/dist/config-mutator-DKNHE6VP.js +0 -2
  101. package/dist/processes-EWARF6ZW.js +0 -2
  102. package/dist/program-24C3VBSD.js.map +0 -1
  103. package/dist/schedule-tool-UM3CAPDX.js +0 -2
  104. package/dist/wiki-enrich-K54LGNU3.js +0 -2
  105. /package/dist/{App-UXX5TGFF.js.map → App-XWSSUYKF.js.map} +0 -0
  106. /package/dist/{ChatApp-X635NOAE.js.map → ChatApp-UT2BRHYE.js.map} +0 -0
  107. /package/dist/{absorb-eval-4ZPDWNBA.js.map → absorb-eval-SFGUURBD.js.map} +0 -0
  108. /package/dist/{adapter-Z23K544D.js.map → adapter-UHR7FVM7.js.map} +0 -0
  109. /package/dist/{agent-OBRH5BJZ.js.map → agent-5NTFSCEO.js.map} +0 -0
  110. /package/dist/{chunk-SDINSYTN.js.map → chunk-343MPMLD.js.map} +0 -0
  111. /package/dist/{chunk-WKU7YFDV.js.map → chunk-4KNHLHE3.js.map} +0 -0
  112. /package/dist/{chunk-WZUY7VGL.js.map → chunk-4WSJKKSA.js.map} +0 -0
  113. /package/dist/{chunk-ZSY6PFHD.js.map → chunk-5NGQQOVK.js.map} +0 -0
  114. /package/dist/{chunk-FRVFRWFN.js.map → chunk-5YG2ZQQW.js.map} +0 -0
  115. /package/dist/{chunk-7RVJWLIP.js.map → chunk-7WGJZLVJ.js.map} +0 -0
  116. /package/dist/{chunk-CF7CPE7K.js.map → chunk-BY3AUZYM.js.map} +0 -0
  117. /package/dist/{chunk-IRZYRLXQ.js.map → chunk-FDX4IGLK.js.map} +0 -0
  118. /package/dist/{chunk-SD6UDSXV.js.map → chunk-FYFJ7IQJ.js.map} +0 -0
  119. /package/dist/{chunk-HBQRVCLU.js.map → chunk-GEFZMDDX.js.map} +0 -0
  120. /package/dist/{chunk-TZ7GB7FI.js.map → chunk-H2KOXGDX.js.map} +0 -0
  121. /package/dist/{chunk-UFUQQ5J5.js.map → chunk-IFHVAHQM.js.map} +0 -0
  122. /package/dist/{chunk-LZY6YN2J.js.map → chunk-IGBW4VVM.js.map} +0 -0
  123. /package/dist/{chunk-OYCMFCME.js.map → chunk-JNWXHOJE.js.map} +0 -0
  124. /package/dist/{chunk-PCWXHXTM.js.map → chunk-NIPMVM3G.js.map} +0 -0
  125. /package/dist/{chunk-DOBTHQ32.js.map → chunk-NRUUT5TL.js.map} +0 -0
  126. /package/dist/{chunk-IYITREE5.js.map → chunk-QB6UPODO.js.map} +0 -0
  127. /package/dist/{chunk-J56YGKUO.js.map → chunk-Y4TVCWWF.js.map} +0 -0
  128. /package/dist/{chunk-33DLG4I2.js.map → chunk-Y5TBOMHY.js.map} +0 -0
  129. /package/dist/{chunk-UHTIZCKU.js.map → chunk-YSPBVLTZ.js.map} +0 -0
  130. /package/dist/{chunk-NI2XD6P3.js.map → chunk-YX4R2VGD.js.map} +0 -0
  131. /package/dist/{chunk-U5S6IP7Z.js.map → chunk-Z4XVPGPZ.js.map} +0 -0
  132. /package/dist/{chunk-DMCMV4UJ.js.map → chunk-ZRALOFEG.js.map} +0 -0
  133. /package/dist/{client-ILPJFCTF.js.map → client-SQMU25PS.js.map} +0 -0
  134. /package/dist/{config-JVWOL233.js.map → config-56NBA4SF.js.map} +0 -0
  135. /package/dist/{config-mutate-WYCHP6VK.js.map → config-mutate-PD4O3HZ7.js.map} +0 -0
  136. /package/dist/{config-mutator-DKNHE6VP.js.map → config-mutator-ITL64FBW.js.map} +0 -0
  137. /package/dist/{contributions-XD66HYWE.js.map → contributions-DKTJ623L.js.map} +0 -0
  138. /package/dist/{doctor-DYTYJQYC.js.map → doctor-OI6GJZR5.js.map} +0 -0
  139. /package/dist/{follow-up-tool-HPET6LZW.js.map → follow-up-tool-DYSLS6ZI.js.map} +0 -0
  140. /package/dist/{hub-L5FFJPS3.js.map → hub-4HDMTSR7.js.map} +0 -0
  141. /package/dist/{processes-EWARF6ZW.js.map → processes-M7YPWX7H.js.map} +0 -0
  142. /package/dist/{promote-XI6W27JK.js.map → promote-3272TZNI.js.map} +0 -0
  143. /package/dist/{query-MGG5QKNC.js.map → query-7XM6V4QG.js.map} +0 -0
  144. /package/dist/{query-settings-CALZYYWD.js.map → query-settings-HHVBIIVQ.js.map} +0 -0
  145. /package/dist/{registry-XJWSLJ4O.js.map → registry-QL3AM3UH.js.map} +0 -0
  146. /package/dist/{request-planner-JCRGGJUO.js.map → request-planner-WNEDEA7X.js.map} +0 -0
  147. /package/dist/{review-candidates-OEBEEAEZ.js.map → review-candidates-TGPDJMWJ.js.map} +0 -0
  148. /package/dist/{routing-CGH54RYG.js.map → routing-ALXY25NE.js.map} +0 -0
  149. /package/dist/{schedule-tool-UM3CAPDX.js.map → schedule-tool-22UBZXCG.js.map} +0 -0
  150. /package/dist/{scheduler-2K5YEV2U.js.map → scheduler-5PHNW243.js.map} +0 -0
  151. /package/dist/{seat-DEL5YUOS.js.map → seat-ZYVVEILY.js.map} +0 -0
  152. /package/dist/{select-MRTWSI7U.js.map → select-6QLEV6AC.js.map} +0 -0
  153. /package/dist/{set-enabled-XTDCFCZY.js.map → set-enabled-SYYTKJPC.js.map} +0 -0
  154. /package/dist/{sprint-tool-N7WPDX5J.js.map → sprint-tool-PYVHPHR2.js.map} +0 -0
  155. /package/dist/{tool-BQEJOTF3.js.map → tool-GIYOYXXM.js.map} +0 -0
  156. /package/dist/{tool-NZTJZDSB.js.map → tool-TDOUM3BJ.js.map} +0 -0
  157. /package/dist/{tool-KZHWJ7BC.js.map → tool-ZKZ4KYJT.js.map} +0 -0
  158. /package/dist/{wiki-YERCKD3E.js.map → wiki-ZRGLGMII.js.map} +0 -0
  159. /package/dist/{wiki-enrich-K54LGNU3.js.map → wiki-enrich-CTID7JQW.js.map} +0 -0
@@ -1,10 +1,10 @@
1
- import{a as Fe}from"./chunk-GTJIKXDB.js";import{C as vn,J as Cn,k as P}from"./chunk-G6ZRPC6E.js";import{f as An,g as In,h as Tn,k as Dn}from"./chunk-WZUY7VGL.js";import{a as k}from"./chunk-N6VBEITO.js";import{b as $n}from"./chunk-2VDO2HEK.js";import{f as En,i as _n,k as Me,l as Ue,n as G,o as j,q as Rn}from"./chunk-CTNZVRPA.js";import{t as Sn,u as xn}from"./chunk-SDINSYTN.js";import{d as wn,e as kn}from"./chunk-AQASR6KR.js";import{a as dn,b as pn,d as gn,e as fn}from"./chunk-MNG2AMKZ.js";import{h as K,j as mn,l as hn,m as bn,n as yn}from"./chunk-RX5O5637.js";import{h as on,i as an,j as ln,l as cn,m as un}from"./chunk-TZ7GB7FI.js";import{a as rn,c as sn}from"./chunk-KP7KDLZ2.js";import{Aa as Oe,Ca as Pe,b as Ce,s as Ne,u as Le,xa as nn,za as le}from"./chunk-VK3M3TVL.js";import{r as tn}from"./chunk-SD6UDSXV.js";import{a as Qt,b as ae,e as en}from"./chunk-IRZYRLXQ.js";import{a as Zt}from"./chunk-QUFIUXMQ.js";import{da as Ht,ea as zt,fb as De,ga as Xt,ha as Kt,ob as Gt,p as ie,pb as Jt,q as Vt,r as Bt,s as ro,yb as Yt}from"./chunk-KOY3EOPH.js";import{a as Ie,h as so}from"./chunk-VJ5HC63R.js";import{j as Te,r as oo}from"./chunk-UEEB3UTU.js";import{existsSync as io,readdirSync as ao,readFileSync as lo,statSync as co}from"fs";import{resolve as uo}from"path";function Nn(t,e,n=Date.now(),r=7){let s=r*864e5,o=new Map;for(let i of e){let a=o.get(i.workflowId);a?a.push(i):o.set(i.workflowId,[i])}return t.map(i=>{let a=o.get(i.id)??[],l=a.filter(f=>n-f.at<=s),u=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?u.length>0&&l.length===0?"dormant":l.length>0&&c*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:u.length,failed:c,paused:d}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ce=new Map;function Uc(t,e=1e3){if(!io(t))return[];let n=ao(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=uo(t,o);return{path:i,mtime:co(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of ce.keys())r.has(o)||ce.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=ce.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=po(o,i);ce.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function po(t,e){try{let n=lo(t,"utf-8").split(`
2
- `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),s=r.run?.workflowId;if(!s)return null;let o=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),l=a.status??a.run?.status;if(l){o=l;break}}return{workflowId:s,status:o,at:e}}catch{return null}}var Ln=7,go={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},S={routines:200,summary:160,filters:6,filterValue:60,text:120},fo=(t,e,n)=>{try{return tn(t,e,n)}catch{return null}},On=864e5;function qc(t){let e=t.now??Date.now(),n={...go,...t.thresholds},r=t.nextFire??fo,s=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],u=a.timezone||"UTC",c=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:I(a.id,S.text),trigger:{schedule:I(a.schedule,S.text),timezone:u},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?We(a.nextRun)??We(r(a.schedule,new Date(e),u)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:ko(d.status==="success"?void 0:d.errorSummary,S.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Pn(c),sampledRuns:l.length,flags:[],attention:null,recent:l.slice(0,Ln).map(g=>({at:g.startedAt,status:g.status}))};p.flags=Mn(p,c,a.schedule,u,null,e,n,r),s.push(Un(p))}let o=new Map(Nn(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(w=>w.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let u=l.config??{},c=a.state||"active",d=c==="active",p=(i.get(a.id)??[]).slice().sort((w,Ae)=>Ae.at-w.at),g=p.map(w=>({at:w.at,status:bo(w.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof u.spec=="string"?u.spec:"",v=typeof u.timezone=="string"?u.timezone:"UTC",W={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:I(a.title||a.id,S.text),trigger:m?{schedule:I(b,S.text),timezone:v}:{event:I(typeof u.event=="string"?u.event:"",S.text),filters:wo(u.filter,a)},agent:yo(a),enabled:d,state:c,nextRunAt:m&&d&&b?We(r(b,new Date(e),v)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let w=g.find(Ae=>Ae.status==="success");return w?new Date(w.at).toISOString():null})(),consecutiveFailures:Pn(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,Ln).map(w=>({at:new Date(w.at).toISOString(),status:w.status}))},oe=Date.parse(a.updated||a.created||"");W.flags=m?Mn(W,g,b,v,Number.isFinite(oe)?oe:null,e,n,r):mo(W,o.get(a.id)?.state==="dormant",Number.isFinite(oe)?oe:null,e,n),s.push(Un(W))}return s.sort(ho).slice(0,S.routines)}function Pn(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 Mn(t,e,n,r,s,o,i,a){let l=[],u=e.length?e[0].at:null;if(!t.enabled){let p=Wn(u,s,o,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),u===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let c=new Date(u),d=null;for(let p=0;p<i.missedFires&&(d=a(n,c,r),!!d);p++)c=d;return d&&o>d.getTime()+i.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(u).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function mo(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Wn(i,n,r,s);return a&&o.push(a),o}return t.consecutiveFailures>=s.failStreak&&o.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?o.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&o.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),o}function Wn(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*On?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/On)} days`:"Disabled and never ran"}}function Un(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 Fn={critical:0,warning:1,info:2};function ho(t,e){let n=t.attention?Fn[t.attention]:3,r=e.attention?Fn[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function bo(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 yo(t){if(t.ownerAgent)return I(t.ownerAgent,S.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?I(String(e.config.agentId),S.text):null}function wo(t,e){let n=[],r=e?.project;if(r&&n.push(I(`project=${r}`,S.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[s,o]of Object.entries(t)){let i=Array.isArray(o)?o.map(String):o==null?[]:[String(o)];i.length&&n.push(I(`${s}=${i.join(",")}`,S.filterValue))}return n.slice(0,S.filters)}function We(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function I(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function ko(t,e){return t===void 0?void 0:I(t,e)}import{mkdirSync as So,readFileSync as xo,renameSync as vo,writeFileSync as $o}from"fs";import{resolve as Eo}from"path";function jn(t){return Eo(Ue(t),"_state.json")}function $(t){try{let e=JSON.parse(xo(jn(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 J(t,e){So(Ue(t),{recursive:!0});let n=jn(t),r=`${n}.${process.pid}.tmp`;$o(r,JSON.stringify(e,null,2)+`
3
- `),vo(r,n)}function qn(t,e,n,r=Date.now()){let s=$(t),o={};for(let[i,a]of Object.entries(s.snoozed))Date.parse(a)>r&&(o[i]=a);o[e]=n.toISOString(),J(t,{...s,snoozed:o})}function Xc(t,e){J(t,{...$(t),lastDigest:e})}function je(t,e,n,r=Date.now()){let s=$(t),o=new Set(n),i={};for(let[l,u]of Object.entries(s.popped??{}))o.has(l)&&(i[l]=u);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(l=>l!==e&&o.has(l));J(t,{...s,popped:i,wanted:a})}function Vn(t,e){let n=$(t);J(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Kc(t,e=Date.now()){J(t,{...$(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as _o,readFileSync as Ro}from"fs";Yt();so();function Bn(t){let e=Qt(t),n={};if(_o(e))try{n=Gt(JSON.parse(Ro(e,"utf-8")))}catch{n={}}let r=De.safeParse(n?.requests);return r.success?r.data:De.parse(void 0)}async function eu(t,e={}){let n=(t.channels??[]).filter(r=>!Ie.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Ie].join(", ")}`}:ae(r=>{let s=r.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])t[o]!==void 0&&(s[o]=t[o]);if(t.plans){let o=s.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(o[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((s.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let o=s.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(o[i]=t.catchPromises[i])}if(t.checkers){let o=s.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(o[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as Y,readdirSync as Go,readFileSync as ze}from"fs";import{dirname as Jo,resolve as E}from"path";import{randomBytes as Xn}from"crypto";import{existsSync as Io,mkdirSync as To,readdirSync as Do,readFileSync as Co,renameSync as Kn,unlinkSync as No,writeFileSync as Lo}from"fs";import{resolve as Gn}from"path";function Hn(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Ao=t=>t.trim().split(`
4
- `).pop()?.slice(0,300)||"no output";async function zn(t,e,n,r=Fe){let s=await r(t.bin,[...Hn(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Ao(s.stderr||s.stdout)}`}}async function ru(t,e,n,r,s=Fe){return(await s(t.bin,[...Hn(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Oo=2e3,Po=t=>zn(t.wacli,t.to,t.text);function qe(t){return Gn(t,".agentx","whatsapp-triage","drafts")}var Mo=t=>/^[a-z0-9-]{8,64}$/.test(t),ue=(t,e)=>Gn(qe(t),`${e}.json`);function Jn(t,e){To(qe(t),{recursive:!0});let n=ue(t,e.id),r=`${n}.${process.pid}.tmp`;Lo(r,JSON.stringify(e,null,2)+`
5
- `,{mode:384}),Kn(r,n)}function cu(t,e,n=Date.now()){let r=e.text.trim().slice(0,Oo);if(!r)throw new Error("empty draft");let s={...e,text:r,id:`${n.toString(36)}-${Xn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Jn(t,s),s}function de(t,e){if(!Mo(e))return null;try{return JSON.parse(Co(ue(t,e),"utf-8"))}catch{return null}}function Yn(t,e){let n=qe(t);return Io(n)?Do(n).filter(r=>r.endsWith(".json")).map(r=>de(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,s)=>r.created_at.localeCompare(s.created_at)):[]}async function Zn(t,e,n,r={}){let s=de(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let o=`${ue(t,e)}.${process.pid}.${Xn(3).toString("hex")}.claim`;try{Kn(ue(t,e),o)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...s,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")i.status="rejected";else{let a=await(r.send??Po)(s).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Jn(t,i);try{No(o)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as Fo,writeFileSync as Wo}from"fs";import{resolve as er}from"path";function Ve(t,e,n,r){let s=t.agents?.[e];if(!s)return null;let o=s.integrations;if(!Array.isArray(o))return null;let i=o.find(a=>a.enabled!==!1&&a.kind===n&&(!r||a.label===r));return i?{agentId:e,integration:i}:null}function Uo(t,e){let r=(t.credentials??{})[e];if(!r)return{status:"no-credential",reason:`integration "${t.label}" has no ${String(e)} configured`};if(e==="auth"&&r==="keyring")return{status:"ok"};if(typeof r=="string"&&/^[A-Z][A-Z0-9_]*$/.test(r)){let s=process.env[r];return s?{status:"ok",value:s,envVar:r}:{status:"env-unset",envVar:r,reason:`env var ${r} is unset (declared by integration "${t.label}")`}}return typeof r=="string"?{status:"ok",value:r}:{status:"no-credential",reason:`unrecognized credential ref shape for ${String(e)}`}}function du(t,e,n,r,s){let o=Ve(t,e,n,s);return o?Uo(o.integration,r):{status:"kind-not-found",reason:`agent "${e}" has no integration of kind "${n}"${s?` with label "${s}"`:""}`}}var tr="ready",jo="202510";function qo(t){let e=t.date??t.created_at.slice(0,10);return er(t.workspace,tr,`${e}-${t.platform}-${t.id}.txt`)}function Qn(t){let e=qo(t);return Fo(er(t.workspace,tr),{recursive:!0}),Wo(e,t.text.endsWith(`
1
+ import{a as We}from"./chunk-GTJIKXDB.js";import{C as En,J as Ln,k as P}from"./chunk-XI2HH5NR.js";import{f as Tn,g as Dn,h as Cn,k as Nn}from"./chunk-4WSJKKSA.js";import{a as k}from"./chunk-7PQQZC6B.js";import{b as Rn}from"./chunk-2VDO2HEK.js";import{f as _n,i as An,k as Ue,l as Fe,n as G,o as j,q as In}from"./chunk-CTNZVRPA.js";import{t as vn,u as $n}from"./chunk-343MPMLD.js";import{d as Sn,e as xn}from"./chunk-AQASR6KR.js";import{a as gn,b as fn,d as mn,e as hn}from"./chunk-MNG2AMKZ.js";import{h as K,j as bn,l as yn,m as wn,n as kn}from"./chunk-RX5O5637.js";import{h as ln,i as cn,j as un,l as dn,m as pn}from"./chunk-H2KOXGDX.js";import{a as on,c as an}from"./chunk-KP7KDLZ2.js";import{Aa as Pe,Ca as Me,b as Ne,s as Le,u as Oe,xa as sn,za as le}from"./chunk-QGNV2HA4.js";import{r as rn}from"./chunk-FYFJ7IQJ.js";import{a as tn,b as ae,e as nn}from"./chunk-FDX4IGLK.js";import{a as en}from"./chunk-QUFIUXMQ.js";import{A as io,Gb as Qt,d as Ie,f as Bt,j as oo,la as Xt,ma as Kt,nb as Ce,oa as Gt,pa as Jt,wb as Yt,x as ie,xb as Zt,y as Ht,z as zt}from"./chunk-MD2HCGSC.js";import{a as Te,h as ao}from"./chunk-VJ5HC63R.js";import{j as De,r as lo}from"./chunk-UEEB3UTU.js";import{existsSync as co,readdirSync as uo,readFileSync as po,statSync as go}from"fs";import{resolve as fo}from"path";function On(t,e,n=Date.now(),r=7){let s=r*864e5,o=new Map;for(let i of e){let a=o.get(i.workflowId);a?a.push(i):o.set(i.workflowId,[i])}return t.map(i=>{let a=o.get(i.id)??[],l=a.filter(f=>n-f.at<=s),u=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?u.length>0&&l.length===0?"dormant":l.length>0&&c*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:u.length,failed:c,paused:d}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ce=new Map;function jc(t,e=1e3){if(!co(t))return[];let n=uo(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=fo(t,o);return{path:i,mtime:go(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of ce.keys())r.has(o)||ce.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=ce.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=mo(o,i);ce.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function mo(t,e){try{let n=po(t,"utf-8").split(`
2
+ `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),s=r.run?.workflowId;if(!s)return null;let o=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),l=a.status??a.run?.status;if(l){o=l;break}}return{workflowId:s,status:o,at:e}}catch{return null}}var Pn=7,ho={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},S={routines:200,summary:160,filters:6,filterValue:60,text:120},bo=(t,e,n)=>{try{return rn(t,e,n)}catch{return null}},Mn=864e5;function Hc(t){let e=t.now??Date.now(),n={...ho,...t.thresholds},r=t.nextFire??bo,s=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],u=a.timezone||"UTC",c=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:I(a.id,S.text),trigger:{schedule:I(a.schedule,S.text),timezone:u},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?je(a.nextRun)??je(r(a.schedule,new Date(e),u)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:vo(d.status==="success"?void 0:d.errorSummary,S.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Un(c),sampledRuns:l.length,flags:[],attention:null,recent:l.slice(0,Pn).map(g=>({at:g.startedAt,status:g.status}))};p.flags=Fn(p,c,a.schedule,u,null,e,n,r),s.push(Wn(p))}let o=new Map(On(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(w=>w.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let u=l.config??{},c=a.state||"active",d=c==="active",p=(i.get(a.id)??[]).slice().sort((w,Ae)=>Ae.at-w.at),g=p.map(w=>({at:w.at,status:ko(w.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof u.spec=="string"?u.spec:"",v=typeof u.timezone=="string"?u.timezone:"UTC",W={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:I(a.title||a.id,S.text),trigger:m?{schedule:I(b,S.text),timezone:v}:{event:I(typeof u.event=="string"?u.event:"",S.text),filters:xo(u.filter,a)},agent:So(a),enabled:d,state:c,nextRunAt:m&&d&&b?je(r(b,new Date(e),v)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let w=g.find(Ae=>Ae.status==="success");return w?new Date(w.at).toISOString():null})(),consecutiveFailures:Un(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,Pn).map(w=>({at:new Date(w.at).toISOString(),status:w.status}))},oe=Date.parse(a.updated||a.created||"");W.flags=m?Fn(W,g,b,v,Number.isFinite(oe)?oe:null,e,n,r):yo(W,o.get(a.id)?.state==="dormant",Number.isFinite(oe)?oe:null,e,n),s.push(Wn(W))}return s.sort(wo).slice(0,S.routines)}function Un(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 Fn(t,e,n,r,s,o,i,a){let l=[],u=e.length?e[0].at:null;if(!t.enabled){let p=qn(u,s,o,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),u===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let c=new Date(u),d=null;for(let p=0;p<i.missedFires&&(d=a(n,c,r),!!d);p++)c=d;return d&&o>d.getTime()+i.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(u).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function yo(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=qn(i,n,r,s);return a&&o.push(a),o}return t.consecutiveFailures>=s.failStreak&&o.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?o.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&o.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),o}function qn(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*Mn?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/Mn)} days`:"Disabled and never ran"}}function Wn(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 jn={critical:0,warning:1,info:2};function wo(t,e){let n=t.attention?jn[t.attention]:3,r=e.attention?jn[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ko(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 So(t){if(t.ownerAgent)return I(t.ownerAgent,S.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?I(String(e.config.agentId),S.text):null}function xo(t,e){let n=[],r=e?.project;if(r&&n.push(I(`project=${r}`,S.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[s,o]of Object.entries(t)){let i=Array.isArray(o)?o.map(String):o==null?[]:[String(o)];i.length&&n.push(I(`${s}=${i.join(",")}`,S.filterValue))}return n.slice(0,S.filters)}function je(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function I(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function vo(t,e){return t===void 0?void 0:I(t,e)}import{mkdirSync as $o,readFileSync as Eo,renameSync as Ro,writeFileSync as _o}from"fs";import{resolve as Ao}from"path";function Vn(t){return Ao(Fe(t),"_state.json")}function $(t){try{let e=JSON.parse(Eo(Vn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function J(t,e){$o(Fe(t),{recursive:!0});let n=Vn(t),r=`${n}.${process.pid}.tmp`;_o(r,JSON.stringify(e,null,2)+`
3
+ `),Ro(r,n)}function Bn(t,e,n,r=Date.now()){let s=$(t),o={};for(let[i,a]of Object.entries(s.snoozed))Date.parse(a)>r&&(o[i]=a);o[e]=n.toISOString(),J(t,{...s,snoozed:o})}function Jc(t,e){J(t,{...$(t),lastDigest:e})}function qe(t,e,n,r=Date.now()){let s=$(t),o=new Set(n),i={};for(let[l,u]of Object.entries(s.popped??{}))o.has(l)&&(i[l]=u);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(l=>l!==e&&o.has(l));J(t,{...s,popped:i,wanted:a})}function Hn(t,e){let n=$(t);J(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Yc(t,e=Date.now()){J(t,{...$(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as Io,readFileSync as To}from"fs";Qt();ao();function zn(t){let e=tn(t),n={};if(Io(e))try{n=Yt(JSON.parse(To(e,"utf-8")))}catch{n={}}let r=Ce.safeParse(n?.requests);return r.success?r.data:Ce.parse(void 0)}async function ru(t,e={}){let n=(t.channels??[]).filter(r=>!Te.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Te].join(", ")}`}:ae(r=>{let s=r.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])t[o]!==void 0&&(s[o]=t[o]);if(t.plans){let o=s.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(o[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((s.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let o=s.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(o[i]=t.catchPromises[i])}if(t.checkers){let o=s.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(o[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as Y,readdirSync as Zo,readFileSync as Xe}from"fs";import{dirname as Qo,resolve as E}from"path";import{randomBytes as Gn}from"crypto";import{existsSync as Co,mkdirSync as No,readdirSync as Lo,readFileSync as Oo,renameSync as Jn,unlinkSync as Po,writeFileSync as Mo}from"fs";import{resolve as Yn}from"path";function Xn(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Do=t=>t.trim().split(`
4
+ `).pop()?.slice(0,300)||"no output";async function Kn(t,e,n,r=We){let s=await r(t.bin,[...Xn(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Do(s.stderr||s.stdout)}`}}async function iu(t,e,n,r,s=We){return(await s(t.bin,[...Xn(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Uo=2e3,Fo=t=>Kn(t.wacli,t.to,t.text);function Ve(t){return Yn(t,".agentx","whatsapp-triage","drafts")}var Wo=t=>/^[a-z0-9-]{8,64}$/.test(t),ue=(t,e)=>Yn(Ve(t),`${e}.json`);function Zn(t,e){No(Ve(t),{recursive:!0});let n=ue(t,e.id),r=`${n}.${process.pid}.tmp`;Mo(r,JSON.stringify(e,null,2)+`
5
+ `,{mode:384}),Jn(r,n)}function pu(t,e,n=Date.now()){let r=e.text.trim().slice(0,Uo);if(!r)throw new Error("empty draft");let s={...e,text:r,id:`${n.toString(36)}-${Gn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Zn(t,s),s}function de(t,e){if(!Wo(e))return null;try{return JSON.parse(Oo(ue(t,e),"utf-8"))}catch{return null}}function Qn(t,e){let n=Ve(t);return Co(n)?Lo(n).filter(r=>r.endsWith(".json")).map(r=>de(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,s)=>r.created_at.localeCompare(s.created_at)):[]}async function er(t,e,n,r={}){let s=de(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let o=`${ue(t,e)}.${process.pid}.${Gn(3).toString("hex")}.claim`;try{Jn(ue(t,e),o)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...s,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")i.status="rejected";else{let a=await(r.send??Fo)(s).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Zn(t,i);try{Po(o)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as qo,writeFileSync as Vo}from"fs";import{resolve as nr}from"path";function Be(t,e,n,r){let s=t.agents?.[e];if(!s)return null;let o=s.integrations;if(!Array.isArray(o))return null;let i=o.find(a=>a.enabled!==!1&&a.kind===n&&(!r||a.label===r));return i?{agentId:e,integration:i}:null}function jo(t,e){let r=(t.credentials??{})[e];if(!r)return{status:"no-credential",reason:`integration "${t.label}" has no ${String(e)} configured`};if(e==="auth"&&r==="keyring")return{status:"ok"};if(typeof r=="string"&&/^[A-Z][A-Z0-9_]*$/.test(r)){let s=process.env[r];return s?{status:"ok",value:s,envVar:r}:{status:"env-unset",envVar:r,reason:`env var ${r} is unset (declared by integration "${t.label}")`}}return typeof r=="string"?{status:"ok",value:r}:{status:"no-credential",reason:`unrecognized credential ref shape for ${String(e)}`}}function fu(t,e,n,r,s){let o=Be(t,e,n,s);return o?jo(o.integration,r):{status:"kind-not-found",reason:`agent "${e}" has no integration of kind "${n}"${s?` with label "${s}"`:""}`}}var rr="ready",Bo="202510";function Ho(t){let e=t.date??t.created_at.slice(0,10);return nr(t.workspace,rr,`${e}-${t.platform}-${t.id}.txt`)}function tr(t){let e=Ho(t);return qo(nr(t.workspace,rr),{recursive:!0}),Vo(e,t.text.endsWith(`
6
6
  `)?t.text:`${t.text}
7
- `),e}function nr(t,e,n){let r=Ve(t.config,e,n);if(!r)return null;let s=t.env??process.env,o=r.integration.credentials?.tokenEnv,i=o?s[o]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function rr(t,e,n){return nr(t,e,n)!==null}async function Vo(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let s=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??jo),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!s.ok)throw new Error(`LinkedIn said ${s.status}: ${(await s.text().catch(()=>"")).slice(0,200)}`);let o=s.headers.get("x-restli-id");return o?{url:`https://www.linkedin.com/feed/update/${o}/`}:{}}async function Bo(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let s=await r.json().catch(()=>({}));return s.data?.id?{url:`https://x.com/i/web/status/${s.data.id}`}:{}}async function Ho(t,e){let n=nr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Qn(t)};let r=e.fetch??fetch;try{let s=t.platform==="linkedin"?await Vo(t.text,n,r):await Bo(t.text,n,r);return{ok:!0,posted:!0,...s.url?{url:s.url}:{}}}catch(s){let o=Qn(t);return{ok:!1,error:`not posted on ${K[t.platform]}: ${s?.message??s}. Saved to paste by hand: ${o}`,file:o}}}function sr(t){return e=>Ho(e,t)}oo();Kt();Kt();var wu=["done","skipped"],zo=1e3;function Xo(t){t.exec(`
7
+ `),e}function sr(t,e,n){let r=Be(t.config,e,n);if(!r)return null;let s=t.env??process.env,o=r.integration.credentials?.tokenEnv,i=o?s[o]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function or(t,e,n){return sr(t,e,n)!==null}async function zo(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let s=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??Bo),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!s.ok)throw new Error(`LinkedIn said ${s.status}: ${(await s.text().catch(()=>"")).slice(0,200)}`);let o=s.headers.get("x-restli-id");return o?{url:`https://www.linkedin.com/feed/update/${o}/`}:{}}async function Xo(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let s=await r.json().catch(()=>({}));return s.data?.id?{url:`https://x.com/i/web/status/${s.data.id}`}:{}}async function Ko(t,e){let n=sr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:tr(t)};let r=e.fetch??fetch;try{let s=t.platform==="linkedin"?await zo(t.text,n,r):await Xo(t.text,n,r);return{ok:!0,posted:!0,...s.url?{url:s.url}:{}}}catch(s){let o=tr(t);return{ok:!1,error:`not posted on ${K[t.platform]}: ${s?.message??s}. Saved to paste by hand: ${o}`,file:o}}}function ir(t){return e=>Ko(e,t)}lo();Jt();Jt();var xu=["done","skipped"],Go=1e3;function Jo(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,
@@ -52,10 +52,10 @@ import{a as Fe}from"./chunk-GTJIKXDB.js";import{C as vn,J as Cn,k as P}from"./ch
52
52
  FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
53
53
  );
54
54
  CREATE INDEX IF NOT EXISTS idx_request_plan_events ON request_plan_events(request_id, at);
55
- `)}function ir(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function Be(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 or(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var Ko={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"},pe=class{constructor(e){this.db=e;Xo(e)}create(e,n,r,s){let o=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
55
+ `)}function lr(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function He(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 ar(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var Yo={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"},pe=class{constructor(e){this.db=e;Jo(e)}create(e,n,r,s){let o=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
56
56
  to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at)
57
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{o.run(e,n,s),r.forEach((a,l)=>{let u=l===0,c=u&&a.agentId===n&&a.kind!=="message";i.run(e,l+1,a.name,a.kind,a.agentId,a.doneWhen,u?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,c?s:null,s)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,s)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?Be(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(or)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?or(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(Be)}updateStep(e,n,r){let s=[],o=[];for(let[i,a]of Object.entries(r)){let l=Ko[i];!l||a===void 0||(s.push(`${l} = ?`),o.push(typeof a=="boolean"?a?1:0:a))}s.length&&this.db.prepare(`UPDATE request_plan_steps SET ${s.join(", ")} WHERE request_id = ? AND idx = ?`).run(...o,e,n)}finish(e,n,r){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,r,e).changes>0}markNotified(e,n){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(n,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(Be)}event(e,n,r,s,o){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,o,r,s.replace(/\s+/g," ").trim().slice(0,zo))}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at, rowid LIMIT ?").all(e,n).map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}},ku=Ht;var cr=["card","schedule","agent","memory","wiki","whatsapp","email","content","request"],Yo=280;function D(t,e=Yo){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function q(t){if(t.configPath)return E(t.configPath);let e=[E(t.root,"agentx.json"),E(t.root,".agentx","config.json")];return e.find(n=>Y(n))??e[0]}function Xe(t){return t.wikiDir?E(t.wikiDir):E(t.root,".agentx","wiki")}function Zo(t){return j(t.root,"pending").map(Qo)}function Qo(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:D([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function ei(t){let e=q(t);if(!Y(e))return[];let n;try{n=JSON.parse(ze(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),s=[];for(let[o,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let l=i.timezone||"UTC",u=i.schedule?on(i.schedule):"",c=i.schedule?`${u.charAt(0).toLowerCase()}${u.slice(1)} (${i.schedule})`:"no schedule",d=String(i.prompt??i.command??""),p=a.action==="create";s.push({key:`schedule:${o}`,kind:"schedule",title:p?`New schedule "${o}" for ${i.agent??"an agent"}`:`Delete schedule "${o}"`,ask:p?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${o}" (${c})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:D(`${d}${p&&i.schedule?` \xB7 first run ${ln(an(i.schedule,l,r),l)}`:""}`),more:"agentx schedule list"})}return s}function ur(t){let e=E(t,".agentx","memory");return Y(e)?Go(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ti(t){let e=ur(t.root);if(e.length===0)return[];let n=new Ce(t.root),r=[];for(let s of e)for(let o of n.held(s))r.push({key:`memory:${s}/${o.id}`,kind:"memory",title:`Fact ${s} learned from ${o.source.channel}`,ask:`Let ${s} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:s,created_at:o.createdAt,detail:D(o.content),more:`agentx memory facts held --agent ${s}`});return r}function ni(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 ri(t){return kn(Xe(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:D(`${ni(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function si(t){return Yn(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:D(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function oi(t){return In(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:D(`Last try not sent: ${e.error}`)}:{}}))}function ii(t){let e=Object.entries(Ne(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=ge(t).agents??{};return e.map(([r,s])=>{let o=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${o.name||r}", created by ${s.by}`,ask:`Let ${o.name||r} (${o.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:s.by,created_at:s.at,detail:D(`Workspace: ${o.workspace||"?"}. Instructions: ${o.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function ge(t){try{return JSON.parse(ze(q(t),"utf-8"))}catch{return{}}}function He(t){let e={};try{e=Object.fromEntries(Zt(ze(E(Jo(q(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function ai(t){let e=bn(t.root,"pending");if(e.length===0)return[];let n=ge(t),r=He(t);return e.map(s=>{let o=K[s.platform]??s.platform;return{key:`content:${s.id}`,kind:"content",title:`${o} post${s.topic?`: ${s.topic}`:""}${s.date?` (for ${s.date})`:""}`,ask:`Publish this on ${o}? "${s.text}"`,yes:rr({config:n,env:r},s.agent,s.platform)?`post it on ${o}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:s.agent,created_at:s.created_at,detail:D(`Follows your past posts: ${s.samples.join(", ")}`),more:`agentx content show ${s.id}`,text_hash:mn(s.text)}})}function M(t){if(t.requests)return t.requests;if(E(t.root)!==process.cwd()||!Y(E(t.root,".agentx","db.sqlite")))return null;let e=Te({quiet:!0});if(!e)return null;let n=ar.get(e);return!n&&!zt(e)?null:(n||ar.set(e,n=new Xt(e)),n)}var ar=new WeakMap;function Vu(t){if(t.plans)return t.plans;if(t.requests||E(t.root)!==process.cwd()||!Y(E(t.root,".agentx","db.sqlite")))return null;let e=Te({quiet:!0});if(!e||!ir(e))return null;let n=lr.get(e);return n||lr.set(e,n=new pe(e)),n}var lr=new WeakMap;function li(t){let e=M(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:P(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:D(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var dr={card:Zo,schedule:ei,agent:ii,memory:ti,wiki:ri,whatsapp:si,email:oi,content:ai,request:li};function ci(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 pr(t,e={}){let n=t.now??Date.now(),{snoozed:r}=$(t.root),s=[],o=[],i=0;for(let a of e.kinds??cr){let l;try{l=dr[a](t)}catch(u){o.push({kind:a,error:String(u?.message??u).slice(0,200)});continue}for(let u of l){let c=r[u.key];if(c&&Date.parse(c)>n){if(!e.includeSnoozed){i++;continue}u.snoozed_until=c}s.push(u)}}return s.sort(ci),{items:s,snoozed:i,errors:o}}function ui(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!cr.includes(n)||!r?null:{kind:n,ref:r}}function di(t,e,n){switch(e){case"card":return G(t.root,n)?.status==="pending";case"wiki":return wn(Xe(t),n)?.status==="pending";case"whatsapp":return de(t.root,n)?.status==="pending";case"email":return An(t.root,n)?.status==="pending";case"content":return hn(t.root,n)?.status==="pending";default:return dr[e](t).some(r=>r.key===`${e}:${n}`)}}async function gr(t,e,n,r={}){let s=ui(e);if(!s)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:o,ref:i}=s,a=t.now??Date.now(),l=r.by??"operator";if(n==="later"){if(!di(t,o,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,d=new Date(a+c*36e5);return qn(t.root,e,d,a),{ok:!0,message:`${e} put off until ${d.toISOString()}`}}let u=n==="yes";switch(o){case"card":{let c=Rn(t.root,i,u?"yes":"no",{by:l,note:r.note,now:a,choice:r.choice,text:r.text});return c.ok?{ok:!0,message:`${e}: ${c.card.raised_by} will be told ${u?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(u?cn:un)(i,{configPath:q(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(Ne(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(u)return Le(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=[],d=await ae(p=>{en(p,`agents.${i}`);for(let[g,f]of Object.entries(p.crons??{}))f?.agent===i&&(delete p.crons[g],c.push(g))},{configPath:q(t),reload:t.reload});return d.success?(Le(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:d.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 d=i.slice(0,c),p=i.slice(c+1);if(!ur(t.root).includes(d))return{ok:!1,error:`no memory for agent "${d}"`};let g=new Ce(t.root);return g.held(d).some(f=>f.id===p)?(g.review(d,p,u?"approved":"rejected",l),{ok:!0,message:`${e} ${u?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let c=Xe(t),d=u?Sn(c,i,{by:l,force:r.force,now:a}):xn(c,i,{by:l,reason:r.note,now:a});return d.ok?{ok:!0,message:u?`${d.proposal.article.path} written to the shared wiki`:`${e} rejected`}:d}case"whatsapp":{let c=await Zn(t.root,i,u?"yes":"no",{by:l,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:u?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Dn(ge(t),He(t)),d=await Tn(t.root,i,u?"yes":"no",{by:l,now:a,text:r.text,send:c});return d.ok?{ok:!0,message:u?`${e}: sent to ${d.draft.to}${d.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:d}case"content":{let c=t.publishContent??sr({config:ge(t),env:He(t)}),d=await yn(t.root,i,u?"yes":"no",{by:l,now:a,text:r.text,seen:r.seen,publish:c});if(!d.ok)return d;if(!u)return{ok:!0,message:`${e}: dropped, nothing published`};let p=K[d.draft.platform];return{ok:!0,message:d.draft.status==="posted"?`${e}: posted on ${p}${d.draft.url?` (${d.draft.url})`:""}`:`${e}: no ${p} connector is set, so it is saved ready to paste: ${d.draft.file}`}}case"request":{let c=M(t),d=c?.get(i);return!c||!d||d.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:u?Bn(q(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${d.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${l}`,a),{ok:!0,message:`${e}: dropped`})}}}var pi=3,gi=7,fi=50,Ge=120,mi=280,Ke=600,mr=36e5,hi=24*mr;function zu(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 V(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var fe=t=>new Date(t).toISOString();function bi(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:V(e.title,Ge),...e.ask?{ask:V(e.ask,Ke)}:{},...e.detail?{facts:V(e.detail,mi)}:{},...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 yi={done:"Done",declined:"Declined",dropped:"Dropped"};function hr(t,e,n){let{record:r,links:s}=e,o=P(r,Ge),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:o.headline,need:o.need,...r.headline?{said:V(o.said,Ke)}:{},agent:r.agentId,askedAt:fe(r.createdAt),changedAt:fe(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return s.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:V(r.question,Ke)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=s.some(u=>u.kind==="run"&&!!t.liveRuns?.has(u.ref)),l=t.now-r.updatedAt<(t.quietHours??pi)*mr;return{...i,column:a||l?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:fe(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:yi[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function wi(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 ki(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:V(e.title,Ge),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:wi(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var _=t=>t&&Date.parse(t)||0,fr=(t,e)=>t.map(n=>n[e]).filter(n=>!!_(n)).sort((n,r)=>_(n)-_(r))[0];function Je(t){let e=[],n=[];for(let s of t.inbox){s.error&&n.push(`What waits on ${s.nodeName} could not be read: ${s.error}`);for(let o of s.items)e.push(bi(s,o,s.node===t.node))}let r=br(t,e);for(let s of t.requests??[]){let o=hr(t,s,r);o?.column==="yours"&&e.push(o)}return{cards:e,errors:n}}function br(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Xu(t){let e=Je(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,s=br(t,n),o=[],i=[],a=[];for(let p of t.requests??[]){let g=hr(t,p,s);g&&g.column!=="yours"&&{agent:o,quiet:i,done:a}[g.column].push(g)}let l=t.now-(t.doneDays??gi)*hi;for(let p of t.cards)p.status!=="pending"&&_(p.decided_at)>=l&&a.push(ki(t,p));o.sort((p,g)=>_(g.changedAt)-_(p.changedAt)),i.sort((p,g)=>_(p.changedAt)-_(g.changedAt)),a.sort((p,g)=>_(g.changedAt)-_(p.changedAt));let u=a.filter(p=>_(p.changedAt)>=l).slice(0,fi),c=fr(n,"askedAt"),d=fr(i,"changedAt");return{ts:fe(t.now),cards:[...n,...o,...i,...u],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:o.length},quiet:{count:i.length,...d?{oldest:d}:{}},done:{count:u.length}},errors:r}}function Si(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 xi(t,e,n){let r=t.map(s=>s.askedAt).filter(s=>!!s&&!!Date.parse(s)).sort((s,o)=>Date.parse(s)-Date.parse(o));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function Yu(t,e){let n=t.now??Date.now(),r=[],s=pr(t,{includeSnoozed:!0});for(let c of s.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let o=s.items.filter(c=>!c.snoozed_until),i=new Set(s.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=M(t);c&&(a=c.listByState("waiting_owner").map(d=>({record:d,links:c.links(d.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:l,errors:u}=Je({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:o.map(Si)}],requests:a,deferred:i});return xi(l,i.size,[...r,...u])}import{readFileSync as vi}from"fs";var $i=1e4,yr=/^[0-9a-f]{7,64}$/i;function ed(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&yr.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($i)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let s=await r.json().catch(()=>null),o=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,s);return typeof o=="string"&&yr.test(o.trim())?{source:n,commit:o.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function td(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=vi(n.tokenFile,"utf-8").trim().split(`
58
- `)[0].trim()||void 0}catch{}let s=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??s?.host??"https://gitlab.com",token:e?.gitlab?.token??s?.token}}}var wr=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function rd(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||t==="/content"||t.startsWith("/content/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"}function sd(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 od(t){return wr.has(t)}function id(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(wr.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 ad(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 ld(t,e,n=process.env){let r=o=>o.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(o=>r(o.url)===e)?.token)||n.MESH_TOKEN||void 0}function me(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Ei(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function _i(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function ud(t,e=_i()){let n=me(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let s=Ei(n),o=[me(t.host),me(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return s&&o.includes(s)?"same-origin":"foreign"}let r=me(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function dd(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{existsSync as Br,mkdirSync as ta,readFileSync as na,renameSync as ra,writeFileSync as sa}from"fs";import{homedir as oa}from"os";import{dirname as ia,join as aa}from"path";import{execFile as Mi,execFileSync as Ui}from"child_process";import{execFileSync as Ri}from"child_process";import{existsSync as Sr,mkdirSync as Ai,readdirSync as Ii,readFileSync as xr,renameSync as Ti,writeFileSync as Di}from"fs";import{homedir as vr}from"os";import{join as Ze}from"path";var R="siri:",$r="com.apple.ttsbundle.gryphon-neural_",Er=t=>!!t&&t.startsWith($r),Ci=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],Ni=()=>{try{return Ri("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},Ye;function Qe(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&Ye!==void 0)return Ye;let{platform:n=process.platform,exists:r=Sr,prefDomain:s=Ni}=t,o=n==="darwin"&&Ci.every(i=>r(i))&&s();return e||(Ye=o),o}var _r=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Rr={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},et=t=>Rr[t.toLowerCase()]??null;function he(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 Li=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function Oi(t){let e=new Map;for(let n of t)for(let[,r,s,o]of n.matchAll(Li)){let i=`${r}-${s}`,a=`${$r}${o}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:o[0].toUpperCase()+o.slice(1),locale:i,quality:"premium",gender:Rr[o]??null,siri:!0})}return[...e.values()]}function be(t=_r,e={}){if(!Qe(e))return[];let n=[];for(let r of t){let s;try{s=Ii(r)}catch{continue}for(let o of s)try{n.push(xr(Ze(r,o,"Info.plist"),"latin1"))}catch{}}return Oi(n)}var kr=`#!/bin/sh
57
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{o.run(e,n,s),r.forEach((a,l)=>{let u=l===0,c=u&&a.agentId===n&&a.kind!=="message";i.run(e,l+1,a.name,a.kind,a.agentId,a.doneWhen,u?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,c?s:null,s)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,s)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?He(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(ar)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?ar(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(He)}updateStep(e,n,r){let s=[],o=[];for(let[i,a]of Object.entries(r)){let l=Yo[i];!l||a===void 0||(s.push(`${l} = ?`),o.push(typeof a=="boolean"?a?1:0:a))}s.length&&this.db.prepare(`UPDATE request_plan_steps SET ${s.join(", ")} WHERE request_id = ? AND idx = ?`).run(...o,e,n)}finish(e,n,r){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,r,e).changes>0}markNotified(e,n){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(n,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(He)}event(e,n,r,s,o){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,o,r,s.replace(/\s+/g," ").trim().slice(0,Go))}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at, rowid LIMIT ?").all(e,n).map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}},vu=Xt;var dr=["card","schedule","agent","memory","wiki","whatsapp","email","content","request"],ei=280;function D(t,e=ei){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function q(t){if(t.configPath)return E(t.configPath);let e=[E(t.root,"agentx.json"),E(t.root,".agentx","config.json")];return e.find(n=>Y(n))??e[0]}function Ke(t){return t.wikiDir?E(t.wikiDir):E(t.root,".agentx","wiki")}function ti(t){return j(t.root,"pending").map(ni)}function ni(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:D([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function ri(t){let e=q(t);if(!Y(e))return[];let n;try{n=JSON.parse(Xe(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),s=[];for(let[o,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let l=i.timezone||"UTC",u=i.schedule?ln(i.schedule):"",c=i.schedule?`${u.charAt(0).toLowerCase()}${u.slice(1)} (${i.schedule})`:"no schedule",d=String(i.prompt??i.command??""),p=a.action==="create";s.push({key:`schedule:${o}`,kind:"schedule",title:p?`New schedule "${o}" for ${i.agent??"an agent"}`:`Delete schedule "${o}"`,ask:p?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${o}" (${c})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:D(`${d}${p&&i.schedule?` \xB7 first run ${un(cn(i.schedule,l,r),l)}`:""}`),more:"agentx schedule list"})}return s}function pr(t){let e=E(t,".agentx","memory");return Y(e)?Zo(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function si(t){let e=pr(t.root);if(e.length===0)return[];let n=new Ne(t.root),r=[];for(let s of e)for(let o of n.held(s))r.push({key:`memory:${s}/${o.id}`,kind:"memory",title:`Fact ${s} learned from ${o.source.channel}`,ask:`Let ${s} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:s,created_at:o.createdAt,detail:D(o.content),more:`agentx memory facts held --agent ${s}`});return r}function oi(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 ii(t){return xn(Ke(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:D(`${oi(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function ai(t){return Qn(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:D(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function li(t){return Dn(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:D(`Last try not sent: ${e.error}`)}:{}}))}function ci(t){let e=Object.entries(Le(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=ge(t).agents??{};return e.map(([r,s])=>{let o=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${o.name||r}", created by ${s.by}`,ask:`Let ${o.name||r} (${o.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:s.by,created_at:s.at,detail:D(`Workspace: ${o.workspace||"?"}. Instructions: ${o.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function ge(t){try{return JSON.parse(Xe(q(t),"utf-8"))}catch{return{}}}function ze(t){let e={};try{e=Object.fromEntries(en(Xe(E(Qo(q(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function ui(t){let e=wn(t.root,"pending");if(e.length===0)return[];let n=ge(t),r=ze(t);return e.map(s=>{let o=K[s.platform]??s.platform;return{key:`content:${s.id}`,kind:"content",title:`${o} post${s.topic?`: ${s.topic}`:""}${s.date?` (for ${s.date})`:""}`,ask:`Publish this on ${o}? "${s.text}"`,yes:or({config:n,env:r},s.agent,s.platform)?`post it on ${o}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:s.agent,created_at:s.created_at,detail:D(`Follows your past posts: ${s.samples.join(", ")}`),more:`agentx content show ${s.id}`,text_hash:bn(s.text)}})}function M(t){if(t.requests)return t.requests;if(E(t.root)!==process.cwd()||!Y(E(t.root,".agentx","db.sqlite")))return null;let e=De({quiet:!0});if(!e)return null;let n=cr.get(e);return!n&&!Kt(e)?null:(n||cr.set(e,n=new Gt(e)),n)}var cr=new WeakMap;function zu(t){if(t.plans)return t.plans;if(t.requests||E(t.root)!==process.cwd()||!Y(E(t.root,".agentx","db.sqlite")))return null;let e=De({quiet:!0});if(!e||!lr(e))return null;let n=ur.get(e);return n||ur.set(e,n=new pe(e)),n}var ur=new WeakMap;function di(t){let e=M(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:P(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:D(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var gr={card:ti,schedule:ri,agent:ci,memory:si,wiki:ii,whatsapp:ai,email:li,content:ui,request:di};function pi(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 fr(t,e={}){let n=t.now??Date.now(),{snoozed:r}=$(t.root),s=[],o=[],i=0;for(let a of e.kinds??dr){let l;try{l=gr[a](t)}catch(u){o.push({kind:a,error:String(u?.message??u).slice(0,200)});continue}for(let u of l){let c=r[u.key];if(c&&Date.parse(c)>n){if(!e.includeSnoozed){i++;continue}u.snoozed_until=c}s.push(u)}}return s.sort(pi),{items:s,snoozed:i,errors:o}}function gi(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!dr.includes(n)||!r?null:{kind:n,ref:r}}function fi(t,e,n){switch(e){case"card":return G(t.root,n)?.status==="pending";case"wiki":return Sn(Ke(t),n)?.status==="pending";case"whatsapp":return de(t.root,n)?.status==="pending";case"email":return Tn(t.root,n)?.status==="pending";case"content":return yn(t.root,n)?.status==="pending";default:return gr[e](t).some(r=>r.key===`${e}:${n}`)}}async function mr(t,e,n,r={}){let s=gi(e);if(!s)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:o,ref:i}=s,a=t.now??Date.now(),l=r.by??"operator";if(n==="later"){if(!fi(t,o,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,d=new Date(a+c*36e5);return Bn(t.root,e,d,a),{ok:!0,message:`${e} put off until ${d.toISOString()}`}}let u=n==="yes";switch(o){case"card":{let c=In(t.root,i,u?"yes":"no",{by:l,note:r.note,now:a,choice:r.choice,text:r.text});return c.ok?{ok:!0,message:`${e}: ${c.card.raised_by} will be told ${u?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(u?dn:pn)(i,{configPath:q(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(Le(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(u)return Oe(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=[],d=await ae(p=>{nn(p,`agents.${i}`);for(let[g,f]of Object.entries(p.crons??{}))f?.agent===i&&(delete p.crons[g],c.push(g))},{configPath:q(t),reload:t.reload});return d.success?(Oe(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:d.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 d=i.slice(0,c),p=i.slice(c+1);if(!pr(t.root).includes(d))return{ok:!1,error:`no memory for agent "${d}"`};let g=new Ne(t.root);return g.held(d).some(f=>f.id===p)?(g.review(d,p,u?"approved":"rejected",l),{ok:!0,message:`${e} ${u?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let c=Ke(t),d=u?vn(c,i,{by:l,force:r.force,now:a}):$n(c,i,{by:l,reason:r.note,now:a});return d.ok?{ok:!0,message:u?`${d.proposal.article.path} written to the shared wiki`:`${e} rejected`}:d}case"whatsapp":{let c=await er(t.root,i,u?"yes":"no",{by:l,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:u?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Nn(ge(t),ze(t)),d=await Cn(t.root,i,u?"yes":"no",{by:l,now:a,text:r.text,send:c});return d.ok?{ok:!0,message:u?`${e}: sent to ${d.draft.to}${d.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:d}case"content":{let c=t.publishContent??ir({config:ge(t),env:ze(t)}),d=await kn(t.root,i,u?"yes":"no",{by:l,now:a,text:r.text,seen:r.seen,publish:c});if(!d.ok)return d;if(!u)return{ok:!0,message:`${e}: dropped, nothing published`};let p=K[d.draft.platform];return{ok:!0,message:d.draft.status==="posted"?`${e}: posted on ${p}${d.draft.url?` (${d.draft.url})`:""}`:`${e}: no ${p} connector is set, so it is saved ready to paste: ${d.draft.file}`}}case"request":{let c=M(t),d=c?.get(i);return!c||!d||d.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:u?zn(q(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${d.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${l}`,a),{ok:!0,message:`${e}: dropped`})}}}var mi=3,hi=7,bi=50,Je=120,yi=280,Ge=600,br=36e5,wi=24*br;function Gu(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 V(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var fe=t=>new Date(t).toISOString();function ki(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:V(e.title,Je),...e.ask?{ask:V(e.ask,Ge)}:{},...e.detail?{facts:V(e.detail,yi)}:{},...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 Si={done:"Done",declined:"Declined",dropped:"Dropped"};function yr(t,e,n){let{record:r,links:s}=e,o=P(r,Je),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:o.headline,need:o.need,...r.headline?{said:V(o.said,Ge)}:{},agent:r.agentId,askedAt:fe(r.createdAt),changedAt:fe(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return s.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:V(r.question,Ge)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=s.some(u=>u.kind==="run"&&!!t.liveRuns?.has(u.ref)),l=t.now-r.updatedAt<(t.quietHours??mi)*br;return{...i,column:a||l?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:fe(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Si[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function xi(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 vi(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:V(e.title,Je),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:xi(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var R=t=>t&&Date.parse(t)||0,hr=(t,e)=>t.map(n=>n[e]).filter(n=>!!R(n)).sort((n,r)=>R(n)-R(r))[0];function Ye(t){let e=[],n=[];for(let s of t.inbox){s.error&&n.push(`What waits on ${s.nodeName} could not be read: ${s.error}`);for(let o of s.items)e.push(ki(s,o,s.node===t.node))}let r=wr(t,e);for(let s of t.requests??[]){let o=yr(t,s,r);o?.column==="yours"&&e.push(o)}return{cards:e,errors:n}}function wr(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Ju(t){let e=Ye(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,s=wr(t,n),o=[],i=[],a=[];for(let p of t.requests??[]){let g=yr(t,p,s);g&&g.column!=="yours"&&{agent:o,quiet:i,done:a}[g.column].push(g)}let l=t.now-(t.doneDays??hi)*wi;for(let p of t.cards)p.status!=="pending"&&R(p.decided_at)>=l&&a.push(vi(t,p));o.sort((p,g)=>R(g.changedAt)-R(p.changedAt)),i.sort((p,g)=>R(p.changedAt)-R(g.changedAt)),a.sort((p,g)=>R(g.changedAt)-R(p.changedAt));let u=a.filter(p=>R(p.changedAt)>=l).slice(0,bi),c=hr(n,"askedAt"),d=hr(i,"changedAt");return{ts:fe(t.now),cards:[...n,...o,...i,...u],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:o.length},quiet:{count:i.length,...d?{oldest:d}:{}},done:{count:u.length}},errors:r}}function $i(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 Ei(t,e,n){let r=t.map(s=>s.askedAt).filter(s=>!!s&&!!Date.parse(s)).sort((s,o)=>Date.parse(s)-Date.parse(o));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function ed(t,e){let n=t.now??Date.now(),r=[],s=fr(t,{includeSnoozed:!0});for(let c of s.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let o=s.items.filter(c=>!c.snoozed_until),i=new Set(s.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=M(t);c&&(a=c.listByState("waiting_owner").map(d=>({record:d,links:c.links(d.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:l,errors:u}=Ye({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:o.map($i)}],requests:a,deferred:i});return Ei(l,i.size,[...r,...u])}import{readFileSync as Ri}from"fs";var _i=1e4,kr=/^[0-9a-f]{7,64}$/i;function rd(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&kr.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(_i)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let s=await r.json().catch(()=>null),o=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,s);return typeof o=="string"&&kr.test(o.trim())?{source:n,commit:o.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function sd(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Ri(n.tokenFile,"utf-8").trim().split(`
58
+ `)[0].trim()||void 0}catch{}let s=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??s?.host??"https://gitlab.com",token:e?.gitlab?.token??s?.token}}}var Sr=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function id(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||t==="/content"||t.startsWith("/content/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"}function ad(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 ld(t){return Sr.has(t)}function cd(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Sr.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 ud(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 dd(t,e,n=process.env){let r=o=>o.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(o=>r(o.url)===e)?.token)||n.MESH_TOKEN||void 0}function me(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Ai(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ii(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function gd(t,e=Ii()){let n=me(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let s=Ai(n),o=[me(t.host),me(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return s&&o.includes(s)?"same-origin":"foreign"}let r=me(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function fd(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{existsSync as zr,mkdirSync as sa,readFileSync as oa,renameSync as ia,writeFileSync as aa}from"fs";import{homedir as la}from"os";import{dirname as ca,join as ua}from"path";import{execFile as Wi,execFileSync as ji}from"child_process";import{execFileSync as Ti}from"child_process";import{existsSync as vr,mkdirSync as Di,readdirSync as Ci,readFileSync as $r,renameSync as Ni,writeFileSync as Li}from"fs";import{homedir as Er}from"os";import{join as Qe}from"path";var _="siri:",Rr="com.apple.ttsbundle.gryphon-neural_",_r=t=>!!t&&t.startsWith(Rr),Oi=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],Pi=()=>{try{return Ti("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},Ze;function et(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&Ze!==void 0)return Ze;let{platform:n=process.platform,exists:r=vr,prefDomain:s=Pi}=t,o=n==="darwin"&&Oi.every(i=>r(i))&&s();return e||(Ze=o),o}var Ar=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Ir={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"},tt=t=>Ir[t.toLowerCase()]??null;function he(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 Mi=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function Ui(t){let e=new Map;for(let n of t)for(let[,r,s,o]of n.matchAll(Mi)){let i=`${r}-${s}`,a=`${Rr}${o}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:o[0].toUpperCase()+o.slice(1),locale:i,quality:"premium",gender:Ir[o]??null,siri:!0})}return[...e.values()]}function be(t=Ar,e={}){if(!et(e))return[];let n=[];for(let r of t){let s;try{s=Ci(r)}catch{continue}for(let o of s)try{n.push($r(Qe(r,o,"Info.plist"),"latin1"))}catch{}}return Ui(n)}var xr=`#!/bin/sh
59
59
  # Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
60
60
  # siri-say.sh [voice] < text speak one line. A Siri voice id switches
61
61
  # the OS default for it; any other id is
@@ -67,7 +67,7 @@ D=com.apple.Accessibility K=SpokenContentDefaultVoiceSelectionsByLanguage
67
67
  dir="$HOME/.agentx/voice" lock="$HOME/.agentx/voice/siri.lock" saved="$HOME/.agentx/voice/siri-saved.plist"
68
68
  stops="$dir/stop"
69
69
  read_s=\${AGENTX_SAY_READ_S:-5} stale_s=\${AGENTX_SAY_STALE_S:-30} max_s=\${AGENTX_SAY_MAX_S:-300}
70
- assets=\${AGENTX_SIRI_ASSET_DIRS:-"${_r.join(" ")}"}
70
+ assets=\${AGENTX_SIRI_ASSET_DIRS:-"${Ar.join(" ")}"}
71
71
  if [ "$1" = --stop ]; then
72
72
  mkdir -p "$dir" || exit 1
73
73
  # Queued lines see this change and drop. The owner's trap stops say,
@@ -160,29 +160,29 @@ wait "$say_pid"
160
160
  status=$?
161
161
  say_pid=
162
162
  finish $status
163
- `,Pi=(t=vr())=>Ze(t,".agentx","voice","siri-say.sh");function Ar(t=vr()){let e=Pi(t);return Sr(e)&&xr(e,"utf8")===kr||(Ai(Ze(t,".agentx","voice"),{recursive:!0}),Di(`${e}.tmp`,kr,{mode:493}),Ti(`${e}.tmp`,e)),e}var Ir=`ObjC.import("AVFoundation")
163
+ `,Fi=(t=Er())=>Qe(t,".agentx","voice","siri-say.sh");function Tr(t=Er()){let e=Fi(t);return vr(e)&&$r(e,"utf8")===xr||(Di(Qe(t,".agentx","voice"),{recursive:!0}),Li(`${e}.tmp`,xr,{mode:493}),Ni(`${e}.tmp`,e)),e}var Dr=`ObjC.import("AVFoundation")
164
164
  const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
165
165
  for (let i = 0; i < vs.count; i++) {
166
166
  const v = vs.objectAtIndex(i)
167
167
  out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
168
168
  }
169
- out.join("\\n")`,Fi=new Set(["Fred","Kathy","Ralph","Junior"]),Wi={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 Tr(t){let e=[];for(let n of t.split(`
170
- `)){let[r,s,o,i,a]=n.split(" ");!r||!s||!o||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!Fi.has(s)||e.push({id:r,name:s,locale:o,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":Wi[s]??null})}return e}var ji=10*60*1e3,kd=60*1e3,B=null,tt=!1;function nt(t=Date.now(),e=ji){if(process.platform!=="darwin")return[];if(B)t-B.at>e&&!tt&&(tt=!0,Mi("osascript",["-l","JavaScript","-e",Ir],{timeout:1e4},(n,r)=>{tt=!1,n||(B={at:Date.now(),voices:[...Tr(String(r)),...be()]})}));else try{B={at:t,voices:[...Tr(Ui("osascript",["-l","JavaScript","-e",Ir],{encoding:"utf8",timeout:1e4})),...be()]}}catch(n){rt(`[voice] could not list system voices: ${String(n?.message??n).split(`
171
- `)[0]}`),B={at:t,voices:be()}}return B.voices}var rt=t=>process.stderr.write(t+`
172
- `),ye=new Set;function Sd(t){rt=t}function U(t,e){ye.has(t)||(ye.add(t),rt(e))}function Nr(t){for(let e of ye)t(e)&&ye.delete(e)}var Lr=()=>{};function xd(t){Lr=t}function Or(t){try{Lr(t)}catch(e){U("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var qi={premium:3,enhanced:2,standard:1},Vi=new Set(["Grandma","Grandpa"]);function Dr(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!Vi.has(t.name)?1:0;return qi[t.quality]*10+e}var H=t=>t.toLowerCase().split(/[-_]/)[0],Cr=t=>t.id.startsWith("com.apple.voice.");function st(t,e,n,r=new Set){let s=Z(t.filter(a=>!a.siri&&H(a.locale)===H(e)),e);if(s.some(Cr)&&(s=s.filter(Cr)),n==="female"||n==="male"){let a=s.filter(l=>l.gender===n);a.length&&(s=a)}if(!s.length)return null;let o=s.filter(a=>a.quality===s[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return o.find(a=>!i.has(a.name.toLowerCase()))??o[0]}function Z(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=H(e),s=t.filter(o=>H(o.locale)===r);return(s.length?s:t).slice().sort((o,i)=>Dr(i)-Dr(o)||+(i.locale.toLowerCase()===n)-+(o.locale.toLowerCase()===n)||o.name.localeCompare(i.name)||o.locale.localeCompare(i.locale))}function Q(t,e,n="en"){let r=t.trim();if(!r)return null;let s=e.find(u=>u.id===r);if(s)return s;if(r.toLowerCase().startsWith(R)){let u=r.slice(R.length).trim().toLowerCase(),c=Z(e.filter(p=>p.siri&&p.name.toLowerCase()===u),n)[0];if(c||!u)return c??null;let d=Q(u,e.filter(p=>H(p.locale)===H(n)),n);return d&&U(`siri:${u}`,`[voice] Siri voice "${u}" is not installed; speaking with ${d.name} (${d.locale}) instead.`),d}e=e.filter(u=>!u.siri);let o=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(o?o[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=Z(e.filter(u=>u.name.toLowerCase()===i),n);return(o?a.find(u=>u.quality===o[2].toLowerCase()):void 0)??a[0]??null}function Pr(t,e,n=new Set){let r=new Map;if(!e.length)return r;let s=new Set([...n].map(i=>i.toLowerCase())),o="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",l=a?i.gender:o,u=e.filter(d=>!s.has(d.name.toLowerCase())),c=u.find(d=>d.gender===l)??(a?e.find(d=>d.gender===l):void 0)??u[0]??e[r.size%e.length];r.set(i.id,c),s.add(c.name.toLowerCase()),a||(o=o==="female"?"male":"female")}return r}Vt();var ot="system",Bi=t=>t.trim().toLowerCase()===ot,Hi="21m00Tcm4TlvDq8ikWAM";function it(t,e,n={},r=nt()){let s=e[t],o=s?.name||t,i=s?.voice,a=lt(e,n,r).get(t)??null,l=Gi(t,i?.system,i?.gender,n,r);return{agentId:t,name:o,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?ke(a):null,systemByLanguage:l,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||Yi(o,s?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var ke=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function zi(t,e,n,r){if(!e||!n.length)return null;let s=Q(e,n,r);return s||(U(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Or(e)),s}function Wr(t,e){let n=t.trim();if(n.toLowerCase().startsWith(R))return{locale:e,gender:et(n.slice(R.length).trim())};let r=he(n);return r?{locale:r.locale,gender:et(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var jr=t=>t.toLowerCase().split(/[-_]/)[0],Mr=(t,e)=>typeof t=="string"?t:t?.[jr(e)];function we(t,e,n,r){if(e!==void 0)return Bi(e)?null:zi(t,e,n,r)??void 0}var at=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function Xi(t,e,n,r=new Set){let s=e.locale??"en",o=new Map,i=[],a=we("voice.system",Mr(e.system,s),n,s),l=()=>new Set([...r,...[...o.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let d=Mr(c.system,s),p=we(c.id,d,n,s),g=p!==void 0?p:d!==void 0&&n.length?Ki(c,d,s,a,n,l()):a!==void 0&&at(a,c.gender)?a:void 0;g!==void 0?o.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let u=l();for(let[c,d]of Pr(i,Z(n.filter(p=>!p.siri),s),u))o.set(c,d);return o}function Ki(t,e,n,r,s,o){for(let a of t.fallbacks??[]){let l=we(`${t.id}.fallbacks`,a,s,n);if(l!==void 0)return l}if(r!==void 0&&at(r,t.gender))return r;let i=Wr(e,n);return st(s,i.locale,t.gender??i.gender,o)??void 0}function Gi(t,e,n,r,s){if(typeof e=="string")return{};let o={},i=(a,l,u)=>{if(!(!l||typeof l=="string"))for(let[c,d]of Object.entries(l)){let p=we(`${a}.${c}`,d,s,c);p===void 0&&s.length&&(p=st(s,c,n??Wr(d,c).gender)??void 0),p!==void 0&&u(p)&&(o[jr(c)]=p)}};return i("voice.system",r.system,a=>at(a,n)),i(t,e,()=>!0),o}function Rd(t,e){let n=e?ie(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?ke(r):null}}function lt(t,e={},n=nt()){let r=Object.entries(t).map(([s,o])=>({id:s,system:o.voice?.system,gender:o.voice?.gender,fallbacks:o.voice?.fallbacks}));return Xi(r,e,n)}function ct(t,e){let n={provider:t.provider,elevenlabs:Ji(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([s,o])=>[s,o?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function Ji(t,e){return t||e||process.env.AGENTX_VOICE_ID||Hi}function Yi(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let s=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[o,...i]=s.split(/,\s*/),a=i.join(", ");return a&&o.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(s)&&s.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${s}.`:`Hello, this is ${t}, ${s}.`}var Zi=8*60*60*1e3,Qi=500,Ur=class{constructor(e=Zi){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let s=this.lastSpoke.get(Fr(e,n));return s===void 0||r-s>this.gapMs}spoke(e,n,r=Date.now()){let s=Fr(e,n);this.lastSpoke.delete(s),this.lastSpoke.set(s,r),this.lastSpoke.size>Qi&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},Fr=(t,e)=>`${t}\0${e}`;function qr(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 Ad(t,e,n,r={}){let s=e[t],o=it(t,e,r),i=(s?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:o.name,voice:ct(o),persona:i||`You are ${o.name}.`,introLine:qr(o,n)}}var ea="[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 Id(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=o=>typeof o=="string"?o.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),s={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:r||"Hello."};return`${ea}
173
- ${qr(s,e.voice.introduce===!0&&!!r)}`}var la="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Hr=(t=oa())=>aa(t,".agentx","voice","health.json");function ca(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===ot)return!0;if(r.toLowerCase().startsWith(R)){let s=r.slice(R.length).trim().toLowerCase();return e.some(o=>o.siri&&o.name.toLowerCase()===s)}return Q(r,e,n)!==null}function ua(t){let e=t.voice?.locale??"en",n=[],r=(s,o)=>{if(typeof o=="string")n.push({owner:s,name:o,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(o??{}))n.push({owner:s,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[s,o]of Object.entries(t.agents))(o.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(s,o.voice?.system);return n}function da(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:s,name:o,locale:i,perLanguage:a}of ua(t)){if(ca(o,e,i))continue;r??=lt(t.agents,t.voice,e);let l=n.get(o)??{voice:o,agents:[],speaksWith:{}};l.agents.includes(s)||l.agents.push(s);let u=r.get(s);s!=="voice.system"&&!a&&(l.speaksWith[s]=u?ke(u):"the OS default voice"),n.set(o,l)}return[...n.values()]}function ut(t){let e=he(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(R)){let n=t.slice(R.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function pa(t){let e=t.map(n=>{let r=n.agents.map(s=>n.speaksWith[s]?`${s} (now ${n.speaksWith[s]})`:s).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(`
169
+ out.join("\\n")`,qi=new Set(["Fred","Kathy","Ralph","Junior"]),Vi={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 Cr(t){let e=[];for(let n of t.split(`
170
+ `)){let[r,s,o,i,a]=n.split(" ");!r||!s||!o||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!qi.has(s)||e.push({id:r,name:s,locale:o,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":Vi[s]??null})}return e}var Bi=10*60*1e3,vd=60*1e3,B=null,nt=!1;function rt(t=Date.now(),e=Bi){if(process.platform!=="darwin")return[];if(B)t-B.at>e&&!nt&&(nt=!0,Wi("osascript",["-l","JavaScript","-e",Dr],{timeout:1e4},(n,r)=>{nt=!1,n||(B={at:Date.now(),voices:[...Cr(String(r)),...be()]})}));else try{B={at:t,voices:[...Cr(ji("osascript",["-l","JavaScript","-e",Dr],{encoding:"utf8",timeout:1e4})),...be()]}}catch(n){st(`[voice] could not list system voices: ${String(n?.message??n).split(`
171
+ `)[0]}`),B={at:t,voices:be()}}return B.voices}var st=t=>process.stderr.write(t+`
172
+ `),ye=new Set;function $d(t){st=t}function U(t,e){ye.has(t)||(ye.add(t),st(e))}function Or(t){for(let e of ye)t(e)&&ye.delete(e)}var Pr=()=>{};function Ed(t){Pr=t}function Mr(t){try{Pr(t)}catch(e){U("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var Hi={premium:3,enhanced:2,standard:1},zi=new Set(["Grandma","Grandpa"]);function Nr(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!zi.has(t.name)?1:0;return Hi[t.quality]*10+e}var H=t=>t.toLowerCase().split(/[-_]/)[0],Lr=t=>t.id.startsWith("com.apple.voice.");function ot(t,e,n,r=new Set){let s=Z(t.filter(a=>!a.siri&&H(a.locale)===H(e)),e);if(s.some(Lr)&&(s=s.filter(Lr)),n==="female"||n==="male"){let a=s.filter(l=>l.gender===n);a.length&&(s=a)}if(!s.length)return null;let o=s.filter(a=>a.quality===s[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return o.find(a=>!i.has(a.name.toLowerCase()))??o[0]}function Z(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=H(e),s=t.filter(o=>H(o.locale)===r);return(s.length?s:t).slice().sort((o,i)=>Nr(i)-Nr(o)||+(i.locale.toLowerCase()===n)-+(o.locale.toLowerCase()===n)||o.name.localeCompare(i.name)||o.locale.localeCompare(i.locale))}function Q(t,e,n="en"){let r=t.trim();if(!r)return null;let s=e.find(u=>u.id===r);if(s)return s;if(r.toLowerCase().startsWith(_)){let u=r.slice(_.length).trim().toLowerCase(),c=Z(e.filter(p=>p.siri&&p.name.toLowerCase()===u),n)[0];if(c||!u)return c??null;let d=Q(u,e.filter(p=>H(p.locale)===H(n)),n);return d&&U(`siri:${u}`,`[voice] Siri voice "${u}" is not installed; speaking with ${d.name} (${d.locale}) instead.`),d}e=e.filter(u=>!u.siri);let o=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(o?o[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=Z(e.filter(u=>u.name.toLowerCase()===i),n);return(o?a.find(u=>u.quality===o[2].toLowerCase()):void 0)??a[0]??null}function Ur(t,e,n=new Set){let r=new Map;if(!e.length)return r;let s=new Set([...n].map(i=>i.toLowerCase())),o="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",l=a?i.gender:o,u=e.filter(d=>!s.has(d.name.toLowerCase())),c=u.find(d=>d.gender===l)??(a?e.find(d=>d.gender===l):void 0)??u[0]??e[r.size%e.length];r.set(i.id,c),s.add(c.name.toLowerCase()),a||(o=o==="female"?"male":"female")}return r}Ht();var it="system",Xi=t=>t.trim().toLowerCase()===it,Ki="21m00Tcm4TlvDq8ikWAM";function at(t,e,n={},r=rt()){let s=e[t],o=s?.name||t,i=s?.voice,a=ct(e,n,r).get(t)??null,l=Zi(t,i?.system,i?.gender,n,r);return{agentId:t,name:o,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?ke(a):null,systemByLanguage:l,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||ea(o,s?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var ke=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function Gi(t,e,n,r){if(!e||!n.length)return null;let s=Q(e,n,r);return s||(U(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Mr(e)),s}function qr(t,e){let n=t.trim();if(n.toLowerCase().startsWith(_))return{locale:e,gender:tt(n.slice(_.length).trim())};let r=he(n);return r?{locale:r.locale,gender:tt(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var Vr=t=>t.toLowerCase().split(/[-_]/)[0],Fr=(t,e)=>typeof t=="string"?t:t?.[Vr(e)];function we(t,e,n,r){if(e!==void 0)return Xi(e)?null:Gi(t,e,n,r)??void 0}var lt=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function Ji(t,e,n,r=new Set){let s=e.locale??"en",o=new Map,i=[],a=we("voice.system",Fr(e.system,s),n,s),l=()=>new Set([...r,...[...o.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let d=Fr(c.system,s),p=we(c.id,d,n,s),g=p!==void 0?p:d!==void 0&&n.length?Yi(c,d,s,a,n,l()):a!==void 0&&lt(a,c.gender)?a:void 0;g!==void 0?o.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let u=l();for(let[c,d]of Ur(i,Z(n.filter(p=>!p.siri),s),u))o.set(c,d);return o}function Yi(t,e,n,r,s,o){for(let a of t.fallbacks??[]){let l=we(`${t.id}.fallbacks`,a,s,n);if(l!==void 0)return l}if(r!==void 0&&lt(r,t.gender))return r;let i=qr(e,n);return ot(s,i.locale,t.gender??i.gender,o)??void 0}function Zi(t,e,n,r,s){if(typeof e=="string")return{};let o={},i=(a,l,u)=>{if(!(!l||typeof l=="string"))for(let[c,d]of Object.entries(l)){let p=we(`${a}.${c}`,d,s,c);p===void 0&&s.length&&(p=ot(s,c,n??qr(d,c).gender)??void 0),p!==void 0&&u(p)&&(o[Vr(c)]=p)}};return i("voice.system",r.system,a=>lt(a,n)),i(t,e,()=>!0),o}function Td(t,e){let n=e?ie(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?ke(r):null}}function ct(t,e={},n=rt()){let r=Object.entries(t).map(([s,o])=>({id:s,system:o.voice?.system,gender:o.voice?.gender,fallbacks:o.voice?.fallbacks}));return Ji(r,e,n)}function ut(t,e){let n={provider:t.provider,elevenlabs:Qi(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([s,o])=>[s,o?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function Qi(t,e){return t||e||process.env.AGENTX_VOICE_ID||Ki}function ea(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let s=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[o,...i]=s.split(/,\s*/),a=i.join(", ");return a&&o.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(s)&&s.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${s}.`:`Hello, this is ${t}, ${s}.`}var ta=8*60*60*1e3,na=500,Wr=class{constructor(e=ta){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let s=this.lastSpoke.get(jr(e,n));return s===void 0||r-s>this.gapMs}spoke(e,n,r=Date.now()){let s=jr(e,n);this.lastSpoke.delete(s),this.lastSpoke.set(s,r),this.lastSpoke.size>na&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},jr=(t,e)=>`${t}\0${e}`;function Br(t,e){let n=t.style?` Your speaking manner: ${t.style}.`:"";return e?`[VOICE INTRO] This is your first spoken exchange with this person in a while. Open with one short sentence introducing yourself in your own manner, along the lines of "${t.intro}", then answer.${n}`:"[VOICE CASUAL] You have already introduced yourself in this voice conversation. Do not introduce yourself or greet again; talk casually, like a colleague in the same office."+n}function Dd(t,e,n,r={}){let s=e[t],o=at(t,e,r),i=(s?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:o.name,voice:ut(o),persona:i||`You are ${o.name}.`,introLine:Br(o,n)}}var ra="[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 Cd(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=o=>typeof o=="string"?o.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),s={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:r||"Hello."};return`${ra}
173
+ ${Br(s,e.voice.introduce===!0&&!!r)}`}var da="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Xr=(t=la())=>ua(t,".agentx","voice","health.json");function pa(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===it)return!0;if(r.toLowerCase().startsWith(_)){let s=r.slice(_.length).trim().toLowerCase();return e.some(o=>o.siri&&o.name.toLowerCase()===s)}return Q(r,e,n)!==null}function ga(t){let e=t.voice?.locale??"en",n=[],r=(s,o)=>{if(typeof o=="string")n.push({owner:s,name:o,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(o??{}))n.push({owner:s,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[s,o]of Object.entries(t.agents))(o.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(s,o.voice?.system);return n}function fa(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:s,name:o,locale:i,perLanguage:a}of ga(t)){if(pa(o,e,i))continue;r??=ct(t.agents,t.voice,e);let l=n.get(o)??{voice:o,agents:[],speaksWith:{}};l.agents.includes(s)||l.agents.push(s);let u=r.get(s);s!=="voice.system"&&!a&&(l.speaksWith[s]=u?ke(u):"the OS default voice"),n.set(o,l)}return[...n.values()]}function dt(t){let e=he(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(_)){let n=t.slice(_.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function ma(t){let e=t.map(n=>{let r=n.agents.map(s=>n.speaksWith[s]?`${s} (now ${n.speaksWith[s]})`:s).join(", ");return`\u2022 ${dt(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
174
174
  `)}
175
- Reinstall in ${la}. Agents switch back on their own once it is installed.`}}function ga(t=Hr()){if(!Br(t))return null;try{let e=JSON.parse(na(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function fa(t,e){ta(ia(t),{recursive:!0}),sa(`${t}.tmp`,JSON.stringify(e,null,2)+`
176
- `),ra(`${t}.tmp`,t)}var Vr=class{constructor(e){this.deps=e}running=!1;missingNow=!1;hasMissing(){return this.missingNow}async check(e,n,r=new Date){if(this.running||!n.length)return null;this.running=!0;try{let s=this.deps.file??Hr(),o=new Map((ga(s)?.missing??[]).map(d=>[d.voice,d])),i=da(e,n),a=i.map(d=>({...d,since:o.get(d.voice)?.since??r.toISOString(),...o.get(d.voice)?.notifiedAt?{notifiedAt:o.get(d.voice).notifiedAt}:{}})),l=[...o.keys()].filter(d=>!i.some(p=>p.voice===d));for(let d of l)this.deps.log(`[voice] ${ut(d)} is installed again; its agents speak with it again`);l.length&&Nr(d=>l.some(p=>d===p||d.endsWith(`:${p}`)));let u=a.filter(d=>!d.notifiedAt);if(u.length){let{title:d,message:p}=pa(u);try{await this.deps.notify(d,p);for(let g of u)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${u.map(g=>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(!Br(s)||JSON.stringify(a)!==JSON.stringify([...o.values()]))&&fa(s,c),c}finally{this.running=!1}}};import{readFileSync as pt,writeFileSync as Yr,existsSync as gt,readdirSync as $a,statSync as Ea}from"fs";import{resolve as ft,join as _a}from"path";import{existsSync as zr,mkdirSync as ma,readFileSync as ha,writeFileSync as Xr}from"fs";import{dirname as ba,resolve as Kr}from"path";import{z as h}from"zod";var ya=h.object({type:h.enum(["gitlab","github"]),host:h.string().optional(),project:h.string(),iid:h.number().int().positive(),url:h.string()}),wa=h.object({id:h.string(),title:h.string(),description:h.string().optional(),assignee:h.string().optional(),labels:h.array(h.string()).default([]),milestone:h.string().optional(),status:h.enum(["todo","doing","blocked","done"]).default("todo"),priority:h.number().int().optional(),estimatedSeconds:h.number().int().optional(),source:ya.optional(),importedAt:h.string().optional(),createdAt:h.string(),updatedAt:h.string(),blocker:h.string().optional(),doneNote:h.string().optional()}),ka=h.object({version:h.literal(1),items:h.array(wa).default([])}),Se=class{constructor(e){this.path=e}jsonPath(){return Kr(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Kr(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return zr(this.jsonPath())}load(){let e=this.jsonPath();if(!zr(e))return{version:1,items:[]};let n=ha(e,"utf-8");try{return ka.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();ma(ba(n),{recursive:!0}),Xr(n,JSON.stringify(e,null,2)+`
177
- `),Xr(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(n=>n.id===e)}add(e){let n=this.load();if(n.items.some(o=>o.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),s={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return n.items.push(s),this.save(n),s}addMany(e){let n=this.load(),r=new Set(n.items.map(i=>i.id)),s=new Date().toISOString(),o=[];for(let i of e){if(r.has(i.id))continue;let a={...i,labels:i.labels??[],status:i.status??"todo",createdAt:i.createdAt??s,updatedAt:s};n.items.push(a),o.push(a),r.add(a.id)}return o.length&&this.save(n),o}update(e,n){let r=this.load(),s=r.items.findIndex(i=>i.id===e);if(s<0)throw new Error(`backlog item ${e} not found`);let o={...r.items[s],...n,id:r.items[s].id,createdAt:r.items[s].createdAt,updatedAt:new Date().toISOString()};return r.items[s]=o,this.save(r),o}remove(e){let n=this.load(),r=n.items.length;return n.items=n.items.filter(s=>s.id!==e),n.items.length===r?!1:(this.save(n),!0)}toMarkdown(e){let n=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],r={doing:[],blocked:[],todo:[],done:[]};for(let o of e.items)r[o.status].push(o);let s=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[o,i]of s)if(r[o].length){n.push(`## ${i}`,"");for(let a of r[o]){let l=o==="done"?"x":" ",u=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",d=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${l}] ${u}${a.title}${c}${d}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
178
- `)}};function jd(t){return`${t.type}:${t.project}:${t.iid}`}function Gr(t,e,n){let r=[];if(e.type==="gitlab"){let s=n.channels.gitlab?.agentMappings??[];for(let o of t){let i=s.find(a=>a.agentId===o);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(o)}}else if(e.type==="github"){let s=n.channels.github?.agentMappings??[];for(let o of t){let i=s.find(a=>a.agentId===o);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(o)}}return r}async function dt(t,e,n,r=()=>{}){return t.source?Sa(t.source,e,n,r):{ok:!0,attempts:[]}}async function Sa(t,e,n,r=()=>{}){return t.type==="gitlab"?xa(t,e,n,r):t.type==="github"?va(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function xa(t,e,n,r){let s=n.channels.gitlab,o=s?.token,i=s?.host||(t.host?`https://${t.host}`:void 0);if(!o||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],l=async(g,f={})=>fetch(`${i}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":o,"Content-Type":"application/json",...f.headers||{}}}),u=encodeURIComponent(t.project),c;e.assigneeUsernames!==void 0&&(c=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let m=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":o}});if(!m.ok)return null;let b=await m.json();return Array.isArray(b)&&b[0]?.id?b[0].id:null}catch{return null}}))).filter(f=>typeof f=="number"));let d;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")d=0;else try{let g=await l(`/projects/${u}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let f=await g.json();Array.isArray(f)&&f[0]?.id&&(d=f[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.description=e.description),e.labels!==void 0&&(p.labels=e.labels.join(",")),e.addLabels?.length&&(p.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(p.remove_labels=e.removeLabels.join(",")),c!==void 0&&(p.assignee_ids=c),d!==void 0&&(p.milestone_id=d),e.state&&(p.state_event=e.state==="closed"?"close":"reopen"),Object.keys(p).length)try{let g=await l(`/projects/${u}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(p)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${f.slice(0,200)}`,url:t.url}}}catch(g){return a.push({kind:"PUT issue",ok:!1,error:g.message}),{ok:!1,attempts:a,error:g.message,url:t.url}}if(e.note)try{let g=await l(`/projects/${u}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function va(t,e,n,r){let o=n.channels.github?.token;if(!o)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(p,g={})=>fetch(`https://api.github.com${p}`,{...g,headers:{Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),l=t.project,u;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")u=null;else try{let p=await a(`/repos/${l}/milestones?state=all&per_page=100`);if(p.ok){let g=await p.json(),f=Array.isArray(g)?g.find(m=>m.title===e.milestoneTitle):null;f?.number&&(u=f.number)}}catch(p){r(`[backlog-sync] github milestone lookup failed: ${p.message}`)}let c;if(e.labels!==void 0)c=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let p=await a(`/repos/${l}/issues/${t.iid}`);if(p.ok){let g=await p.json(),f=Array.isArray(g.labels)?g.labels.map(b=>typeof b=="string"?b:b.name):[],m=new Set([...f,...e.addLabels??[]]);for(let b of e.removeLabels??[])m.delete(b);c=[...m]}}catch(p){r(`[backlog-sync] github label fetch failed: ${p.message}`)}if(c===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let d={};if(e.title!==void 0&&(d.title=e.title),e.description!==void 0&&(d.body=e.description),c!==void 0&&(d.labels=c),e.assigneeUsernames!==void 0&&(d.assignees=e.assigneeUsernames),u!==void 0&&(d.milestone=u),e.state&&(d.state=e.state),Object.keys(d).length)try{let p=await a(`/repos/${l}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(d)});if(i.push({kind:"PATCH issue",ok:p.ok,status:p.status}),!p.ok){let g=await p.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${p.status}: ${g.slice(0,200)}`,url:t.url}}}catch(p){return i.push({kind:"PATCH issue",ok:!1,error:p.message}),{ok:!1,attempts:i,error:p.message,url:t.url}}if(e.note)try{let p=await a(`/repos/${l}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:p.ok,status:p.status})}catch(p){i.push({kind:"POST comment",ok:!1,error:p.message})}return{ok:i.every(p=>p.ok),attempts:i,url:t.url}}var mt=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,xe=/@([a-z0-9_-]+)/i,Jr=/\[time:\s*([0-9hm\s]+)\]/i;function Ra(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 ht=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new Se(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=ft(process.cwd(),this.path);return gt(e)?pt(e,"utf-8").split(`
179
- `):[]}writeMd(e){let n=ft(process.cwd(),this.path);Yr(n,e.join(`
180
- `))}async listOpen(e){if(this.store.exists())return this.store.list().filter(o=>o.status!=="done"&&(!o.assignee||o.assignee.toLowerCase()===e.toLowerCase())).map(o=>this.toWorkItem(o));let n=this.readMd(),r=[];for(let s=0;s<n.length;s++){let o=n[s].match(mt);if(!o||o[2].toLowerCase()==="x")continue;let a=o[3],l=a.match(xe);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let u=a.match(Jr),c=a.replace(xe,"").replace(Jr,"").trim();r.push({id:`backlog:${s}`,title:c||`Task at line ${s+1}`,assignee:l?l[1]:void 0,estimatedSeconds:u?Ra(u[1]):void 0,priority:s})}return r}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let r=this.store.findById(n);if(!r)return;let s=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(s.source&&this.daemon){let o=Gr([s.assignee||e],s.source,this.daemon);dt(s,{assigneeUsernames:o,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(i=>this.log(`[backlog-sync] claim failed for ${n}: ${i?.message??i}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let l=this.store.update(e,a);if(l.source&&this.daemon){let u={};n.status==="done"?(u.addLabels=["Done"],u.removeLabels=["Doing"]):n.status==="blocked"&&(u.addLabels=["Blocked"]),n.note&&(u.note=n.note),Object.keys(u).length&&dt(l,u,this.daemon,this.log).catch(c=>this.log(`[backlog-sync] report failed for ${e}: ${c?.message??c}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let r=parseInt(e.slice(8),10),s=this.readMd(),o=s[r];if(!o)throw new Error(`backlog line ${r} missing`);if(!o.match(mt))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){s[r]=o.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";s.splice(r+1,0,a)}else n.status==="blocked"?s.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&s.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(s)}toWorkItem(e){let n={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},bt=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(gt(e))for(let r of $a(e)){let s=_a(e,r);Ea(s).isDirectory()?this.walk(s,n):r.endsWith(".md")&&n.push(s)}}async listOpen(e){let n=[];this.walk(ft(process.cwd(),this.root),n);let r=[];for(let s of n){let o=pt(s,"utf-8").split(`
181
- `);for(let i=0;i<o.length;i++){let a=o[i].match(mt);if(!a||a[2].toLowerCase()==="x")continue;let l=a[3].match(xe);!l||l[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${s}:${i}`,title:a[3].replace(xe,"").trim(),assignee:l[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),s=parseInt(r[r.length-1],10),o=r.slice(1,-1).join(":");if(!gt(o))return;let i=pt(o,"utf-8").split(`
182
- `);n.status==="done"&&i[s]&&(i[s]=i[s].replace(/- \[ \]/,"- [x]"),Yr(o,i.join(`
183
- `)))}},yt=class{constructor(e,n,r,s,o){this.host=e;this.token=n;this.projects=r;this.agentUsernames=s;this.log=o}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(s=>s.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,s=[],o;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(o=e.labels.map(u=>({name:u.name,color:u.color,text_color:u.text_color})),s=o.map(u=>u.name)):s=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(u=>({username:u.username,name:u.name,avatarUrl:u.avatar_url})),l=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:l?this.usernameToAgent(l)||l:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:s,labelDetails:o,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],s=this.projects.length?this.projects:["__ALL__"];for(let o of n)for(let i of s)try{let a=`assignee_username=${encodeURIComponent(o)}&state=opened&scope=all&per_page=20`,l=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,u=await this.api(l);for(let c of u){let d=this.mapIssue(c,i);d.assignee=e,r.push(d)}}catch(a){this.log(`[business] GitLab listOpen failed for ${o} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:s,type:o}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${o==="issue"?"issues":"merge_requests"}/${s}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:s,type:o}=this.parseId(e),i=o==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),l=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}/add_spent_time?duration=${encodeURIComponent(l)}`,{method:"POST"})}catch(u){this.log(`[business] add_spent_time failed: ${u.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),s=new URLSearchParams,o=e.state??"opened";s.set("state",o),s.set("updated_after",r),s.set("scope","all"),s.set("per_page","100"),s.set("with_labels_details","true"),s.set("order_by","updated_at"),s.set("sort","desc"),e.labels?.length&&s.set("labels",e.labels.join(",")),e.milestone&&s.set("milestone",e.milestone),e.search&&s.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let u of i)try{let c=u==="__ALL__"?`/issues?${s.toString()}`:`/projects/${encodeURIComponent(u)}/issues?${s.toString()}`,d=await this.api(c);for(let p of d)a.push(this.mapIssue(p,u))}catch(c){this.log(`[business] GitLab listAll failed on ${u}: ${c.message}`)}let l=a;if(e.notLabels?.length){let u=new Set(e.notLabels);l=l.filter(c=>!(c.labels||[]).some(d=>u.has(d)))}if(e.withoutScopedPrefix){let u=e.withoutScopedPrefix+"::";l=l.filter(c=>!(c.labels||[]).some(d=>d.startsWith(u)))}return l}async setState(e,n){let{project:r,iid:s,type:o}=this.parseId(e),i=o==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let s=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(s,n),descriptionHtml:s.description_html||void 0,createdAt:s.created_at,author:s.author?{username:s.author.username,name:s.author.name,avatarUrl:s.author.avatar_url}:void 0,allLabels:Array.isArray(s.labels)?typeof s.labels[0]=="object"?s.labels.map(i=>i.name):s.labels:[]}}catch(s){return this.log(`[board] GitLab getItem failed for ${e}: ${s.message}`),null}}async updateItem(e,n){let{project:r,iid:s}=this.parseId(e),o;n.assigneeUsernames&&(o=(await Promise.all(n.assigneeUsernames.map(async c=>{try{let d=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(d)&&d[0]?.id?d[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let u=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(u)&&u[0]?.id&&(i=u[0].id)}catch(u){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${u.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),o!==void 0&&(a.assignee_ids=o),i!==void 0&&(a.milestone_id=i);let l=await this.api(`/projects/${encodeURIComponent(r)}/issues/${s}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(l,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let s of r)s.username&&!e.has(s.username)&&e.set(s.username,{username:s.username,name:s.name,avatarUrl:s.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let s=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let o of s)o.title&&!e.has(o.title)&&e.set(o.title,{id:o.id,title:o.title,state:o.state,dueDate:o.due_date})}catch(s){this.log(`[board] listMilestones failed for ${r}: ${s.message}`)}let n=[...e.values()];return n.sort((r,s)=>r.state!==s.state?r.state==="active"?-1:1:r.title.localeCompare(s.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,s=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];s.length&&(r=(await Promise.all(s.map(async u=>{try{let c=await this.api(`/users?username=${encodeURIComponent(u)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${u}: ${c.message}`),null}}))).filter(u=>typeof u=="number"));let o;if(e.milestoneTitle)try{let l=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(o=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${l.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),o!==void 0&&(i.milestone_id=o);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:s,iid:o,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",l=new URLSearchParams;n.length&&l.set("add_labels",n.join(",")),r.length&&l.set("remove_labels",r.join(",")),l.toString()&&await this.api(`/projects/${encodeURIComponent(s)}/${a}/${o}?${l.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),s=r.pop(),o=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:o,iid:s}}};function Kd(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new ht(r.path,e,n);case"wiki":return new bt(r.path,r.glob);case"gitlab":{let s=e.channels.gitlab;if(!s?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let o={};for(let a of s.agentMappings)a.gitlabUsernames.length&&(o[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:s.routes.map(a=>a.project);return new yt(s.host,s.token,i,o,n)}}}var wt="unmapped";function kt(t,e=[]){if(!t)return wt;let n=e.find(s=>s.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function Aa(t){let e=new Map,n=t.projects??[],r=t.orgChart??{};for(let o of n)o.pm&&(e.has(o.pm)||e.set(o.pm,kt(o.id,n)));let s=(o,i=new Set)=>{if(e.has(o))return e.get(o);if(i.has(o))return;i.add(o);let a=r[o]?.reportsTo;if(!a)return;let l=s(a,i);return l&&e.set(o,l),l};for(let o of Object.keys(r))s(o);return e}function Ia(t,e,n=[]){if(!n.length)return;let r=n.filter(s=>!s.channel||s.channel===t);return r.find(s=>s.chatId&&e.chatId&&s.chatId===e.chatId)??r.find(s=>s.username&&e.username&&s.username===e.username)??r.find(s=>s.senderId&&e.senderId&&s.senderId===e.senderId)??r.find(s=>s.channel&&!s.chatId&&!s.username&&!s.senderId)}function Jd(t,e){let n=Ia(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return kt(t.project,e.projects);if(t.agentId){let r=Aa(e).get(t.agentId);if(r)return r}return wt}function Yd(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,s,...o]=n,i=o.join(":"),a={agentId:e||r,channel:s};return s==="gitlab"||s==="github"?a.project=i.split(":")[0]:s==="cron"||s==="api"||(a.chatId=i.split("@")[0]),a}var Ta=t=>t===wt?"internal":"client";function Da(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Ta(t),respondWithinMinutes:Ca(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function Zd(t){let e=new Set;for(let n of t.projects??[])e.add(kt(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=>Da(n,t))}function Ca(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 Na}from"crypto";var tp={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},La=40,Oa=20,np=90,Pa=2e3,Zr=36e5;function Ma(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
184
- ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<La?null:`text:${Na("sha256").update(r).digest("hex").slice(0,24)}`}function rp(t){let e=t.indexOf(`
185
- `);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function St(t){t.exec(`
175
+ Reinstall in ${da}. Agents switch back on their own once it is installed.`}}function ha(t=Xr()){if(!zr(t))return null;try{let e=JSON.parse(oa(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function ba(t,e){sa(ca(t),{recursive:!0}),aa(`${t}.tmp`,JSON.stringify(e,null,2)+`
176
+ `),ia(`${t}.tmp`,t)}var Hr=class{constructor(e){this.deps=e}running=!1;missingNow=!1;hasMissing(){return this.missingNow}async check(e,n,r=new Date){if(this.running||!n.length)return null;this.running=!0;try{let s=this.deps.file??Xr(),o=new Map((ha(s)?.missing??[]).map(d=>[d.voice,d])),i=fa(e,n),a=i.map(d=>({...d,since:o.get(d.voice)?.since??r.toISOString(),...o.get(d.voice)?.notifiedAt?{notifiedAt:o.get(d.voice).notifiedAt}:{}})),l=[...o.keys()].filter(d=>!i.some(p=>p.voice===d));for(let d of l)this.deps.log(`[voice] ${dt(d)} is installed again; its agents speak with it again`);l.length&&Or(d=>l.some(p=>d===p||d.endsWith(`:${p}`)));let u=a.filter(d=>!d.notifiedAt);if(u.length){let{title:d,message:p}=ma(u);try{await this.deps.notify(d,p);for(let g of u)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${u.map(g=>dt(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(!zr(s)||JSON.stringify(a)!==JSON.stringify([...o.values()]))&&ba(s,c),c}finally{this.running=!1}}};import{readFileSync as gt,writeFileSync as Qr,existsSync as ft,readdirSync as _a,statSync as Aa}from"fs";import{resolve as mt,join as Ia}from"path";import{existsSync as Kr,mkdirSync as ya,readFileSync as wa,writeFileSync as Gr}from"fs";import{dirname as ka,resolve as Jr}from"path";import{z as h}from"zod";var Sa=h.object({type:h.enum(["gitlab","github"]),host:h.string().optional(),project:h.string(),iid:h.number().int().positive(),url:h.string()}),xa=h.object({id:h.string(),title:h.string(),description:h.string().optional(),assignee:h.string().optional(),labels:h.array(h.string()).default([]),milestone:h.string().optional(),status:h.enum(["todo","doing","blocked","done"]).default("todo"),priority:h.number().int().optional(),estimatedSeconds:h.number().int().optional(),source:Sa.optional(),importedAt:h.string().optional(),createdAt:h.string(),updatedAt:h.string(),blocker:h.string().optional(),doneNote:h.string().optional()}),va=h.object({version:h.literal(1),items:h.array(xa).default([])}),Se=class{constructor(e){this.path=e}jsonPath(){return Jr(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Jr(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return Kr(this.jsonPath())}load(){let e=this.jsonPath();if(!Kr(e))return{version:1,items:[]};let n=wa(e,"utf-8");try{return va.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();ya(ka(n),{recursive:!0}),Gr(n,JSON.stringify(e,null,2)+`
177
+ `),Gr(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(n=>n.id===e)}add(e){let n=this.load();if(n.items.some(o=>o.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),s={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return n.items.push(s),this.save(n),s}addMany(e){let n=this.load(),r=new Set(n.items.map(i=>i.id)),s=new Date().toISOString(),o=[];for(let i of e){if(r.has(i.id))continue;let a={...i,labels:i.labels??[],status:i.status??"todo",createdAt:i.createdAt??s,updatedAt:s};n.items.push(a),o.push(a),r.add(a.id)}return o.length&&this.save(n),o}update(e,n){let r=this.load(),s=r.items.findIndex(i=>i.id===e);if(s<0)throw new Error(`backlog item ${e} not found`);let o={...r.items[s],...n,id:r.items[s].id,createdAt:r.items[s].createdAt,updatedAt:new Date().toISOString()};return r.items[s]=o,this.save(r),o}remove(e){let n=this.load(),r=n.items.length;return n.items=n.items.filter(s=>s.id!==e),n.items.length===r?!1:(this.save(n),!0)}toMarkdown(e){let n=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],r={doing:[],blocked:[],todo:[],done:[]};for(let o of e.items)r[o.status].push(o);let s=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[o,i]of s)if(r[o].length){n.push(`## ${i}`,"");for(let a of r[o]){let l=o==="done"?"x":" ",u=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",d=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${l}] ${u}${a.title}${c}${d}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
178
+ `)}};function Bd(t){return`${t.type}:${t.project}:${t.iid}`}function Yr(t,e,n){let r=[];if(e.type==="gitlab"){let s=n.channels.gitlab?.agentMappings??[];for(let o of t){let i=s.find(a=>a.agentId===o);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(o)}}else if(e.type==="github"){let s=n.channels.github?.agentMappings??[];for(let o of t){let i=s.find(a=>a.agentId===o);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(o)}}return r}async function pt(t,e,n,r=()=>{}){return t.source?$a(t.source,e,n,r):{ok:!0,attempts:[]}}async function $a(t,e,n,r=()=>{}){return t.type==="gitlab"?Ea(t,e,n,r):t.type==="github"?Ra(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Ea(t,e,n,r){let s=n.channels.gitlab,o=s?.token,i=s?.host||(t.host?`https://${t.host}`:void 0);if(!o||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],l=async(g,f={})=>fetch(`${i}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":o,"Content-Type":"application/json",...f.headers||{}}}),u=encodeURIComponent(t.project),c;e.assigneeUsernames!==void 0&&(c=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let m=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":o}});if(!m.ok)return null;let b=await m.json();return Array.isArray(b)&&b[0]?.id?b[0].id:null}catch{return null}}))).filter(f=>typeof f=="number"));let d;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")d=0;else try{let g=await l(`/projects/${u}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let f=await g.json();Array.isArray(f)&&f[0]?.id&&(d=f[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.description=e.description),e.labels!==void 0&&(p.labels=e.labels.join(",")),e.addLabels?.length&&(p.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(p.remove_labels=e.removeLabels.join(",")),c!==void 0&&(p.assignee_ids=c),d!==void 0&&(p.milestone_id=d),e.state&&(p.state_event=e.state==="closed"?"close":"reopen"),Object.keys(p).length)try{let g=await l(`/projects/${u}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(p)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${f.slice(0,200)}`,url:t.url}}}catch(g){return a.push({kind:"PUT issue",ok:!1,error:g.message}),{ok:!1,attempts:a,error:g.message,url:t.url}}if(e.note)try{let g=await l(`/projects/${u}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function Ra(t,e,n,r){let o=n.channels.github?.token;if(!o)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(p,g={})=>fetch(`https://api.github.com${p}`,{...g,headers:{Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),l=t.project,u;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")u=null;else try{let p=await a(`/repos/${l}/milestones?state=all&per_page=100`);if(p.ok){let g=await p.json(),f=Array.isArray(g)?g.find(m=>m.title===e.milestoneTitle):null;f?.number&&(u=f.number)}}catch(p){r(`[backlog-sync] github milestone lookup failed: ${p.message}`)}let c;if(e.labels!==void 0)c=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let p=await a(`/repos/${l}/issues/${t.iid}`);if(p.ok){let g=await p.json(),f=Array.isArray(g.labels)?g.labels.map(b=>typeof b=="string"?b:b.name):[],m=new Set([...f,...e.addLabels??[]]);for(let b of e.removeLabels??[])m.delete(b);c=[...m]}}catch(p){r(`[backlog-sync] github label fetch failed: ${p.message}`)}if(c===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let d={};if(e.title!==void 0&&(d.title=e.title),e.description!==void 0&&(d.body=e.description),c!==void 0&&(d.labels=c),e.assigneeUsernames!==void 0&&(d.assignees=e.assigneeUsernames),u!==void 0&&(d.milestone=u),e.state&&(d.state=e.state),Object.keys(d).length)try{let p=await a(`/repos/${l}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(d)});if(i.push({kind:"PATCH issue",ok:p.ok,status:p.status}),!p.ok){let g=await p.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${p.status}: ${g.slice(0,200)}`,url:t.url}}}catch(p){return i.push({kind:"PATCH issue",ok:!1,error:p.message}),{ok:!1,attempts:i,error:p.message,url:t.url}}if(e.note)try{let p=await a(`/repos/${l}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:p.ok,status:p.status})}catch(p){i.push({kind:"POST comment",ok:!1,error:p.message})}return{ok:i.every(p=>p.ok),attempts:i,url:t.url}}var ht=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,xe=/@([a-z0-9_-]+)/i,Zr=/\[time:\s*([0-9hm\s]+)\]/i;function Ta(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 bt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new Se(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=mt(process.cwd(),this.path);return ft(e)?gt(e,"utf-8").split(`
179
+ `):[]}writeMd(e){let n=mt(process.cwd(),this.path);Qr(n,e.join(`
180
+ `))}async listOpen(e){if(this.store.exists())return this.store.list().filter(o=>o.status!=="done"&&(!o.assignee||o.assignee.toLowerCase()===e.toLowerCase())).map(o=>this.toWorkItem(o));let n=this.readMd(),r=[];for(let s=0;s<n.length;s++){let o=n[s].match(ht);if(!o||o[2].toLowerCase()==="x")continue;let a=o[3],l=a.match(xe);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let u=a.match(Zr),c=a.replace(xe,"").replace(Zr,"").trim();r.push({id:`backlog:${s}`,title:c||`Task at line ${s+1}`,assignee:l?l[1]:void 0,estimatedSeconds:u?Ta(u[1]):void 0,priority:s})}return r}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let r=this.store.findById(n);if(!r)return;let s=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(s.source&&this.daemon){let o=Yr([s.assignee||e],s.source,this.daemon);pt(s,{assigneeUsernames:o,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(i=>this.log(`[backlog-sync] claim failed for ${n}: ${i?.message??i}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let l=this.store.update(e,a);if(l.source&&this.daemon){let u={};n.status==="done"?(u.addLabels=["Done"],u.removeLabels=["Doing"]):n.status==="blocked"&&(u.addLabels=["Blocked"]),n.note&&(u.note=n.note),Object.keys(u).length&&pt(l,u,this.daemon,this.log).catch(c=>this.log(`[backlog-sync] report failed for ${e}: ${c?.message??c}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let r=parseInt(e.slice(8),10),s=this.readMd(),o=s[r];if(!o)throw new Error(`backlog line ${r} missing`);if(!o.match(ht))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){s[r]=o.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";s.splice(r+1,0,a)}else n.status==="blocked"?s.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&s.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(s)}toWorkItem(e){let n={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},yt=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(ft(e))for(let r of _a(e)){let s=Ia(e,r);Aa(s).isDirectory()?this.walk(s,n):r.endsWith(".md")&&n.push(s)}}async listOpen(e){let n=[];this.walk(mt(process.cwd(),this.root),n);let r=[];for(let s of n){let o=gt(s,"utf-8").split(`
181
+ `);for(let i=0;i<o.length;i++){let a=o[i].match(ht);if(!a||a[2].toLowerCase()==="x")continue;let l=a[3].match(xe);!l||l[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${s}:${i}`,title:a[3].replace(xe,"").trim(),assignee:l[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),s=parseInt(r[r.length-1],10),o=r.slice(1,-1).join(":");if(!ft(o))return;let i=gt(o,"utf-8").split(`
182
+ `);n.status==="done"&&i[s]&&(i[s]=i[s].replace(/- \[ \]/,"- [x]"),Qr(o,i.join(`
183
+ `)))}},wt=class{constructor(e,n,r,s,o){this.host=e;this.token=n;this.projects=r;this.agentUsernames=s;this.log=o}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(s=>s.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,s=[],o;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(o=e.labels.map(u=>({name:u.name,color:u.color,text_color:u.text_color})),s=o.map(u=>u.name)):s=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(u=>({username:u.username,name:u.name,avatarUrl:u.avatar_url})),l=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:l?this.usernameToAgent(l)||l:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:s,labelDetails:o,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],s=this.projects.length?this.projects:["__ALL__"];for(let o of n)for(let i of s)try{let a=`assignee_username=${encodeURIComponent(o)}&state=opened&scope=all&per_page=20`,l=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,u=await this.api(l);for(let c of u){let d=this.mapIssue(c,i);d.assignee=e,r.push(d)}}catch(a){this.log(`[business] GitLab listOpen failed for ${o} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:s,type:o}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${o==="issue"?"issues":"merge_requests"}/${s}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:s,type:o}=this.parseId(e),i=o==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),l=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}/add_spent_time?duration=${encodeURIComponent(l)}`,{method:"POST"})}catch(u){this.log(`[business] add_spent_time failed: ${u.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),s=new URLSearchParams,o=e.state??"opened";s.set("state",o),s.set("updated_after",r),s.set("scope","all"),s.set("per_page","100"),s.set("with_labels_details","true"),s.set("order_by","updated_at"),s.set("sort","desc"),e.labels?.length&&s.set("labels",e.labels.join(",")),e.milestone&&s.set("milestone",e.milestone),e.search&&s.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let u of i)try{let c=u==="__ALL__"?`/issues?${s.toString()}`:`/projects/${encodeURIComponent(u)}/issues?${s.toString()}`,d=await this.api(c);for(let p of d)a.push(this.mapIssue(p,u))}catch(c){this.log(`[business] GitLab listAll failed on ${u}: ${c.message}`)}let l=a;if(e.notLabels?.length){let u=new Set(e.notLabels);l=l.filter(c=>!(c.labels||[]).some(d=>u.has(d)))}if(e.withoutScopedPrefix){let u=e.withoutScopedPrefix+"::";l=l.filter(c=>!(c.labels||[]).some(d=>d.startsWith(u)))}return l}async setState(e,n){let{project:r,iid:s,type:o}=this.parseId(e),i=o==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${s}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let s=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(s,n),descriptionHtml:s.description_html||void 0,createdAt:s.created_at,author:s.author?{username:s.author.username,name:s.author.name,avatarUrl:s.author.avatar_url}:void 0,allLabels:Array.isArray(s.labels)?typeof s.labels[0]=="object"?s.labels.map(i=>i.name):s.labels:[]}}catch(s){return this.log(`[board] GitLab getItem failed for ${e}: ${s.message}`),null}}async updateItem(e,n){let{project:r,iid:s}=this.parseId(e),o;n.assigneeUsernames&&(o=(await Promise.all(n.assigneeUsernames.map(async c=>{try{let d=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(d)&&d[0]?.id?d[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let u=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(u)&&u[0]?.id&&(i=u[0].id)}catch(u){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${u.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),o!==void 0&&(a.assignee_ids=o),i!==void 0&&(a.milestone_id=i);let l=await this.api(`/projects/${encodeURIComponent(r)}/issues/${s}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(l,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let s of r)s.username&&!e.has(s.username)&&e.set(s.username,{username:s.username,name:s.name,avatarUrl:s.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let s=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let o of s)o.title&&!e.has(o.title)&&e.set(o.title,{id:o.id,title:o.title,state:o.state,dueDate:o.due_date})}catch(s){this.log(`[board] listMilestones failed for ${r}: ${s.message}`)}let n=[...e.values()];return n.sort((r,s)=>r.state!==s.state?r.state==="active"?-1:1:r.title.localeCompare(s.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,s=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];s.length&&(r=(await Promise.all(s.map(async u=>{try{let c=await this.api(`/users?username=${encodeURIComponent(u)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${u}: ${c.message}`),null}}))).filter(u=>typeof u=="number"));let o;if(e.milestoneTitle)try{let l=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(o=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${l.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),o!==void 0&&(i.milestone_id=o);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:s,iid:o,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",l=new URLSearchParams;n.length&&l.set("add_labels",n.join(",")),r.length&&l.set("remove_labels",r.join(",")),l.toString()&&await this.api(`/projects/${encodeURIComponent(s)}/${a}/${o}?${l.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),s=r.pop(),o=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:o,iid:s}}};function Yd(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new bt(r.path,e,n);case"wiki":return new yt(r.path,r.glob);case"gitlab":{let s=e.channels.gitlab;if(!s?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let o={};for(let a of s.agentMappings)a.gitlabUsernames.length&&(o[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:s.routes.map(a=>a.project);return new wt(s.host,s.token,i,o,n)}}}oo();var kt="unmapped";function St(t,e=[]){if(!t)return kt;let n=e.find(s=>s.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function Da(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},s=new Map;for(let i of Bt(t)){let a=Ie(i.from),l=Ie(i.to);i.type==="reports-to"&&a.kind==="agent"&&l.kind==="agent"&&s.set(a.id,l.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,St(i.id,n)));let o=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let l=s.get(i);if(!l)return;let u=o(l,a);return u&&e.set(i,u),u};for(let i of Object.keys(r))o(i);return e}function Ca(t,e,n=[]){if(!n.length)return;let r=n.filter(s=>!s.channel||s.channel===t);return r.find(s=>s.chatId&&e.chatId&&s.chatId===e.chatId)??r.find(s=>s.username&&e.username&&s.username===e.username)??r.find(s=>s.senderId&&e.senderId&&s.senderId===e.senderId)??r.find(s=>s.channel&&!s.chatId&&!s.username&&!s.senderId)}function ep(t,e){let n=Ca(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return St(t.project,e.projects);if(t.agentId){let r=Da(e).get(t.agentId);if(r)return r}return kt}function tp(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,s,...o]=n,i=o.join(":"),a={agentId:e||r,channel:s};return s==="gitlab"||s==="github"?a.project=i.split(":")[0]:s==="cron"||s==="api"||(a.chatId=i.split("@")[0]),a}var Na=t=>t===kt?"internal":"client";function La(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Na(t),respondWithinMinutes:Oa(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function np(t){let e=new Set;for(let n of t.projects??[])e.add(St(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=>La(n,t))}function Oa(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 Pa}from"crypto";var op={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},Ma=40,Ua=20,ip=90,Fa=2e3,es=36e5;function Wa(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
184
+ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<Ma?null:`text:${Pa("sha256").update(r).digest("hex").slice(0,24)}`}function ap(t){let e=t.indexOf(`
185
+ `);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function xt(t){t.exec(`
186
186
  CREATE TABLE IF NOT EXISTS owner_told (
187
187
  id INTEGER PRIMARY KEY AUTOINCREMENT,
188
188
  at INTEGER NOT NULL,
@@ -200,34 +200,34 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<La?null:`text:${N
200
200
  CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
201
201
  CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
202
202
  CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
203
- `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of Ua)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(s){if(!/duplicate column/i.test(String(s?.message)))throw s}}var Ua=[["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 Qr=class{constructor(e){this.db=e;St(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
204
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,Pa),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 s=this.db.prepare(`SELECT * FROM owner_told WHERE item_key = ? AND at >= ? AND outcome IN ('sent', 'held'${r?", 'digest'":""}) ORDER BY at DESC LIMIT 1`).get(e,n);return s?ve(s):null}waitingForDigest(e=500){return this.db.prepare("SELECT * FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL ORDER BY at LIMIT ?").all(e).map(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 s of e)r.run(n,s)})()}since(e,n=200){return this.db.prepare("SELECT * FROM owner_told WHERE at >= ? ORDER BY at DESC, id DESC LIMIT ?").all(e,n).map(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,
203
+ `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of ja)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(s){if(!/duplicate column/i.test(String(s?.message)))throw s}}var ja=[["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 ts=class{constructor(e){this.db=e;xt(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
204
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,Fa),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 s=this.db.prepare(`SELECT * FROM owner_told WHERE item_key = ? AND at >= ? AND outcome IN ('sent', 'held'${r?", 'digest'":""}) ORDER BY at DESC LIMIT 1`).get(e,n);return s?ve(s):null}waitingForDigest(e=500){return this.db.prepare("SELECT * FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL ORDER BY at LIMIT ?").all(e).map(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 s of e)r.run(n,s)})()}since(e,n=200){return this.db.prepare("SELECT * FROM owner_told WHERE at >= ? ORDER BY at DESC, id DESC LIMIT ?").all(e,n).map(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,
205
205
  SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
206
206
  SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
207
- FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},es=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),s=this.now(),o=Ma(n,e.title,e.text),i=n.kind??"notice",a=(o?.startsWith("text:")?Math.min(r.repeatWindowHours,Oa):r.repeatWindowHours)*Zr,l=r.digestNags&&r.digestAvailable!==!1,u="send";!n.urgent&&o&&this.ledger.lastTold(o,s-a,l)?u="repeat":!n.urgent&&i==="nag"&&l&&(u="digest");let c=this.ledger.add({at:s,key:o??`once:${s}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:u==="send"?"sent":u,urgent:n.urgent===!0});return{verdict:u,key:o,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:Fa(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*Zr)}};function sp(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,s=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,o=r(n.from,100)??r(e,100);return{...r(n.key,190)?{key:`send:${r(n.key,190)}`}:{},...r(n.requestId,100)?{requestId:r(n.requestId,100)}:{},...s?{kind:s}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...o?{from:o}:{}}}function Fa(t,e=5,n=3){let r=new Map;for(let a of t){let[l,...u]=a.title.split(": "),c=u.join(": ").trim(),d=r.get(l.trim())??{count:0,names:[]};d.count++,c&&!d.names.includes(c)&&d.names.push(c),r.set(l.trim(),d)}let s=[...r.entries()].sort((a,l)=>l[1].count-a[1].count),o=s.slice(0,e).map(([a,{count:l,names:u}])=>{let c=u.length?` (${u.slice(0,n).join(", ")}${u.length>n?", \u2026":""})`:"";return`${a}${l>1?` \xD7${l}`:""}${c}`}),i=s.length>e?`; ${s.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${o.join("; ")}${i}.`}var Wa=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,ja=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function ts(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(ja)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],s=qa(r);if(!s)return{cleanText:t};let o=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,o)+i+t.slice(o+n[0].length)).trim(),ui:s}}function ip(t){if(!t||!t.includes("agentx:ui"))return t;let e=Wa.exec(t);return e?t.slice(0,e.index).trimEnd():t}function qa(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let r=[],s=[],o=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?r.push({label:i.label,url:i.url}):typeof i.reply=="string"&&i.reply.trim()?s.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&o.push(i.label));r.length&&(n.buttons=r),s.length&&(n.replies=s),o.length&&(n.skippedActions=o)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,s=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(s)&&s.filter(o=>typeof o=="string").length>=2&&(n.poll={question:r,options:s.filter(o=>typeof o=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:s,caption:o}=e.media;["image","document","audio","video"].includes(r)&&typeof s=="string"&&s&&(n.media={type:r,url:s,...typeof o=="string"?{caption:o}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(s=>typeof s=="string"&&s.trim()).map(s=>s.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function lp(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 Va=5*6e4;function L(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var ns=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(L)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${L(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let s=r.filter(o=>o.expiresAt>e);s.length===0?this.pending.delete(n):s.length!==r.length&&this.pending.set(n,s)}for(let[n,r]of this.recentRings)r<=e&&this.recentRings.delete(n)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,n,r){return this.addSubscriber(e,n,{kind:"sse",res:r})}subscribeInternal(e,n,r){return this.addSubscriber(e,n,{kind:"callback",deliver:r})}addSubscriber(e,n,r){let s={callId:e,recipient:n,sink:r};this.subs.add(s);let o=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${o}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let l=Date.now(),u=a.filter(c=>c.expiresAt>l);for(let{signal:c}of u)this.deliverTo(s,c);this.pending.delete(i),u.length&&this.log(`flushed ${u.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(s),this.log(`unsubscribe[${o}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
207
+ FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},ns=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),s=this.now(),o=Wa(n,e.title,e.text),i=n.kind??"notice",a=(o?.startsWith("text:")?Math.min(r.repeatWindowHours,Ua):r.repeatWindowHours)*es,l=r.digestNags&&r.digestAvailable!==!1,u="send";!n.urgent&&o&&this.ledger.lastTold(o,s-a,l)?u="repeat":!n.urgent&&i==="nag"&&l&&(u="digest");let c=this.ledger.add({at:s,key:o??`once:${s}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:u==="send"?"sent":u,urgent:n.urgent===!0});return{verdict:u,key:o,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:qa(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*es)}};function lp(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,s=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,o=r(n.from,100)??r(e,100);return{...r(n.key,190)?{key:`send:${r(n.key,190)}`}:{},...r(n.requestId,100)?{requestId:r(n.requestId,100)}:{},...s?{kind:s}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...o?{from:o}:{}}}function qa(t,e=5,n=3){let r=new Map;for(let a of t){let[l,...u]=a.title.split(": "),c=u.join(": ").trim(),d=r.get(l.trim())??{count:0,names:[]};d.count++,c&&!d.names.includes(c)&&d.names.push(c),r.set(l.trim(),d)}let s=[...r.entries()].sort((a,l)=>l[1].count-a[1].count),o=s.slice(0,e).map(([a,{count:l,names:u}])=>{let c=u.length?` (${u.slice(0,n).join(", ")}${u.length>n?", \u2026":""})`:"";return`${a}${l>1?` \xD7${l}`:""}${c}`}),i=s.length>e?`; ${s.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${o.join("; ")}${i}.`}var Va=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,Ba=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function rs(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(Ba)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],s=Ha(r);if(!s)return{cleanText:t};let o=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,o)+i+t.slice(o+n[0].length)).trim(),ui:s}}function up(t){if(!t||!t.includes("agentx:ui"))return t;let e=Va.exec(t);return e?t.slice(0,e.index).trimEnd():t}function Ha(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let r=[],s=[],o=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?r.push({label:i.label,url:i.url}):typeof i.reply=="string"&&i.reply.trim()?s.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&o.push(i.label));r.length&&(n.buttons=r),s.length&&(n.replies=s),o.length&&(n.skippedActions=o)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,s=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(s)&&s.filter(o=>typeof o=="string").length>=2&&(n.poll={question:r,options:s.filter(o=>typeof o=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:s,caption:o}=e.media;["image","document","audio","video"].includes(r)&&typeof s=="string"&&s&&(n.media={type:r,url:s,...typeof o=="string"?{caption:o}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(s=>typeof s=="string"&&s.trim()).map(s=>s.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function pp(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 za=5*6e4;function L(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var ss=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(L)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${L(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let s=r.filter(o=>o.expiresAt>e);s.length===0?this.pending.delete(n):s.length!==r.length&&this.pending.set(n,s)}for(let[n,r]of this.recentRings)r<=e&&this.recentRings.delete(n)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,n,r){return this.addSubscriber(e,n,{kind:"sse",res:r})}subscribeInternal(e,n,r){return this.addSubscriber(e,n,{kind:"callback",deliver:r})}addSubscriber(e,n,r){let s={callId:e,recipient:n,sink:r};this.subs.add(s);let o=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${o}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let l=Date.now(),u=a.filter(c=>c.expiresAt>l);for(let{signal:c}of u)this.deliverTo(s,c);this.pending.delete(i),u.length&&this.log(`flushed ${u.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(s),this.log(`unsubscribe[${o}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
208
208
  data: ${JSON.stringify(n)}
209
209
 
210
- `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=L(e.to);if(n===L(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let s=await this.forwarder(e.to,e);return s?{ok:s}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&L(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(L(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),s=this.recentRings.get(e.callId);if(s&&s>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+Va),this.ringHandler)try{this.ringHandler(e)}catch(o){this.log(`ringHandler threw: ${o.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),s=this.pending.get(r)||[];s.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,s),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${s.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=L(e.to);for(let s of this.subs)s.callId===e.callId&&L(s.recipient)===r&&(this.deliverTo(s,e)?n++:this.subs.delete(s));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as Ba,readFileSync as rs,renameSync as Ha,rmSync as za,writeFileSync as Xa}from"fs";import{homedir as Ka}from"os";import{dirname as Ga,join as Ja}from"path";var ss=Ja(Ka(),".agentx","call.json");function Ya(t=ss,e=Date.now()){try{let n=JSON.parse(rs(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 os(t=rn,e=Ya){let n=t();return n.active?n:e()}function fp(t,e,n=ss,r=Date.now()){let s=null;try{s=JSON.parse(rs(n,"utf-8"))}catch{}if(s&&s.source&&s.source!=="daemon")return;if(!t){s&&za(n,{force:!0});return}Ba(Ga(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;Xa(o,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
211
- `),Ha(o,n)}var is="owner",$e=6e4,ds=60*$e,Za=24*ds,Qa=7*24*ds,el=2*$e,bp={enabled:!1,escalateAfterMinutes:10,ladder:[]};function tl(t){t.exec(`
210
+ `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=L(e.to);if(n===L(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let s=await this.forwarder(e.to,e);return s?{ok:s}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&L(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(L(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),s=this.recentRings.get(e.callId);if(s&&s>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+za),this.ringHandler)try{this.ringHandler(e)}catch(o){this.log(`ringHandler threw: ${o.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),s=this.pending.get(r)||[];s.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,s),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${s.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=L(e.to);for(let s of this.subs)s.callId===e.callId&&L(s.recipient)===r&&(this.deliverTo(s,e)?n++:this.subs.delete(s));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as Xa,readFileSync as os,renameSync as Ka,rmSync as Ga,writeFileSync as Ja}from"fs";import{homedir as Ya}from"os";import{dirname as Za,join as Qa}from"path";var is=Qa(Ya(),".agentx","call.json");function el(t=is,e=Date.now()){try{let n=JSON.parse(os(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 as(t=on,e=el){let n=t();return n.active?n:e()}function yp(t,e,n=is,r=Date.now()){let s=null;try{s=JSON.parse(os(n,"utf-8"))}catch{}if(s&&s.source&&s.source!=="daemon")return;if(!t){s&&Ga(n,{force:!0});return}Xa(Za(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;Ja(o,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
211
+ `),Ka(o,n)}var ls="owner",$e=6e4,gs=60*$e,tl=24*gs,nl=7*24*gs,rl=2*$e,Sp={enabled:!1,escalateAfterMinutes:10,ladder:[]};function sl(t){t.exec(`
212
212
  CREATE TABLE IF NOT EXISTS owner_presence (
213
213
  person TEXT NOT NULL,
214
214
  surface TEXT NOT NULL,
215
215
  at INTEGER NOT NULL,
216
216
  PRIMARY KEY (person, surface)
217
217
  );
218
- `)}var as=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;tl(e)}written=new Map;touch(e,n=is){let r=this.now(),s=`${n}
218
+ `)}var cs=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;sl(e)}written=new Map;touch(e,n=ls){let r=this.now(),s=`${n}
219
219
  ${e}`;r-(this.written.get(s)??-1/0)<this.throttleMs||(this.written.set(s,r),this.db.prepare(`INSERT INTO owner_presence (person, surface, at) VALUES (?, ?, ?)
220
- ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=is){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function yp(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var ls=class{constructor(e,n=Date.now){this.db=e;this.now=n;St(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
220
+ ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=ls){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function xp(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var us=class{constructor(e,n=Date.now){this.db=e;this.now=n;xt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
221
221
  WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
222
- ORDER BY at DESC LIMIT 500`).all(this.now()-Qa)}seenByRequest(e,n){return this.byRequest(e,r=>this.seen(r,n))}answeredByRequest(e,n,r=this.now()){return this.byRequest(e,s=>this.answered(s,n,r),r)}seenPush(e,n="phone"){let r=[],s=this.db.prepare("SELECT id, title FROM owner_told WHERE channel = 'push' AND outcome IN ('sent', 'held') AND at BETWEEN ? AND ? ORDER BY at DESC");for(let o of e){let i=o.title.endsWith("\u2026")?o.title.slice(0,-1):o.title,l=s.all(o.at-el,o.at).find(u=>u.title===o.title||i!==o.title&&u.title.startsWith(i));l&&r.push(l.id)}return this.seen(r,n)}seen(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET seen_at = ?, seen_via = ?
223
- WHERE seen_at IS NULL AND (${cs(e)})`).run(r,n,...e,...e,...e).changes:0}answered(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET answered_at = ?, answered_via = ?, seen_at = COALESCE(seen_at, ?), seen_via = COALESCE(seen_via, ?)
224
- WHERE answered_at IS NULL AND (${cs(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let s=new Set(e.filter(Boolean));if(!s.size)return 0;let o=this.openRequestRows().filter(i=>s.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(o)}};function cs(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 wp(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(o=>`${o}:default`),...e.addresses],s=[];for(let o of r){let i=o.trim(),a=ee(i);a&&n(a)&&!s.includes(i)&&s.push(i)}return s}function ee(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function nl(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function rl(t){return ee(t)==="push"?["phone","desk"]:[t]}function kp(t,e,n){let r=t.filter(o=>n(ee(o)));if(!r.length)return null;let s=null;for(let o of r){let i=Math.max(-1/0,...e.filter(a=>rl(o).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!s||i>s.at)&&(s={stop:o,at:i})}return s?.stop??r[0]}function sl(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(o=>o!==e&&n(ee(o)))??null}var ol=3;async function Sp(t){let{db:e,ledger:n,settings:r,now:s}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let o=r.escalateAfterMinutes*$e,i=e.prepare(`SELECT id FROM owner_told
222
+ ORDER BY at DESC LIMIT 500`).all(this.now()-nl)}seenByRequest(e,n){return this.byRequest(e,r=>this.seen(r,n))}answeredByRequest(e,n,r=this.now()){return this.byRequest(e,s=>this.answered(s,n,r),r)}seenPush(e,n="phone"){let r=[],s=this.db.prepare("SELECT id, title FROM owner_told WHERE channel = 'push' AND outcome IN ('sent', 'held') AND at BETWEEN ? AND ? ORDER BY at DESC");for(let o of e){let i=o.title.endsWith("\u2026")?o.title.slice(0,-1):o.title,l=s.all(o.at-rl,o.at).find(u=>u.title===o.title||i!==o.title&&u.title.startsWith(i));l&&r.push(l.id)}return this.seen(r,n)}seen(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET seen_at = ?, seen_via = ?
223
+ WHERE seen_at IS NULL AND (${ds(e)})`).run(r,n,...e,...e,...e).changes:0}answered(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET answered_at = ?, answered_via = ?, seen_at = COALESCE(seen_at, ?), seen_via = COALESCE(seen_via, ?)
224
+ WHERE answered_at IS NULL AND (${ds(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let s=new Set(e.filter(Boolean));if(!s.size)return 0;let o=this.openRequestRows().filter(i=>s.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(o)}};function ds(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 vp(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(o=>`${o}:default`),...e.addresses],s=[];for(let o of r){let i=o.trim(),a=ee(i);a&&n(a)&&!s.includes(i)&&s.push(i)}return s}function ee(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function ol(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function il(t){return ee(t)==="push"?["phone","desk"]:[t]}function $p(t,e,n){let r=t.filter(o=>n(ee(o)));if(!r.length)return null;let s=null;for(let o of r){let i=Math.max(-1/0,...e.filter(a=>il(o).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!s||i>s.at)&&(s={stop:o,at:i})}return s?.stop??r[0]}function al(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(o=>o!==e&&n(ee(o)))??null}var ll=3;async function Ep(t){let{db:e,ledger:n,settings:r,now:s}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let o=r.escalateAfterMinutes*$e,i=e.prepare(`SELECT id FROM owner_told
225
225
  WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
226
226
  AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
227
227
  AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
228
- ORDER BY at LIMIT 20`).all(Math.max(s-ol*o,s-Za),s-o),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),l=0;for(let{id:u}of i){if(a.run(s,u).changes!==1)continue;let c=n.get(u);if(!c)continue;let d=`${c.channel}:${c.chatId}`,p=sl(t.stops,d,t.up);if(!p){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${d}; no other address to try`);continue}let g=Math.round((s-c.at)/$e),f=c.outcome==="failed"?`it could not be sent on ${c.channel}`:`not seen on ${c.channel} for ${g} min`,m=`${c.text?`${c.text}
228
+ ORDER BY at LIMIT 20`).all(Math.max(s-ll*o,s-tl),s-o),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),l=0;for(let{id:u}of i){if(a.run(s,u).changes!==1)continue;let c=n.get(u);if(!c)continue;let d=`${c.channel}:${c.chatId}`,p=al(t.stops,d,t.up);if(!p){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${d}; no other address to try`);continue}let g=Math.round((s-c.at)/$e),f=c.outcome==="failed"?`it could not be sent on ${c.channel}`:`not seen on ${c.channel} for ${g} min`,m=`${c.text?`${c.text}
229
229
 
230
- `:""}(Sent again here: ${f}.)`,b=n.add({at:s,key:c.key,requestId:c.requestId,kind:c.kind,channel:ee(p),chatId:nl(p),from:c.from,title:c.title,text:m,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(p,c,m),l++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch(v){n.setOutcome(b,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${p} failed: ${v?.message??v}`)}}return l}var us=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,s]of Object.entries(this.opts.read())){let o=this.state.get(r)??{downSince:null,checks:0,told:!1};if(s.up){o.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}o.downSince??=e,o.checks++,o.reason=s.reason,!o.told&&o.checks>=n&&(o.told=!0,this.opts.log(`[reach] channel ${r} is down: ${s.reason??"no reason given"}`),this.opts.notice(r,s.reason??"no reason given")),this.state.set(r,o)}}downSince(e){return this.state.get(e)?.downSince??void 0}};var il={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},ps=class{constructor(e=il,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(s=>r-s<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},al="That code didn't work. Check it, or run agentx app pair for a new one.",ll=400;async function $p(t,e){let n=Date.now(),r=e.log??(u=>console.log(u)),s=t.socket.remoteAddress||"unknown",o=e.limiter.retryAfter(s);if(o>0)return r(`[app] pair-code refused from ${s}: locked out for ${o}s more`),{status:429,body:{error:"too many attempts",retryAfter:o},retryAfter:o};let i=null;try{i=(await $n(t,1024)).code}catch{}let a=e.codes.redeem(i),l=a?e.verify(a.token):null;return await cl(n,e.minMs??ll),!a||!l?(e.limiter.fail(s),r(`[app] pair-code failed from ${s}`),{status:401,body:{error:al}}):(e.limiter.succeed(s),r(`[app] pair-code paired ${a.tokenId} (${l}) from ${s}`),{status:200,body:{device:l},token:a.token})}async function cl(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as _l}from"child_process";import{mkdtempSync as wl,rmSync as kl,writeFileSync as Sl}from"fs";import{tmpdir as xl}from"os";import{join as bs}from"path";import{randomBytes as ul}from"crypto";var C={top:8,side:32,bottom:60},xt={height:56,keep:52},gs=`
230
+ `:""}(Sent again here: ${f}.)`,b=n.add({at:s,key:c.key,requestId:c.requestId,kind:c.kind,channel:ee(p),chatId:ol(p),from:c.from,title:c.title,text:m,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(p,c,m),l++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch(v){n.setOutcome(b,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${p} failed: ${v?.message??v}`)}}return l}var ps=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,s]of Object.entries(this.opts.read())){let o=this.state.get(r)??{downSince:null,checks:0,told:!1};if(s.up){o.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}o.downSince??=e,o.checks++,o.reason=s.reason,!o.told&&o.checks>=n&&(o.told=!0,this.opts.log(`[reach] channel ${r} is down: ${s.reason??"no reason given"}`),this.opts.notice(r,s.reason??"no reason given")),this.state.set(r,o)}}downSince(e){return this.state.get(e)?.downSince??void 0}};var cl={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},fs=class{constructor(e=cl,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(s=>r-s<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},ul="That code didn't work. Check it, or run agentx app pair for a new one.",dl=400;async function Ap(t,e){let n=Date.now(),r=e.log??(u=>console.log(u)),s=t.socket.remoteAddress||"unknown",o=e.limiter.retryAfter(s);if(o>0)return r(`[app] pair-code refused from ${s}: locked out for ${o}s more`),{status:429,body:{error:"too many attempts",retryAfter:o},retryAfter:o};let i=null;try{i=(await Rn(t,1024)).code}catch{}let a=e.codes.redeem(i),l=a?e.verify(a.token):null;return await pl(n,e.minMs??dl),!a||!l?(e.limiter.fail(s),r(`[app] pair-code failed from ${s}`),{status:401,body:{error:ul}}):(e.limiter.succeed(s),r(`[app] pair-code paired ${a.tokenId} (${l}) from ${s}`),{status:200,body:{device:l},token:a.token})}async function pl(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as Il}from"child_process";import{mkdtempSync as xl,rmSync as vl,writeFileSync as $l}from"fs";import{tmpdir as El}from"os";import{join as ws}from"path";import{randomBytes as gl}from"crypto";var C={top:8,side:32,bottom:60},vt={height:56,keep:52},ms=`
231
231
  :root {
232
232
  --ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
233
233
  --ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
@@ -356,16 +356,16 @@ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: v
356
356
  button.primary:disabled { opacity: .55; cursor: not-allowed; }
357
357
  kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
358
358
  button.primary kbd { color: inherit; opacity: .7; }
359
- `;var fs=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),ms=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function dl(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?fs(n):ms(n)}`}function pl(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[ms(n)],fs(n)].join(" ")}function gl(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 fl(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var vt=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>`,ml=vt('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),hl=vt('<path d="m6 15 6-6 6 6"/>'),bl=vt('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function hs(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,s=ul(12).toString("base64"),o=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",l=fn(t),u=o.map((p,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${k(p)}</span>${g===l.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${k(r)} recommends</span>`:"",d={choices:o,draft:t.draft??"",placeholder:pn,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=o.length?e.pick-1:l.index};return`<!doctype html>
359
+ `;var hs=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),bs=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function fl(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?hs(n):bs(n)}`}function ml(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[bs(n)],hs(n)].join(" ")}function hl(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 bl(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var $t=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>`,yl=$t('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),wl=$t('<path d="m6 15 6-6 6 6"/>'),kl=$t('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function ys(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,s=gl(12).toString("base64"),o=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",l=hn(t),u=o.map((p,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${k(p)}</span>${g===l.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${k(r)} recommends</span>`:"",d={choices:o,draft:t.draft??"",placeholder:fn,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=o.length?e.pick-1:l.index};return`<!doctype html>
360
360
  <html lang="en"><head><meta charset="utf-8">
361
361
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${s}'">
362
362
  <title>AgentX</title>
363
- <style>${gs}</style></head>
363
+ <style>${ms}</style></head>
364
364
  <body><div class="wrap"><main class="card${e.still?" still":""}">
365
- <div class="head" title="Drag to move"><span class="avatar">${k(gl(r))}</span>
366
- <div class="who"><b>${k(r)}</b><span>${k(dl(t.created_at,n))}</span></div>
365
+ <div class="head" title="Drag to move"><span class="avatar">${k(hl(r))}</span>
366
+ <div class="who"><b>${k(r)}</b><span>${k(fl(t.created_at,n))}</span></div>
367
367
  <span class="kind${i?"":" decision"}">${i?"Reminder":a?"Request":"Decision"}</span>
368
- <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${hl}</button></div>
368
+ <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${wl}</button></div>
369
369
  <div class="body"><h1 dir="auto">${k(t.title)}</h1>
370
370
  ${t.context?`<p class="context" dir="auto">${k(t.context)}</p>`:""}
371
371
  <p class="ask" dir="auto">${k(t.ask)}</p>
@@ -374,15 +374,15 @@ ${u?`<div class="options" role="radiogroup">${u}</div>`:""}
374
374
  ${l.why?`<p class="why" dir="auto">${k(l.why)}</p>`:""}
375
375
  ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><span class="edited"><i class="dot"></i>Edited</span><button class="reset" id="reset">Reset</button></div>
376
376
  <textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
377
- <div class="notes"><div>${ml}<span>${a?"It stays in Open requests on the Approvals page until you close it.":`If you don't answer by ${k(pl(t.expires,n))}: ${k(t.if_silent)}.`}</span></div>
378
- <div>${bl}<span>Nothing goes out until you click.</span></div></div>
377
+ <div class="notes"><div>${yl}<span>${a?"It stays in Open requests on the Approvals page until you close it.":`If you don't answer by ${k(ml(t.expires,n))}: ${k(t.if_silent)}.`}</span></div>
378
+ <div>${kl}<span>Nothing goes out until you click.</span></div></div>
379
379
  </div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
380
380
  <button class="btn" id="no">${a?"Drop":"No"}</button>
381
- <button class="btn primary" id="yes">${fl(t)}<kbd>\u2318\u21A9</kbd></button></div>
381
+ <button class="btn primary" id="yes">${bl(t)}<kbd>\u2318\u21A9</kbd></button></div>
382
382
  </main></div>
383
383
  <script type="application/json" id="data">${JSON.stringify(d).replace(/</g,"\\u003c")}</script>
384
- <script nonce="${s}">${yl}</script>
385
- </body></html>`}var yl=`
384
+ <script nonce="${s}">${Sl}</script>
385
+ </body></html>`}var Sl=`
386
386
  (function () {
387
387
  var d = JSON.parse(document.getElementById("data").textContent);
388
388
  var root = document.documentElement;
@@ -471,10 +471,10 @@ ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><sp
471
471
  });
472
472
  } catch (e) {}
473
473
  })();
474
- `;var vl=440,$l=`
474
+ `;var Rl=440,_l=`
475
475
  ObjC.import("Cocoa"); ObjC.import("WebKit")
476
476
  function run(argv) {
477
- var path = argv[0], side = ${C.side}, gripTop = ${C.top}, gripEnd = ${C.top+xt.height}, keep = ${xt.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
477
+ var path = argv[0], side = ${C.side}, gripTop = ${C.top}, gripEnd = ${C.top+vt.height}, keep = ${vt.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
478
478
  var app = $.NSApplication.sharedApplication
479
479
  app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
480
480
  ObjC.registerSubclass({ name: "AgentXCardView", superclass: "WKWebView", methods: {
@@ -546,22 +546,22 @@ function run(argv) {
546
546
  }
547
547
  function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
548
548
  function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
549
- `;function El(t,e){let n=t.trim().split(`
550
- `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&ws.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let s=e.choices??[],o;if(s.length){if(typeof r.choice!="string"||!s.includes(r.choice))return{action:"dismiss"};o=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
551
- `).trim():"",!i||i.length>dn.text)?{action:"dismiss"}:{action:"yes",...o?{choice:o}:{},...i?{text:i}:{}}}async function ys(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=wl(bs(xl(),"agentx-card-"));try{let o=bs(s,"card.html");Sl(o,hs(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",$l,o,String(vl),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?El(a.stdout,t):null}finally{kl(s,{recursive:!0,force:!0})}}var ws=["not now","timed out","closed"],Rl=(t,e,n)=>new Promise(r=>{try{_l(t,e,{timeout:n},(s,o)=>r({ok:!s,stdout:String(o??"")}))}catch{r({ok:!1,stdout:""})}}),ks=160,$t=15e3;function Ss(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>ks?e.slice(0,ks):e}async function Al(t,e,n,r,s){let o=e.sound==="chime"?r?"":"Glass":e.sound,i=o?vn(o):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],$t),!!e.speak)if(s){let a;await Promise.race([s(Ss(t)),new Promise(l=>{a=setTimeout(l,$t)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Ss(t)],$t)}}function $s(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function Il(t,e,n){return $s(["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 xs(t,e,n,r,s){return $s(["on run argv","set AppleScript's text item delimiters to linefeed","set btns to text items of (item 3 of argv)","set secs to (item 5 of argv) as integer","if (count of argv) > 5 then","set r to display dialog (item 2 of argv) with title (item 1 of argv) default answer (item 6 of argv) buttons btns default button (item 4 of argv) giving up after secs","else","set r to display dialog (item 2 of argv) with title (item 1 of argv) buttons btns default button (item 4 of argv) giving up after secs","end if",'if gave up of r then return ""',"if (count of argv) > 5 then return (button returned of r) & linefeed & (text returned of r)","return button returned of r","end run"],[t,e,n.join(`
552
- `),n[n.length-1],String(r),...s!==void 0?[s]:[]])}function vs(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
553
- `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function Et(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
549
+ `;function Al(t,e){let n=t.trim().split(`
550
+ `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Ss.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let s=e.choices??[],o;if(s.length){if(typeof r.choice!="string"||!s.includes(r.choice))return{action:"dismiss"};o=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
551
+ `).trim():"",!i||i.length>gn.text)?{action:"dismiss"}:{action:"yes",...o?{choice:o}:{},...i?{text:i}:{}}}async function ks(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=xl(ws(El(),"agentx-card-"));try{let o=ws(s,"card.html");$l(o,ys(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",_l,o,String(Rl),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?Al(a.stdout,t):null}finally{vl(s,{recursive:!0,force:!0})}}var Ss=["not now","timed out","closed"],Tl=(t,e,n)=>new Promise(r=>{try{Il(t,e,{timeout:n},(s,o)=>r({ok:!s,stdout:String(o??"")}))}catch{r({ok:!1,stdout:""})}}),xs=160,Et=15e3;function vs(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>xs?e.slice(0,xs):e}async function Dl(t,e,n,r,s){let o=e.sound==="chime"?r?"":"Glass":e.sound,i=o?En(o):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],Et),!!e.speak)if(s){let a;await Promise.race([s(vs(t)),new Promise(l=>{a=setTimeout(l,Et)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",vs(t)],Et)}}function Rs(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function Cl(t,e,n){return Rs(["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 $s(t,e,n,r,s){return Rs(["on run argv","set AppleScript's text item delimiters to linefeed","set btns to text items of (item 3 of argv)","set secs to (item 5 of argv) as integer","if (count of argv) > 5 then","set r to display dialog (item 2 of argv) with title (item 1 of argv) default answer (item 6 of argv) buttons btns default button (item 4 of argv) giving up after secs","else","set r to display dialog (item 2 of argv) with title (item 1 of argv) buttons btns default button (item 4 of argv) giving up after secs","end if",'if gave up of r then return ""',"if (count of argv) > 5 then return (button returned of r) & linefeed & (text returned of r)","return button returned of r","end run"],[t,e,n.join(`
552
+ `),n[n.length-1],String(r),...s!==void 0?[s]:[]])}function Es(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
553
+ `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function Rt(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
554
554
 
555
- `)}async function Es(t,e,n={}){let r=n.run??Rl,s=(e.style??"card")==="card",o=Al(t,e,r,s,n.speak).catch(()=>{});if(s){let i=await ys(t,{timeoutSeconds:e.timeoutSeconds,sound:e.sound,volume:e.volume,theme:e.theme,from:n.from,capture:n.capture,pick:n.pick},r).catch(()=>null);if(i)return i}return await o,Tl(t,e,r)}async function Tl(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=(r+5)*1e3,o=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let u=await n("/usr/bin/osascript",Il(o,Et(t),t.choices),s);if(i=u.stdout.replace(/\n$/,""),!u.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let u=i?`${i}
555
+ `)}async function _s(t,e,n={}){let r=n.run??Tl,s=(e.style??"card")==="card",o=Dl(t,e,r,s,n.speak).catch(()=>{});if(s){let i=await ks(t,{timeoutSeconds:e.timeoutSeconds,sound:e.sound,volume:e.volume,theme:e.theme,from:n.from,capture:n.capture,pick:n.pick},r).catch(()=>null);if(i)return i}return await o,Nl(t,e,r)}async function Nl(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),s=(r+5)*1e3,o=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let u=await n("/usr/bin/osascript",Cl(o,Rt(t),t.choices),s);if(i=u.stdout.replace(/\n$/,""),!u.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let u=i?`${i}
556
556
 
557
- Message (edit it if you like):`:`${Et(t)}
557
+ Message (edit it if you like):`:`${Rt(t)}
558
558
 
559
- Message (edit it if you like):`,d=await n("/usr/bin/osascript",xs(o,u,i?["Cancel","Send"]:["Not now","No","Send"],r,gn(t.draft,i)),s),p=d.ok?vs(d.stdout):null;if(p?.button==="Send"){let g=p.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return p?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",xs(o,Et(t),["Not now","No","Yes"],r),s),l=a.ok?vs(a.stdout):null;return l?.button==="Yes"?{action:"yes"}:l?.button==="No"?{action:"no"}:{action:"dismiss"}}var At=24*36e5,_t=!1,Dl=10*6e4,_s=-1/0;function Rs(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s,passAt:o,wanted:i=[]}=$(t.root),a=o?Date.parse(o):NaN,l=j(t.root,"pending").filter(c=>Date.parse(c.expires)>n),u=l.find(c=>i.includes(`card:${c.id}`));if(u)return u;for(let c of l){let d=`card:${c.id}`;if(r[d]||!e(c)||Cn(t.root,c.id,n))continue;let p=s[d];if(p&&Date.parse(p)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>At&&!(g<=a)))return c}return null}function Rt(t){try{return M(t)?.listByState("needs_attention")??[]}catch{return[]}}var As=new Map;function Cl(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s}=$(t.root);return e({})?Rt(t).find(o=>{let i=`request:${o.id}`,a=s[i];return As.get(o.id)===P(o,Me.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-o.updatedAt<=At})??null:null}function Nl(t,e){return{id:t.id,title:P(t,Me.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+At).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function eg(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(_t)return"busy";let s=Rs(e,t.reaches)?null:Cl(e,t.reaches),o=s?Nl(s,e.now??Date.now()):Rs(e,t.reaches);if(!o)return"none";let i=(t.focus??os)();if(i.active)return"held";let a=`${s?"request":"card"}:${o.id}`,l=($(e.root).wanted??[]).includes(a)?null:En(o);if(l){if(s)As.set(s.id,o.title);else{let u=[...j(e.root,"pending").map(c=>`card:${c.id}`),...Rt(e).map(c=>`request:${c.id}`)];je(e.root,a,u,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${o.raised_by}: ${l}`),t.returnToAuthor?.(o,_n(o,l)),"returned"}_t=!0;try{let u=[...j(e.root,"pending").map(b=>`card:${b.id}`),...Rt(e).map(b=>`request:${b.id}`)];je(e.root,a,u,e.now),r(`[approvals] popup: showing ${a} from ${o.raised_by}`);let c=e.now??Date.now(),d=!!s&&c-_s<Dl;s&&n.speak&&(_s=c);let p=t.agentName?.(o.raised_by)??(o.node?`${o.raised_by} on ${o.node}`:void 0),g=await(t.show??Es)(o,d?{...n,speak:!1}:n,{from:p,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${sn(i)} when shown)`),"shown";if(!(s?M(e)?.get(s.id)?.state==="needs_attention":G(e.root,o.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await gr(e,a,g.action,{by:"operator (popup)",...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(m.ok?`[approvals] popup: ${m.message}`:`[approvals] popup: ${a} not recorded: ${m.error}`),"shown"}catch(u){return r(`[approvals] popup failed for ${a}: ${u?.message??u}`),"shown"}finally{_t=!1}}function tg(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:")?G(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Vn(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 Ll,mkdirSync as Ol,readFileSync as Pl,renameSync as Ml,writeFileSync as Ul}from"fs";import{dirname as Fl,resolve as Wl}from"path";var jl=["all","urgent","off"],ql=24*36e5,Is=24*36e5,Vl=30*24*36e5,Ts=t=>jl.includes(t);function og(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:Ts(e)?e:"off",computer:Ts(n)?n:t.popupEnabled?"all":"off"}}function Cs(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=ql}function Ds(t,e,n){return t==="all"||t==="urgent"&&Cs(e,n)}function Ns(t){return Wl(t,".agentx","desk-routed.json")}function Bl(t){let e=Ns(t);if(!Ll(e))return null;try{let n=JSON.parse(Pl(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function It(t,e){let n=Ns(t);Ol(Fl(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Ul(r,JSON.stringify(e,null,2)),Ml(r,n)}async function ig(t){let{root:e,now:n,list:r,routing:s,log:o}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),l=Bl(e);if(!l){let d={};for(let p of r.items)d[p.key]={at:a,seen:a};return It(e,{items:d}),i.primed=!0,i}let u=[],c=[];for(let d of r.items){let p=l.items[d.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>Is&&delete p.computerHeld,p.computerHeld&&c.push(d);continue}l.items[d.key]={at:a,seen:a};let g=d.askedAt?Date.parse(d.askedAt):n;n-g<=Is&&u.push(d)}for(let[d,p]of Object.entries(l.items))n-Date.parse(p.seen)>Vl&&delete l.items[d];It(e,l);for(let d of u)if(Ds(s.phone,d,n))try{await t.phone(d,Cs(d,n)),i.phone.push(d.key)}catch(p){o(`[desk] ${d.key}: not sent to the phone: ${p?.message??p}`)}if(t.computer){let d=!1;for(let p of[...c,...u]){let g=l.items[p.key];if(!Ds(s.computer,p,n)){g.computerHeld&&(delete g.computerHeld,d=!0);continue}try{let f=await t.computer(p);f&&i.computer.push(p.key),f&&g.computerHeld&&(delete g.computerHeld,d=!0),!f&&!g.computerHeld&&(g.computerHeld=!0,d=!0)}catch(f){o(`[desk] ${p.key}: not shown on this computer: ${f?.message??f}`),g.computerHeld&&(delete g.computerHeld,d=!0)}}d&&It(e,l)}return(i.phone.length||i.computer.length)&&o(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function ag(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
560
- Answer it on the Desk.`}}import{closeSync as te,createReadStream as Hl,fstatSync as zl,openSync as Xl,realpathSync as Ls}from"fs";import{isAbsolute as Kl,resolve as Os,sep as Ps}from"path";var gg="/app-files",Gl=/^[A-Za-z0-9_.:-]{1,64}$/;function Jl(t,e,n=process.cwd()){if(!e||e.length>le.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 ${Pe}/ first`};if(!Oe(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Ls(Os(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let s;try{s=Ls(Kl(e)?e:Os(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!s.startsWith(r+Ps))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Pe}/ first`};let o=Oe(s);return o?{ok:!0,path:s,...o}:{ok:!1,status:415,error:"this type of file is not served"}}function Yl(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 Zl(t,e,n){return{"Content-Type":t,"Content-Disposition":Yl(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 Ql(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,s;return n[1]?(r=Number(n[1]),s=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),s=e-1),r>s||r>=e?"unsatisfiable":{start:r,end:s}}function fg(t,e,n,r){let s=(v,W)=>{e.writeHead(v,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(W))};if(t.method!=="GET"&&t.method!=="HEAD")return s(405,{error:"GET only"});let o=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!Gl.test(o))return s(400,{error:"bad agent id"});let a=r.workspaceOf(o);if(!a)return s(404,{error:`no agent "${o}" on this computer`});let l=Jl(a,i,r.cwd);if(!l.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${o}: ${l.error}`),s(l.status,{error:l.error});let u;try{u=Xl(l.path,"r")}catch{return s(404,{error:"file not found"})}let c;try{let v=zl(u);if(!v.isFile())return te(u),s(404,{error:"not a file"});c=v.size}catch{return te(u),s(404,{error:"file not found"})}if(c>le.bytes)return te(u),s(413,{error:`the file is larger than ${le.bytes/1024/1024} MB`});let d=l.path.split(Ps).pop()||"file",p=Zl(l.mime,d,l.kind),g=Ql(t.headers.range,c);if(g==="unsatisfiable"){te(u),e.writeHead(416,{...p,"Content-Range":`bytes */${c}`}),e.end();return}let{start:f,end:m}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(c?m-f+1:0),...g?{"Content-Range":`bytes ${f}-${m}/${c}`}:{}}),t.method==="HEAD"||c===0){te(u),e.end();return}let b=Hl("",{fd:u,start:f,end:m,autoClose:!0});b.on("error",()=>e.destroy()),e.on("close",()=>b.destroy()),b.pipe(e)}import{spawn as ne}from"child_process";import{readFileSync as ec,writeFileSync as tc}from"fs";import{tmpdir as nc}from"os";import{join as rc}from"path";Vt();var Ms=t=>t&&t!==1?Math.round(175*t):null,Ee=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function sc(){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=ec(t,"utf8").trim();if(e)return e}catch{}return null}function vg(t=sc()){let e=0;return async(n,r)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...Ee(n.voice.rate)?{voice_settings:{speed:Ee(n.voice.rate)}}:{}}),signal:r});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text()).slice(0,160)}`);let o=rc(nc(),`agentx-say-${process.pid}-${++e}.mp3`);return tc(o,Buffer.from(await s.arrayBuffer())),o}catch(s){if(r.aborted||!n.voice.fallback)throw s;return U(`elevenlabs:${String(s?.message??s).slice(0,40)}`,`[voice] ElevenLabs failed (${String(s?.message??s).slice(0,160)}); speaking with the system voice`),null}}}function Us(t,e){let n=t.languages&&ie(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var oc=(t,e="")=>{let n=Us(t,e),r=Ms(t.rate);return[...n&&!Er(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function ic(t,e,n){if(!n)return["say",oc(t,e)];let r=Us(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function $g(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function Eg(t=Tt()){if(t)try{ne("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function _g(t=Tt()){if(t)try{ne("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Tt(t={},e){if(!Qe(t))return null;try{return Ar(e)}catch(n){return U("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
561
- `)[0]}); Siri voices will not switch`),null}}var Rg=(t,e)=>{if(!t){let[n,r]=ic(e.voice,e.text,Tt()),s=Ms(e.voice.rate),o=s?{...process.env,AGENTX_SAY_RATE:String(s)}:process.env,i=ne(n,r,{stdio:["pipe","ignore","ignore"],env:o});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?ne("afplay",[t],{stdio:"ignore"}):ne("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Fs}from"child_process";import{accessSync as ac,constants as lc,readFileSync as Ws}from"fs";import{homedir as cc}from"os";import{basename as z,delimiter as js,dirname as uc,extname as dc,join as Dt}from"path";var O={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function qs(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)>O.ms+2e3?{status:413,error:Nt()}:null}var Nt=()=>`The recording is longer than ${O.ms/6e4} minutes.`,pc={"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 Vs(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return pc[e]??null}function Bs(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 Lt(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 Ct(t,e,n=process.env.PATH??""){let r=cc(),s=[Dt(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(js).filter(Boolean)];for(let o of[e,...s.map(i=>Dt(i,t))])if(o)try{return ac(o,lc.X_OK),o}catch{}return null}function Ng(t){return{key:t,mlx:Ct("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:Ct("whisper",process.env.AGENTX_WHISPER),ffmpeg:gc()}}var gc=()=>Ct("ffmpeg",process.env.AGENTX_FFMPEG);async function Hs(t,e){return e?fc(t,e):null}async function fc(t,e){let n=String(O.ms/1e3+5);try{let s=[...(await mc(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],o=s[s.length-1];return o?Number(o[1])*3600+Number(o[2])*60+Number(o[3]):null}catch{return null}}async function zs(t,e,n,r){let s=new FormData;s.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),s.set("file",new Blob([Ws(t)],{type:e}),z(t));let o=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:s,signal:r??AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text().catch(()=>"")).slice(0,160)}`);let i=await o.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function Xs(t,e,n,r,s){let o=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",s,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",s,"--fp16","False"],i={...process.env,PATH:`${uc(r)}${js}${process.env.PATH??""}`};await hc(e,o,12e4,i);try{return Ws(Dt(s,z(n,dc(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function mc(t,e,n){return new Promise((r,s)=>{let o=Fs(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{o.kill("SIGKILL"),s(new Error(`${z(t)} took too long`))},n);o.stderr.on("data",l=>{i=(i+l).slice(-8192)}),o.on("error",l=>{clearTimeout(a),s(l)}),o.on("exit",l=>{clearTimeout(a),l===0?r(i):s(new Error(`${z(t)} exited ${l}`))})})}function hc(t,e,n,r=process.env){return new Promise((s,o)=>{let i=Fs(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",l="",u=setTimeout(()=>{i.kill("SIGKILL"),o(new Error(`${z(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{l.length<4096&&(l+=c)}),i.on("error",c=>{clearTimeout(u),o(c)}),i.on("exit",c=>{clearTimeout(u),c===0?s(a):o(new Error(`${z(t)} exited ${c}: ${l.trim().split(`
562
- `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as bc,rm as yc,writeFile as wc}from"fs/promises";import{tmpdir as kc}from"os";import{join as Ks}from"path";ro();var Sc=64*1024,xc=2,Ot=0;function Bg(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Hg(t,e,n,r){return t.method!=="POST"?y(e,405,{error:"POST"}):n==="/voice/transcribe"?vc(t,e,r):_c(t,e,r)}async function vc(t,e,n){let r=String(t.headers["content-type"]||""),s=Vs(r);if(!s)return y(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let o=qs(t.headers["x-audio-duration-ms"]);if(o)return t.resume(),y(e,o.status,{error:o.error});let i=await Gs(t,O.bytes);if(!i)return y(e,413,{error:Ic()});if(!i.length)return y(e,400,{error:"The recording is empty."});if(Ot>=xc)return y(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),l=n.host(),u=Bs(a,l);if(!l.ffmpeg&&!n.allowUnmeasured?.()){let d=n.nodeName?`on ${n.nodeName}`:"on this computer",p=u.length?"":" "+Lt(a,l);return y(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${d} for voice input from the phone.${p}`,setup:!1})}if(!u.length)return y(e,503,{error:"Voice input isn't set up on this computer.",hint:Lt(a,l),setup:!1});Ot++;let c;try{let d=await bc(Ks(kc(),"agentx-phone-voice-"));try{c=await $c(d,`speech.${s}`,i,r,l,u,n)}finally{await yc(d,{recursive:!0,force:!0}).catch(()=>{})}}finally{Ot--}y(e,c[0],c[1])}async function $c(t,e,n,r,s,o,i){let a=Ks(t,e);if(await wc(a,n,{mode:384}),s.ffmpeg){let u=await(i.measure??Hs)(a,s.ffmpeg);if(u==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(u*1e3>O.ms+2e3)return[413,{error:Nt()}]}let l=[];for(let u of o)try{let c=await Ec(u,a,r,s,t,i);return i.log(`[voice] phone recording transcribed with ${u} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:u}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:u}]}catch(c){let d=String(c?.message??c).split(`
563
- `)[0].slice(0,200);l.push(`${u}: ${d}`),i.log(`[voice] phone transcription with ${u} failed: ${d}`)}return[502,{error:"Speech to text failed on this computer.",detail:l.join("; ")}]}function Ec(t,e,n,r,s,o){let i=o.engines?.[t];if(i)return i(e,n,r,s);if(t==="elevenlabs")return zs(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return Xs(t,a,e,r.ffmpeg,s)}async function _c(t,e,n){let r=await Gs(t,Sc);if(!r)return y(e,413,{error:"request too large"});let s;try{s=JSON.parse(r.toString("utf8")||"{}")}catch{return y(e,400,{error:"expected JSON"})}let o=typeof s?.agent=="string"?s.agent:"",i=typeof s?.peer=="string"&&s.peer?s.peer:void 0;if(!o)return y(e,400,{error:"agent is required"});let a=Rc(typeof s?.text=="string"?s.text:"",n.spokenMaxChars?.());if(!a)return y(e,422,{error:"Nothing in this answer can be said aloud."});let l=n.pronounce?n.pronounce(a):a,u=n.voiceOf(o,i);if(!u)return y(e,404,{error:`Unknown agent: ${o}`});let c=(p,g=200)=>y(e,g,{fallback:"browser",reason:p,text:l});if(u.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let d=n.elevenLabsKey();if(!d)return c("No ElevenLabs key is set on this computer.");try{let p=await(n.synth??Ac)(d,u,l);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(l.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
564
- `)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function Rc(t,e){let n=ts(nn(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Bt(n,e)}async function Ac(t,e,n){let r=Ee(e.rate),s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(e.elevenlabs)}?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n,model_id:"eleven_flash_v2_5",...r?{voice_settings:{speed:r}}:{}}),signal:AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await s.arrayBuffer())}var Ic=()=>`The recording is larger than ${O.bytes/1024/1024} MB, more than ${O.ms/6e4} minutes of speech.`;function zg(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let s=n.agents??{};return s[t]?ct(it(t,s,n.voice)):null}function Gs(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let s=[],o=0;t.on("data",i=>{if(!(o>e)){if(o+=i.length,o>e){s.length=0,n(null);return}s.push(i)}}),t.on("end",()=>{o<=e&&n(Buffer.concat(s))}),t.on("error",r)})}function y(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}import{existsSync as A,readFileSync as Ft,writeFileSync as Wt,mkdirSync as _e,readdirSync as Ut,rmSync as Tc,statSync as T}from"fs";import{resolve as Js,relative as Dc,dirname as jt,join as F,extname as re,basename as qt}from"path";var x=200*1024,Ys=new Set([".md",".markdown",".txt"]),X=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"]),Cc=6,Nc=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function N(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=Js(t);if(A(n)||_e(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=Js(n,e);if(Dc(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function Zs(t){let e=re(t).toLowerCase();if(!Ys.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Pt(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Jg(t){let e=N(t,"."),n=[],r=new Set,s=[];try{s=Ut(e)}catch{}for(let a of Nc){let l=F(e,a);if(A(l)&&T(l).isFile()){let u=T(l).size,c=u>0&&u<x?Mt(l):"";n.push({path:a,title:Pt(c,a),size:u,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of s){if(r.has(a))continue;let l=F(e,a);try{let u=T(l);if(!u.isFile()||!Ys.has(re(a).toLowerCase()))continue;let c=u.size>0&&u.size<x?Mt(l):"";n.push({path:a,title:Pt(c,a),size:u.size,exists:!0})}catch{}}let o=[],i=F(e,".claude","skills");if(A(i))try{for(let a of Ut(i)){let l=F(i,a),u;try{u=T(l)}catch{continue}if(!u.isDirectory())continue;let c=F(l,"SKILL.md");if(!A(c))continue;let d=T(c),p=d.size<x?Mt(c):"";o.push({slug:a,title:Pt(p,a),size:d.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return o.sort((a,l)=>a.slug.localeCompare(l.slug)),{identity:n,skills:o,workspace:e}}function Mt(t){try{return Ft(t,"utf-8")}catch{return""}}function Yg(t,e){let n=N(t,e);if(Zs(n),!A(n))return{path:e,content:""};if(T(n).size>x)throw new Error(`File is too large to edit in the admin panel (> ${x/1024} KB).`);return{path:e,content:Ft(n,"utf-8")}}function Zg(t,e,n){let r=N(t,e);Zs(r);let s=Buffer.from(n,"utf-8");if(s.length>x)throw new Error(`File too large (${s.length} > ${x} bytes).`);return _e(jt(r),{recursive:!0}),Wt(r,s),{path:e,bytes:s.length}}function Qg(t,e,n={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let r=`.claude/skills/${e}/SKILL.md`,s=N(t,r);if(A(s))throw new Error(`Skill "${e}" already exists.`);_e(jt(s),{recursive:!0});let o=n.content?.trim()?n.content:Lc(e,n.title);return Wt(s,o),{slug:e,path:r}}function ef(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=N(t,`.claude/skills/${e}`);if(!A(n))throw new Error(`Skill "${e}" not found.`);if(!T(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return Tc(n,{recursive:!0,force:!0}),{slug:e}}function tf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=N(t,`.claude/skills/${e}`);if(!A(n))throw new Error(`Skill "${e}" not found.`);let r=[];return s(n,"",0,r),r.sort((o,i)=>o.kind!==i.kind?o.kind==="dir"?-1:1:o.path.localeCompare(i.path)),r;function s(o,i,a,l){if(a>Cc)return;let u=[];try{u=Ut(o)}catch{return}for(let c of u){if(c==="node_modules"||c===".git")continue;let d=F(o,c),p=i?`${i}/${c}`:c,g;try{g=T(d)}catch{continue}if(g.isDirectory())l.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),s(d,p,a+1,l);else if(g.isFile()){let f=re(c).toLowerCase(),m=X.has(f)||X.has(c.toLowerCase());l.push({path:p,kind:"file",size:g.size,editable:m&&g.size<x})}}}}function nf(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=N(t,`.claude/skills/${e}/${n}`);if(!A(r)||!T(r).isFile())throw new Error(`File not found: ${n}`);let s=re(r).toLowerCase(),o=qt(r).toLowerCase();if(!X.has(s)&&!X.has(o))throw new Error(`File type not editable: ${n}`);if(T(r).size>x)throw new Error(`File too large to edit (> ${x/1024} KB): ${n}`);return{path:n,content:Ft(r,"utf-8")}}function rf(t,e,n,r){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let s=N(t,`.claude/skills/${e}/${n}`),o=re(s).toLowerCase(),i=qt(s).toLowerCase();if(!X.has(o)&&!X.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>x)throw new Error(`File too large (${a.length} > ${x} bytes).`);return _e(jt(s),{recursive:!0}),Wt(s,a),{path:n,bytes:a.length}}function sf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=N(t,`.claude/skills/${e}`);if(!A(n))throw new Error(`Skill "${e}" not found.`);let r=s=>A(F(n,s));return r("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:r("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:r("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:r("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:r("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function Lc(t,e){return`# ${e?.trim()||t}
559
+ Message (edit it if you like):`,d=await n("/usr/bin/osascript",$s(o,u,i?["Cancel","Send"]:["Not now","No","Send"],r,mn(t.draft,i)),s),p=d.ok?Es(d.stdout):null;if(p?.button==="Send"){let g=p.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return p?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",$s(o,Rt(t),["Not now","No","Yes"],r),s),l=a.ok?Es(a.stdout):null;return l?.button==="Yes"?{action:"yes"}:l?.button==="No"?{action:"no"}:{action:"dismiss"}}var It=24*36e5,_t=!1,Ll=10*6e4,As=-1/0;function Is(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s,passAt:o,wanted:i=[]}=$(t.root),a=o?Date.parse(o):NaN,l=j(t.root,"pending").filter(c=>Date.parse(c.expires)>n),u=l.find(c=>i.includes(`card:${c.id}`));if(u)return u;for(let c of l){let d=`card:${c.id}`;if(r[d]||!e(c)||Ln(t.root,c.id,n))continue;let p=s[d];if(p&&Date.parse(p)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>It&&!(g<=a)))return c}return null}function At(t){try{return M(t)?.listByState("needs_attention")??[]}catch{return[]}}var Ts=new Map;function Ol(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:s}=$(t.root);return e({})?At(t).find(o=>{let i=`request:${o.id}`,a=s[i];return Ts.get(o.id)===P(o,Ue.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-o.updatedAt<=It})??null:null}function Pl(t,e){return{id:t.id,title:P(t,Ue.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+It).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function sg(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(_t)return"busy";let s=Is(e,t.reaches)?null:Ol(e,t.reaches),o=s?Pl(s,e.now??Date.now()):Is(e,t.reaches);if(!o)return"none";let i=(t.focus??as)();if(i.active)return"held";let a=`${s?"request":"card"}:${o.id}`,l=($(e.root).wanted??[]).includes(a)?null:_n(o);if(l){if(s)Ts.set(s.id,o.title);else{let u=[...j(e.root,"pending").map(c=>`card:${c.id}`),...At(e).map(c=>`request:${c.id}`)];qe(e.root,a,u,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${o.raised_by}: ${l}`),t.returnToAuthor?.(o,An(o,l)),"returned"}_t=!0;try{let u=[...j(e.root,"pending").map(b=>`card:${b.id}`),...At(e).map(b=>`request:${b.id}`)];qe(e.root,a,u,e.now),r(`[approvals] popup: showing ${a} from ${o.raised_by}`);let c=e.now??Date.now(),d=!!s&&c-As<Ll;s&&n.speak&&(As=c);let p=t.agentName?.(o.raised_by)??(o.node?`${o.raised_by} on ${o.node}`:void 0),g=await(t.show??_s)(o,d?{...n,speak:!1}:n,{from:p,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${an(i)} when shown)`),"shown";if(!(s?M(e)?.get(s.id)?.state==="needs_attention":G(e.root,o.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await mr(e,a,g.action,{by:"operator (popup)",...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(m.ok?`[approvals] popup: ${m.message}`:`[approvals] popup: ${a} not recorded: ${m.error}`),"shown"}catch(u){return r(`[approvals] popup failed for ${a}: ${u?.message??u}`),"shown"}finally{_t=!1}}function og(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:")?G(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Hn(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 Ml,mkdirSync as Ul,readFileSync as Fl,renameSync as Wl,writeFileSync as jl}from"fs";import{dirname as ql,resolve as Vl}from"path";var Bl=["all","urgent","off"],Hl=24*36e5,Ds=24*36e5,zl=30*24*36e5,Cs=t=>Bl.includes(t);function cg(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:Cs(e)?e:"off",computer:Cs(n)?n:t.popupEnabled?"all":"off"}}function Ls(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=Hl}function Ns(t,e,n){return t==="all"||t==="urgent"&&Ls(e,n)}function Os(t){return Vl(t,".agentx","desk-routed.json")}function Xl(t){let e=Os(t);if(!Ml(e))return null;try{let n=JSON.parse(Fl(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function Tt(t,e){let n=Os(t);Ul(ql(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;jl(r,JSON.stringify(e,null,2)),Wl(r,n)}async function ug(t){let{root:e,now:n,list:r,routing:s,log:o}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),l=Xl(e);if(!l){let d={};for(let p of r.items)d[p.key]={at:a,seen:a};return Tt(e,{items:d}),i.primed=!0,i}let u=[],c=[];for(let d of r.items){let p=l.items[d.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>Ds&&delete p.computerHeld,p.computerHeld&&c.push(d);continue}l.items[d.key]={at:a,seen:a};let g=d.askedAt?Date.parse(d.askedAt):n;n-g<=Ds&&u.push(d)}for(let[d,p]of Object.entries(l.items))n-Date.parse(p.seen)>zl&&delete l.items[d];Tt(e,l);for(let d of u)if(Ns(s.phone,d,n))try{await t.phone(d,Ls(d,n)),i.phone.push(d.key)}catch(p){o(`[desk] ${d.key}: not sent to the phone: ${p?.message??p}`)}if(t.computer){let d=!1;for(let p of[...c,...u]){let g=l.items[p.key];if(!Ns(s.computer,p,n)){g.computerHeld&&(delete g.computerHeld,d=!0);continue}try{let f=await t.computer(p);f&&i.computer.push(p.key),f&&g.computerHeld&&(delete g.computerHeld,d=!0),!f&&!g.computerHeld&&(g.computerHeld=!0,d=!0)}catch(f){o(`[desk] ${p.key}: not shown on this computer: ${f?.message??f}`),g.computerHeld&&(delete g.computerHeld,d=!0)}}d&&Tt(e,l)}return(i.phone.length||i.computer.length)&&o(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function dg(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
560
+ Answer it on the Desk.`}}import{closeSync as te,createReadStream as Kl,fstatSync as Gl,openSync as Jl,realpathSync as Ps}from"fs";import{isAbsolute as Yl,resolve as Ms,sep as Us}from"path";var bg="/app-files",Zl=/^[A-Za-z0-9_.:-]{1,64}$/;function Ql(t,e,n=process.cwd()){if(!e||e.length>le.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 ${Me}/ first`};if(!Pe(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Ps(Ms(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let s;try{s=Ps(Yl(e)?e:Ms(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!s.startsWith(r+Us))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Me}/ first`};let o=Pe(s);return o?{ok:!0,path:s,...o}:{ok:!1,status:415,error:"this type of file is not served"}}function ec(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 tc(t,e,n){return{"Content-Type":t,"Content-Disposition":ec(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 nc(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,s;return n[1]?(r=Number(n[1]),s=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),s=e-1),r>s||r>=e?"unsatisfiable":{start:r,end:s}}function yg(t,e,n,r){let s=(v,W)=>{e.writeHead(v,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(W))};if(t.method!=="GET"&&t.method!=="HEAD")return s(405,{error:"GET only"});let o=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!Zl.test(o))return s(400,{error:"bad agent id"});let a=r.workspaceOf(o);if(!a)return s(404,{error:`no agent "${o}" on this computer`});let l=Ql(a,i,r.cwd);if(!l.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${o}: ${l.error}`),s(l.status,{error:l.error});let u;try{u=Jl(l.path,"r")}catch{return s(404,{error:"file not found"})}let c;try{let v=Gl(u);if(!v.isFile())return te(u),s(404,{error:"not a file"});c=v.size}catch{return te(u),s(404,{error:"file not found"})}if(c>le.bytes)return te(u),s(413,{error:`the file is larger than ${le.bytes/1024/1024} MB`});let d=l.path.split(Us).pop()||"file",p=tc(l.mime,d,l.kind),g=nc(t.headers.range,c);if(g==="unsatisfiable"){te(u),e.writeHead(416,{...p,"Content-Range":`bytes */${c}`}),e.end();return}let{start:f,end:m}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(c?m-f+1:0),...g?{"Content-Range":`bytes ${f}-${m}/${c}`}:{}}),t.method==="HEAD"||c===0){te(u),e.end();return}let b=Kl("",{fd:u,start:f,end:m,autoClose:!0});b.on("error",()=>e.destroy()),e.on("close",()=>b.destroy()),b.pipe(e)}import{spawn as ne}from"child_process";import{readFileSync as rc,writeFileSync as sc}from"fs";import{tmpdir as oc}from"os";import{join as ic}from"path";Ht();var Fs=t=>t&&t!==1?Math.round(175*t):null,Ee=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function ac(){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=rc(t,"utf8").trim();if(e)return e}catch{}return null}function _g(t=ac()){let e=0;return async(n,r)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...Ee(n.voice.rate)?{voice_settings:{speed:Ee(n.voice.rate)}}:{}}),signal:r});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text()).slice(0,160)}`);let o=ic(oc(),`agentx-say-${process.pid}-${++e}.mp3`);return sc(o,Buffer.from(await s.arrayBuffer())),o}catch(s){if(r.aborted||!n.voice.fallback)throw s;return U(`elevenlabs:${String(s?.message??s).slice(0,40)}`,`[voice] ElevenLabs failed (${String(s?.message??s).slice(0,160)}); speaking with the system voice`),null}}}function Ws(t,e){let n=t.languages&&ie(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var lc=(t,e="")=>{let n=Ws(t,e),r=Fs(t.rate);return[...n&&!_r(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function cc(t,e,n){if(!n)return["say",lc(t,e)];let r=Ws(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function Ag(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function Ig(t=Dt()){if(t)try{ne("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Tg(t=Dt()){if(t)try{ne("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Dt(t={},e){if(!et(t))return null;try{return Tr(e)}catch(n){return U("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
561
+ `)[0]}); Siri voices will not switch`),null}}var Dg=(t,e)=>{if(!t){let[n,r]=cc(e.voice,e.text,Dt()),s=Fs(e.voice.rate),o=s?{...process.env,AGENTX_SAY_RATE:String(s)}:process.env,i=ne(n,r,{stdio:["pipe","ignore","ignore"],env:o});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?ne("afplay",[t],{stdio:"ignore"}):ne("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as js}from"child_process";import{accessSync as uc,constants as dc,readFileSync as qs}from"fs";import{homedir as pc}from"os";import{basename as z,delimiter as Vs,dirname as gc,extname as fc,join as Ct}from"path";var O={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function Bs(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>O.ms+2e3?{status:413,error:Lt()}:null}var Lt=()=>`The recording is longer than ${O.ms/6e4} minutes.`,mc={"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 Hs(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return mc[e]??null}function zs(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 Ot(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 Nt(t,e,n=process.env.PATH??""){let r=pc(),s=[Ct(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(Vs).filter(Boolean)];for(let o of[e,...s.map(i=>Ct(i,t))])if(o)try{return uc(o,dc.X_OK),o}catch{}return null}function Mg(t){return{key:t,mlx:Nt("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:Nt("whisper",process.env.AGENTX_WHISPER),ffmpeg:hc()}}var hc=()=>Nt("ffmpeg",process.env.AGENTX_FFMPEG);async function Xs(t,e){return e?bc(t,e):null}async function bc(t,e){let n=String(O.ms/1e3+5);try{let s=[...(await yc(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],o=s[s.length-1];return o?Number(o[1])*3600+Number(o[2])*60+Number(o[3]):null}catch{return null}}async function Ks(t,e,n,r){let s=new FormData;s.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),s.set("file",new Blob([qs(t)],{type:e}),z(t));let o=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:s,signal:r??AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text().catch(()=>"")).slice(0,160)}`);let i=await o.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function Gs(t,e,n,r,s){let o=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",s,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",s,"--fp16","False"],i={...process.env,PATH:`${gc(r)}${Vs}${process.env.PATH??""}`};await wc(e,o,12e4,i);try{return qs(Ct(s,z(n,fc(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function yc(t,e,n){return new Promise((r,s)=>{let o=js(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{o.kill("SIGKILL"),s(new Error(`${z(t)} took too long`))},n);o.stderr.on("data",l=>{i=(i+l).slice(-8192)}),o.on("error",l=>{clearTimeout(a),s(l)}),o.on("exit",l=>{clearTimeout(a),l===0?r(i):s(new Error(`${z(t)} exited ${l}`))})})}function wc(t,e,n,r=process.env){return new Promise((s,o)=>{let i=js(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",l="",u=setTimeout(()=>{i.kill("SIGKILL"),o(new Error(`${z(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{l.length<4096&&(l+=c)}),i.on("error",c=>{clearTimeout(u),o(c)}),i.on("exit",c=>{clearTimeout(u),c===0?s(a):o(new Error(`${z(t)} exited ${c}: ${l.trim().split(`
562
+ `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as kc,rm as Sc,writeFile as xc}from"fs/promises";import{tmpdir as vc}from"os";import{join as Js}from"path";io();var $c=64*1024,Ec=2,Pt=0;function Kg(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Gg(t,e,n,r){return t.method!=="POST"?y(e,405,{error:"POST"}):n==="/voice/transcribe"?Rc(t,e,r):Ic(t,e,r)}async function Rc(t,e,n){let r=String(t.headers["content-type"]||""),s=Hs(r);if(!s)return y(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let o=Bs(t.headers["x-audio-duration-ms"]);if(o)return t.resume(),y(e,o.status,{error:o.error});let i=await Ys(t,O.bytes);if(!i)return y(e,413,{error:Cc()});if(!i.length)return y(e,400,{error:"The recording is empty."});if(Pt>=Ec)return y(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),l=n.host(),u=zs(a,l);if(!l.ffmpeg&&!n.allowUnmeasured?.()){let d=n.nodeName?`on ${n.nodeName}`:"on this computer",p=u.length?"":" "+Ot(a,l);return y(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${d} for voice input from the phone.${p}`,setup:!1})}if(!u.length)return y(e,503,{error:"Voice input isn't set up on this computer.",hint:Ot(a,l),setup:!1});Pt++;let c;try{let d=await kc(Js(vc(),"agentx-phone-voice-"));try{c=await _c(d,`speech.${s}`,i,r,l,u,n)}finally{await Sc(d,{recursive:!0,force:!0}).catch(()=>{})}}finally{Pt--}y(e,c[0],c[1])}async function _c(t,e,n,r,s,o,i){let a=Js(t,e);if(await xc(a,n,{mode:384}),s.ffmpeg){let u=await(i.measure??Xs)(a,s.ffmpeg);if(u==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(u*1e3>O.ms+2e3)return[413,{error:Lt()}]}let l=[];for(let u of o)try{let c=await Ac(u,a,r,s,t,i);return i.log(`[voice] phone recording transcribed with ${u} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:u}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:u}]}catch(c){let d=String(c?.message??c).split(`
563
+ `)[0].slice(0,200);l.push(`${u}: ${d}`),i.log(`[voice] phone transcription with ${u} failed: ${d}`)}return[502,{error:"Speech to text failed on this computer.",detail:l.join("; ")}]}function Ac(t,e,n,r,s,o){let i=o.engines?.[t];if(i)return i(e,n,r,s);if(t==="elevenlabs")return Ks(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return Gs(t,a,e,r.ffmpeg,s)}async function Ic(t,e,n){let r=await Ys(t,$c);if(!r)return y(e,413,{error:"request too large"});let s;try{s=JSON.parse(r.toString("utf8")||"{}")}catch{return y(e,400,{error:"expected JSON"})}let o=typeof s?.agent=="string"?s.agent:"",i=typeof s?.peer=="string"&&s.peer?s.peer:void 0;if(!o)return y(e,400,{error:"agent is required"});let a=Tc(typeof s?.text=="string"?s.text:"",n.spokenMaxChars?.());if(!a)return y(e,422,{error:"Nothing in this answer can be said aloud."});let l=n.pronounce?n.pronounce(a):a,u=n.voiceOf(o,i);if(!u)return y(e,404,{error:`Unknown agent: ${o}`});let c=(p,g=200)=>y(e,g,{fallback:"browser",reason:p,text:l});if(u.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let d=n.elevenLabsKey();if(!d)return c("No ElevenLabs key is set on this computer.");try{let p=await(n.synth??Dc)(d,u,l);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(l.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
564
+ `)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function Tc(t,e){let n=rs(sn(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return zt(n,e)}async function Dc(t,e,n){let r=Ee(e.rate),s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(e.elevenlabs)}?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n,model_id:"eleven_flash_v2_5",...r?{voice_settings:{speed:r}}:{}}),signal:AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await s.arrayBuffer())}var Cc=()=>`The recording is larger than ${O.bytes/1024/1024} MB, more than ${O.ms/6e4} minutes of speech.`;function Jg(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let s=n.agents??{};return s[t]?ut(at(t,s,n.voice)):null}function Ys(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let s=[],o=0;t.on("data",i=>{if(!(o>e)){if(o+=i.length,o>e){s.length=0,n(null);return}s.push(i)}}),t.on("end",()=>{o<=e&&n(Buffer.concat(s))}),t.on("error",r)})}function y(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}import{existsSync as A,readFileSync as Wt,writeFileSync as jt,mkdirSync as Re,readdirSync as Ft,rmSync as Nc,statSync as T}from"fs";import{resolve as Zs,relative as Lc,dirname as qt,join as F,extname as re,basename as Vt}from"path";var x=200*1024,Qs=new Set([".md",".markdown",".txt"]),X=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"]),Oc=6,Pc=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function N(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=Zs(t);if(A(n)||Re(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=Zs(n,e);if(Lc(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function eo(t){let e=re(t).toLowerCase();if(!Qs.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Mt(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function ef(t){let e=N(t,"."),n=[],r=new Set,s=[];try{s=Ft(e)}catch{}for(let a of Pc){let l=F(e,a);if(A(l)&&T(l).isFile()){let u=T(l).size,c=u>0&&u<x?Ut(l):"";n.push({path:a,title:Mt(c,a),size:u,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of s){if(r.has(a))continue;let l=F(e,a);try{let u=T(l);if(!u.isFile()||!Qs.has(re(a).toLowerCase()))continue;let c=u.size>0&&u.size<x?Ut(l):"";n.push({path:a,title:Mt(c,a),size:u.size,exists:!0})}catch{}}let o=[],i=F(e,".claude","skills");if(A(i))try{for(let a of Ft(i)){let l=F(i,a),u;try{u=T(l)}catch{continue}if(!u.isDirectory())continue;let c=F(l,"SKILL.md");if(!A(c))continue;let d=T(c),p=d.size<x?Ut(c):"";o.push({slug:a,title:Mt(p,a),size:d.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return o.sort((a,l)=>a.slug.localeCompare(l.slug)),{identity:n,skills:o,workspace:e}}function Ut(t){try{return Wt(t,"utf-8")}catch{return""}}function tf(t,e){let n=N(t,e);if(eo(n),!A(n))return{path:e,content:""};if(T(n).size>x)throw new Error(`File is too large to edit in the admin panel (> ${x/1024} KB).`);return{path:e,content:Wt(n,"utf-8")}}function nf(t,e,n){let r=N(t,e);eo(r);let s=Buffer.from(n,"utf-8");if(s.length>x)throw new Error(`File too large (${s.length} > ${x} bytes).`);return Re(qt(r),{recursive:!0}),jt(r,s),{path:e,bytes:s.length}}function rf(t,e,n={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let r=`.claude/skills/${e}/SKILL.md`,s=N(t,r);if(A(s))throw new Error(`Skill "${e}" already exists.`);Re(qt(s),{recursive:!0});let o=n.content?.trim()?n.content:Mc(e,n.title);return jt(s,o),{slug:e,path:r}}function sf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=N(t,`.claude/skills/${e}`);if(!A(n))throw new Error(`Skill "${e}" not found.`);if(!T(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return Nc(n,{recursive:!0,force:!0}),{slug:e}}function of(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=N(t,`.claude/skills/${e}`);if(!A(n))throw new Error(`Skill "${e}" not found.`);let r=[];return s(n,"",0,r),r.sort((o,i)=>o.kind!==i.kind?o.kind==="dir"?-1:1:o.path.localeCompare(i.path)),r;function s(o,i,a,l){if(a>Oc)return;let u=[];try{u=Ft(o)}catch{return}for(let c of u){if(c==="node_modules"||c===".git")continue;let d=F(o,c),p=i?`${i}/${c}`:c,g;try{g=T(d)}catch{continue}if(g.isDirectory())l.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),s(d,p,a+1,l);else if(g.isFile()){let f=re(c).toLowerCase(),m=X.has(f)||X.has(c.toLowerCase());l.push({path:p,kind:"file",size:g.size,editable:m&&g.size<x})}}}}function af(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=N(t,`.claude/skills/${e}/${n}`);if(!A(r)||!T(r).isFile())throw new Error(`File not found: ${n}`);let s=re(r).toLowerCase(),o=Vt(r).toLowerCase();if(!X.has(s)&&!X.has(o))throw new Error(`File type not editable: ${n}`);if(T(r).size>x)throw new Error(`File too large to edit (> ${x/1024} KB): ${n}`);return{path:n,content:Wt(r,"utf-8")}}function lf(t,e,n,r){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let s=N(t,`.claude/skills/${e}/${n}`),o=re(s).toLowerCase(),i=Vt(s).toLowerCase();if(!X.has(o)&&!X.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>x)throw new Error(`File too large (${a.length} > ${x} bytes).`);return Re(qt(s),{recursive:!0}),jt(s,a),{path:n,bytes:a.length}}function cf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=N(t,`.claude/skills/${e}`);if(!A(n))throw new Error(`Skill "${e}" not found.`);let r=s=>A(F(n,s));return r("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:r("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:r("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:r("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:r("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function Mc(t,e){return`# ${e?.trim()||t}
565
565
 
566
566
  Describe what this skill does and when the agent should use it. Keep it under ~5 lines \u2014 the agent reads this to decide whether to invoke the skill.
567
567
 
@@ -574,7 +574,7 @@ Document the arguments, commands, or files the skill expects. Example:
574
574
 
575
575
  \`\`\`bash
576
576
  # Example invocation
577
- claude-code ${qt(t)} --arg value
577
+ claude-code ${Vt(t)} --arg value
578
578
  \`\`\`
579
- `}Yt();var Qs={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function eo(t){return{...Qs,...t??{},regions:{...t?.regions??{}},buffer:{...Qs.buffer,...t?.buffer??{}}}}function lf(t){try{return eo(Jt(t).screen)}catch{return eo(void 0)}}var Oc=/^[a-z][\w-]*$/,to=["window","screen","menubar","notifications"];function se(t,e,n,r){let s=Number(t);if(t===""||t===null||!Number.isFinite(s)||!n(s))throw new Error(`${e} must be ${r}`);return s}var Re=(t,e)=>se(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function no(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 cf(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Re(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Re(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Re(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=se(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=se(e.changeThreshold,"changeThreshold",s=>s>=0&&s<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let s={...n.regions??{}};for(let[o,i]of Object.entries(e.regions)){if(!Oc.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=no(i)}n.regions=s}if(e.buffer&&typeof e.buffer=="object"){let s=e.buffer,o={...n.buffer??{}};"enabled"in s&&(o.enabled=!!s.enabled),"seconds"in s&&(o.seconds=se(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=se(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=Re(s.maxPixels,"buffer.maxPixels")),"region"in s&&(o.region=String(s.region).trim()),n.buffer=o}let r=n.buffer?.region;if(r!==void 0&&!to.includes(r)&&!n.regions?.[r])try{no(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...to,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Nn as a,Uc as b,kt as c,Aa as d,Ia as e,Jd as f,Yd as g,Zd as h,tp as i,np as j,rp as k,Qr as l,es as m,sp as n,ts as o,ip as p,lp as q,L as r,ns as s,S as t,qc as u,os as v,fp as w,bp as x,as as y,yp as z,ls as A,wp as B,ee as C,nl as D,kp as E,Sp as F,us as G,ru as H,Po as I,cu as J,Zn as K,du as L,$ as M,Xc as N,Kc as O,wu as P,pe as Q,ku as R,Bn as S,eu as T,M as U,Vu as V,pr as W,gr as X,gi as Y,fi as Z,zu as _,Xu as $,Si as aa,Yu as ba,ps as ca,$p as da,ed as ea,td as fa,Gr as ga,dt as ha,Sa as ia,Es as ja,eg as ka,tg as la,jl as ma,og as na,Ds as oa,ig as pa,ag as qa,gg as ra,Zl as sa,fg as ta,rd as ua,sd as va,od as wa,id as xa,ad as ya,ld as za,ud as Aa,dd as Ba,kd as Ca,nt as Da,Sd as Ea,xd as Fa,Z as Ga,Q as Ha,sc as Ia,vg as Ja,$g as Ka,Eg as La,_g as Ma,Tt as Na,Rg as Oa,ot as Pa,it as Qa,ke as Ra,Xi as Sa,Gi as Ta,Rd as Ua,lt as Va,ct as Wa,Ji as Xa,Yi as Ya,Ur as Za,qr as _a,Ad as $a,ea as ab,Id as bb,la as cb,da as db,ut as eb,ga as fb,Vr as gb,O as hb,qs as ib,Vs as jb,Bs as kb,Ct as lb,Ng as mb,gc as nb,zs as ob,Xs as pb,Bg as qb,Hg as rb,Ic as sb,zg as tb,Gs as ub,Se as vb,jd as wb,yt as xb,Kd as yb,Jg as zb,Yg as Ab,Zg as Bb,Qg as Cb,ef as Db,tf as Eb,nf as Fb,rf as Gb,sf as Hb,Qs as Ib,eo as Jb,lf as Kb,to as Lb,cf as Mb};
580
- //# sourceMappingURL=chunk-KVAWRQBA.js.map
579
+ `}Qt();var to={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function no(t){return{...to,...t??{},regions:{...t?.regions??{}},buffer:{...to.buffer,...t?.buffer??{}}}}function pf(t){try{return no(Zt(t).screen)}catch{return no(void 0)}}var Uc=/^[a-z][\w-]*$/,ro=["window","screen","menubar","notifications"];function se(t,e,n,r){let s=Number(t);if(t===""||t===null||!Number.isFinite(s)||!n(s))throw new Error(`${e} must be ${r}`);return s}var _e=(t,e)=>se(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function so(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 gf(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=_e(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=_e(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=_e(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=se(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=se(e.changeThreshold,"changeThreshold",s=>s>=0&&s<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let s={...n.regions??{}};for(let[o,i]of Object.entries(e.regions)){if(!Uc.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=so(i)}n.regions=s}if(e.buffer&&typeof e.buffer=="object"){let s=e.buffer,o={...n.buffer??{}};"enabled"in s&&(o.enabled=!!s.enabled),"seconds"in s&&(o.seconds=se(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=se(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=_e(s.maxPixels,"buffer.maxPixels")),"region"in s&&(o.region=String(s.region).trim()),n.buffer=o}let r=n.buffer?.region;if(r!==void 0&&!ro.includes(r)&&!n.regions?.[r])try{so(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...ro,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{On as a,jc as b,St as c,Da as d,Ca as e,ep as f,tp as g,np as h,op as i,ip as j,ap as k,ts as l,ns as m,lp as n,rs as o,up as p,pp as q,L as r,ss as s,S as t,Hc as u,as as v,yp as w,Sp as x,cs as y,xp as z,us as A,vp as B,ee as C,ol as D,$p as E,Ep as F,ps as G,iu as H,Fo as I,pu as J,er as K,fu as L,$ as M,Jc as N,Yc as O,xu as P,pe as Q,vu as R,zn as S,ru as T,M as U,zu as V,fr as W,mr as X,hi as Y,bi as Z,Gu as _,Ju as $,$i as aa,ed as ba,fs as ca,Ap as da,rd as ea,sd as fa,Yr as ga,pt as ha,$a as ia,_s as ja,sg as ka,og as la,Bl as ma,cg as na,Ns as oa,ug as pa,dg as qa,bg as ra,tc as sa,yg as ta,id as ua,ad as va,ld as wa,cd as xa,ud as ya,dd as za,gd as Aa,fd as Ba,vd as Ca,rt as Da,$d as Ea,Ed as Fa,Z as Ga,Q as Ha,ac as Ia,_g as Ja,Ag as Ka,Ig as La,Tg as Ma,Dt as Na,Dg as Oa,it as Pa,at as Qa,ke as Ra,Ji as Sa,Zi as Ta,Td as Ua,ct as Va,ut as Wa,Qi as Xa,ea as Ya,Wr as Za,Br as _a,Dd as $a,ra as ab,Cd as bb,da as cb,fa as db,dt as eb,ha as fb,Hr as gb,O as hb,Bs as ib,Hs as jb,zs as kb,Nt as lb,Mg as mb,hc as nb,Ks as ob,Gs as pb,Kg as qb,Gg as rb,Cc as sb,Jg as tb,Ys as ub,Se as vb,Bd as wb,wt as xb,Yd as yb,ef as zb,tf as Ab,nf as Bb,rf as Cb,sf as Db,of as Eb,af as Fb,lf as Gb,cf as Hb,to as Ib,no as Jb,pf as Kb,ro as Lb,gf as Mb};
580
+ //# sourceMappingURL=chunk-R3CDFSNF.js.map