agentix-cli 0.205.0 → 0.206.1

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 (172) hide show
  1. package/dist/{App-JDW5V4HT.js → App-IEUOKINQ.js} +2 -2
  2. package/dist/{ChatApp-SNM2PORO.js → ChatApp-CCDBG6YZ.js} +2 -2
  3. package/dist/{absorb-eval-WDAV4AI2.js → absorb-eval-IIF7CY3Q.js} +2 -2
  4. package/dist/{adapter-C47BTKT6.js → adapter-LTHULD3D.js} +2 -2
  5. package/dist/{agent-EVMKJXJO.js → agent-TZ3GGNS5.js} +2 -2
  6. package/dist/{board-dashboard-VSDTP4Y7.js → board-dashboard-JS6OJDH6.js} +365 -351
  7. package/dist/board-dashboard-JS6OJDH6.js.map +1 -0
  8. package/dist/{chunk-AK46ORUI.js → chunk-37EABHYL.js} +2 -2
  9. package/dist/chunk-3AHYZLGE.js +115 -0
  10. package/dist/chunk-3AHYZLGE.js.map +1 -0
  11. package/dist/{chunk-PQUK6XEW.js → chunk-6U34GZ7U.js} +2 -2
  12. package/dist/{chunk-GWBFEVLO.js → chunk-6ZVVAGTR.js} +2 -2
  13. package/dist/{chunk-IU63JGY3.js → chunk-7GD5GTWC.js} +2 -2
  14. package/dist/{chunk-X6SXZDTY.js → chunk-7JHB3X5N.js} +16 -16
  15. package/dist/chunk-7JHB3X5N.js.map +1 -0
  16. package/dist/{chunk-SKCOIP5R.js → chunk-A2K6C6W3.js} +3 -3
  17. package/dist/{chunk-OLKYIKAZ.js → chunk-B35GIWMR.js} +2 -2
  18. package/dist/{chunk-DUCYRNCT.js → chunk-CARVBJB7.js} +20 -20
  19. package/dist/chunk-CARVBJB7.js.map +1 -0
  20. package/dist/{chunk-KRHVM26D.js → chunk-E2MW5OCE.js} +2 -2
  21. package/dist/{chunk-WJMYBRM5.js → chunk-FXA2WIIP.js} +2 -2
  22. package/dist/{chunk-KWZ6NMXZ.js → chunk-GCBFLU64.js} +10 -10
  23. package/dist/{chunk-S6YN3IBM.js → chunk-GJOKXP5D.js} +2 -2
  24. package/dist/{chunk-PQX2VJUA.js → chunk-I4753XPP.js} +45 -45
  25. package/dist/chunk-I4753XPP.js.map +1 -0
  26. package/dist/{chunk-2VSK6FAR.js → chunk-I74PTSUQ.js} +2 -2
  27. package/dist/{chunk-ERVJLPS4.js → chunk-JDU4CXGC.js} +2 -2
  28. package/dist/{chunk-DV42WUMD.js → chunk-K435U2FC.js} +2 -2
  29. package/dist/chunk-KEUW6YLL.js +2 -0
  30. package/dist/{chunk-VJ5HC63R.js.map → chunk-KEUW6YLL.js.map} +1 -1
  31. package/dist/{chunk-DOO4MUTS.js → chunk-KXMC7Z5X.js} +2 -2
  32. package/dist/chunk-LY4G7PCW.js +2 -0
  33. package/dist/chunk-LY4G7PCW.js.map +1 -0
  34. package/dist/{chunk-5STGF4MI.js → chunk-M37WJANA.js} +88 -88
  35. package/dist/chunk-M37WJANA.js.map +1 -0
  36. package/dist/{chunk-CXFVIDJV.js → chunk-R6XJWFMC.js} +2 -2
  37. package/dist/{chunk-245IOYDJ.js → chunk-RPL2P7EP.js} +2 -2
  38. package/dist/{chunk-UGRMFQAG.js → chunk-RRLQTU3X.js} +2 -2
  39. package/dist/{chunk-ZUHUCSGT.js → chunk-TLRTJV2U.js} +311 -303
  40. package/dist/chunk-TLRTJV2U.js.map +1 -0
  41. package/dist/{chunk-JT5PIBCM.js → chunk-U3OJO7B7.js} +2 -2
  42. package/dist/{chunk-RXX4MYFL.js → chunk-UN7D7HWU.js} +2 -2
  43. package/dist/{chunk-2P3SHT5I.js → chunk-VALKXSXZ.js} +2 -2
  44. package/dist/{chunk-CZVCT5ZV.js → chunk-WI7J22NL.js} +2 -2
  45. package/dist/{chunk-PTZNM2JU.js → chunk-WTCMJZW3.js} +2 -2
  46. package/dist/chunk-XL7UWG36.js +12 -0
  47. package/dist/chunk-XL7UWG36.js.map +1 -0
  48. package/dist/{chunk-IDGEDPRJ.js → chunk-XTIPWYW5.js} +2 -2
  49. package/dist/{chunk-QASIUKZJ.js → chunk-Z6J3RTYJ.js} +2 -2
  50. package/dist/{chunk-PW3WG6JT.js → chunk-ZOK6VMEP.js} +2 -2
  51. package/dist/cli.js +1 -1
  52. package/dist/{client-WN7YI7DE.js → client-NPC2JAWL.js} +2 -2
  53. package/dist/{config-QUXKGIZX.js → config-TIMTRSFH.js} +2 -2
  54. package/dist/config-mutate-V3DRUCK4.js +2 -0
  55. package/dist/{config-mutator-OLLQR3ZD.js → config-mutator-HOYYIPNW.js} +2 -2
  56. package/dist/{contributions-LL7B4BP3.js → contributions-TYVRQG7F.js} +2 -2
  57. package/dist/doctor-TNQ4Q2OS.js +2 -0
  58. package/dist/{facts-ALJBF7IA.js → facts-XGZWX6CR.js} +2 -2
  59. package/dist/{follow-up-tool-I2HTKMP4.js → follow-up-tool-3P2YCRBL.js} +2 -2
  60. package/dist/{grants-5GIY7347.js → grants-TWDH3Z4K.js} +2 -2
  61. package/dist/hub-GVTRKPAU.js +2 -0
  62. package/dist/index.d.ts +107 -45
  63. package/dist/index.js +1 -1
  64. package/dist/{org-tool-JCGGJJU6.js → org-tool-EKO7GCPL.js} +2 -2
  65. package/dist/{program-7VNYZPRO.js → program-Y55FFHIJ.js} +86 -86
  66. package/dist/{promote-NSPUPPHB.js → promote-JYYV44FK.js} +2 -2
  67. package/dist/{query-VW63IHDI.js → query-PUWWCFET.js} +2 -2
  68. package/dist/{query-settings-RS7DJI4H.js → query-settings-IJPG3N6D.js} +2 -2
  69. package/dist/registry-QJGTPSK2.js +2 -0
  70. package/dist/{request-planner-HZWQIRZO.js → request-planner-HHJXCWCG.js} +2 -2
  71. package/dist/{review-candidates-2TXOUASP.js → review-candidates-XZUQELL5.js} +2 -2
  72. package/dist/rotation-memo-store-ZH6254YR.js +2 -0
  73. package/dist/rotation-memo-store-ZH6254YR.js.map +1 -0
  74. package/dist/{routing-ZV4VSZDV.js → routing-HWZHJ4LZ.js} +2 -2
  75. package/dist/schedule-tool-7W5CRUN4.js +2 -0
  76. package/dist/{scheduler-SAID6RKQ.js → scheduler-WG3KXJIH.js} +2 -2
  77. package/dist/{seat-XHBWBSTS.js → seat-5BOBWKBX.js} +2 -2
  78. package/dist/{select-QUCTTAH3.js → select-FIHHBFNR.js} +2 -2
  79. package/dist/{set-enabled-CGMXLFC6.js → set-enabled-K7OM7PSO.js} +2 -2
  80. package/dist/{sprint-tool-SWRYSX3Q.js → sprint-tool-O6TTSWJN.js} +2 -2
  81. package/dist/{tool-DA25L4ND.js → tool-4KVS2JWC.js} +2 -2
  82. package/dist/{tool-ELGOVIM5.js → tool-BYU6EZKM.js} +2 -2
  83. package/dist/{tool-MMH2JNP7.js → tool-HTUSCV22.js} +2 -2
  84. package/dist/{tool-6G63ZQW4.js → tool-HVCLZGYE.js} +2 -2
  85. package/dist/{wiki-4ZL4QXA7.js → wiki-ZMEMGR7R.js} +2 -2
  86. package/dist/wiki-enrich-QZHQV7VZ.js +2 -0
  87. package/dist/workspace-setup-GTSXWYU4.js +2 -0
  88. package/package.json +1 -1
  89. package/dist/board-dashboard-VSDTP4Y7.js.map +0 -1
  90. package/dist/chunk-36X7D4JA.js +0 -2
  91. package/dist/chunk-36X7D4JA.js.map +0 -1
  92. package/dist/chunk-5STGF4MI.js.map +0 -1
  93. package/dist/chunk-DUCYRNCT.js.map +0 -1
  94. package/dist/chunk-IFNXMUEG.js +0 -115
  95. package/dist/chunk-IFNXMUEG.js.map +0 -1
  96. package/dist/chunk-PQX2VJUA.js.map +0 -1
  97. package/dist/chunk-VJ5HC63R.js +0 -2
  98. package/dist/chunk-WDGATQV3.js +0 -12
  99. package/dist/chunk-WDGATQV3.js.map +0 -1
  100. package/dist/chunk-X6SXZDTY.js.map +0 -1
  101. package/dist/chunk-ZUHUCSGT.js.map +0 -1
  102. package/dist/config-mutate-HJH24ITC.js +0 -2
  103. package/dist/doctor-WJ5H7QQW.js +0 -2
  104. package/dist/hub-7ASBN76I.js +0 -2
  105. package/dist/registry-6KREAROB.js +0 -2
  106. package/dist/rotation-memo-store-WMDI7NND.js +0 -2
  107. package/dist/rotation-memo-store-WMDI7NND.js.map +0 -1
  108. package/dist/schedule-tool-D357NLXS.js +0 -2
  109. package/dist/wiki-enrich-N5MUKDVW.js +0 -2
  110. package/dist/workspace-setup-QXFJRNSK.js +0 -2
  111. /package/dist/{App-JDW5V4HT.js.map → App-IEUOKINQ.js.map} +0 -0
  112. /package/dist/{ChatApp-SNM2PORO.js.map → ChatApp-CCDBG6YZ.js.map} +0 -0
  113. /package/dist/{absorb-eval-WDAV4AI2.js.map → absorb-eval-IIF7CY3Q.js.map} +0 -0
  114. /package/dist/{adapter-C47BTKT6.js.map → adapter-LTHULD3D.js.map} +0 -0
  115. /package/dist/{agent-EVMKJXJO.js.map → agent-TZ3GGNS5.js.map} +0 -0
  116. /package/dist/{chunk-AK46ORUI.js.map → chunk-37EABHYL.js.map} +0 -0
  117. /package/dist/{chunk-PQUK6XEW.js.map → chunk-6U34GZ7U.js.map} +0 -0
  118. /package/dist/{chunk-GWBFEVLO.js.map → chunk-6ZVVAGTR.js.map} +0 -0
  119. /package/dist/{chunk-IU63JGY3.js.map → chunk-7GD5GTWC.js.map} +0 -0
  120. /package/dist/{chunk-SKCOIP5R.js.map → chunk-A2K6C6W3.js.map} +0 -0
  121. /package/dist/{chunk-OLKYIKAZ.js.map → chunk-B35GIWMR.js.map} +0 -0
  122. /package/dist/{chunk-KRHVM26D.js.map → chunk-E2MW5OCE.js.map} +0 -0
  123. /package/dist/{chunk-WJMYBRM5.js.map → chunk-FXA2WIIP.js.map} +0 -0
  124. /package/dist/{chunk-KWZ6NMXZ.js.map → chunk-GCBFLU64.js.map} +0 -0
  125. /package/dist/{chunk-S6YN3IBM.js.map → chunk-GJOKXP5D.js.map} +0 -0
  126. /package/dist/{chunk-2VSK6FAR.js.map → chunk-I74PTSUQ.js.map} +0 -0
  127. /package/dist/{chunk-ERVJLPS4.js.map → chunk-JDU4CXGC.js.map} +0 -0
  128. /package/dist/{chunk-DV42WUMD.js.map → chunk-K435U2FC.js.map} +0 -0
  129. /package/dist/{chunk-DOO4MUTS.js.map → chunk-KXMC7Z5X.js.map} +0 -0
  130. /package/dist/{chunk-CXFVIDJV.js.map → chunk-R6XJWFMC.js.map} +0 -0
  131. /package/dist/{chunk-245IOYDJ.js.map → chunk-RPL2P7EP.js.map} +0 -0
  132. /package/dist/{chunk-UGRMFQAG.js.map → chunk-RRLQTU3X.js.map} +0 -0
  133. /package/dist/{chunk-JT5PIBCM.js.map → chunk-U3OJO7B7.js.map} +0 -0
  134. /package/dist/{chunk-RXX4MYFL.js.map → chunk-UN7D7HWU.js.map} +0 -0
  135. /package/dist/{chunk-2P3SHT5I.js.map → chunk-VALKXSXZ.js.map} +0 -0
  136. /package/dist/{chunk-CZVCT5ZV.js.map → chunk-WI7J22NL.js.map} +0 -0
  137. /package/dist/{chunk-PTZNM2JU.js.map → chunk-WTCMJZW3.js.map} +0 -0
  138. /package/dist/{chunk-IDGEDPRJ.js.map → chunk-XTIPWYW5.js.map} +0 -0
  139. /package/dist/{chunk-QASIUKZJ.js.map → chunk-Z6J3RTYJ.js.map} +0 -0
  140. /package/dist/{chunk-PW3WG6JT.js.map → chunk-ZOK6VMEP.js.map} +0 -0
  141. /package/dist/{client-WN7YI7DE.js.map → client-NPC2JAWL.js.map} +0 -0
  142. /package/dist/{config-QUXKGIZX.js.map → config-TIMTRSFH.js.map} +0 -0
  143. /package/dist/{config-mutate-HJH24ITC.js.map → config-mutate-V3DRUCK4.js.map} +0 -0
  144. /package/dist/{config-mutator-OLLQR3ZD.js.map → config-mutator-HOYYIPNW.js.map} +0 -0
  145. /package/dist/{contributions-LL7B4BP3.js.map → contributions-TYVRQG7F.js.map} +0 -0
  146. /package/dist/{doctor-WJ5H7QQW.js.map → doctor-TNQ4Q2OS.js.map} +0 -0
  147. /package/dist/{facts-ALJBF7IA.js.map → facts-XGZWX6CR.js.map} +0 -0
  148. /package/dist/{follow-up-tool-I2HTKMP4.js.map → follow-up-tool-3P2YCRBL.js.map} +0 -0
  149. /package/dist/{grants-5GIY7347.js.map → grants-TWDH3Z4K.js.map} +0 -0
  150. /package/dist/{hub-7ASBN76I.js.map → hub-GVTRKPAU.js.map} +0 -0
  151. /package/dist/{org-tool-JCGGJJU6.js.map → org-tool-EKO7GCPL.js.map} +0 -0
  152. /package/dist/{program-7VNYZPRO.js.map → program-Y55FFHIJ.js.map} +0 -0
  153. /package/dist/{promote-NSPUPPHB.js.map → promote-JYYV44FK.js.map} +0 -0
  154. /package/dist/{query-VW63IHDI.js.map → query-PUWWCFET.js.map} +0 -0
  155. /package/dist/{query-settings-RS7DJI4H.js.map → query-settings-IJPG3N6D.js.map} +0 -0
  156. /package/dist/{registry-6KREAROB.js.map → registry-QJGTPSK2.js.map} +0 -0
  157. /package/dist/{request-planner-HZWQIRZO.js.map → request-planner-HHJXCWCG.js.map} +0 -0
  158. /package/dist/{review-candidates-2TXOUASP.js.map → review-candidates-XZUQELL5.js.map} +0 -0
  159. /package/dist/{routing-ZV4VSZDV.js.map → routing-HWZHJ4LZ.js.map} +0 -0
  160. /package/dist/{schedule-tool-D357NLXS.js.map → schedule-tool-7W5CRUN4.js.map} +0 -0
  161. /package/dist/{scheduler-SAID6RKQ.js.map → scheduler-WG3KXJIH.js.map} +0 -0
  162. /package/dist/{seat-XHBWBSTS.js.map → seat-5BOBWKBX.js.map} +0 -0
  163. /package/dist/{select-QUCTTAH3.js.map → select-FIHHBFNR.js.map} +0 -0
  164. /package/dist/{set-enabled-CGMXLFC6.js.map → set-enabled-K7OM7PSO.js.map} +0 -0
  165. /package/dist/{sprint-tool-SWRYSX3Q.js.map → sprint-tool-O6TTSWJN.js.map} +0 -0
  166. /package/dist/{tool-DA25L4ND.js.map → tool-4KVS2JWC.js.map} +0 -0
  167. /package/dist/{tool-ELGOVIM5.js.map → tool-BYU6EZKM.js.map} +0 -0
  168. /package/dist/{tool-MMH2JNP7.js.map → tool-HTUSCV22.js.map} +0 -0
  169. /package/dist/{tool-6G63ZQW4.js.map → tool-HVCLZGYE.js.map} +0 -0
  170. /package/dist/{wiki-4ZL4QXA7.js.map → wiki-ZMEMGR7R.js.map} +0 -0
  171. /package/dist/{wiki-enrich-N5MUKDVW.js.map → wiki-enrich-QZHQV7VZ.js.map} +0 -0
  172. /package/dist/{workspace-setup-QXFJRNSK.js.map → workspace-setup-GTSXWYU4.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{Hb as l,Rb as m}from"./chunk-DUCYRNCT.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
1
+ import{Hb as l,Rb as m}from"./chunk-CARVBJB7.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
2
2
  `,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
4
- //# sourceMappingURL=chunk-IU63JGY3.js.map
4
+ //# sourceMappingURL=chunk-7GD5GTWC.js.map
@@ -1,10 +1,10 @@
1
- import{a as mt}from"./chunk-GTJIKXDB.js";import{H as br,O as Ar,k as K}from"./chunk-GWBFEVLO.js";import{f as Er,g as _r,h as $r,l as Tr}from"./chunk-PQUK6XEW.js";import{a as Sr}from"./chunk-JSCVOB4G.js";import{a as wr,i as xr,l as kr,n as pt,o as gt,q as pe,r as ee,t as vr}from"./chunk-WDGATQV3.js";import{b as yr}from"./chunk-2VDO2HEK.js";import{t as fr,u as hr}from"./chunk-PW3WG6JT.js";import{d as gr,e as mr}from"./chunk-AQASR6KR.js";import{a as Zn,b as er,d as tr,e as nr}from"./chunk-MNG2AMKZ.js";import{h as ue,j as rr,l as or,m as sr,n as ir}from"./chunk-RX5O5637.js";import{h as Kn,i as Gn,j as Yn,l as Jn,m as Qn}from"./chunk-KRHVM26D.js";import{a as ar,c as lr,e as cr,f as lt,h as dr,j as ur,k as pr,l as ct,m as dt,n as ut}from"./chunk-5ELIX7BQ.js";import{a as Xn,c as zn}from"./chunk-KP7KDLZ2.js";import{c as Re,d as Hn,e as Vn}from"./chunk-XVV7ZZ77.js";import{Aa as de,Ca as at,b as ot,f as Fn,s as st,u as it,xa as Ae,ya as Bn,za as W}from"./chunk-JT5PIBCM.js";import{a as $e,b as ce,e as Un}from"./chunk-7AB3QUGH.js";import{s as qn}from"./chunk-IDGEDPRJ.js";import{a as Wn,b as Te,e as jn}from"./chunk-2P3SHT5I.js";import{b as Z}from"./chunk-5ONH4ITT.js";import{a as Mn,c as rt}from"./chunk-ILEC3IAV.js";import{a as Pn}from"./chunk-QUFIUXMQ.js";import{E as _e,F as _n,G as $n,Gb as Nn,H as ki,Hb as On,Rb as Ln,f as Qe,g as C,i as Ee,j as E,k as le,l as Sn,o as En,p as Ze,ta as Rn,ua as In,wa as Dn,xa as Cn,xb as nt}from"./chunk-DUCYRNCT.js";import{a as et,h as vi}from"./chunk-VJ5HC63R.js";import{j as tt,q as Tn,r as An}from"./chunk-UEEB3UTU.js";import{existsSync as Si,readdirSync as Ei,readFileSync as _i,statSync as $i}from"fs";import{resolve as Ti}from"path";function Rr(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],d=a.filter(m=>n-m.at<=o),l=a.filter(m=>n-m.at>o&&n-m.at<=o*2),c=d.filter(m=>m.status==="failed").length,p=a.filter(m=>m.status==="paused").length,u=a.length?Math.max(...a.map(m=>m.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var Ie=new Map;function Du(t,e=1e3){if(!Si(t))return[];let n=Ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ti(t,s);return{path:i,mtime:$i(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of Ie.keys())r.has(s)||Ie.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=Ie.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Ai(s,i);Ie.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Ai(t,e){try{let n=_i(t,"utf-8").split(`
2
- `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Ir=7,Ri={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},A={routines:200,summary:160,filters:6,filterValue:60,text:120},Ii=(t,e,n)=>{try{return qn(t,e,n)}catch{return null}},Dr=864e5;function Lu(t){let e=t.now??Date.now(),n={...Ri,...t.thresholds},r=t.nextFire??Ii,o=[];for(let a of t.crons){let d=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",c=d.map(g=>({at:Date.parse(g.startedAt),status:g.status})),p=d[0],u={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:F(a.id,A.text),trigger:{schedule:F(a.schedule,A.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?ft(a.nextRun)??ft(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:Pi(p.status==="success"?void 0:p.errorSummary,A.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Cr(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Ir).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Nr(u,c,a.schedule,l,null,e,n,r),o.push(Or(u))}let s=new Map(Rr(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let d=i.get(a.workflowId);d?d.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let d=a.nodes.find(k=>k.type.startsWith("trigger."));if(!d||d.type!=="trigger.cron"&&d.type!=="trigger.hook")continue;let l=d.config??{},c=a.state||"active",p=c==="active",u=(i.get(a.id)??[]).slice().sort((k,D)=>D.at-k.at),g=u.map(k=>({at:k.at,status:Ni(k.status)})),m=g[0],f=d.type==="trigger.cron",w=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",b={id:`workflow:${a.id}`,source:"workflow",kind:f?"schedule":"event",name:F(a.title||a.id,A.text),trigger:f?{schedule:F(w,A.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",A.text),filters:Li(l.filter,a)},agent:Oi(a),enabled:p,state:c,nextRunAt:f&&p&&w?ft(r(w,new Date(e),x)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let k=g.find(D=>D.status==="success");return k?new Date(k.at).toISOString():null})(),consecutiveFailures:Cr(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Ir).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=f?Nr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):Di(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Or(b))}return o.sort(Ci).slice(0,A.routines)}function Cr(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 Nr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=Pr(l,o,s,i);return u&&d.push(u),d}if(t.consecutiveFailures>=i.failStreak&&d.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return d.push({reason:"never-ran",detail:"No persisted attempt"}),d;let c=new Date(l),p=null;for(let u=0;u<i.missedFires&&(p=a(n,c,r),!!p);u++)c=p;return p&&s>p.getTime()+i.graceMs&&d.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),d}function Di(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Pr(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function Pr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Dr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Dr)} days`:"Disabled and never ran"}}function Or(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 Lr={critical:0,warning:1,info:2};function Ci(t,e){let n=t.attention?Lr[t.attention]:3,r=e.attention?Lr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Ni(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 Oi(t){if(t.ownerAgent)return F(t.ownerAgent,A.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?F(String(e.config.agentId),A.text):null}function Li(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,A.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(F(`${o}=${i.join(",")}`,A.filterValue))}return n.slice(0,A.filters)}function ft(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function F(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Pi(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as Mi,readFileSync as Fi,renameSync as Ui,writeFileSync as Wi}from"fs";import{resolve as ji}from"path";function Mr(t){return ji(gt(t),"_state.json")}function N(t){try{let e=JSON.parse(Fi(Mr(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function ge(t,e){Mi(gt(t),{recursive:!0});let n=Mr(t),r=`${n}.${process.pid}.tmp`;Wi(r,JSON.stringify(e,null,2)+`
3
- `),Ui(r,n)}function Fr(t,e,n,r=Date.now()){let o=N(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),ge(t,{...o,snoozed:s})}function Wu(t,e){ge(t,{...N(t),lastDigest:e})}function ht(t,e,n,r=Date.now()){let o=N(t),s=new Set(n),i={};for(let[d,l]of Object.entries(o.popped??{}))s.has(d)&&(i[d]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(d=>d!==e&&s.has(d));ge(t,{...o,popped:i,wanted:a})}function Ur(t,e){let n=N(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function ju(t,e=Date.now()){ge(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as qi,readFileSync as Bi}from"fs";Ln();vi();function Wr(t){let e=Wn(t),n={};if(qi(e))try{n=Nn(JSON.parse(Bi(e,"utf-8")))}catch{n={}}let r=nt.safeParse(n?.requests);return r.success?r.data:nt.parse(void 0)}async function zu(t,e={}){let n=(t.channels??[]).filter(r=>!et.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...et].join(", ")}`}:Te(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as H,readdirSync as da,readFileSync as xt,statSync as ua}from"fs";import{dirname as io,resolve as T}from"path";import{randomBytes as Br}from"crypto";import{existsSync as Vi,mkdirSync as Xi,readdirSync as zi,readFileSync as Ki,renameSync as Hr,unlinkSync as Gi,writeFileSync as Yi}from"fs";import{resolve as Vr}from"path";function jr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Hi=t=>t.trim().split(`
1
+ import{a as mt}from"./chunk-GTJIKXDB.js";import{H as kr,O as Ar,k as K}from"./chunk-6ZVVAGTR.js";import{f as Er,g as _r,h as $r,l as Tr}from"./chunk-6U34GZ7U.js";import{a as Sr}from"./chunk-JSCVOB4G.js";import{b as vr}from"./chunk-2VDO2HEK.js";import{t as wr,u as xr}from"./chunk-ZOK6VMEP.js";import{d as br,e as yr}from"./chunk-AQASR6KR.js";import{h as pe,j as ar,l as lr,m as cr,n as dr}from"./chunk-RX5O5637.js";import{h as nr,i as rr,j as or,l as sr,m as ir}from"./chunk-E2MW5OCE.js";import{a as ur,c as pr,e as gr,f as dt,h as mr,j as fr,k as hr,l as ut,m as pt,n as gt}from"./chunk-5ELIX7BQ.js";import{a as er,c as tr}from"./chunk-KP7KDLZ2.js";import{c as Re,d as Qn,e as Zn}from"./chunk-XVV7ZZ77.js";import{Aa as ue,Ca as ct,b as it,f as Xn,s as at,u as lt,xa as Ae,ya as Jn,za as W}from"./chunk-U3OJO7B7.js";import{a as $e,b as de,e as zn}from"./chunk-7AB3QUGH.js";import{s as Yn}from"./chunk-XTIPWYW5.js";import{a as Kn,b as Te,e as Gn}from"./chunk-VALKXSXZ.js";import{b as ee}from"./chunk-5ONH4ITT.js";import{a as Vn,c as st}from"./chunk-ILEC3IAV.js";import{a as Pn}from"./chunk-QUFIUXMQ.js";import{a as Mn,i as qn,l as Bn,n as rt,o as ot,r as ce,s as Z,u as Hn}from"./chunk-XL7UWG36.js";import{a as Fn,b as Un,d as Wn,e as jn}from"./chunk-MNG2AMKZ.js";import{E as _e,F as _n,G as $n,Gb as Nn,H as ki,Hb as On,Rb as Ln,f as Qe,g as C,i as Ee,j as E,k as le,l as Sn,o as En,p as Ze,ta as Rn,ua as In,wa as Dn,xa as Cn,xb as nt}from"./chunk-CARVBJB7.js";import{a as et,h as vi}from"./chunk-KEUW6YLL.js";import{j as tt,q as Tn,r as An}from"./chunk-UEEB3UTU.js";import{existsSync as Si,readdirSync as Ei,readFileSync as _i,statSync as $i}from"fs";import{resolve as Ti}from"path";function Rr(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],d=a.filter(m=>n-m.at<=o),l=a.filter(m=>n-m.at>o&&n-m.at<=o*2),c=d.filter(m=>m.status==="failed").length,p=a.filter(m=>m.status==="paused").length,u=a.length?Math.max(...a.map(m=>m.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var Ie=new Map;function Du(t,e=1e3){if(!Si(t))return[];let n=Ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ti(t,s);return{path:i,mtime:$i(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of Ie.keys())r.has(s)||Ie.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=Ie.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Ai(s,i);Ie.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Ai(t,e){try{let n=_i(t,"utf-8").split(`
2
+ `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Ir=7,Ri={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},A={routines:200,summary:160,filters:6,filterValue:60,text:120},Ii=(t,e,n)=>{try{return Yn(t,e,n)}catch{return null}},Dr=864e5;function Lu(t){let e=t.now??Date.now(),n={...Ri,...t.thresholds},r=t.nextFire??Ii,o=[];for(let a of t.crons){let d=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",c=d.map(g=>({at:Date.parse(g.startedAt),status:g.status})),p=d[0],u={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:F(a.id,A.text),trigger:{schedule:F(a.schedule,A.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?ft(a.nextRun)??ft(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:Pi(p.status==="success"?void 0:p.errorSummary,A.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Cr(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Ir).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Nr(u,c,a.schedule,l,null,e,n,r),o.push(Or(u))}let s=new Map(Rr(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let d=i.get(a.workflowId);d?d.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let d=a.nodes.find(k=>k.type.startsWith("trigger."));if(!d||d.type!=="trigger.cron"&&d.type!=="trigger.hook")continue;let l=d.config??{},c=a.state||"active",p=c==="active",u=(i.get(a.id)??[]).slice().sort((k,D)=>D.at-k.at),g=u.map(k=>({at:k.at,status:Ni(k.status)})),m=g[0],f=d.type==="trigger.cron",w=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",b={id:`workflow:${a.id}`,source:"workflow",kind:f?"schedule":"event",name:F(a.title||a.id,A.text),trigger:f?{schedule:F(w,A.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",A.text),filters:Li(l.filter,a)},agent:Oi(a),enabled:p,state:c,nextRunAt:f&&p&&w?ft(r(w,new Date(e),x)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let k=g.find(D=>D.status==="success");return k?new Date(k.at).toISOString():null})(),consecutiveFailures:Cr(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Ir).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=f?Nr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):Di(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Or(b))}return o.sort(Ci).slice(0,A.routines)}function Cr(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 Nr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=Pr(l,o,s,i);return u&&d.push(u),d}if(t.consecutiveFailures>=i.failStreak&&d.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return d.push({reason:"never-ran",detail:"No persisted attempt"}),d;let c=new Date(l),p=null;for(let u=0;u<i.missedFires&&(p=a(n,c,r),!!p);u++)c=p;return p&&s>p.getTime()+i.graceMs&&d.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),d}function Di(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Pr(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function Pr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Dr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Dr)} days`:"Disabled and never ran"}}function Or(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 Lr={critical:0,warning:1,info:2};function Ci(t,e){let n=t.attention?Lr[t.attention]:3,r=e.attention?Lr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Ni(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 Oi(t){if(t.ownerAgent)return F(t.ownerAgent,A.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?F(String(e.config.agentId),A.text):null}function Li(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,A.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(F(`${o}=${i.join(",")}`,A.filterValue))}return n.slice(0,A.filters)}function ft(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function F(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Pi(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as Mi,readFileSync as Fi,renameSync as Ui,writeFileSync as Wi}from"fs";import{resolve as ji}from"path";function Mr(t){return ji(ot(t),"_state.json")}function N(t){try{let e=JSON.parse(Fi(Mr(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function ge(t,e){Mi(ot(t),{recursive:!0});let n=Mr(t),r=`${n}.${process.pid}.tmp`;Wi(r,JSON.stringify(e,null,2)+`
3
+ `),Ui(r,n)}function Fr(t,e,n,r=Date.now()){let o=N(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),ge(t,{...o,snoozed:s})}function Wu(t,e){ge(t,{...N(t),lastDigest:e})}function ht(t,e,n,r=Date.now()){let o=N(t),s=new Set(n),i={};for(let[d,l]of Object.entries(o.popped??{}))s.has(d)&&(i[d]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(d=>d!==e&&s.has(d));ge(t,{...o,popped:i,wanted:a})}function Ur(t,e){let n=N(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function ju(t,e=Date.now()){ge(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as qi,readFileSync as Bi}from"fs";Ln();vi();function Wr(t){let e=Kn(t),n={};if(qi(e))try{n=Nn(JSON.parse(Bi(e,"utf-8")))}catch{n={}}let r=nt.safeParse(n?.requests);return r.success?r.data:nt.parse(void 0)}async function zu(t,e={}){let n=(t.channels??[]).filter(r=>!et.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...et].join(", ")}`}:Te(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as H,readdirSync as da,readFileSync as xt,statSync as ua}from"fs";import{dirname as io,resolve as T}from"path";import{randomBytes as Br}from"crypto";import{existsSync as Vi,mkdirSync as Xi,readdirSync as zi,readFileSync as Ki,renameSync as Hr,unlinkSync as Gi,writeFileSync as Yi}from"fs";import{resolve as Vr}from"path";function jr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Hi=t=>t.trim().split(`
4
4
  `).pop()?.slice(0,300)||"no output";async function qr(t,e,n,r=mt){let o=await r(t.bin,[...jr(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Hi(o.stderr||o.stdout)}`}}async function Yu(t,e,n,r,o=mt){return(await o(t.bin,[...jr(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Ji=2e3,Qi=t=>qr(t.wacli,t.to,t.text);function bt(t){return Vr(t,".agentx","whatsapp-triage","drafts")}var Zi=t=>/^[a-z0-9-]{8,64}$/.test(t),De=(t,e)=>Vr(bt(t),`${e}.json`);function Xr(t,e){Xi(bt(t),{recursive:!0});let n=De(t,e.id),r=`${n}.${process.pid}.tmp`;Yi(r,JSON.stringify(e,null,2)+`
5
5
  `,{mode:384}),Hr(r,n)}function np(t,e,n=Date.now()){let r=e.text.trim().slice(0,Ji);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${Br(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Xr(t,o),o}function Ce(t,e){if(!Zi(e))return null;try{return JSON.parse(Ki(De(t,e),"utf-8"))}catch{return null}}function zr(t,e){let n=bt(t);return Vi(n)?zi(n).filter(r=>r.endsWith(".json")).map(r=>Ce(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function Kr(t,e,n,r={}){let o=Ce(t,e);if(!o||o.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${De(t,e)}.${process.pid}.${Br(3).toString("hex")}.claim`;try{Hr(De(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...o,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")i.status="rejected";else{let a=await(r.send??Qi)(o).catch(d=>({ok:!1,error:String(d?.message??d)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Xr(t,i);try{Gi(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as ea,writeFileSync as ta}from"fs";import{resolve as Yr}from"path";var Jr="ready",na="202510";function ra(t){let e=t.date??t.created_at.slice(0,10);return Yr(t.workspace,Jr,`${e}-${t.platform}-${t.id}.txt`)}function Gr(t){let e=ra(t);return ea(Yr(t.workspace,Jr),{recursive:!0}),ta(e,t.text.endsWith(`
6
6
  `)?t.text:`${t.text}
7
- `),e}function Qr(t,e,n){let r=Sr(t.config,e,n);if(!r)return null;let o=t.env??process.env,s=r.integration.credentials?.tokenEnv,i=s?o[s]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function Zr(t,e,n){return Qr(t,e,n)!==null}async function oa(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let o=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??na),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!o.ok)throw new Error(`LinkedIn said ${o.status}: ${(await o.text().catch(()=>"")).slice(0,200)}`);let s=o.headers.get("x-restli-id");return s?{url:`https://www.linkedin.com/feed/update/${s}/`}:{}}async function sa(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let o=await r.json().catch(()=>({}));return o.data?.id?{url:`https://x.com/i/web/status/${o.data.id}`}:{}}async function ia(t,e){let n=Qr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Gr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await oa(t.text,n,r):await sa(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Gr(t);return{ok:!1,error:`not posted on ${ue[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function eo(t){return e=>ia(e,t)}An();Cn();Cn();An();var up=["done","skipped"],aa=1e3;function la(t){t.exec(`
7
+ `),e}function Qr(t,e,n){let r=Sr(t.config,e,n);if(!r)return null;let o=t.env??process.env,s=r.integration.credentials?.tokenEnv,i=s?o[s]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function Zr(t,e,n){return Qr(t,e,n)!==null}async function oa(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let o=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??na),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!o.ok)throw new Error(`LinkedIn said ${o.status}: ${(await o.text().catch(()=>"")).slice(0,200)}`);let s=o.headers.get("x-restli-id");return s?{url:`https://www.linkedin.com/feed/update/${s}/`}:{}}async function sa(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let o=await r.json().catch(()=>({}));return o.data?.id?{url:`https://x.com/i/web/status/${o.data.id}`}:{}}async function ia(t,e){let n=Qr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Gr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await oa(t.text,n,r):await sa(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Gr(t);return{ok:!1,error:`not posted on ${pe[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function eo(t){return e=>ia(e,t)}An();Cn();Cn();An();var up=["done","skipped"],aa=1e3;function la(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,
@@ -64,8 +64,8 @@ import{a as mt}from"./chunk-GTJIKXDB.js";import{H as br,O as Ar,k as K}from"./ch
64
64
  to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)
65
65
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,d)=>{let l=d===0,c=l&&a.agentId===n&&a.kind!=="message";i.run(e,d+1,a.name,a.kind,a.agentId,a.doneWhen,l?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,c?o:null,o,a.checkCount??null)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,o)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?yt(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(to)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?to(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(yt)}updateStep(e,n,r){let o=[],s=[];for(let[i,a]of Object.entries(r)){let d=ca[i];!d||a===void 0||(o.push(`${d} = ?`),s.push(typeof a=="boolean"?a?1:0:a))}o.length&&this.db.prepare(`UPDATE request_plan_steps SET ${o.join(", ")} WHERE request_id = ? AND idx = ?`).run(...s,e,n)}finish(e,n,r){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,r,e).changes>0}markNotified(e,n){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(n,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(yt)}event(e,n,r,o,s){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,s,r,o.replace(/\s+/g," ").trim().slice(0,aa))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
66
66
  ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,
67
- told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},pp=Rn;var ao=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],pa=280;function O(t,e=pa){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function te(t){if(t.configPath)return T(t.configPath);let e=[T(t.root,"agentx.json"),T(t.root,".agentx","config.json")];return e.find(n=>H(n))??e[0]}function V(t){return t.wikiDir?T(t.wikiDir):T(t.root,".agentx","wiki")}function ga(t){return ee(t.root,"pending").map(ma)}function ma(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:O([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function fa(t){let e=te(t);if(!H(e))return[];let n;try{n=JSON.parse(xt(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),o=[];for(let[s,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let d=i.timezone||"UTC",l=i.schedule?Kn(i.schedule):"",c=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",p=String(i.prompt??i.command??""),u=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:u?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:u?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${s}" (${c})?`,yes:u?"enable it":"remove it",no:u?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:O(`${p}${u&&i.schedule?` \xB7 first run ${Yn(Gn(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function lo(t){let e=T(t,".agentx","memory");return H(e)?da(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ha(t){let e=lo(t.root);if(e.length===0)return[];let n=new ot(t.root),r=[];for(let o of e)for(let s of n.held(o))r.push({key:`memory:${o}/${s.id}`,kind:"memory",title:`Fact ${o} learned from ${s.source.channel}`,ask:`Let ${o} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:o,created_at:s.createdAt,detail:O(s.content),more:`agentx memory facts held --agent ${o}`});return r}function ba(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 ya(t){return mr(V(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:O(`${ba(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var ro=new Map;function co(t,e){let n=ua(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=ro.get(t);if(o?.version===r)return o.value;let s=e();return ro.set(t,{version:r,value:s}),s}function wa(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${O(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:O(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function xa(t,e){let n=V(t);if(!H(T(n,"_facts.json")))return;let r=Re(new Z(n),"pending").find(o=>o.id===e);return r?wa(r):void 0}function ka(t){let e=T(V(t),"_facts.json");if(!H(e))return;let n=co(e,()=>Re(new Z(io(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function va(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function uo(t){let e=V(t),n=new rt(e);if(!H(n.path))return[];let r=co(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new Z(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:va(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function Sa(t){return zr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:O(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function Ea(t){return _r(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:O(`Last try not sent: ${e.error}`)}:{}}))}function _a(t){let e=Object.entries(st(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Oe(t).agents??{};return e.map(([r,o])=>{let s=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${s.name||r}", created by ${o.by}`,ask:`Let ${s.name||r} (${s.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:o.by,created_at:o.at,detail:O(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Oe(t){try{return JSON.parse(xt(te(t),"utf-8"))}catch{return{}}}function wt(t){let e={};try{e=Object.fromEntries(Pn(xt(T(io(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function $a(t){let e=sr(t.root,"pending");if(e.length===0)return[];let n=Oe(t),r=wt(t);return e.map(o=>{let s=ue[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:Zr({config:n,env:r},o.agent,o.platform)?`post it on ${s}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:o.agent,created_at:o.created_at,detail:O(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:rr(o.text)}})}function G(t){if(t.requests)return t.requests;if(T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e)return null;let n=oo.get(e);return!n&&!In(e)?null:(n||oo.set(e,n=new Dn(e)),n)}var oo=new WeakMap;function Wp(t){if(t.plans)return t.plans;if(t.requests||T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e||!no(e))return null;let n=so.get(e);return n||so.set(e,n=new Ne(e)),n}var so=new WeakMap;function Ta(t){let e=G(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:K(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:O(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var po={card:ga,schedule:fa,agent:_a,memory:ha,wiki:ya,fact:()=>[],question:uo,whatsapp:Sa,email:Ea,content:$a,request:Ta};function Aa(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function go(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??ao){if(d==="fact"){try{let c=ka(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=po[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Aa),{items:o,snoozed:a,errors:s,backlog:i}}function mo(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!ao.includes(n)||!r?null:{kind:n,ref:r}}function Ra(t,e,n){switch(e){case"card":return pe(t.root,n)?.status==="pending";case"wiki":return gr(V(t),n)?.status==="pending";case"whatsapp":return Ce(t.root,n)?.status==="pending";case"email":return Er(t.root,n)?.status==="pending";case"content":return or(t.root,n)?.status==="pending";default:return!!fo(t,e,n)}}function fo(t,e,n){return e==="fact"?xa(t,n):po[e](t).find(r=>r.key===`${e}:${n}`)}async function ho(t,e,n,r={}){let o=n==="later"?null:mo(e),s;if(o)try{s=fo(t,o.kind,o.ref)}catch{s=void 0}let i=await Ia(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;wr(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ia(t,e,n,r){let o=mo(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),d=r.by??"operator";if(n==="later"){if(!Ra(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return Fr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=vr(t.root,i,l?"yes":"no",{by:d,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 ${l?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(l?Jn:Qn)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(st(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return it(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let c=[],p=await Te(u=>{jn(u,`agents.${i}`);for(let[g,m]of Object.entries(u.crons??{}))m?.agent===i&&(delete u.crons[g],c.push(g))},{configPath:te(t),reload:t.reload});return p.success?(it(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${c.length?`, with its schedules ${c.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:p.error||"could not remove it from agentx.json"}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let p=i.slice(0,c),u=i.slice(c+1);if(!lo(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new ot(t.root);return g.held(p).some(m=>m.id===u)?(g.review(p,u,l?"approved":"rejected",d),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${u}" isn't waiting for review`}}case"wiki":{let c=V(t),p=l?fr(c,i,{by:d,force:r.force,now:a}):hr(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Da(t,e,i,l,d,r);case"question":return Na(t,e,i,l,d,r);case"whatsapp":{let c=await Kr(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Tr(Oe(t),wt(t)),p=await $r(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,send:c});return p.ok?{ok:!0,message:l?`${e}: sent to ${p.draft.to}${p.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:p}case"content":{let c=t.publishContent??eo({config:Oe(t),env:wt(t)}),p=await ir(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=ue[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Wr(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a),{ok:!0,message:`${e}: dropped`})}}}function Da(t,e,n,r,o,s){let i=new Z(V(t));try{let a=Re(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return Vn(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=Hn(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function Ca(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function Na(t,e,n,r,o,s){let i=V(t),a=new rt(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Mn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=uo(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=Ca(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,m)=>`${m+1}. ${g}`).join(", ")}`};let p=new Z(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var Oa=3,La=7,Pa=50,vt=120,Ma=280,kt=600,yo=36e5,Fa=24*yo;function Bp(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function ne(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Le=t=>new Date(t).toISOString();function Ua(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:ne(e.title,vt),...e.ask?{ask:ne(e.ask,kt)}:{},...e.detail?{facts:ne(e.detail,Ma)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var Wa={done:"Done",declined:"Declined",dropped:"Dropped"};function wo(t,e,n){let{record:r,links:o}=e,s=K(r,vt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:ne(s.said,kt)}:{},agent:r.agentId,askedAt:Le(r.createdAt),changedAt:Le(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return o.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:ne(r.question,kt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),d=t.now-r.updatedAt<(t.quietHours??Oa)*yo;return{...i,column:a||d?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:Le(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Wa[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function ja(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function qa(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:ne(e.title,vt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:ja(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,bo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function St(t){let e=[],n=[];for(let o of t.inbox){o.error&&n.push(`What waits on ${o.nodeName} could not be read: ${o.error}`);for(let s of o.items)e.push(Ua(o,s,o.node===t.node))}let r=xo(t,e);for(let o of t.requests??[]){let s=wo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function xo(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Hp(t){let e=St(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,o=xo(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=wo(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??La)*Fa;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(qa(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,Pa),c=bo(n,"askedAt"),p=bo(i,"changedAt");return{ts:Le(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...p?{oldest:p}:{}},done:{count:l.length}},errors:r}}function Ba(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 Ha(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function Kp(t,e){let n=t.now??Date.now(),r=[],o=go(t,{includeSnoozed:!0});for(let c of o.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let s=o.items.filter(c=>!c.snoozed_until),i=new Set(o.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=G(t);c&&(a=c.listByState("waiting_owner").map(p=>({record:p,links:c.links(p.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:d,errors:l}=St({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Ba)}],requests:a,deferred:i});return Ha(d,i.size,[...r,...l])}import{readFileSync as Va}from"fs";var Xa=1e4,ko=/^[0-9a-f]{7,64}$/i;function Jp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&ko.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(Xa)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&ko.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Qp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Va(n.tokenFile,"utf-8").trim().split(`
68
- `)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var vo=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function eg(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/api/org"||t.startsWith("/api/org/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"}function tg(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 ng(t){return vo.has(t)}function rg(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(vo.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 og(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 sg(t,e,n=process.env){let r=s=>s.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(s=>r(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function Pe(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function za(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ka(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function ag(t,e=Ka()){let n=Pe(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=za(n),s=[Pe(t.host),Pe(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=Pe(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function lg(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var Et="/api/admin/pictures",Ga=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Ya=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function _(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function Ja(t){let e={agent:{},person:{}};for(let n of ar)for(let[r,o]of Object.entries(dr(t,n)))e[n][r]=ur(n,r,o);return e}function ug(t,e,n,r,o){let s=n.match(Ga);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return _(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=pr(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":lr,"Content-Length":String(a.length),"Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'"}),e.end(a),!0):(_(e,404,{error:"no such picture"}),!0)}async function pg(t,e,n,r){if(n!==Et&&!n.startsWith(`${Et}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===Et)return o!=="GET"?(_(e,405,{error:"GET only"}),!0):(_(e,200,{...Ja(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Ya);if(!s)return _(e,404,{error:"not found"}),!0;if(o!=="PUT"&&o!=="DELETE")return _(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return _(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=s[1],d=decodeURIComponent(s[2]),l=a==="agent"?r.agentIds():r.personIds();if(!cr.test(d)||!l.includes(d))return _(e,404,{error:a==="agent"?`no agent "${d}" in agentx.json`:`no person "${d}" in agentx.json`}),!0;if(o==="DELETE"){let c=dt(r.root,a,d);return _(e,200,{ok:!0,removed:c}),!0}try{let c=await ut(t),p=await ct(r.root,a,d,c);_(e,200,{ok:!0,url:p.url})}catch(c){if(c instanceof lt)return _(e,c.status,{error:c.message}),!0;throw c}return!0}async function gg(t,e,n,r){let o=(t.method||"GET").toUpperCase();if(o!=="PUT"&&o!=="DELETE"){_(e,405,{error:"PUT or DELETE only"});return}let s=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(s);if(!i){_(e,403,{error:"Only an agent sets its own picture, from its own run: send X-AgentX-Task (or X-AgentX-Channel and X-AgentX-Chat) of a running turn. The owner sets pictures in Settings."});return}if(s&&s!==i){_(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${s}".`});return}if(o==="DELETE"){_(e,200,{ok:!0,agent:i,removed:dt(r.root,"agent",i)});return}try{let a=await ct(r.root,"agent",i,await ut(t));_(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof lt){_(e,a.status,{error:a.message});return}throw a}}var So={};function hg(t){So=t}function bg(){return So}var yg=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
67
+ told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},pp=Rn;var ao=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],pa=280;function O(t,e=pa){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function te(t){if(t.configPath)return T(t.configPath);let e=[T(t.root,"agentx.json"),T(t.root,".agentx","config.json")];return e.find(n=>H(n))??e[0]}function V(t){return t.wikiDir?T(t.wikiDir):T(t.root,".agentx","wiki")}function ga(t){return Z(t.root,"pending").map(ma)}function ma(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:O([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function fa(t){let e=te(t);if(!H(e))return[];let n;try{n=JSON.parse(xt(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),o=[];for(let[s,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let d=i.timezone||"UTC",l=i.schedule?nr(i.schedule):"",c=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",p=String(i.prompt??i.command??""),u=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:u?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:u?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${s}" (${c})?`,yes:u?"enable it":"remove it",no:u?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:O(`${p}${u&&i.schedule?` \xB7 first run ${or(rr(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function lo(t){let e=T(t,".agentx","memory");return H(e)?da(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ha(t){let e=lo(t.root);if(e.length===0)return[];let n=new it(t.root),r=[];for(let o of e)for(let s of n.held(o))r.push({key:`memory:${o}/${s.id}`,kind:"memory",title:`Fact ${o} learned from ${s.source.channel}`,ask:`Let ${o} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:o,created_at:s.createdAt,detail:O(s.content),more:`agentx memory facts held --agent ${o}`});return r}function ba(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 ya(t){return yr(V(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:O(`${ba(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var ro=new Map;function co(t,e){let n=ua(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=ro.get(t);if(o?.version===r)return o.value;let s=e();return ro.set(t,{version:r,value:s}),s}function wa(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${O(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:O(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function xa(t,e){let n=V(t);if(!H(T(n,"_facts.json")))return;let r=Re(new ee(n),"pending").find(o=>o.id===e);return r?wa(r):void 0}function ka(t){let e=T(V(t),"_facts.json");if(!H(e))return;let n=co(e,()=>Re(new ee(io(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function va(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function uo(t){let e=V(t),n=new st(e);if(!H(n.path))return[];let r=co(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ee(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:va(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function Sa(t){return zr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:O(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function Ea(t){return _r(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:O(`Last try not sent: ${e.error}`)}:{}}))}function _a(t){let e=Object.entries(at(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Oe(t).agents??{};return e.map(([r,o])=>{let s=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${s.name||r}", created by ${o.by}`,ask:`Let ${s.name||r} (${s.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:o.by,created_at:o.at,detail:O(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Oe(t){try{return JSON.parse(xt(te(t),"utf-8"))}catch{return{}}}function wt(t){let e={};try{e=Object.fromEntries(Pn(xt(T(io(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function $a(t){let e=cr(t.root,"pending");if(e.length===0)return[];let n=Oe(t),r=wt(t);return e.map(o=>{let s=pe[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:Zr({config:n,env:r},o.agent,o.platform)?`post it on ${s}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:o.agent,created_at:o.created_at,detail:O(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:ar(o.text)}})}function G(t){if(t.requests)return t.requests;if(T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e)return null;let n=oo.get(e);return!n&&!In(e)?null:(n||oo.set(e,n=new Dn(e)),n)}var oo=new WeakMap;function Wp(t){if(t.plans)return t.plans;if(t.requests||T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e||!no(e))return null;let n=so.get(e);return n||so.set(e,n=new Ne(e)),n}var so=new WeakMap;function Ta(t){let e=G(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:K(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:O(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var po={card:ga,schedule:fa,agent:_a,memory:ha,wiki:ya,fact:()=>[],question:uo,whatsapp:Sa,email:Ea,content:$a,request:Ta};function Aa(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function go(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??ao){if(d==="fact"){try{let c=ka(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=po[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Aa),{items:o,snoozed:a,errors:s,backlog:i}}function mo(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!ao.includes(n)||!r?null:{kind:n,ref:r}}function Ra(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return br(V(t),n)?.status==="pending";case"whatsapp":return Ce(t.root,n)?.status==="pending";case"email":return Er(t.root,n)?.status==="pending";case"content":return lr(t.root,n)?.status==="pending";default:return!!fo(t,e,n)}}function fo(t,e,n){return e==="fact"?xa(t,n):po[e](t).find(r=>r.key===`${e}:${n}`)}async function ho(t,e,n,r={}){let o=n==="later"?null:mo(e),s;if(o)try{s=fo(t,o.kind,o.ref)}catch{s=void 0}let i=await Ia(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;Mn(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ia(t,e,n,r){let o=mo(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),d=r.by??"operator";if(n==="later"){if(!Ra(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return Fr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=Hn(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text,popup:r.popup});return c.ok?{ok:!0,message:`${e}: ${c.card.raised_by} will be told ${l?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(l?sr:ir)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(at(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return lt(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let c=[],p=await Te(u=>{Gn(u,`agents.${i}`);for(let[g,m]of Object.entries(u.crons??{}))m?.agent===i&&(delete u.crons[g],c.push(g))},{configPath:te(t),reload:t.reload});return p.success?(lt(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${c.length?`, with its schedules ${c.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:p.error||"could not remove it from agentx.json"}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let p=i.slice(0,c),u=i.slice(c+1);if(!lo(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new it(t.root);return g.held(p).some(m=>m.id===u)?(g.review(p,u,l?"approved":"rejected",d),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${u}" isn't waiting for review`}}case"wiki":{let c=V(t),p=l?wr(c,i,{by:d,force:r.force,now:a}):xr(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Da(t,e,i,l,d,r);case"question":return Na(t,e,i,l,d,r);case"whatsapp":{let c=await Kr(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Tr(Oe(t),wt(t)),p=await $r(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,send:c});return p.ok?{ok:!0,message:l?`${e}: sent to ${p.draft.to}${p.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:p}case"content":{let c=t.publishContent??eo({config:Oe(t),env:wt(t)}),p=await dr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=pe[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Wr(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a),{ok:!0,message:`${e}: dropped`})}}}function Da(t,e,n,r,o,s){let i=new ee(V(t));try{let a=Re(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return Zn(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=Qn(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function Ca(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function Na(t,e,n,r,o,s){let i=V(t),a=new st(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Vn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=uo(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=Ca(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,m)=>`${m+1}. ${g}`).join(", ")}`};let p=new ee(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var Oa=3,La=7,Pa=50,vt=120,Ma=280,kt=600,yo=36e5,Fa=24*yo;function Bp(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function ne(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Le=t=>new Date(t).toISOString();function Ua(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:ne(e.title,vt),...e.ask?{ask:ne(e.ask,kt)}:{},...e.detail?{facts:ne(e.detail,Ma)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var Wa={done:"Done",declined:"Declined",dropped:"Dropped"};function wo(t,e,n){let{record:r,links:o}=e,s=K(r,vt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:ne(s.said,kt)}:{},agent:r.agentId,askedAt:Le(r.createdAt),changedAt:Le(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return o.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:ne(r.question,kt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),d=t.now-r.updatedAt<(t.quietHours??Oa)*yo;return{...i,column:a||d?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:Le(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Wa[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function ja(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function qa(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:ne(e.title,vt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:ja(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,bo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function St(t){let e=[],n=[];for(let o of t.inbox){o.error&&n.push(`What waits on ${o.nodeName} could not be read: ${o.error}`);for(let s of o.items)e.push(Ua(o,s,o.node===t.node))}let r=xo(t,e);for(let o of t.requests??[]){let s=wo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function xo(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Hp(t){let e=St(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,o=xo(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=wo(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??La)*Fa;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(qa(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,Pa),c=bo(n,"askedAt"),p=bo(i,"changedAt");return{ts:Le(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...p?{oldest:p}:{}},done:{count:l.length}},errors:r}}function Ba(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 Ha(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function Kp(t,e){let n=t.now??Date.now(),r=[],o=go(t,{includeSnoozed:!0});for(let c of o.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let s=o.items.filter(c=>!c.snoozed_until),i=new Set(o.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=G(t);c&&(a=c.listByState("waiting_owner").map(p=>({record:p,links:c.links(p.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:d,errors:l}=St({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Ba)}],requests:a,deferred:i});return Ha(d,i.size,[...r,...l])}import{readFileSync as Va}from"fs";var Xa=1e4,ko=/^[0-9a-f]{7,64}$/i;function Jp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&ko.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(Xa)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&ko.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Qp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Va(n.tokenFile,"utf-8").trim().split(`
68
+ `)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var vo=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function eg(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/api/org"||t.startsWith("/api/org/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"}function tg(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 ng(t){return vo.has(t)}function rg(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(vo.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 og(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 sg(t,e,n=process.env){let r=s=>s.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(s=>r(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function Pe(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function za(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ka(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function ag(t,e=Ka()){let n=Pe(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=za(n),s=[Pe(t.host),Pe(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=Pe(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function lg(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var Et="/api/admin/pictures",Ga=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Ya=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function _(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function Ja(t){let e={agent:{},person:{}};for(let n of ur)for(let[r,o]of Object.entries(mr(t,n)))e[n][r]=fr(n,r,o);return e}function ug(t,e,n,r,o){let s=n.match(Ga);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return _(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=hr(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":pr,"Content-Length":String(a.length),"Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'"}),e.end(a),!0):(_(e,404,{error:"no such picture"}),!0)}async function pg(t,e,n,r){if(n!==Et&&!n.startsWith(`${Et}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===Et)return o!=="GET"?(_(e,405,{error:"GET only"}),!0):(_(e,200,{...Ja(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Ya);if(!s)return _(e,404,{error:"not found"}),!0;if(o!=="PUT"&&o!=="DELETE")return _(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return _(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=s[1],d=decodeURIComponent(s[2]),l=a==="agent"?r.agentIds():r.personIds();if(!gr.test(d)||!l.includes(d))return _(e,404,{error:a==="agent"?`no agent "${d}" in agentx.json`:`no person "${d}" in agentx.json`}),!0;if(o==="DELETE"){let c=pt(r.root,a,d);return _(e,200,{ok:!0,removed:c}),!0}try{let c=await gt(t),p=await ut(r.root,a,d,c);_(e,200,{ok:!0,url:p.url})}catch(c){if(c instanceof dt)return _(e,c.status,{error:c.message}),!0;throw c}return!0}async function gg(t,e,n,r){let o=(t.method||"GET").toUpperCase();if(o!=="PUT"&&o!=="DELETE"){_(e,405,{error:"PUT or DELETE only"});return}let s=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(s);if(!i){_(e,403,{error:"Only an agent sets its own picture, from its own run: send X-AgentX-Task (or X-AgentX-Channel and X-AgentX-Chat) of a running turn. The owner sets pictures in Settings."});return}if(s&&s!==i){_(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${s}".`});return}if(o==="DELETE"){_(e,200,{ok:!0,agent:i,removed:pt(r.root,"agent",i)});return}try{let a=await ut(r.root,"agent",i,await gt(t));_(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof dt){_(e,a.status,{error:a.message});return}throw a}}var So={};function hg(t){So=t}function bg(){return So}var yg=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
69
69
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">
70
70
  <link rel="preconnect" href="https://fonts.googleapis.com">
71
71
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
@@ -355,7 +355,7 @@ import{a as mt}from"./chunk-GTJIKXDB.js";import{H as br,O as Ar,k as K}from"./ch
355
355
  <span class="name">${j(r.name)}</span>
356
356
  <span class="chev">\u25BE</span>
357
357
  <div class="ax-mesh-menu" role="menu">${o}</div>
358
- </div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:$e,href:ce},{id:"live",label:"Live",href:`${ce}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:Un},{id:"people",label:"People",href:`${ce}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:`${ce}#page=settings`}]}].map(l=>{let c=l.tabs.map(p=>{let u=p.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=p.external?' target="_blank" rel="noopener"':"",m=p.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${p.href}" class="${u}"${g}>${p.label}${m}</a>`}).join("");return`<div class="ax-topbar__group" title="${j(l.name)} tier"><span class="ax-topbar__group-label">${j(l.name)}</span>${c}</div>`}).join("");return`<header class="ax-topbar">
358
+ </div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:$e,href:de},{id:"live",label:"Live",href:`${de}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:zn},{id:"people",label:"People",href:`${de}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:`${de}#page=settings`}]}].map(l=>{let c=l.tabs.map(p=>{let u=p.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=p.external?' target="_blank" rel="noopener"':"",m=p.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${p.href}" class="${u}"${g}>${p.label}${m}</a>`}).join("");return`<div class="ax-topbar__group" title="${j(l.name)} tier"><span class="ax-topbar__group-label">${j(l.name)}</span>${c}</div>`}).join("");return`<header class="ax-topbar">
359
359
  <div class="ax-topbar__left">
360
360
  <div class="ax-brand">
361
361
  <span class="ax-brand__mark">AX</span>
@@ -516,7 +516,7 @@ Reinstall in ${Ol}. Agents switch back on their own once it is installed.`}}func
516
516
  WHERE c.device_id = ? AND m.role = 'assistant' AND m.at > COALESCE(c.read_at, 0)
517
517
  ORDER BY m.at DESC, m.id DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>({id:o.id,title:o.title,agent:o.agent,...o.agent_name?{agentName:o.agent_name}:{},...o.color?{color:o.color}:{},answer:String(o.answer??"").trim(),status:o.status==="error"||o.status==="stopped"?o.status:"done",at:o.at}))}append(e,n,r){return this.appendWithFiles(e,n,r)!==null}appendWithFiles(e,n,r,o=[]){if(!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e))return null;let i=r.content.length>J.content?r.content.slice(0,J.content)+`
518
518
 
519
- [Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,J.toolsPerMessage),d=[];for(let u of o){if(d.length>=J.filesPerMessage)break;let g=u.filename.trim(),m=de(g);if(!m||!g||g.length>W.pathChars||g.includes("\0"))continue;let f=(g.split(/[\\/]/).pop()||g).slice(0,120);d.push({id:Yo(16).toString("hex"),name:f,mime:m.mime,kind:m.kind,path:g})}let l=d.map(u=>({id:u.id,name:u.name,mime:u.mime,kind:u.kind})),c=this.db.prepare(`INSERT INTO app_chat_messages (conversation_id, role, content, status, error, ui, tools, files, at)
519
+ [Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,J.toolsPerMessage),d=[];for(let u of o){if(d.length>=J.filesPerMessage)break;let g=u.filename.trim(),m=ue(g);if(!m||!g||g.length>W.pathChars||g.includes("\0"))continue;let f=(g.split(/[\\/]/).pop()||g).slice(0,120);d.push({id:Yo(16).toString("hex"),name:f,mime:m.mime,kind:m.kind,path:g})}let l=d.map(u=>({id:u.id,name:u.name,mime:u.mime,kind:u.kind})),c=this.db.prepare(`INSERT INTO app_chat_messages (conversation_id, role, content, status, error, ui, tools, files, at)
520
520
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,r.role,i,r.status??null,r.error?.slice(0,500)??null,r.ui?JSON.stringify(r.ui):null,a?.length?JSON.stringify(a):null,l.length?JSON.stringify(l):null,r.at),p=this.db.prepare(`INSERT INTO app_chat_files (id, conversation_id, message_id, path, name, mime, kind, created_at)
521
521
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let u of d)p.run(u.id,n,Number(c.lastInsertRowid),u.path,u.name,u.mime,u.kind,r.at);return this.db.prepare(`DELETE FROM app_chat_messages WHERE conversation_id = ? AND id NOT IN
522
522
  (SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,J.messagesPerConversation),this.db.prepare(`DELETE FROM app_chat_files WHERE conversation_id = ? AND message_id NOT IN
@@ -556,7 +556,7 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<dc?null:`text:${c
556
556
  FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},ls=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),o=this.now(),s=gc(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,uc):r.repeatWindowHours)*is,d=r.digestNags&&r.digestAvailable!==!1,l="send";!n.urgent&&s&&this.ledger.lastTold(s,o-a,d)?l="repeat":!n.urgent&&i==="nag"&&d&&(l="digest");let c=this.ledger.add({at:o,key:s??`once:${o}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:l==="send"?"sent":l,urgent:n.urgent===!0});return{verdict:l,key:s,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:fc(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*is)}};function wm(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,o=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,s=r(n.from,100)??r(e,100);return{...r(n.key,190)?{key:`send:${r(n.key,190)}`}:{},...r(n.requestId,100)?{requestId:r(n.requestId,100)}:{},...o?{kind:o}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...s?{from:s}:{}}}function fc(t,e=5,n=3){let r=new Map;for(let a of t){let[d,...l]=a.title.split(": "),c=l.join(": ").trim(),p=r.get(d.trim())??{count:0,names:[]};p.count++,c&&!p.names.includes(c)&&p.names.push(c),r.set(d.trim(),p)}let o=[...r.entries()].sort((a,d)=>d[1].count-a[1].count),s=o.slice(0,e).map(([a,{count:d,names:l}])=>{let c=l.length?` (${l.slice(0,n).join(", ")}${l.length>n?", \u2026":""})`:"";return`${a}${d>1?` \xD7${d}`:""}${c}`}),i=o.length>e?`; ${o.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${s.join("; ")}${i}.`}var hc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,bc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Ve(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(bc)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],o=yc(r);if(!o)return{cleanText:t};let s=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,s)+i+t.slice(s+n[0].length)).trim(),ui:o}}function km(t){if(!t||!t.includes("agentx:ui"))return t;let e=hc.exec(t);return e?t.slice(0,e.index).trimEnd():t}function yc(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let r=[],o=[],s=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?r.push({label:i.label,url:i.url}):typeof i.reply=="string"&&i.reply.trim()?o.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&s.push(i.label));r.length&&(n.buttons=r),o.length&&(n.replies=o),s.length&&(n.skippedActions=s)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,o=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(o)&&o.filter(s=>typeof s=="string").length>=2&&(n.poll={question:r,options:o.filter(s=>typeof s=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:o,caption:s}=e.media;["image","document","audio","video"].includes(r)&&typeof o=="string"&&o&&(n.media={type:r,url:o,...typeof s=="string"?{caption:s}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function Sm(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 wc=5*6e4;function X(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var cs=class{subs=new Set;log;forwarder;localName;allowedCallers;pending=new Map;cleanupTimer;ringHandler;recentRings=new Map;constructor(e,n=[],r=console.error.bind(console,"[webrtc]")){this.localName=e,this.allowedCallers=new Set(n.map(X)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${X(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let o=r.filter(s=>s.expiresAt>e);o.length===0?this.pending.delete(n):o.length!==r.length&&this.pending.set(n,o)}for(let[n,r]of this.recentRings)r<=e&&this.recentRings.delete(n)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,n,r){return this.addSubscriber(e,n,{kind:"sse",res:r})}subscribeInternal(e,n,r){return this.addSubscriber(e,n,{kind:"callback",deliver:r})}addSubscriber(e,n,r){let o={callId:e,recipient:n,sink:r};this.subs.add(o);let s=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${s}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let d=Date.now(),l=a.filter(c=>c.expiresAt>d);for(let{signal:c}of l)this.deliverTo(o,c);this.pending.delete(i),l.length&&this.log(`flushed ${l.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(o),this.log(`unsubscribe[${s}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
557
557
  data: ${JSON.stringify(n)}
558
558
 
559
- `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=X(e.to);if(n===X(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let o=await this.forwarder(e.to,e);return o?{ok:o}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&X(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(X(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),o=this.recentRings.get(e.callId);if(o&&o>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+wc),this.ringHandler)try{this.ringHandler(e)}catch(s){this.log(`ringHandler threw: ${s.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),o=this.pending.get(r)||[];o.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,o),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${o.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=X(e.to);for(let o of this.subs)o.callId===e.callId&&X(o.recipient)===r&&(this.deliverTo(o,e)?n++:this.subs.delete(o));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as xc,readFileSync as ds,renameSync as kc,rmSync as vc,writeFileSync as Sc}from"fs";import{homedir as Ec}from"os";import{dirname as _c,join as $c}from"path";var us=$c(Ec(),".agentx","call.json");function Tc(t=us,e=Date.now()){try{let n=JSON.parse(ds(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 ps(t=Xn,e=Tc){let n=t();return n.active?n:e()}function Rm(t,e,n=us,r=Date.now()){let o=null;try{o=JSON.parse(ds(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&vc(n,{force:!0});return}xc(_c(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;Sc(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
559
+ `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=X(e.to);if(n===X(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let o=await this.forwarder(e.to,e);return o?{ok:o}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&X(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(X(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),o=this.recentRings.get(e.callId);if(o&&o>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+wc),this.ringHandler)try{this.ringHandler(e)}catch(s){this.log(`ringHandler threw: ${s.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),o=this.pending.get(r)||[];o.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,o),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${o.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=X(e.to);for(let o of this.subs)o.callId===e.callId&&X(o.recipient)===r&&(this.deliverTo(o,e)?n++:this.subs.delete(o));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as xc,readFileSync as ds,renameSync as kc,rmSync as vc,writeFileSync as Sc}from"fs";import{homedir as Ec}from"os";import{dirname as _c,join as $c}from"path";var us=$c(Ec(),".agentx","call.json");function Tc(t=us,e=Date.now()){try{let n=JSON.parse(ds(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 ps(t=er,e=Tc){let n=t();return n.active?n:e()}function Rm(t,e,n=us,r=Date.now()){let o=null;try{o=JSON.parse(ds(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&vc(n,{force:!0});return}xc(_c(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;Sc(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
560
560
  `),kc(s,n)}var gs="owner",Xe=6e4,ys=60*Xe,Ac=24*ys,Rc=7*24*ys,Ic=2*Xe,Cm={enabled:!1,escalateAfterMinutes:10,ladder:[]};function Dc(t){t.exec(`
561
561
  CREATE TABLE IF NOT EXISTS owner_presence (
562
562
  person TEXT NOT NULL,
@@ -609,7 +609,7 @@ ${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this
609
609
  .oe-form > *, .oe-role { flex: 1 1 100%; }
610
610
  .oe-legend { grid-template-columns: 1fr; }
611
611
  }
612
- `;Ze();function Jt(t){let e=n=>[...new Set((n??[]).filter(Boolean).map(E))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:E(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function ws(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&Ee(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=Ee(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let m=s(u);if(m)return`Department ${l.name} cannot list ${m.name}: ${i(m)}`;let f=a.get(u);if(f)return`"${u}" is in both department ${f} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=xs(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=Ee(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function xs(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function Bm(t,e){let n=new Set,r=xs(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}Ze();var ks=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},ze=["mon","tue","wed","thu","fri","sat","sun"],Qt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Fc(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",be.start),r=e(t.end,"end",be.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!ze.includes(a));if(s)throw new Error(`"${s}" is not a day. Use mon, tue, wed, thu, fri, sat or sun.`);let i=o.length?ze.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Uc(t){let e=ze.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>ze.indexOf(r)===e+o))return`${Qt[t[0]]} to ${Qt[t[t.length-1]]}`;let n=t.map(r=>Qt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var Zt={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function en(t){let e=Array.isArray(t?.people)?t.people:[],n=new Map;for(let r of e)r?.id&&n.set(String(r.id),String(r.name||r.id));return n}function $s(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function Wc(t){let e=t?.business?.roles??{};return{agents:[...$s(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...en(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Qe}}function jc(t){let e=t?.business??{},n=e.roles??{},r=$s(t),o=en(t),s=le(e),i=(c,p,u,g)=>({ref:`${c}:${p}`,kind:c,id:p,name:(c==="agent"?r.get(p):o.get(p))??p,...u?{role:u,title:String(n[u]?.title||u)}:{},...g&&typeof g=="object"?{schedule:{start:String(g.start??""),end:String(g.end??""),days:Array.isArray(g.days)?g.days.map(String):[...be.days]}}:{}}),a=[...Object.entries(e.orgChart??{}).map(([c,p])=>i("agent",c,p?.role,p?.schedule)),...Object.entries(e.orgPeople??{}).map(([c,p])=>i("person",c,p?.role))],d=new Set(a.map(c=>c.ref)),l=[...s.flatMap(c=>[c.from,c.to]),...Jt(e).flatMap(c=>[...c.head?[c.head]:[],...c.members])];for(let c of l){let p=C(c);p.kind==="person"&&!d.has(c)&&(d.add(c),a.push(i("person",p.id,void 0)))}return{members:a,relations:s}}function vs(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(en(t).keys()),o=En(t),s=Array.isArray(t?.people)?t.people:[],i=new Map(s.flatMap(a=>a?.id&&(a.role==="client"||a.role==="guest")?[[String(a.id),{name:String(a.name||a.id),role:a.role}]]:[]));return Sn(le(e),n,r,o)??ws(Jt(e),n,r,o,i)}function qc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&E(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>E(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>E(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function Ss(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function Es(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>ks)throw new Error(`Keep the role under ${ks} characters.`);return e}function Bc(t,e,n){let r=new Set;for(let o=e;o&&!r.has(o);o=t.find(s=>s.type==="reports-to"&&s.from===o)?.to){if(o===n)return!0;r.add(o)}return!1}function _s(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:E(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:E(o.from),to:E(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function zm(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=vs(n),s=jc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=Wc(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?E(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:m}=C(u),f=d.get(u);if(!f)throw new Error(g==="agent"?`There is no agent "${m}" on this computer.`:`There is no person "${m}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${f} is already in the org chart.`);let w=Es(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?Ss(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[m]={role:x,schedule:{...be},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[m]=x?{role:x}:{}),c=`${f} added to the org chart`;break}case"set-role":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=Es(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?Ss(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=m:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=m?{role:m}:{}),c=m?`${u.name} is now ${r.roles[m]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let m=_s(r,w=>w.from===u.ref||w.to===u.ref),f=qc(r,u.ref);u.kind==="agent"?delete r.orgChart[u.id]:r.orgPeople&&(delete r.orgPeople[u.id],Object.keys(r.orgPeople).length===0&&delete r.orgPeople),c=`${u.name} removed from the org chart`+(m?`, with ${m} ${m===1?"line":"lines"}`:"")+(f.length?` and out of ${f.join(", ")}`:"");break}case"add-relation":{let u=String(e.type??"").trim(),g=[String(e.from??"").trim(),String(e.to??"").trim()];if(!g[0]||!g[1]||!u)throw new Error("Pick a member, a kind of relation and a target.");if(!Qe.includes(u))throw new Error(`"${u}" is not a kind of relation. Pick reports to, dotted line or acts for.`);let[m,f]=g.map(E);for(let x of[m,f])if(!i.has(x))throw new Error(`${l(x)} is not in the org chart. Add them first.`);if(m===f)throw new Error(`${l(m)} cannot be linked to themself.`);let w={from:m,to:f,type:u};if(s.relations.some(x=>x.from===m&&x.to===f&&x.type===u))throw new Error(`${l(m)} already ${Zt[u]} ${l(f)}.`);if(u==="acts-for"&&i.get(m).kind!=="agent")throw new Error(`Only an agent can act for someone: ${l(m)} is a person.`);if(u==="acts-for"&&i.get(f).kind!=="person")throw new Error(`An agent acts for a person: ${l(f)} is an agent.`);if(u==="reports-to"){let x=s.relations.find(b=>b.type==="reports-to"&&b.from===m);if(x)throw new Error(`${l(m)} already reports to ${l(x.to)}. Remove that line first: each member has one boss.`);if(Bc(s.relations,f,m))throw new Error(`${l(m)} cannot report to ${l(f)}: ${l(f)} already reports up to ${l(m)}.`)}if(u==="reports-to"&&i.get(m).kind==="agent"){let x=C(f);r.orgChart[C(m).id].reportsTo=x.kind==="agent"?x.id:f}else r.relations=[...r.relations??[],w];c=`${l(m)} ${Zt[u]} ${l(f)}`;break}case"remove-relation":{let u={from:E(String(e.from??"")),to:E(String(e.to??"")),type:String(e.type??"")};if(!_s(r,g=>g.from===u.from&&g.to===u.to&&g.type===u.type))throw new Error("That line is not in the org chart any more. Reload the page.");c=`${l(u.from)} no longer ${Zt[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);if(u.kind!=="agent")throw new Error(`Working hours are for agents: ${u.name} is a person.`);let g=Fc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Uc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=vs(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}var Hc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Ts=class{constructor(e=Hc,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},Vc="That code didn't work. Check it, or run agentx app pair for a new one.",Xc=400;async function Ym(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await yr(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await zc(n,e.minMs??Xc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Vc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function zc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as dd}from"child_process";import{mkdtempSync as rd,rmSync as od,writeFileSync as sd}from"fs";import{tmpdir as id}from"os";import{join as Cs}from"path";import{randomBytes as Kc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var q={top:8,side:32,bottom:60},tn={height:56,keep:52},As=`
612
+ `;Ze();function Jt(t){let e=n=>[...new Set((n??[]).filter(Boolean).map(E))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:E(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function ws(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&Ee(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=Ee(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let m=s(u);if(m)return`Department ${l.name} cannot list ${m.name}: ${i(m)}`;let f=a.get(u);if(f)return`"${u}" is in both department ${f} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=xs(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=Ee(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function xs(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function Bm(t,e){let n=new Set,r=xs(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}Ze();var ks=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},ze=["mon","tue","wed","thu","fri","sat","sun"],Qt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Fc(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",be.start),r=e(t.end,"end",be.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!ze.includes(a));if(s)throw new Error(`"${s}" is not a day. Use mon, tue, wed, thu, fri, sat or sun.`);let i=o.length?ze.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Uc(t){let e=ze.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>ze.indexOf(r)===e+o))return`${Qt[t[0]]} to ${Qt[t[t.length-1]]}`;let n=t.map(r=>Qt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var Zt={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function en(t){let e=Array.isArray(t?.people)?t.people:[],n=new Map;for(let r of e)r?.id&&n.set(String(r.id),String(r.name||r.id));return n}function $s(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function Wc(t){let e=t?.business?.roles??{};return{agents:[...$s(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...en(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Qe}}function jc(t){let e=t?.business??{},n=e.roles??{},r=$s(t),o=en(t),s=le(e),i=(c,p,u,g)=>({ref:`${c}:${p}`,kind:c,id:p,name:(c==="agent"?r.get(p):o.get(p))??p,...u?{role:u,title:String(n[u]?.title||u)}:{},...g&&typeof g=="object"?{schedule:{start:String(g.start??""),end:String(g.end??""),days:Array.isArray(g.days)?g.days.map(String):[...be.days]}}:{}}),a=[...Object.entries(e.orgChart??{}).map(([c,p])=>i("agent",c,p?.role,p?.schedule)),...Object.entries(e.orgPeople??{}).map(([c,p])=>i("person",c,p?.role))],d=new Set(a.map(c=>c.ref)),l=[...s.flatMap(c=>[c.from,c.to]),...Jt(e).flatMap(c=>[...c.head?[c.head]:[],...c.members])];for(let c of l){let p=C(c);p.kind==="person"&&!d.has(c)&&(d.add(c),a.push(i("person",p.id,void 0)))}return{members:a,relations:s}}function vs(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(en(t).keys()),o=En(t),s=Array.isArray(t?.people)?t.people:[],i=new Map(s.flatMap(a=>a?.id&&(a.role==="client"||a.role==="guest")?[[String(a.id),{name:String(a.name||a.id),role:a.role}]]:[]));return Sn(le(e),n,r,o)??ws(Jt(e),n,r,o,i)}function qc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&E(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>E(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>E(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function Ss(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function Es(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>ks)throw new Error(`Keep the role under ${ks} characters.`);return e}function Bc(t,e,n){let r=new Set;for(let o=e;o&&!r.has(o);o=t.find(s=>s.type==="reports-to"&&s.from===o)?.to){if(o===n)return!0;r.add(o)}return!1}function _s(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:E(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:E(o.from),to:E(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function zm(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=vs(n),s=jc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=Wc(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?E(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:m}=C(u),f=d.get(u);if(!f)throw new Error(g==="agent"?`There is no agent "${m}" on this computer.`:`There is no person "${m}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${f} is already in the org chart.`);let w=Es(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?Ss(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[m]={role:x,schedule:{...be},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[m]=x?{role:x}:{}),c=`${f} added to the org chart`;break}case"set-role":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=Es(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?Ss(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=m:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=m?{role:m}:{}),c=m?`${u.name} is now ${r.roles[m]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let m=_s(r,w=>w.from===u.ref||w.to===u.ref),f=qc(r,u.ref);u.kind==="agent"?delete r.orgChart[u.id]:r.orgPeople&&(delete r.orgPeople[u.id],Object.keys(r.orgPeople).length===0&&delete r.orgPeople),c=`${u.name} removed from the org chart`+(m?`, with ${m} ${m===1?"line":"lines"}`:"")+(f.length?` and out of ${f.join(", ")}`:"");break}case"add-relation":{let u=String(e.type??"").trim(),g=[String(e.from??"").trim(),String(e.to??"").trim()];if(!g[0]||!g[1]||!u)throw new Error("Pick a member, a kind of relation and a target.");if(!Qe.includes(u))throw new Error(`"${u}" is not a kind of relation. Pick reports to, dotted line or acts for.`);let[m,f]=g.map(E);for(let x of[m,f])if(!i.has(x))throw new Error(`${l(x)} is not in the org chart. Add them first.`);if(m===f)throw new Error(`${l(m)} cannot be linked to themself.`);let w={from:m,to:f,type:u};if(s.relations.some(x=>x.from===m&&x.to===f&&x.type===u))throw new Error(`${l(m)} already ${Zt[u]} ${l(f)}.`);if(u==="acts-for"&&i.get(m).kind!=="agent")throw new Error(`Only an agent can act for someone: ${l(m)} is a person.`);if(u==="acts-for"&&i.get(f).kind!=="person")throw new Error(`An agent acts for a person: ${l(f)} is an agent.`);if(u==="reports-to"){let x=s.relations.find(b=>b.type==="reports-to"&&b.from===m);if(x)throw new Error(`${l(m)} already reports to ${l(x.to)}. Remove that line first: each member has one boss.`);if(Bc(s.relations,f,m))throw new Error(`${l(m)} cannot report to ${l(f)}: ${l(f)} already reports up to ${l(m)}.`)}if(u==="reports-to"&&i.get(m).kind==="agent"){let x=C(f);r.orgChart[C(m).id].reportsTo=x.kind==="agent"?x.id:f}else r.relations=[...r.relations??[],w];c=`${l(m)} ${Zt[u]} ${l(f)}`;break}case"remove-relation":{let u={from:E(String(e.from??"")),to:E(String(e.to??"")),type:String(e.type??"")};if(!_s(r,g=>g.from===u.from&&g.to===u.to&&g.type===u.type))throw new Error("That line is not in the org chart any more. Reload the page.");c=`${l(u.from)} no longer ${Zt[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);if(u.kind!=="agent")throw new Error(`Working hours are for agents: ${u.name} is a person.`);let g=Fc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Uc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=vs(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}var Hc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Ts=class{constructor(e=Hc,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},Vc="That code didn't work. Check it, or run agentx app pair for a new one.",Xc=400;async function Ym(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await vr(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await zc(n,e.minMs??Xc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Vc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function zc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as dd}from"child_process";import{mkdtempSync as rd,rmSync as od,writeFileSync as sd}from"fs";import{tmpdir as id}from"os";import{join as Cs}from"path";import{randomBytes as Kc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var q={top:8,side:32,bottom:60},tn={height:56,keep:52},As=`
613
613
  :root {
614
614
  --ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
615
615
  --ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
@@ -738,7 +738,7 @@ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: v
738
738
  button.primary:disabled { opacity: .55; cursor: not-allowed; }
739
739
  kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
740
740
  button.primary kbd { color: inherit; opacity: .7; }
741
- `;var Rs=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Is=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Gc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Rs(n):Is(n)}`}function Yc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Is(n)],Rs(n)].join(" ")}function Jc(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 Qc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var nn=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>`,Zc=nn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),ed=nn('<path d="m6 15 6-6 6 6"/>'),td=nn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Ds(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Kc(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=nr(t),l=s.map((u,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${R(u)}</span>${g===d.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${R(r)} recommends</span>`:"",p={choices:s,draft:t.draft??"",placeholder:er,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=s.length?e.pick-1:d.index};return`<!doctype html>
741
+ `;var Rs=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Is=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Gc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Rs(n):Is(n)}`}function Yc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Is(n)],Rs(n)].join(" ")}function Jc(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 Qc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var nn=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>`,Zc=nn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),ed=nn('<path d="m6 15 6-6 6 6"/>'),td=nn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Ds(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Kc(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=jn(t),l=s.map((u,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${R(u)}</span>${g===d.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${R(r)} recommends</span>`:"",p={choices:s,draft:t.draft??"",placeholder:Un,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=s.length?e.pick-1:d.index};return`<!doctype html>
742
742
  <html lang="en"><head><meta charset="utf-8">
743
743
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${o}'">
744
744
  <title>AgentX</title>
@@ -930,7 +930,7 @@ function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
930
930
  function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
931
931
  `;function cd(t,e){let n=t.trim().split(`
932
932
  `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Os.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let o=e.choices??[],s;if(o.length){if(typeof r.choice!="string"||!o.includes(r.choice))return{action:"dismiss"};s=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
933
- `).trim():"",!i||i.length>Zn.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Ns(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=rd(Cs(id(),"agentx-card-"));try{let s=Cs(o,"card.html");sd(s,Ds(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",ld,s,String(ad),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?cd(a.stdout,t):null}finally{od(o,{recursive:!0,force:!0})}}var Os=["not now","timed out","closed"],ud=(t,e,n)=>new Promise(r=>{try{dd(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Ls=160,rn=15e3;function Ps(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Ls?e.slice(0,Ls):e}async function pd(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?br(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],rn),!!e.speak)if(o){let a;await Promise.race([o(Ps(t)),new Promise(d=>{a=setTimeout(d,rn)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Ps(t)],rn)}}function Us(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function gd(t,e,n){return Us(["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 Ms(t,e,n,r,o){return Us(["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(`
933
+ `).trim():"",!i||i.length>Fn.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Ns(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=rd(Cs(id(),"agentx-card-"));try{let s=Cs(o,"card.html");sd(s,Ds(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",ld,s,String(ad),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?cd(a.stdout,t):null}finally{od(o,{recursive:!0,force:!0})}}var Os=["not now","timed out","closed"],ud=(t,e,n)=>new Promise(r=>{try{dd(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Ls=160,rn=15e3;function Ps(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Ls?e.slice(0,Ls):e}async function pd(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?kr(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],rn),!!e.speak)if(o){let a;await Promise.race([o(Ps(t)),new Promise(d=>{a=setTimeout(d,rn)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Ps(t)],rn)}}function Us(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function gd(t,e,n){return Us(["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 Ms(t,e,n,r,o){return Us(["on run argv","set AppleScript's text item delimiters to linefeed","set btns to text items of (item 3 of argv)","set secs to (item 5 of argv) as integer","if (count of argv) > 5 then","set r to display dialog (item 2 of argv) with title (item 1 of argv) default answer (item 6 of argv) buttons btns default button (item 4 of argv) giving up after secs","else","set r to display dialog (item 2 of argv) with title (item 1 of argv) buttons btns default button (item 4 of argv) giving up after secs","end if",'if gave up of r then return ""',"if (count of argv) > 5 then return (button returned of r) & linefeed & (text returned of r)","return button returned of r","end run"],[t,e,n.join(`
934
934
  `),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function Fs(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
935
935
  `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function on(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
936
936
 
@@ -938,14 +938,14 @@ function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
938
938
 
939
939
  Message (edit it if you like):`:`${on(t)}
940
940
 
941
- Message (edit it if you like):`,p=await n("/usr/bin/osascript",Ms(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,tr(t.draft,i)),o),u=p.ok?Fs(p.stdout):null;if(u?.button==="Send"){let g=u.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return u?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",Ms(s,on(t),["Not now","No","Yes"],r),o),d=a.ok?Fs(a.stdout):null;return d?.button==="Yes"?{action:"yes"}:d?.button==="No"?{action:"no"}:{action:"dismiss"}}var ln=24*36e5,sn=!1,fd=10*6e4,js=-1/0;function qs(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o,passAt:s,wanted:i=[]}=N(t.root),a=s?Date.parse(s):NaN,d=ee(t.root,"pending").filter(c=>Date.parse(c.expires)>n),l=d.find(c=>i.includes(`card:${c.id}`));if(l)return l;for(let c of d){let p=`card:${c.id}`;if(r[p]||!e(c)||Ar(t.root,c.id,n))continue;let u=o[p];if(u&&Date.parse(u)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>ln&&!(g<=a)))return c}return null}function an(t){try{return G(t)?.listByState("needs_attention")??[]}catch{return[]}}var Bs=new Map;function hd(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=N(t.root);return e({})?an(t).find(s=>{let i=`request:${s.id}`,a=o[i];return Bs.get(s.id)===K(s,pt.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=ln})??null:null}function bd(t,e){return{id:t.id,title:K(t,pt.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+ln).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Rf(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(sn)return"busy";let o=qs(e,t.reaches)?null:hd(e,t.reaches),s=o?bd(o,e.now??Date.now()):qs(e,t.reaches);if(!s)return"none";let i=(t.focus??ps)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,d=(N(e.root).wanted??[]).includes(a)?null:xr(s);if(d){if(o)Bs.set(o.id,s.title);else{let l=[...ee(e.root,"pending").map(c=>`card:${c.id}`),...an(e).map(c=>`request:${c.id}`)];ht(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${d}`),t.returnToAuthor?.(s,kr(s,d)),"returned"}sn=!0;try{let l=[...ee(e.root,"pending").map(w=>`card:${w.id}`),...an(e).map(w=>`request:${w.id}`)];ht(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),p=!!o&&c-js<fd;o&&n.speak&&(js=c);let u=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??Ws)(s,p?{...n,speak:!1}:n,{from:u,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${zn(i)} when shown)`),"shown";if(!(o?G(e)?.get(o.id)?.state==="needs_attention":pe(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let f=await ho(e,a,g.action,{by:"operator (popup)",...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(f.ok?`[approvals] popup: ${f.message}`:`[approvals] popup: ${a} not recorded: ${f.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{sn=!1}}function If(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:")?pe(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Ur(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 yd,mkdirSync as wd,readFileSync as xd,renameSync as kd,writeFileSync as vd}from"fs";import{dirname as Sd,resolve as Ed}from"path";var _d=["all","urgent","off"],$d=24*36e5,Hs=24*36e5,Td=30*24*36e5,Vs=t=>_d.includes(t);function Of(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:Vs(e)?e:"off",computer:Vs(n)?n:t.popupEnabled?"all":"off"}}function zs(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=$d}function Xs(t,e,n){return t==="all"||t==="urgent"&&zs(e,n)}function Ks(t){return Ed(t,".agentx","desk-routed.json")}function Ad(t){let e=Ks(t);if(!yd(e))return null;try{let n=JSON.parse(xd(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function cn(t,e){let n=Ks(t);wd(Sd(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;vd(r,JSON.stringify(e,null,2)),kd(r,n)}async function Lf(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),d=Ad(e);if(!d){let p={};for(let u of r.items)p[u.key]={at:a,seen:a};return cn(e,{items:p}),i.primed=!0,i}let l=[],c=[];for(let p of r.items){let u=d.items[p.key];if(u){u.seen=a,u.computerHeld&&n-Date.parse(u.at)>Hs&&delete u.computerHeld,u.computerHeld&&c.push(p);continue}d.items[p.key]={at:a,seen:a};let g=p.askedAt?Date.parse(p.askedAt):n;n-g<=Hs&&l.push(p)}for(let[p,u]of Object.entries(d.items))n-Date.parse(u.seen)>Td&&delete d.items[p];cn(e,d);for(let p of l)if(Xs(o.phone,p,n))try{await t.phone(p,zs(p,n)),i.phone.push(p.key)}catch(u){s(`[desk] ${p.key}: not sent to the phone: ${u?.message??u}`)}if(t.computer){let p=!1;for(let u of[...c,...l]){let g=d.items[u.key];if(!Xs(o.computer,u,n)){g.computerHeld&&(delete g.computerHeld,p=!0);continue}try{let m=await t.computer(u);m&&i.computer.push(u.key),m&&g.computerHeld&&(delete g.computerHeld,p=!0),!m&&!g.computerHeld&&(g.computerHeld=!0,p=!0)}catch(m){s(`[desk] ${u.key}: not shown on this computer: ${m?.message??m}`),g.computerHeld&&(delete g.computerHeld,p=!0)}}p&&cn(e,d)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Pf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
942
- Answer it on the Desk.`}}import{closeSync as ye,createReadStream as Rd,fstatSync as Id,openSync as Dd,realpathSync as Gs}from"fs";import{isAbsolute as Cd,resolve as Ys,sep as Js}from"path";var qf="/app-files",Nd=/^[A-Za-z0-9_.:-]{1,64}$/;function Od(t,e,n=process.cwd()){if(!e||e.length>W.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:`the path leaves the workspace: copy the file into ${at}/ first`};if(!de(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Gs(Ys(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=Gs(Cd(e)?e:Ys(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Js))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${at}/ first`};let s=de(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function Ld(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 Pd(t,e,n){return{"Content-Type":t,"Content-Disposition":Ld(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 Md(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,o;return n[1]?(r=Number(n[1]),o=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),o=e-1),r>o||r>=e?"unsatisfiable":{start:r,end:o}}function Bf(t,e,n,r){let o=(x,b)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(b))};if(t.method!=="GET"&&t.method!=="HEAD")return o(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!Nd.test(s))return o(400,{error:"bad agent id"});let a=r.workspaceOf(s);if(!a)return o(404,{error:`no agent "${s}" on this computer`});let d=Od(a,i,r.cwd);if(!d.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${d.error}`),o(d.status,{error:d.error});let l;try{l=Dd(d.path,"r")}catch{return o(404,{error:"file not found"})}let c;try{let x=Id(l);if(!x.isFile())return ye(l),o(404,{error:"not a file"});c=x.size}catch{return ye(l),o(404,{error:"file not found"})}if(c>W.bytes)return ye(l),o(413,{error:`the file is larger than ${W.bytes/1024/1024} MB`});let p=d.path.split(Js).pop()||"file",u=Pd(d.mime,p,d.kind),g=Md(t.headers.range,c);if(g==="unsatisfiable"){ye(l),e.writeHead(416,{...u,"Content-Range":`bytes */${c}`}),e.end();return}let{start:m,end:f}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...u,"Content-Length":String(c?f-m+1:0),...g?{"Content-Range":`bytes ${m}-${f}/${c}`}:{}}),t.method==="HEAD"||c===0){ye(l),e.end();return}let w=Rd("",{fd:l,start:m,end:f,autoClose:!0});w.on("error",()=>e.destroy()),e.on("close",()=>w.destroy()),w.pipe(e)}import{spawn as we}from"child_process";import{readFileSync as Fd,writeFileSync as Ud}from"fs";import{tmpdir as Wd}from"os";import{join as jd}from"path";_n();var Qs=t=>t&&t!==1?Math.round(175*t):null,Ke=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function qd(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=Fd(t,"utf8").trim();if(e)return e}catch{}return null}function Qf(t=qd()){let e=0;return async(n,r)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...Ke(n.voice.rate)?{voice_settings:{speed:Ke(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=jd(Wd(),`agentx-say-${process.pid}-${++e}.mp3`);return Ud(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return Y(`elevenlabs:${String(o?.message??o).slice(0,40)}`,`[voice] ElevenLabs failed (${String(o?.message??o).slice(0,160)}); speaking with the system voice`),null}}}function Zs(t,e){let n=t.languages&&_e(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Bd=(t,e="")=>{let n=Zs(t,e),r=Qs(t.rate);return[...n&&!Ro(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Hd(t,e,n){if(!n)return["say",Bd(t,e)];let r=Zs(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function Zf(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function eh(t=dn()){if(t)try{we("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function th(t=dn()){if(t)try{we("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function dn(t={},e){if(!Tt(t))return null;try{return Co(e)}catch(n){return Y("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
941
+ Message (edit it if you like):`,p=await n("/usr/bin/osascript",Ms(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,Wn(t.draft,i)),o),u=p.ok?Fs(p.stdout):null;if(u?.button==="Send"){let g=u.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return u?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",Ms(s,on(t),["Not now","No","Yes"],r),o),d=a.ok?Fs(a.stdout):null;return d?.button==="Yes"?{action:"yes"}:d?.button==="No"?{action:"no"}:{action:"dismiss"}}var ln=24*36e5,sn=!1,fd=10*6e4,js=-1/0;function qs(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o,passAt:s,wanted:i=[]}=N(t.root),a=s?Date.parse(s):NaN,d=Z(t.root,"pending").filter(c=>Date.parse(c.expires)>n),l=d.find(c=>i.includes(`card:${c.id}`));if(l)return l;for(let c of d){let p=`card:${c.id}`;if(r[p]||!e(c)||Ar(t.root,c.id,n))continue;let u=o[p];if(u&&Date.parse(u)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>ln&&!(g<=a)))return c}return null}function an(t){try{return G(t)?.listByState("needs_attention")??[]}catch{return[]}}var Bs=new Map;function hd(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=N(t.root);return e({})?an(t).find(s=>{let i=`request:${s.id}`,a=o[i];return Bs.get(s.id)===K(s,rt.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=ln})??null:null}function bd(t,e){return{id:t.id,title:K(t,rt.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+ln).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Rf(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(sn)return"busy";let o=qs(e,t.reaches)?null:hd(e,t.reaches),s=o?bd(o,e.now??Date.now()):qs(e,t.reaches);if(!s)return"none";let i=(t.focus??ps)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,d=(N(e.root).wanted??[]).includes(a)?null:qn(s);if(d){if(o)Bs.set(o.id,s.title);else{let l=[...Z(e.root,"pending").map(c=>`card:${c.id}`),...an(e).map(c=>`request:${c.id}`)];ht(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${d}`),t.returnToAuthor?.(s,Bn(s,d)),"returned"}sn=!0;try{let l=[...Z(e.root,"pending").map(w=>`card:${w.id}`),...an(e).map(w=>`request:${w.id}`)];ht(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),p=!!o&&c-js<fd;o&&n.speak&&(js=c);let u=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??Ws)(s,p?{...n,speak:!1}:n,{from:u,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${tr(i)} when shown)`),"shown";if(!(o?G(e)?.get(o.id)?.state==="needs_attention":ce(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let f=await ho(e,a,g.action,{by:"operator (popup)",popup:!0,...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(f.ok?`[approvals] popup: ${f.message}`:`[approvals] popup: ${a} not recorded: ${f.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{sn=!1}}function If(t,e,n){if(!n)return{ok:!1,error:"the Mac popup is off; turn it on with `agentx approvals settings --popup on`"};let r=e.startsWith("card:")?ce(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Ur(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 yd,mkdirSync as wd,readFileSync as xd,renameSync as kd,writeFileSync as vd}from"fs";import{dirname as Sd,resolve as Ed}from"path";var _d=["all","urgent","off"],$d=24*36e5,Hs=24*36e5,Td=30*24*36e5,Vs=t=>_d.includes(t);function Of(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:Vs(e)?e:"off",computer:Vs(n)?n:t.popupEnabled?"all":"off"}}function zs(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=$d}function Xs(t,e,n){return t==="all"||t==="urgent"&&zs(e,n)}function Ks(t){return Ed(t,".agentx","desk-routed.json")}function Ad(t){let e=Ks(t);if(!yd(e))return null;try{let n=JSON.parse(xd(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function cn(t,e){let n=Ks(t);wd(Sd(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;vd(r,JSON.stringify(e,null,2)),kd(r,n)}async function Lf(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),d=Ad(e);if(!d){let p={};for(let u of r.items)p[u.key]={at:a,seen:a};return cn(e,{items:p}),i.primed=!0,i}let l=[],c=[];for(let p of r.items){let u=d.items[p.key];if(u){u.seen=a,u.computerHeld&&n-Date.parse(u.at)>Hs&&delete u.computerHeld,u.computerHeld&&c.push(p);continue}d.items[p.key]={at:a,seen:a};let g=p.askedAt?Date.parse(p.askedAt):n;n-g<=Hs&&l.push(p)}for(let[p,u]of Object.entries(d.items))n-Date.parse(u.seen)>Td&&delete d.items[p];cn(e,d);for(let p of l)if(Xs(o.phone,p,n))try{await t.phone(p,zs(p,n)),i.phone.push(p.key)}catch(u){s(`[desk] ${p.key}: not sent to the phone: ${u?.message??u}`)}if(t.computer){let p=!1;for(let u of[...c,...l]){let g=d.items[u.key];if(!Xs(o.computer,u,n)){g.computerHeld&&(delete g.computerHeld,p=!0);continue}try{let m=await t.computer(u);m&&i.computer.push(u.key),m&&g.computerHeld&&(delete g.computerHeld,p=!0),!m&&!g.computerHeld&&(g.computerHeld=!0,p=!0)}catch(m){s(`[desk] ${u.key}: not shown on this computer: ${m?.message??m}`),g.computerHeld&&(delete g.computerHeld,p=!0)}}p&&cn(e,d)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Pf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
942
+ Answer it on the Desk.`}}import{closeSync as ye,createReadStream as Rd,fstatSync as Id,openSync as Dd,realpathSync as Gs}from"fs";import{isAbsolute as Cd,resolve as Ys,sep as Js}from"path";var qf="/app-files",Nd=/^[A-Za-z0-9_.:-]{1,64}$/;function Od(t,e,n=process.cwd()){if(!e||e.length>W.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:`the path leaves the workspace: copy the file into ${ct}/ first`};if(!ue(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Gs(Ys(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=Gs(Cd(e)?e:Ys(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Js))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${ct}/ first`};let s=ue(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function Ld(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 Pd(t,e,n){return{"Content-Type":t,"Content-Disposition":Ld(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 Md(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,o;return n[1]?(r=Number(n[1]),o=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),o=e-1),r>o||r>=e?"unsatisfiable":{start:r,end:o}}function Bf(t,e,n,r){let o=(x,b)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(b))};if(t.method!=="GET"&&t.method!=="HEAD")return o(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!Nd.test(s))return o(400,{error:"bad agent id"});let a=r.workspaceOf(s);if(!a)return o(404,{error:`no agent "${s}" on this computer`});let d=Od(a,i,r.cwd);if(!d.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${d.error}`),o(d.status,{error:d.error});let l;try{l=Dd(d.path,"r")}catch{return o(404,{error:"file not found"})}let c;try{let x=Id(l);if(!x.isFile())return ye(l),o(404,{error:"not a file"});c=x.size}catch{return ye(l),o(404,{error:"file not found"})}if(c>W.bytes)return ye(l),o(413,{error:`the file is larger than ${W.bytes/1024/1024} MB`});let p=d.path.split(Js).pop()||"file",u=Pd(d.mime,p,d.kind),g=Md(t.headers.range,c);if(g==="unsatisfiable"){ye(l),e.writeHead(416,{...u,"Content-Range":`bytes */${c}`}),e.end();return}let{start:m,end:f}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...u,"Content-Length":String(c?f-m+1:0),...g?{"Content-Range":`bytes ${m}-${f}/${c}`}:{}}),t.method==="HEAD"||c===0){ye(l),e.end();return}let w=Rd("",{fd:l,start:m,end:f,autoClose:!0});w.on("error",()=>e.destroy()),e.on("close",()=>w.destroy()),w.pipe(e)}import{spawn as we}from"child_process";import{readFileSync as Fd,writeFileSync as Ud}from"fs";import{tmpdir as Wd}from"os";import{join as jd}from"path";_n();var Qs=t=>t&&t!==1?Math.round(175*t):null,Ke=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function qd(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=Fd(t,"utf8").trim();if(e)return e}catch{}return null}function Qf(t=qd()){let e=0;return async(n,r)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...Ke(n.voice.rate)?{voice_settings:{speed:Ke(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=jd(Wd(),`agentx-say-${process.pid}-${++e}.mp3`);return Ud(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return Y(`elevenlabs:${String(o?.message??o).slice(0,40)}`,`[voice] ElevenLabs failed (${String(o?.message??o).slice(0,160)}); speaking with the system voice`),null}}}function Zs(t,e){let n=t.languages&&_e(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Bd=(t,e="")=>{let n=Zs(t,e),r=Qs(t.rate);return[...n&&!Ro(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Hd(t,e,n){if(!n)return["say",Bd(t,e)];let r=Zs(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function Zf(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function eh(t=dn()){if(t)try{we("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function th(t=dn()){if(t)try{we("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function dn(t={},e){if(!Tt(t))return null;try{return Co(e)}catch(n){return Y("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
943
943
  `)[0]}); Siri voices will not switch`),null}}var nh=(t,e)=>{if(!t){let[n,r]=Hd(e.voice,e.text,dn()),o=Qs(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=we(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?we("afplay",[t],{stdio:"ignore"}):we("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as ei}from"child_process";import{accessSync as Vd,constants as Xd,readFileSync as ti}from"fs";import{homedir as zd}from"os";import{basename as se,delimiter as ni,dirname as Kd,extname as Gd,join as un}from"path";var z={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function ri(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>z.ms+2e3?{status:413,error:gn()}:null}var gn=()=>`The recording is longer than ${z.ms/6e4} minutes.`,Yd={"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 oi(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Yd[e]??null}function si(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 mn(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 pn(t,e,n=process.env.PATH??""){let r=zd(),o=[un(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(ni).filter(Boolean)];for(let s of[e,...o.map(i=>un(i,t))])if(s)try{return Vd(s,Xd.X_OK),s}catch{}return null}function lh(t){return{key:t,mlx:pn("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:pn("whisper",process.env.AGENTX_WHISPER),ffmpeg:Jd()}}var Jd=()=>pn("ffmpeg",process.env.AGENTX_FFMPEG);async function ii(t,e){return e?Qd(t,e):null}async function Qd(t,e){let n=String(z.ms/1e3+5);try{let o=[...(await Zd(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],s=o[o.length-1];return s?Number(s[1])*3600+Number(s[2])*60+Number(s[3]):null}catch{return null}}async function ai(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([ti(t)],{type:e}),se(t));let s=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:o,signal:r??AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);let i=await s.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function li(t,e,n,r,o){let s=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",o,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",o,"--fp16","False"],i={...process.env,PATH:`${Kd(r)}${ni}${process.env.PATH??""}`};await eu(e,s,12e4,i);try{return ti(un(o,se(n,Gd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Zd(t,e,n){return new Promise((r,o)=>{let s=ei(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${se(t)} took too long`))},n);s.stderr.on("data",d=>{i=(i+d).slice(-8192)}),s.on("error",d=>{clearTimeout(a),o(d)}),s.on("exit",d=>{clearTimeout(a),d===0?r(i):o(new Error(`${se(t)} exited ${d}`))})})}function eu(t,e,n,r=process.env){return new Promise((o,s)=>{let i=ei(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",d="",l=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${se(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{d.length<4096&&(d+=c)}),i.on("error",c=>{clearTimeout(l),s(c)}),i.on("exit",c=>{clearTimeout(l),c===0?o(a):s(new Error(`${se(t)} exited ${c}: ${d.trim().split(`
944
944
  `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as tu,rm as nu,writeFile as ru}from"fs/promises";import{tmpdir as ou}from"os";import{join as ci}from"path";ki();var su=64*1024,iu=2,fn=0;function wh(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function xh(t,e,n,r){return t.method!=="POST"?$(e,405,{error:"POST"}):n==="/voice/transcribe"?au(t,e,r):du(t,e,r)}async function au(t,e,n){let r=String(t.headers["content-type"]||""),o=oi(r);if(!o)return $(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=ri(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),$(e,s.status,{error:s.error});let i=await di(t,z.bytes);if(!i)return $(e,413,{error:gu()});if(!i.length)return $(e,400,{error:"The recording is empty."});if(fn>=iu)return $(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),d=n.host(),l=si(a,d);if(!d.ffmpeg&&!n.allowUnmeasured?.()){let p=n.nodeName?`on ${n.nodeName}`:"on this computer",u=l.length?"":" "+mn(a,d);return $(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${p} for voice input from the phone.${u}`,setup:!1})}if(!l.length)return $(e,503,{error:"Voice input isn't set up on this computer.",hint:mn(a,d),setup:!1});fn++;let c;try{let p=await tu(ci(ou(),"agentx-phone-voice-"));try{c=await lu(p,`speech.${o}`,i,r,d,l,n)}finally{await nu(p,{recursive:!0,force:!0}).catch(()=>{})}}finally{fn--}$(e,c[0],c[1])}async function lu(t,e,n,r,o,s,i){let a=ci(t,e);if(await ru(a,n,{mode:384}),o.ffmpeg){let l=await(i.measure??ii)(a,o.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>z.ms+2e3)return[413,{error:gn()}]}let d=[];for(let l of s)try{let c=await cu(l,a,r,o,t,i);return i.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(c){let p=String(c?.message??c).split(`
945
945
  `)[0].slice(0,200);d.push(`${l}: ${p}`),i.log(`[voice] phone transcription with ${l} failed: ${p}`)}return[502,{error:"Speech to text failed on this computer.",detail:d.join("; ")}]}function cu(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return ai(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return li(t,a,e,r.ffmpeg,o)}async function du(t,e,n){let r=await di(t,su);if(!r)return $(e,413,{error:"request too large"});let o;try{o=JSON.parse(r.toString("utf8")||"{}")}catch{return $(e,400,{error:"expected JSON"})}let s=typeof o?.agent=="string"?o.agent:"",i=typeof o?.peer=="string"&&o.peer?o.peer:void 0;if(!s)return $(e,400,{error:"agent is required"});let a=uu(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return $(e,422,{error:"Nothing in this answer can be said aloud."});let d=n.pronounce?n.pronounce(a):a,l=n.voiceOf(s,i);if(!l)return $(e,404,{error:`Unknown agent: ${s}`});let c=(u,g=200)=>$(e,g,{fallback:"browser",reason:u,text:d});if(l.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let p=n.elevenLabsKey();if(!p)return c("No ElevenLabs key is set on this computer.");try{let u=await(n.synth??pu)(p,l,d);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":u.length,"Cache-Control":"no-store","X-Spoken-Chars":String(d.length)}),e.end(u)}catch(u){return n.log(`[voice] phone answer synthesis failed: ${String(u?.message??u).split(`
946
946
  `)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function uu(t,e){let n=Ve(Ae(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return $n(n,e)}async function pu(t,e,n){let r=Ke(e.rate),o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(e.elevenlabs)}?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n,model_id:"eleven_flash_v2_5",...r?{voice_settings:{speed:r}}:{}}),signal:AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await o.arrayBuffer())}var gu=()=>`The recording is larger than ${z.bytes/1024/1024} MB, more than ${z.ms/6e4} minutes of speech.`;function kh(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?Mt(Ot(t,o,n.voice)):null}function di(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let o=[],s=0;t.on("data",i=>{if(!(s>e)){if(s+=i.length,s>e){o.length=0,n(null);return}o.push(i)}}),t.on("end",()=>{s<=e&&n(Buffer.concat(o))}),t.on("error",r)})}function $(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}var mu="[Live voice call on the owner's watch or headset. Your answer is read aloud to them and they can't see a screen. Answer what they just said, in a few short spoken sentences.]",fu="operator",hu=50,ui=4,pi=500;function bu(t){let e={channel:"app",chatId:t.chatId,sender:fu,...t.spoken?{via:"voice"}:{}},n=t.call==="watch"?`${mu}
947
947
 
948
- ${t.message}`:t.message;return t.node==="local"?{path:"/task",body:{agent:t.agent,message:n,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:n,stream:!0,context:e}}}async function $h(t,e,n,r){let{path:o,body:s}=bu(e),i="",a=!1,d=[],l=new Map,c=(p,u,g)=>{let m=p!=="done",f=a?{text:Bn(u,m),artifacts:[]}:Ae(u,W.perMessage,m),{cleanText:w,ui:x}=p==="done"?Ve(f.text):{cleanText:f.text,ui:void 0},b=a?void 0:wu(x);return{status:p,text:w,tools:d,files:f.artifacts,...b?{ui:b}:{},...g?{error:g}:{}}};try{let p=await fetch(t.url.replace(/\/+$/,"")+o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(s),signal:n});if(!p.ok||!p.body){let u=await p.json().then(g=>g?.error).catch(()=>"");return c("error",i,u||`AgentX answered HTTP ${p.status}.`)}for await(let u of xu(p.body)){r(u.event,u.data);let g=u.data??{};if(u.event==="start")a=g.rich===!1;else if(u.event==="text"&&typeof g.text=="string")i+=g.text;else if(u.event==="tool"&&g.status==="start"&&d.length<hu){let m={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};d.push(m),g.id&&l.set(String(g.id),m)}else if(u.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(u.event==="done")return c("done",typeof g.content=="string"&&g.content?g.content:i);if(u.event==="error")return c("error",i,yu(g.error))}}return n.aborted?c("stopped",i):c("error",i,"The connection to the agent closed before it answered.")}catch(p){return n.aborted?c("stopped",i):c("error",i,`Could not reach AgentX: ${p?.message||p}`)}}function yu(t){let e=String(t||"The agent could not answer.");return Fn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function wu(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let o=(t.quickReplies??[]).slice(0,ui).map(i=>i.slice(0,pi));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,ui).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,pi)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*xu(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=n.decode(s,{stream:!0}).replace(/\r\n/g,`
948
+ ${t.message}`:t.message;return t.node==="local"?{path:"/task",body:{agent:t.agent,message:n,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:n,stream:!0,context:e}}}async function $h(t,e,n,r){let{path:o,body:s}=bu(e),i="",a=!1,d=[],l=new Map,c=(p,u,g)=>{let m=p!=="done",f=a?{text:Jn(u,m),artifacts:[]}:Ae(u,W.perMessage,m),{cleanText:w,ui:x}=p==="done"?Ve(f.text):{cleanText:f.text,ui:void 0},b=a?void 0:wu(x);return{status:p,text:w,tools:d,files:f.artifacts,...b?{ui:b}:{},...g?{error:g}:{}}};try{let p=await fetch(t.url.replace(/\/+$/,"")+o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(s),signal:n});if(!p.ok||!p.body){let u=await p.json().then(g=>g?.error).catch(()=>"");return c("error",i,u||`AgentX answered HTTP ${p.status}.`)}for await(let u of xu(p.body)){r(u.event,u.data);let g=u.data??{};if(u.event==="start")a=g.rich===!1;else if(u.event==="text"&&typeof g.text=="string")i+=g.text;else if(u.event==="tool"&&g.status==="start"&&d.length<hu){let m={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};d.push(m),g.id&&l.set(String(g.id),m)}else if(u.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(u.event==="done")return c("done",typeof g.content=="string"&&g.content?g.content:i);if(u.event==="error")return c("error",i,yu(g.error))}}return n.aborted?c("stopped",i):c("error",i,"The connection to the agent closed before it answered.")}catch(p){return n.aborted?c("stopped",i):c("error",i,`Could not reach AgentX: ${p?.message||p}`)}}function yu(t){let e=String(t||"The agent could not answer.");return Xn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function wu(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let o=(t.quickReplies??[]).slice(0,ui).map(i=>i.slice(0,pi));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,ui).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,pi)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*xu(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=n.decode(s,{stream:!0}).replace(/\r\n/g,`
949
949
  `);let i;for(;(i=r.indexOf(`
950
950
 
951
951
  `))!==-1;){let a=r.slice(0,i);r=r.slice(i+2);let d="message",l=[];for(let c of a.split(`
@@ -966,4 +966,4 @@ Document the arguments, commands, or files the skill expects. Example:
966
966
  claude-code ${vn(t)} --arg value
967
967
  \`\`\`
968
968
  `}Ln();var bi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function yi(t){return{...bi,...t??{},regions:{...t?.regions??{}},buffer:{...bi.buffer,...t?.buffer??{}}}}function Hh(t){try{return yi(On(t).screen)}catch{return yi(void 0)}}var Au=/^[a-z][\w-]*$/,wi=["window","screen","menubar","notifications"];function ke(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var Ye=(t,e)=>ke(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function xi(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 Vh(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Ye(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Ye(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Ye(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ke(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ke(e.changeThreshold,"changeThreshold",o=>o>=0&&o<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let o={...n.regions??{}};for(let[s,i]of Object.entries(e.regions)){if(!Au.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=xi(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=ke(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ke(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Ye(o.maxPixels,"buffer.maxPixels")),"region"in o&&(s.region=String(o.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!wi.includes(r)&&!n.regions?.[r])try{xi(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...wi,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Rr as a,Du as b,Gt as c,oc as d,sc as e,um as f,pm as g,gm as h,hm as i,bm as j,ym as k,as as l,ls as m,wm as n,Ve as o,km as p,Sm as q,X as r,cs as s,A as t,Lu as u,ps as v,Rm as w,Cm as x,ms as y,Nm as z,fs as A,Om as B,he as C,Cc as D,Lm as E,Pm as F,bs as G,Yu as H,Qi as I,np as J,Kr as K,N as L,Wu as M,ju as N,up as O,Ne as P,pp as Q,Wr as R,zu as S,G as T,Wp as U,go as V,ho as W,Pc as X,Fm as Y,Mc as Z,Um as _,Wm as $,Jt as aa,ws as ba,Bm as ca,Zt as da,Wc as ea,jc as fa,zm as ga,La as ha,Pa as ia,Bp as ja,Hp as ka,Ba as la,Kp as ma,Ts as na,Ym as oa,Jp as pa,Qp as qa,rs as ra,Wt as sa,Jl as ta,R as ua,Ws as va,Rf as wa,If as xa,_d as ya,Of as za,Xs as Aa,Lf as Ba,Pf as Ca,qf as Da,Od as Ea,Pd as Fa,Bf as Ga,eg as Ha,tg as Ia,ng as Ja,rg as Ka,og as La,sg as Ma,ag as Na,lg as Oa,ug as Pa,pg as Qa,gg as Ra,hg as Sa,bg as Ta,yg as Ua,wg as Va,xg as Wa,kg as Xa,vg as Ya,Dg as Za,It as _a,Cg as $a,Ng as ab,me as bb,fe as cb,qd as db,Qf as eb,Zf as fb,eh as gb,th as hb,dn as ib,nh as jb,Nt as kb,Ot as lb,je as mb,wl as nb,kl as ob,Fg as pb,Pt as qb,Mt as rb,vl as sb,Sl as tb,qo as ub,Xo as vb,Ug as wb,$l as xb,Wg as yb,Ol as zb,Ml as Ab,Ft as Bb,Ul as Cb,zo as Db,z as Eb,ri as Fb,oi as Gb,si as Hb,pn as Ib,lh as Jb,Jd as Kb,ai as Lb,li as Mb,wh as Nb,xh as Ob,gu as Pb,kh as Qb,di as Rb,Jo as Sb,$h as Tb,wu as Ub,Ah as Vb,Rh as Wb,qe as Xb,tm as Yb,zt as Zb,lm as _b,Nh as $b,Oh as ac,Lh as bc,Ph as cc,Mh as dc,Fh as ec,Uh as fc,Wh as gc,jh as hc,bi as ic,yi as jc,Hh as kc,wi as lc,Vh as mc};
969
- //# sourceMappingURL=chunk-X6SXZDTY.js.map
969
+ //# sourceMappingURL=chunk-7JHB3X5N.js.map