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,2 +1,2 @@
1
- import{s as p}from"./chunk-IDGEDPRJ.js";import{b as i,c as u,d as l,e as c}from"./chunk-2P3SHT5I.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,g=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',m=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function x(e){return m.test(e)}function w(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function S(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function $(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??g,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.report==="exceptions"&&(t.report="exceptions"),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){return e.deliverResult===!1?"(failures only)":e.report==="exceptions"?"(exceptions and failures)":"(results and failures)"}function T(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function A(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function D(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function y(e){return e?.approval?.action==="create"}async function R(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&y(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,x as c,w as d,S as e,$ as f,P as g,T as h,A as i,D as j,y as k,R as l,I as m,O as n};
2
- //# sourceMappingURL=chunk-KRHVM26D.js.map
1
+ import{s as p}from"./chunk-XTIPWYW5.js";import{b as i,c as u,d as l,e as c}from"./chunk-VALKXSXZ.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,g=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',m=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function x(e){return m.test(e)}function w(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function S(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function $(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??g,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.report==="exceptions"&&(t.report="exceptions"),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){return e.deliverResult===!1?"(failures only)":e.report==="exceptions"?"(exceptions and failures)":"(results and failures)"}function T(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function A(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function D(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function y(e){return e?.approval?.action==="create"}async function R(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&y(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,x as c,w as d,S as e,$ as f,P as g,T as h,A as i,D as j,y as k,R as l,I as m,O as n};
2
+ //# sourceMappingURL=chunk-E2MW5OCE.js.map
@@ -1,6 +1,6 @@
1
- import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-245IOYDJ.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-RPL2P7EP.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
6
- //# sourceMappingURL=chunk-WJMYBRM5.js.map
6
+ //# sourceMappingURL=chunk-FXA2WIIP.js.map
@@ -1,4 +1,4 @@
1
- import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{Ib as Ge,Ua as Ke,Va as Ye,Wa as Je,Ya as Xe,c as He,ua as _,za as qe}from"./chunk-X6SXZDTY.js";import{a as V}from"./chunk-IMLAPB7G.js";import{k as Be}from"./chunk-PQUK6XEW.js";import{a as Z,b as Ue}from"./chunk-IU63JGY3.js";import{b as Fe}from"./chunk-MRIVENBY.js";import{q as ue,s as We}from"./chunk-WDGATQV3.js";import{b as Q}from"./chunk-2VDO2HEK.js";import{c as Le,e as Ne}from"./chunk-LQE73AZR.js";import{ga as G}from"./chunk-JT5PIBCM.js";import{b as ge}from"./chunk-7AB3QUGH.js";import{a as K,b as X}from"./chunk-2P3SHT5I.js";import{a as je}from"./chunk-PTZNM2JU.js";import{c as Oe,d as De}from"./chunk-OWNQ2FD4.js";import{a as Me}from"./chunk-ROLSSYXE.js";import{Db as pe,Gb as q,Hb as Re,Rb as xe,ab as Ee,g as le,hb as at,j as F,ma as ce,na as Pe,p as Za,xa as et}from"./chunk-DUCYRNCT.js";import{existsSync as Y,readFileSync as xa,writeFileSync as ga,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var ve=`:root {
1
+ import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{Ib as Ge,Ua as Ke,Va as Ye,Wa as Je,Ya as Xe,c as Le,ua as _,za as qe}from"./chunk-7JHB3X5N.js";import{a as V}from"./chunk-IMLAPB7G.js";import{k as Be}from"./chunk-6U34GZ7U.js";import{a as Z,b as Ue}from"./chunk-7GD5GTWC.js";import{b as Fe}from"./chunk-MRIVENBY.js";import{b as Q}from"./chunk-2VDO2HEK.js";import{c as Ne,e as We}from"./chunk-LQE73AZR.js";import{ga as G}from"./chunk-U3OJO7B7.js";import{b as ue}from"./chunk-7AB3QUGH.js";import{a as K,b as X}from"./chunk-VALKXSXZ.js";import{a as He}from"./chunk-WTCMJZW3.js";import{c as De,d as Me}from"./chunk-OWNQ2FD4.js";import{a as je}from"./chunk-ROLSSYXE.js";import{r as ge,t as Oe}from"./chunk-XL7UWG36.js";import{Db as pe,Gb as q,Hb as Re,Rb as xe,ab as Ee,g as le,hb as at,j as F,ma as ce,na as Pe,p as Za,xa as et}from"./chunk-CARVBJB7.js";import{existsSync as Y,readFileSync as xa,writeFileSync as ga,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var ve=`:root {
2
2
  /* --- Brand (agentina) --------------------------------------------- */
3
3
  --ax-blue: #2979FF;
4
4
  --ax-blue-d: #1B5FD9;
@@ -2045,7 +2045,7 @@ ${e.noAssistant?"":`<script>${da({markdownToHtml:V})}${sa}</script>`}
2045
2045
  </div>
2046
2046
  </div>
2047
2047
  <div class="ax-topbar__right">
2048
- <a href="${ge}#page=live" class="ax-skip">Skip \u2014 open dashboard</a>
2048
+ <a href="${ue}#page=live" class="ax-skip">Skip \u2014 open dashboard</a>
2049
2049
  <div class="ax-theme-switch" role="tablist" aria-label="Theme">
2050
2050
  <button data-theme-opt="dark">Dark</button>
2051
2051
  <button data-theme-opt="light">Light</button>
@@ -2075,7 +2075,7 @@ ${e.noAssistant?"":`<script>${da({markdownToHtml:V})}${sa}</script>`}
2075
2075
  ${s}
2076
2076
  <footer class="ax-actions">
2077
2077
  ${ee("Save and continue",{type:"submit",primary:!0,id:"submitBtn"})}
2078
- ${ee("Skip, I'll do it later",{onclick:`window.location.href='${ge}#page=live'`})}
2078
+ ${ee("Skip, I'll do it later",{onclick:`window.location.href='${ue}#page=live'`})}
2079
2079
  </footer>
2080
2080
  </form>
2081
2081
  </div>`;return ye({title:"AgentX \u2014 Setup",activeTab:"custom",subtitle:"Setup",customHeader:r,noMain:!0,noAssistant:!0,body:l,css:st,scripts:dt})}var st=`
@@ -2217,8 +2217,8 @@ ${g}
2217
2217
  `)?"":`
2218
2218
  `;lt(e,o+n.join(`
2219
2219
  `)+`
2220
- `)}}function _n(e,a){let t=ua(),r=t.nodeName||gt().replace(/\.local$/,""),n=ca(t,r);a.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),a.end(n)}async function Sn(e,a){let t="";await new Promise(n=>{e.on("data",o=>{t+=o}),e.on("end",()=>n())});let r;try{r=JSON.parse(t)}catch{a.writeHead(400,{"Content-Type":"application/json"}),a.end(JSON.stringify({error:"Invalid JSON"}));return}try{let n=mt(r);a.writeHead(200,{"Content-Type":"application/json"}),a.end(JSON.stringify(n))}catch(n){a.writeHead(400,{"Content-Type":"application/json"}),a.end(JSON.stringify({error:n.message||"wizard failed"}))}}async function Cn(e,a){a.setHeader("Content-Type","application/json");let t;try{t=Re().node?.bind||"127.0.0.1:18800"}catch(i){a.writeHead(400),a.end(JSON.stringify({ok:!1,error:`Config validation failed: ${i.message}`}));return}let r=`http://${t.replace(/^0\.0\.0\.0/,"127.0.0.1")}`;if(await pa(r)){a.writeHead(200),a.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!0}));return}let n=process.argv[1]||M(pt(xt(import.meta.url)),"cli.js");try{ut(process.execPath,[n,"daemon","start"],{detached:!0,stdio:"ignore",cwd:process.cwd()}).unref()}catch(i){a.writeHead(500),a.end(JSON.stringify({ok:!1,error:`Failed to spawn daemon: ${i.message}`,manualUrl:r}));return}let o=Date.now()+12e3;for(;Date.now()<o;)if(await new Promise(i=>setTimeout(i,400)),await pa(r)){a.writeHead(200),a.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!1}));return}a.writeHead(504),a.end(JSON.stringify({ok:!1,error:"Daemon spawn succeeded but never bound the port within 12s \u2014 check `agentx daemon status` and the dotfile log for errors.",manualUrl:r}))}async function pa(e){try{let a=await fetch(e,{method:"GET",signal:AbortSignal.timeout(800)});return a.status>0&&a.status<600}catch{return!1}}import{mkdirSync as vt,readFileSync as wt,renameSync as yt,writeFileSync as kt}from"fs";import{dirname as $t,isAbsolute as _t,resolve as St}from"path";import{createHash as Ct,randomBytes as At}from"crypto";var Rn=".agentx/app-pins.json",On=12,ba=40,va=2e3,Tt=/^pin_[a-z0-9]{6,32}$/;function It(e,a){return _t(a)?a:St(e,a)}function te(e){let a=typeof e=="string"?e.trim().replace(/\s+/g," "):"";return a?/[\p{Cc}\p{Cf}]/u.test(a)?{ok:!1,error:"Use only letters, numbers, spaces and punctuation in the name."}:[...a].length>ba?{ok:!1,error:`Keep the name under ${ba} characters.`}:{ok:!0,value:a}:{ok:!1,error:"Give the button a name."}}function $e(e){let a=typeof e=="string"?e.trim():"";if(!a)return{ok:!1,error:"Give the page's address."};if(a.length>va)return{ok:!1,error:`Keep the address under ${va} characters.`};let t;try{t=new URL(a)}catch{return{ok:!1,error:"That is not a web address. It should start with https://"}}return t.protocol!=="https:"||!t.hostname?{ok:!1,error:"Only https:// pages can be pinned."}:t.username||t.password?{ok:!1,error:"Leave the user name and password out of the address."}:{ok:!0,value:t.href}}function zt(e){return`cfg_${Ct("sha256").update(e).digest("hex").slice(0,12)}`}function Pt(e){let a=[];for(let t of e){let r=te(t.label),n=$e(t.url);!r.ok||!n.ok||a.some(o=>o.url===n.value||o.label.toLowerCase()===r.value.toLowerCase())||a.push({id:zt(n.value),label:r.value,url:n.value,source:"config"})}return a}var wa="This button is set in agentx.json (app.pins.pages). Change or remove it there.";function Et(e){let a=te(e.label);if(!a.ok)return a;let t=$e(e.url);return t.ok?{ok:!0,value:{label:a.value,url:t.value}}:t}var ke=class{constructor(a,t=Date.now,r=[]){this.path=a;this.now=t;this.fixed=r}list(){return[...this.fixed,...this.load().pins.filter(a=>!this.shadowed(a))]}shadowed(a){return this.fixed.some(t=>t.url===a.url||t.label.toLowerCase()===a.label.toLowerCase())}isFixed(a){return this.fixed.some(t=>t.id===a)}load(){let a;try{a=wt(this.path,"utf-8")}catch(o){return{pins:[],damaged:o?.code!=="ENOENT"}}let t;try{t=JSON.parse(a)}catch{return{pins:[],damaged:!0}}let r=Array.isArray(t?.pins)?t.pins:[],n=r.filter(o=>{let i=o;return!!i&&typeof i.id=="string"&&Tt.test(i.id)&&te(i.label).ok&&$e(i.url).ok});return{pins:n,damaged:!Array.isArray(t?.pins)||n.length!==r.length}}locked(a){try{return De(this.path,a,{what:"The pinned pages file"})}catch(t){if(t instanceof Oe)return{ok:!1,status:409,error:t.message};throw t}}editable(){let{pins:a,damaged:t}=this.load();return t?{ok:!1,status:409,error:`The pinned pages file (${this.path}) can't be read. Fix or remove it on the computer, then try again.`}:{ok:!0,pins:a}}write(a){vt($t(this.path),{recursive:!0});let t=`${this.path}.${process.pid}.tmp`;kt(t,JSON.stringify({pins:a},null,2)+`
2221
- `,{mode:384}),yt(t,this.path)}add(a,t){return this.locked(()=>this.addUnlocked(a,t))}addUnlocked(a,t){let r=this.editable();if(!r.ok)return r;let n=r.pins;if(n.filter(i=>!this.shadowed(i)).length+this.fixed.length>=t)return{ok:!1,status:409,error:`You already have ${t} pinned pages, the most allowed (app.pins.max). Remove one first.`};if([...this.fixed,...n].some(i=>i.label.toLowerCase()===a.label.toLowerCase()))return{ok:!1,status:409,error:`You already have a button called ${a.label}.`};if(this.fixed.some(i=>i.url===a.url))return{ok:!1,status:409,error:"This page is already a button, set in agentx.json (app.pins.pages)."};let o={id:`pin_${At(6).toString("hex")}`,...a,createdAt:new Date(this.now()).toISOString()};return n.push(o),this.write(n),{ok:!0,pin:o}}rename(a,t){return this.locked(()=>this.renameUnlocked(a,t))}renameUnlocked(a,t){if(this.isFixed(a))return{ok:!1,status:409,error:wa};let r=this.editable();if(!r.ok)return r;let n=r.pins,o=n.find(i=>i.id===a);return o?[...this.fixed,...n].some(i=>i.id!==a&&i.label.toLowerCase()===t.toLowerCase())?{ok:!1,status:409,error:`You already have a button called ${t}.`}:(o.label=t,this.write(n),{ok:!0,pin:o}):{ok:!1,status:404,error:"No such pinned page."}}remove(a){return this.locked(()=>this.removeUnlocked(a))}removeUnlocked(a){if(this.isFixed(a))return{ok:!1,status:409,error:wa};let t=this.editable();if(!t.ok)return t;let r=t.pins.filter(n=>n.id!==a);return r.length===t.pins.length?{ok:!1,status:404,error:"No such pinned page."}:(this.write(r),{ok:!0})}};function Dn(e,a){let t=e.app.pins;return{store:new ke(It(a,t.file),Date.now,Pt(t.pages)),max:t.max}}async function Mn(e,a,t,r,n){if(t!=="/api/app/pins"&&!t.startsWith("/api/app/pins/"))return!1;let o=t.slice(13);if(r==="GET"&&o==="")return P(a,200,{pins:n.store.list(),max:n.max});if(r!=="POST")return P(a,404,{error:"not found"});let i;try{i=await Q(e,4096)}catch(d){return P(a,400,{error:d.message})}let s=typeof i.id=="string"?i.id:"";if(o==="/add"){let d=Et(i);if(!d.ok)return P(a,400,{error:d.error});let l=n.store.add(d.value,n.max);return l.ok?P(a,200,{ok:!0,pin:l.pin}):P(a,l.status,{error:l.error})}if(o==="/rename"){let d=te(i.label);if(!d.ok)return P(a,400,{error:d.error});let l=n.store.rename(s,d.value);return l.ok?P(a,200,{ok:!0,pin:l.pin}):P(a,l.status,{error:l.error})}if(o==="/remove"){let d=n.store.remove(s);return d.ok?P(a,200,{ok:!0}):P(a,d.status,{error:d.error})}return P(a,404,{error:"not found"})}function P(e,a,t){return e.writeHead(a,{"Content-Type":"application/json","Cache-Control":"no-store"}),e.end(JSON.stringify(t)),!0}import{existsSync as ya,readFileSync as ka}from"fs";xe();function Rt(e){let a=K(e),t={};if(ya(a))try{t=q(JSON.parse(ka(a,"utf-8")))}catch{t={}}let r=pe.safeParse(t?.approvals);return r.success?r.data:pe.parse(void 0)}function Bn(e){let a=K(e),t={};if(ya(a))try{t=q(JSON.parse(ka(a,"utf-8")))}catch{t={}}return qe({desk:t?.notifications?.desk,popupEnabled:!!Rt(e).popup?.enabled})}function Un(e){let a=e.indexOf(":");return a<=0||a===e.length-1?null:{channel:e.slice(0,a).trim(),chatId:e.slice(a+1).trim()}}async function Fn(e,a={}){return X(t=>{let r=t.approvals??={};if(e.defaultExpiryDays!==void 0&&(r.defaultExpiryDays=e.defaultExpiryDays),e.maxExpiryDays!==void 0&&(r.maxExpiryDays=e.maxExpiryDays),e.laterHours!==void 0&&(r.laterHours=e.laterHours),e.notifyAgent!==void 0&&(r.notifyAgent=e.notifyAgent),e.forwardTo===null)delete r.forwardTo;else if(e.forwardTo!==void 0){let l=Array.isArray(t.mesh?.peers)?t.mesh.peers:[];if(!l.some(c=>c.name===e.forwardTo))throw new Error(`"${e.forwardTo}" is not in mesh.peers${l.length?` (known: ${l.map(c=>c.name).join(", ")})`:""}; pair the machines first`);r.forwardTo=e.forwardTo}let n=r.digest??={};e.digestEnabled!==void 0&&(n.enabled=e.digestEnabled),e.digestTime!==void 0&&(n.time=e.digestTime),e.digestTimezone===null?delete n.timezone:e.digestTimezone!==void 0&&(n.timezone=e.digestTimezone),e.destination===null?delete n.destination:e.destination!==void 0&&(n.destination=e.destination);let o=r.popup??={};e.popupEnabled!==void 0&&(o.enabled=e.popupEnabled),e.popupSpeak!==void 0&&(o.speak=e.popupSpeak),e.popupVoice===null?delete o.voice:e.popupVoice!==void 0&&(o.voice=e.popupVoice),e.popupSound!==void 0&&(o.sound=e.popupSound),e.popupTimeoutSeconds!==void 0&&(o.timeoutSeconds=e.popupTimeoutSeconds),e.popupStyle!==void 0&&(o.style=e.popupStyle),e.popupTheme!==void 0&&(o.theme=e.popupTheme);let i=r.checkin??={};if(e.checkinEnabled!==void 0&&(i.enabled=e.checkinEnabled),e.checkinTimes!==void 0&&(i.times=e.checkinTimes),e.checkinDailyAt!==void 0&&(i.dailyAt=e.checkinDailyAt),e.checkinLists!==void 0&&(i.lists=e.checkinLists),e.checkinAgent===null?delete i.agent:e.checkinAgent!==void 0&&(i.agent=e.checkinAgent),e.deskPhone!==void 0||e.deskComputer!==void 0){let l=(t.notifications??={}).desk??={};e.deskPhone!==void 0&&(l.phone=e.deskPhone),e.deskComputer!==void 0&&(l.computer=e.deskComputer)}let s=r.defaultExpiryDays??3,d=r.maxExpiryDays??30;if(s>d)throw new Error(`defaultExpiryDays (${s}) can't be more than maxExpiryDays (${d})`)},{configPath:a.configPath,reload:a.reload})}import{createServer as Nt}from"http";var re=class{peers;cache=new Map;ttl=3e4;constructor(a){this.peers=a.map(t=>({...t,url:t.url.replace(/\/$/,"")}))}async getRemoteAgents(){let a=[];return await Promise.all(this.peers.map(async t=>{try{let r=await this.fetchJson(`${t.url}/wiki/agents`);t.nodeId=r.nodeId;for(let n of r.agents||[])(n.totalEntries>0||n.totalArticles>0)&&a.push({...n,nodeId:r.nodeId,peerUrl:t.url})}catch{}})),a}async getRemoteArticles(a,t){try{return(await this.fetchJson(`${a}/wiki/articles?agent=${encodeURIComponent(t)}`)).articles||[]}catch{return[]}}async getRemoteArticle(a,t,r){try{let n=await this.fetchJson(`${a}/wiki/article?agent=${encodeURIComponent(t)}&path=${encodeURIComponent(r)}`);return{meta:{title:n.title,tags:n.tags||[],owner:n.owner,access:"public",created:n.created,lastUpdated:n.lastUpdated,sources:n.sources||[]},content:n.content,path:n.path}}catch{return null}}async fetchJson(a){let t=this.cache.get(a);if(t&&Date.now()-t.ts<this.ttl)return t.data;let r=this.peers.find(i=>a.startsWith(`${i.url}/`))?.token,n=await fetch(a,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(5e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);let o=await n.json();return this.cache.set(a,{data:o,ts:Date.now()}),o}};var $a=864e5;function _e(e){let a=new Map;for(let t of e.entities.values()){let r=a.get(t.type)??[];r.push(t),a.set(t.type,r)}return a}function Se(e,a){if(a.type==="event")return a.date||a.updated;let t=Ze(e,a,new Set(["event"]))[0],r=a.updated||a.date;return t&&t.date>r?t.date:r}function _a(e,a,t=Date.now()){let r=[],n=new Date(t+14*$a).toISOString().slice(0,10),o=new Date(t).toISOString().slice(0,10);for(let s of a){let d=s.statements.find(c=>c.property==="due"&&/^\d{4}-\d{2}-\d{2}/.test(c.value)),l=s.statements.some(c=>c.property==="fulfilled_by")||s.statements.some(c=>c.property==="status"&&/^(fulfilled|done|paid|filed)$/i.test(c.value));s.statements.some(c=>c.property==="status"&&/^late$/i.test(c.value))?r.push({e:s,chip:"late",why:"marked late"}):d&&!l&&d.value<o?r.push({e:s,chip:"late",why:`was due ${d.value}`}):d&&!l&&d.value<=n?r.push({e:s,chip:"due",why:`due ${d.value}`}):s.statements.some(c=>c.status==="proposed")?r.push({e:s,chip:"proposed",why:"statements wait for confirmation"}):s.type==="event"&&s.importanceProposed&&s.importanceProposed!==s.importance?r.push({e:s,chip:"proposed",why:`proposed as ${s.importanceProposed}; the owner decides`}):s.type==="event"&&s.importance==="major"&&s.date&&t-Date.parse(s.date)<=30*$a&&r.push({e:s,chip:"major",why:`major event ${s.date}`})}let i={late:0,due:1,major:2,proposed:3};return r.sort((s,d)=>i[s.chip]-i[d.chip])}function ne(e,a,t="",r){return`<div class="ox-row"><span class="ox-ic">${ea(e.ontology,a.type)}</span><div class="t"><a href="${he(a.id)}">${k(a.title)}</a><div class="ox-sub">${k(r??`${fe(e.ontology,a.type).toLowerCase()} \xB7 ${Se(e,a)}`)}</div></div><div class="r">${t}</div></div>`}function Sa(e,a){let t=a.slice(0,6).map(r=>ne(e,r.e,`<span class="ox-st ${r.chip}">${r.chip}</span>`,r.why)).join("");return`<section class="ox-card"><div class="ox-card-h"><h2>Needs attention</h2><span class="note">${a.length}</span></div>${t||'<div class="ox-empty">Nothing waits on a person.</div>'}</section>`}function Ot(e){return e.length?`<div class="ox-err"><b>ontology.yaml has ${e.length} problem${e.length===1?"":"s"}</b> \u2014 the defaults are used where they apply. <a href="/ontology">See them</a></div>`:""}function Ca(e,a){let t=_e(e),r=`<div class="ox-bar">${H([])}</div>`;r+=`<div class="ox-head"><div class="ox-avatar">${D("home")}</div><div><h1>Wiki</h1><p>${e.entities.size} things, merged from every agent's pages and typed by the <a href="/ontology">ontology</a>. <a href="/agents">Agent wikis</a> \xB7 <a href="/entries">raw entries</a></p></div></div>`,r+=Ot(a),r+='<div class="ox-grid3">';for(let o of e.ontology.pillars){let i=e.ontology.types.filter(l=>l.pillar===o.id),s=i.reduce((l,c)=>l+(t.get(c.id)?.length??0),0),d=i.filter(l=>t.get(l.id)?.length).map(l=>`${l.plural??l.label} ${t.get(l.id).length}`).join(" \xB7 ");r+=`<a class="ox-card" href="/p/${encodeURIComponent(o.id)}" style="color:inherit"><div class="ox-card-h"><span class="ox-ic">${D(o.icon)}</span><h2>${k(o.label)}</h2><span class="zin">${s}</span></div><div class="ox-sub" style="white-space:normal">${k(o.description??"")}</div><div class="ox-sub" style="margin-top:6px;white-space:normal">${k(d||"nothing yet")}</div></a>`}r+='</div><div class="ox-grid2">';let n=(t.get("event")??[]).filter(o=>o.importance!=="minor").sort((o,i)=>i.date.localeCompare(o.date)).slice(0,8);return r+='<section class="ox-card"><div class="ox-card-h"><h2>Recent events</h2><span class="note">major and normal</span><a class="zin" href="/p/events">all (Z1) \u2192</a></div>'+(n.map(o=>`<div class="ox-ev"><span class="d">${k(o.date)}</span><span class="ox-st ${o.importance}">${o.importance}</span><a href="${he(o.id)}">${k(o.title)}</a></div>`).join("")||'<div class="ox-empty">No events yet.</div>')+"</section>",r+=Sa(e,_a(e,[...e.entities.values()])),r+="</div>",N("Wiki",L(e,{home:!0}),r)}function Aa(e,a,t){let r=e.ontology.pillars.find(c=>c.id===a);if(!r)return null;let n=_e(e),o=e.ontology.types.filter(c=>c.pillar===r.id),i=o.find(c=>c.id===t)??o.find(c=>n.get(c.id)?.length)??o[0],s=`<div class="ox-bar">${H([{label:r.label}])}${be(1)}</div>`;s+=`<div class="ox-head"><div class="ox-avatar">${D(r.icon)}</div><div><h1>${k(r.label)}</h1><p>${k(r.description??"")}</p></div></div>`,s+=`<nav class="ox-tabs">${o.map(c=>`<a class="${c.id===i?.id?"on":""}" href="/p/${encodeURIComponent(r.id)}?kind=${encodeURIComponent(c.id)}">${k(c.plural??c.label)}<small>${n.get(c.id)?.length??0}</small></a>`).join("")}</nav>`;let d=i?(n.get(i.id)??[]).map(c=>({e:c,at:Se(e,c)})).sort((c,m)=>m.at.localeCompare(c.at)):[];s+='<div class="ox-grid2">',s+=`<section class="ox-card"><div class="ox-card-h"><h2>${k(i?.plural??i?.label??"")}</h2><span class="note">${d.length} \xB7 most active first</span>`+(i?`<a class="zin" href="/p/${encodeURIComponent(r.id)}/${encodeURIComponent(i.id)}">open list (Z3) \u2192</a>`:"")+"</div>"+(d.slice(0,5).map(({e:c,at:m})=>ne(e,c,c.type==="event"?`<span class="ox-st ${c.importance}">${c.importance}</span>`:"",`${aa(c,90)||fe(e.ontology,c.type).toLowerCase()} \xB7 ${m}`)).join("")||`<div class="ox-empty">No ${k((i?.plural??"pages").toLowerCase())} yet.</div>`)+"</section>";let l=o.flatMap(c=>n.get(c.id)??[]);return s+=Sa(e,_a(e,l)),s+="</div>",N(r.label,L(e,{pillar:r.id}),s)}function Ta(e,a,t,r,n){let o=n&&Me.includes(n)?n:null,i=e.ontology.pillars.find(x=>x.id===a),s=e.ontology.types.find(x=>x.id===t&&x.pillar===a);if(!i||!s)return null;let d=[...e.entities.values()].filter(x=>x.type===s.id);o&&(d=d.filter(x=>x.importance===o));let l=d.map(x=>({e:x,at:Se(e,x)})).sort((x,f)=>f.at.localeCompare(x.at)),c=50,m=Math.max(1,Math.ceil(l.length/c)),g=`/p/${encodeURIComponent(i.id)}/${encodeURIComponent(s.id)}`,u=`<div class="ox-bar">${H([{label:i.label,href:`/p/${encodeURIComponent(i.id)}`},{label:s.plural??s.label}])}${be(3)}</div>`;if(u+=`<div class="ox-head"><div class="ox-avatar">${D(s.icon)}</div><div><h1>${k(s.plural??s.label)}</h1><p>${l.length} page${l.length===1?"":"s"}${o?` \xB7 ${k(o)} only`:""}</p></div></div>`,s.id==="event"&&(u+=`<nav class="ox-tabs">${["","major","normal","minor"].map(x=>`<a class="${(o??"")===x?"on":""}" href="${g}${x?`?importance=${x}`:""}">${x||"all"}</a>`).join("")}</nav>`),u+='<section class="ox-card" style="margin-top:16px">'+(l.slice((r-1)*c,r*c).map(({e:x,at:f})=>ne(e,x,x.type==="event"?`<span class="ox-st ${x.importance}">${x.importance}</span>`:"",`${f} \xB7 ${x.pages.map(A=>A.agentId).filter((A,y,v)=>v.indexOf(A)===y).join(", ")}`)).join("")||'<div class="ox-empty">None.</div>')+"</section>",m>1){let x=o?`importance=${o}&`:"";u+=`<div class="ox-pager">${r>1?`<a href="${g}?${x}page=${r-1}">\u2190 previous</a>`:""}<span>page ${r} of ${m}</span>${r<m?`<a href="${g}?${x}page=${r+1}">next \u2192</a>`:""}</div>`}return N(s.plural??s.label,L(e,{pillar:i.id}),u)}function Ia(e,a){let t=a.trim().toLowerCase(),r=[];if(t)for(let o of e.entities.values()){let i=o.title.toLowerCase(),s=i===t?100:i.startsWith(t)?60:i.includes(t)?40:0;!s&&o.pages.some(d=>d.article.content.toLowerCase().includes(t))&&(s=10),s&&r.push({e:o,s})}r.sort((o,i)=>i.s-o.s||i.e.updated.localeCompare(o.e.updated));let n=`<div class="ox-bar">${H([{label:"Search"}])}</div>`;return n+=`<div class="ox-head"><div class="ox-avatar">${D("search")}</div><div><h1>${t?`\u201C${k(a)}\u201D`:"Search"}</h1><p>${r.length} match${r.length===1?"":"es"}</p></div></div>`,n+=`<section class="ox-card">${r.slice(0,60).map(({e:o})=>ne(e,o)).join("")||'<div class="ox-empty">No page matches.</div>'}</section>`,N(`Search: ${a}`,L(e,{}),n,"",a)}function za(e,a,t){let r=e.ontology,n=_e(e),o=`<div class="ox-bar">${H([{label:"Ontology"}])}</div>`;o+=`<div class="ox-head"><div class="ox-avatar">${D("steps")}</div><div><h1>Ontology</h1><p>${t?`Read from ${k(t)}`:"Built-in defaults. Run <code>agentx wiki ontology init</code> to write an ontology.yaml you can edit."}</p></div></div>`,a.length&&(o+=`<div class="ox-err"><b>Problems</b><ul>${a.map(i=>`<li>${k(i)}</li>`).join("")}</ul></div>`),o+=`<section class="ox-card"><div class="ox-card-h"><h2>Types</h2><span class="note">${r.types.length}</span></div>`;for(let i of r.types){let s=r.pillars.find(d=>d.id===i.pillar);o+=`<div class="ox-row"><span class="ox-ic">${D(i.icon)}</span><div class="t"><span class="l">${k(i.label)} <span class="ox-sub">${k(i.id)}</span></span><div class="ox-sub">${k(s?.label??i.pillar)} \xB7 lens: ${k((i.lens??[]).map(d=>d.title??d.panel).join(" \u2192 "))}</div></div><div class="r"><span class="ox-chip">${n.get(i.id)?.length??0}</span></div></div>`}o+=`</section><section class="ox-card" style="margin-top:16px"><div class="ox-card-h"><h2>Relations</h2><span class="note">${r.properties.length}</span></div>`;for(let i of r.properties)o+=`<div class="ox-kv"><span class="k">${k(i.id)}</span><span>${k(i.label)}${i.inverse?` \xB7 inverse: ${k(i.inverse)}`:""}${i.wikidata?` <span class="ox-sub">${k(i.wikidata)}</span>`:""}</span></div>`;return o+=`</section><section class="ox-card" style="margin-top:16px"><div class="ox-card-h"><h2>Event importance</h2></div><div class="ox-kv"><span class="k">default</span><span>${k(r.importance.default)}</span></div><div class="ox-kv"><span class="k">major set by</span><span>${k(r.importance.major_set_by)}</span></div><div class="ox-kv"><span class="k">roll-up</span><span>${r.importance.rollup.min} minor events in ${r.importance.rollup.days} days</span></div></section>`,N("Ontology",L(e,{}),o)}var oe=class{constructor(a,t){this.hub=a;this.wikiDir=t}cache=new Qe;pageAt(a){if(!a.startsWith("/e/"))return null;let{ontology:t}=me(this.wikiDir),n=this.cache.get(this.hub,t).entities.get(a.split("/").filter(Boolean)[1]??"")?.pages[0];return n?{agentId:n.agentId,path:n.article.path,title:n.article.meta.title}:null}handle(a,t){if(!(a==="/"||a===""||a.startsWith("/p/")||a.startsWith("/e/")||a==="/find"||a==="/ontology"))return null;let{ontology:r,errors:n,file:o}=me(this.wikiDir),i=Ve(this.wikiDir,this.hub.listAgents([]),r.agent_names),s=this.cache.get(this.hub,r,i),d=Math.max(1,Number(t.get("page"))||1);if(a==="/"||a==="")return Ca(s,n);if(a==="/find")return Ia(s,t.get("q")??"");if(a==="/ontology")return za(s,n,o);let l=a.split("/").filter(Boolean);if(l[0]==="p")return l.length===2?Aa(s,l[1],t.get("kind")):l.length===3?Ta(s,l[1],l[2],d,t.get("importance")):null;let c=s.entities.get(l[1]??"");if(!c)return null;let m={g:s,readEntries:g=>this.hub.getSharedStore().readEntries(g),versions:(g,u)=>this.hub.getAgentWiki(g).getVersions(u)};return l.length===2?ta(m,c):l.length===3?ra(m,c,l[2],d):l.length===4&&l[2]==="s"?na(m,c,Number(l[3])):null}};var Dt=`
2220
+ `)}}function _n(e,a){let t=ua(),r=t.nodeName||gt().replace(/\.local$/,""),n=ca(t,r);a.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),a.end(n)}async function Sn(e,a){let t="";await new Promise(n=>{e.on("data",o=>{t+=o}),e.on("end",()=>n())});let r;try{r=JSON.parse(t)}catch{a.writeHead(400,{"Content-Type":"application/json"}),a.end(JSON.stringify({error:"Invalid JSON"}));return}try{let n=mt(r);a.writeHead(200,{"Content-Type":"application/json"}),a.end(JSON.stringify(n))}catch(n){a.writeHead(400,{"Content-Type":"application/json"}),a.end(JSON.stringify({error:n.message||"wizard failed"}))}}async function Cn(e,a){a.setHeader("Content-Type","application/json");let t;try{t=Re().node?.bind||"127.0.0.1:18800"}catch(i){a.writeHead(400),a.end(JSON.stringify({ok:!1,error:`Config validation failed: ${i.message}`}));return}let r=`http://${t.replace(/^0\.0\.0\.0/,"127.0.0.1")}`;if(await pa(r)){a.writeHead(200),a.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!0}));return}let n=process.argv[1]||M(pt(xt(import.meta.url)),"cli.js");try{ut(process.execPath,[n,"daemon","start"],{detached:!0,stdio:"ignore",cwd:process.cwd()}).unref()}catch(i){a.writeHead(500),a.end(JSON.stringify({ok:!1,error:`Failed to spawn daemon: ${i.message}`,manualUrl:r}));return}let o=Date.now()+12e3;for(;Date.now()<o;)if(await new Promise(i=>setTimeout(i,400)),await pa(r)){a.writeHead(200),a.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!1}));return}a.writeHead(504),a.end(JSON.stringify({ok:!1,error:"Daemon spawn succeeded but never bound the port within 12s \u2014 check `agentx daemon status` and the dotfile log for errors.",manualUrl:r}))}async function pa(e){try{let a=await fetch(e,{method:"GET",signal:AbortSignal.timeout(800)});return a.status>0&&a.status<600}catch{return!1}}import{mkdirSync as vt,readFileSync as wt,renameSync as yt,writeFileSync as kt}from"fs";import{dirname as $t,isAbsolute as _t,resolve as St}from"path";import{createHash as Ct,randomBytes as At}from"crypto";var Rn=".agentx/app-pins.json",On=12,ba=40,va=2e3,Tt=/^pin_[a-z0-9]{6,32}$/;function It(e,a){return _t(a)?a:St(e,a)}function te(e){let a=typeof e=="string"?e.trim().replace(/\s+/g," "):"";return a?/[\p{Cc}\p{Cf}]/u.test(a)?{ok:!1,error:"Use only letters, numbers, spaces and punctuation in the name."}:[...a].length>ba?{ok:!1,error:`Keep the name under ${ba} characters.`}:{ok:!0,value:a}:{ok:!1,error:"Give the button a name."}}function $e(e){let a=typeof e=="string"?e.trim():"";if(!a)return{ok:!1,error:"Give the page's address."};if(a.length>va)return{ok:!1,error:`Keep the address under ${va} characters.`};let t;try{t=new URL(a)}catch{return{ok:!1,error:"That is not a web address. It should start with https://"}}return t.protocol!=="https:"||!t.hostname?{ok:!1,error:"Only https:// pages can be pinned."}:t.username||t.password?{ok:!1,error:"Leave the user name and password out of the address."}:{ok:!0,value:t.href}}function zt(e){return`cfg_${Ct("sha256").update(e).digest("hex").slice(0,12)}`}function Pt(e){let a=[];for(let t of e){let r=te(t.label),n=$e(t.url);!r.ok||!n.ok||a.some(o=>o.url===n.value||o.label.toLowerCase()===r.value.toLowerCase())||a.push({id:zt(n.value),label:r.value,url:n.value,source:"config"})}return a}var wa="This button is set in agentx.json (app.pins.pages). Change or remove it there.";function Et(e){let a=te(e.label);if(!a.ok)return a;let t=$e(e.url);return t.ok?{ok:!0,value:{label:a.value,url:t.value}}:t}var ke=class{constructor(a,t=Date.now,r=[]){this.path=a;this.now=t;this.fixed=r}list(){return[...this.fixed,...this.load().pins.filter(a=>!this.shadowed(a))]}shadowed(a){return this.fixed.some(t=>t.url===a.url||t.label.toLowerCase()===a.label.toLowerCase())}isFixed(a){return this.fixed.some(t=>t.id===a)}load(){let a;try{a=wt(this.path,"utf-8")}catch(o){return{pins:[],damaged:o?.code!=="ENOENT"}}let t;try{t=JSON.parse(a)}catch{return{pins:[],damaged:!0}}let r=Array.isArray(t?.pins)?t.pins:[],n=r.filter(o=>{let i=o;return!!i&&typeof i.id=="string"&&Tt.test(i.id)&&te(i.label).ok&&$e(i.url).ok});return{pins:n,damaged:!Array.isArray(t?.pins)||n.length!==r.length}}locked(a){try{return Me(this.path,a,{what:"The pinned pages file"})}catch(t){if(t instanceof De)return{ok:!1,status:409,error:t.message};throw t}}editable(){let{pins:a,damaged:t}=this.load();return t?{ok:!1,status:409,error:`The pinned pages file (${this.path}) can't be read. Fix or remove it on the computer, then try again.`}:{ok:!0,pins:a}}write(a){vt($t(this.path),{recursive:!0});let t=`${this.path}.${process.pid}.tmp`;kt(t,JSON.stringify({pins:a},null,2)+`
2221
+ `,{mode:384}),yt(t,this.path)}add(a,t){return this.locked(()=>this.addUnlocked(a,t))}addUnlocked(a,t){let r=this.editable();if(!r.ok)return r;let n=r.pins;if(n.filter(i=>!this.shadowed(i)).length+this.fixed.length>=t)return{ok:!1,status:409,error:`You already have ${t} pinned pages, the most allowed (app.pins.max). Remove one first.`};if([...this.fixed,...n].some(i=>i.label.toLowerCase()===a.label.toLowerCase()))return{ok:!1,status:409,error:`You already have a button called ${a.label}.`};if(this.fixed.some(i=>i.url===a.url))return{ok:!1,status:409,error:"This page is already a button, set in agentx.json (app.pins.pages)."};let o={id:`pin_${At(6).toString("hex")}`,...a,createdAt:new Date(this.now()).toISOString()};return n.push(o),this.write(n),{ok:!0,pin:o}}rename(a,t){return this.locked(()=>this.renameUnlocked(a,t))}renameUnlocked(a,t){if(this.isFixed(a))return{ok:!1,status:409,error:wa};let r=this.editable();if(!r.ok)return r;let n=r.pins,o=n.find(i=>i.id===a);return o?[...this.fixed,...n].some(i=>i.id!==a&&i.label.toLowerCase()===t.toLowerCase())?{ok:!1,status:409,error:`You already have a button called ${t}.`}:(o.label=t,this.write(n),{ok:!0,pin:o}):{ok:!1,status:404,error:"No such pinned page."}}remove(a){return this.locked(()=>this.removeUnlocked(a))}removeUnlocked(a){if(this.isFixed(a))return{ok:!1,status:409,error:wa};let t=this.editable();if(!t.ok)return t;let r=t.pins.filter(n=>n.id!==a);return r.length===t.pins.length?{ok:!1,status:404,error:"No such pinned page."}:(this.write(r),{ok:!0})}};function Dn(e,a){let t=e.app.pins;return{store:new ke(It(a,t.file),Date.now,Pt(t.pages)),max:t.max}}async function Mn(e,a,t,r,n){if(t!=="/api/app/pins"&&!t.startsWith("/api/app/pins/"))return!1;let o=t.slice(13);if(r==="GET"&&o==="")return P(a,200,{pins:n.store.list(),max:n.max});if(r!=="POST")return P(a,404,{error:"not found"});let i;try{i=await Q(e,4096)}catch(d){return P(a,400,{error:d.message})}let s=typeof i.id=="string"?i.id:"";if(o==="/add"){let d=Et(i);if(!d.ok)return P(a,400,{error:d.error});let l=n.store.add(d.value,n.max);return l.ok?P(a,200,{ok:!0,pin:l.pin}):P(a,l.status,{error:l.error})}if(o==="/rename"){let d=te(i.label);if(!d.ok)return P(a,400,{error:d.error});let l=n.store.rename(s,d.value);return l.ok?P(a,200,{ok:!0,pin:l.pin}):P(a,l.status,{error:l.error})}if(o==="/remove"){let d=n.store.remove(s);return d.ok?P(a,200,{ok:!0}):P(a,d.status,{error:d.error})}return P(a,404,{error:"not found"})}function P(e,a,t){return e.writeHead(a,{"Content-Type":"application/json","Cache-Control":"no-store"}),e.end(JSON.stringify(t)),!0}import{existsSync as ya,readFileSync as ka}from"fs";xe();function Rt(e){let a=K(e),t={};if(ya(a))try{t=q(JSON.parse(ka(a,"utf-8")))}catch{t={}}let r=pe.safeParse(t?.approvals);return r.success?r.data:pe.parse(void 0)}function Bn(e){let a=K(e),t={};if(ya(a))try{t=q(JSON.parse(ka(a,"utf-8")))}catch{t={}}return qe({desk:t?.notifications?.desk,popupEnabled:!!Rt(e).popup?.enabled})}function Un(e){let a=e.indexOf(":");return a<=0||a===e.length-1?null:{channel:e.slice(0,a).trim(),chatId:e.slice(a+1).trim()}}async function Fn(e,a={}){return X(t=>{let r=t.approvals??={};if(e.defaultExpiryDays!==void 0&&(r.defaultExpiryDays=e.defaultExpiryDays),e.maxExpiryDays!==void 0&&(r.maxExpiryDays=e.maxExpiryDays),e.laterHours!==void 0&&(r.laterHours=e.laterHours),e.notifyAgent!==void 0&&(r.notifyAgent=e.notifyAgent),e.forwardTo===null)delete r.forwardTo;else if(e.forwardTo!==void 0){let l=Array.isArray(t.mesh?.peers)?t.mesh.peers:[];if(!l.some(c=>c.name===e.forwardTo))throw new Error(`"${e.forwardTo}" is not in mesh.peers${l.length?` (known: ${l.map(c=>c.name).join(", ")})`:""}; pair the machines first`);r.forwardTo=e.forwardTo}let n=r.digest??={};e.digestEnabled!==void 0&&(n.enabled=e.digestEnabled),e.digestTime!==void 0&&(n.time=e.digestTime),e.digestTimezone===null?delete n.timezone:e.digestTimezone!==void 0&&(n.timezone=e.digestTimezone),e.destination===null?delete n.destination:e.destination!==void 0&&(n.destination=e.destination);let o=r.popup??={};e.popupEnabled!==void 0&&(o.enabled=e.popupEnabled),e.popupSpeak!==void 0&&(o.speak=e.popupSpeak),e.popupVoice===null?delete o.voice:e.popupVoice!==void 0&&(o.voice=e.popupVoice),e.popupSound!==void 0&&(o.sound=e.popupSound),e.popupTimeoutSeconds!==void 0&&(o.timeoutSeconds=e.popupTimeoutSeconds),e.popupStyle!==void 0&&(o.style=e.popupStyle),e.popupTheme!==void 0&&(o.theme=e.popupTheme);let i=r.checkin??={};if(e.checkinEnabled!==void 0&&(i.enabled=e.checkinEnabled),e.checkinTimes!==void 0&&(i.times=e.checkinTimes),e.checkinDailyAt!==void 0&&(i.dailyAt=e.checkinDailyAt),e.checkinLists!==void 0&&(i.lists=e.checkinLists),e.checkinAgent===null?delete i.agent:e.checkinAgent!==void 0&&(i.agent=e.checkinAgent),e.deskPhone!==void 0||e.deskComputer!==void 0){let l=(t.notifications??={}).desk??={};e.deskPhone!==void 0&&(l.phone=e.deskPhone),e.deskComputer!==void 0&&(l.computer=e.deskComputer)}let s=r.defaultExpiryDays??3,d=r.maxExpiryDays??30;if(s>d)throw new Error(`defaultExpiryDays (${s}) can't be more than maxExpiryDays (${d})`)},{configPath:a.configPath,reload:a.reload})}import{createServer as Nt}from"http";var re=class{peers;cache=new Map;ttl=3e4;constructor(a){this.peers=a.map(t=>({...t,url:t.url.replace(/\/$/,"")}))}async getRemoteAgents(){let a=[];return await Promise.all(this.peers.map(async t=>{try{let r=await this.fetchJson(`${t.url}/wiki/agents`);t.nodeId=r.nodeId;for(let n of r.agents||[])(n.totalEntries>0||n.totalArticles>0)&&a.push({...n,nodeId:r.nodeId,peerUrl:t.url})}catch{}})),a}async getRemoteArticles(a,t){try{return(await this.fetchJson(`${a}/wiki/articles?agent=${encodeURIComponent(t)}`)).articles||[]}catch{return[]}}async getRemoteArticle(a,t,r){try{let n=await this.fetchJson(`${a}/wiki/article?agent=${encodeURIComponent(t)}&path=${encodeURIComponent(r)}`);return{meta:{title:n.title,tags:n.tags||[],owner:n.owner,access:"public",created:n.created,lastUpdated:n.lastUpdated,sources:n.sources||[]},content:n.content,path:n.path}}catch{return null}}async fetchJson(a){let t=this.cache.get(a);if(t&&Date.now()-t.ts<this.ttl)return t.data;let r=this.peers.find(i=>a.startsWith(`${i.url}/`))?.token,n=await fetch(a,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(5e3)});if(!n.ok)throw new Error(`HTTP ${n.status}`);let o=await n.json();return this.cache.set(a,{data:o,ts:Date.now()}),o}};var $a=864e5;function _e(e){let a=new Map;for(let t of e.entities.values()){let r=a.get(t.type)??[];r.push(t),a.set(t.type,r)}return a}function Se(e,a){if(a.type==="event")return a.date||a.updated;let t=Ze(e,a,new Set(["event"]))[0],r=a.updated||a.date;return t&&t.date>r?t.date:r}function _a(e,a,t=Date.now()){let r=[],n=new Date(t+14*$a).toISOString().slice(0,10),o=new Date(t).toISOString().slice(0,10);for(let s of a){let d=s.statements.find(c=>c.property==="due"&&/^\d{4}-\d{2}-\d{2}/.test(c.value)),l=s.statements.some(c=>c.property==="fulfilled_by")||s.statements.some(c=>c.property==="status"&&/^(fulfilled|done|paid|filed)$/i.test(c.value));s.statements.some(c=>c.property==="status"&&/^late$/i.test(c.value))?r.push({e:s,chip:"late",why:"marked late"}):d&&!l&&d.value<o?r.push({e:s,chip:"late",why:`was due ${d.value}`}):d&&!l&&d.value<=n?r.push({e:s,chip:"due",why:`due ${d.value}`}):s.statements.some(c=>c.status==="proposed")?r.push({e:s,chip:"proposed",why:"statements wait for confirmation"}):s.type==="event"&&s.importanceProposed&&s.importanceProposed!==s.importance?r.push({e:s,chip:"proposed",why:`proposed as ${s.importanceProposed}; the owner decides`}):s.type==="event"&&s.importance==="major"&&s.date&&t-Date.parse(s.date)<=30*$a&&r.push({e:s,chip:"major",why:`major event ${s.date}`})}let i={late:0,due:1,major:2,proposed:3};return r.sort((s,d)=>i[s.chip]-i[d.chip])}function ne(e,a,t="",r){return`<div class="ox-row"><span class="ox-ic">${ea(e.ontology,a.type)}</span><div class="t"><a href="${he(a.id)}">${k(a.title)}</a><div class="ox-sub">${k(r??`${fe(e.ontology,a.type).toLowerCase()} \xB7 ${Se(e,a)}`)}</div></div><div class="r">${t}</div></div>`}function Sa(e,a){let t=a.slice(0,6).map(r=>ne(e,r.e,`<span class="ox-st ${r.chip}">${r.chip}</span>`,r.why)).join("");return`<section class="ox-card"><div class="ox-card-h"><h2>Needs attention</h2><span class="note">${a.length}</span></div>${t||'<div class="ox-empty">Nothing waits on a person.</div>'}</section>`}function Ot(e){return e.length?`<div class="ox-err"><b>ontology.yaml has ${e.length} problem${e.length===1?"":"s"}</b> \u2014 the defaults are used where they apply. <a href="/ontology">See them</a></div>`:""}function Ca(e,a){let t=_e(e),r=`<div class="ox-bar">${H([])}</div>`;r+=`<div class="ox-head"><div class="ox-avatar">${D("home")}</div><div><h1>Wiki</h1><p>${e.entities.size} things, merged from every agent's pages and typed by the <a href="/ontology">ontology</a>. <a href="/agents">Agent wikis</a> \xB7 <a href="/entries">raw entries</a></p></div></div>`,r+=Ot(a),r+='<div class="ox-grid3">';for(let o of e.ontology.pillars){let i=e.ontology.types.filter(l=>l.pillar===o.id),s=i.reduce((l,c)=>l+(t.get(c.id)?.length??0),0),d=i.filter(l=>t.get(l.id)?.length).map(l=>`${l.plural??l.label} ${t.get(l.id).length}`).join(" \xB7 ");r+=`<a class="ox-card" href="/p/${encodeURIComponent(o.id)}" style="color:inherit"><div class="ox-card-h"><span class="ox-ic">${D(o.icon)}</span><h2>${k(o.label)}</h2><span class="zin">${s}</span></div><div class="ox-sub" style="white-space:normal">${k(o.description??"")}</div><div class="ox-sub" style="margin-top:6px;white-space:normal">${k(d||"nothing yet")}</div></a>`}r+='</div><div class="ox-grid2">';let n=(t.get("event")??[]).filter(o=>o.importance!=="minor").sort((o,i)=>i.date.localeCompare(o.date)).slice(0,8);return r+='<section class="ox-card"><div class="ox-card-h"><h2>Recent events</h2><span class="note">major and normal</span><a class="zin" href="/p/events">all (Z1) \u2192</a></div>'+(n.map(o=>`<div class="ox-ev"><span class="d">${k(o.date)}</span><span class="ox-st ${o.importance}">${o.importance}</span><a href="${he(o.id)}">${k(o.title)}</a></div>`).join("")||'<div class="ox-empty">No events yet.</div>')+"</section>",r+=Sa(e,_a(e,[...e.entities.values()])),r+="</div>",N("Wiki",L(e,{home:!0}),r)}function Aa(e,a,t){let r=e.ontology.pillars.find(c=>c.id===a);if(!r)return null;let n=_e(e),o=e.ontology.types.filter(c=>c.pillar===r.id),i=o.find(c=>c.id===t)??o.find(c=>n.get(c.id)?.length)??o[0],s=`<div class="ox-bar">${H([{label:r.label}])}${be(1)}</div>`;s+=`<div class="ox-head"><div class="ox-avatar">${D(r.icon)}</div><div><h1>${k(r.label)}</h1><p>${k(r.description??"")}</p></div></div>`,s+=`<nav class="ox-tabs">${o.map(c=>`<a class="${c.id===i?.id?"on":""}" href="/p/${encodeURIComponent(r.id)}?kind=${encodeURIComponent(c.id)}">${k(c.plural??c.label)}<small>${n.get(c.id)?.length??0}</small></a>`).join("")}</nav>`;let d=i?(n.get(i.id)??[]).map(c=>({e:c,at:Se(e,c)})).sort((c,m)=>m.at.localeCompare(c.at)):[];s+='<div class="ox-grid2">',s+=`<section class="ox-card"><div class="ox-card-h"><h2>${k(i?.plural??i?.label??"")}</h2><span class="note">${d.length} \xB7 most active first</span>`+(i?`<a class="zin" href="/p/${encodeURIComponent(r.id)}/${encodeURIComponent(i.id)}">open list (Z3) \u2192</a>`:"")+"</div>"+(d.slice(0,5).map(({e:c,at:m})=>ne(e,c,c.type==="event"?`<span class="ox-st ${c.importance}">${c.importance}</span>`:"",`${aa(c,90)||fe(e.ontology,c.type).toLowerCase()} \xB7 ${m}`)).join("")||`<div class="ox-empty">No ${k((i?.plural??"pages").toLowerCase())} yet.</div>`)+"</section>";let l=o.flatMap(c=>n.get(c.id)??[]);return s+=Sa(e,_a(e,l)),s+="</div>",N(r.label,L(e,{pillar:r.id}),s)}function Ta(e,a,t,r,n){let o=n&&je.includes(n)?n:null,i=e.ontology.pillars.find(x=>x.id===a),s=e.ontology.types.find(x=>x.id===t&&x.pillar===a);if(!i||!s)return null;let d=[...e.entities.values()].filter(x=>x.type===s.id);o&&(d=d.filter(x=>x.importance===o));let l=d.map(x=>({e:x,at:Se(e,x)})).sort((x,f)=>f.at.localeCompare(x.at)),c=50,m=Math.max(1,Math.ceil(l.length/c)),g=`/p/${encodeURIComponent(i.id)}/${encodeURIComponent(s.id)}`,u=`<div class="ox-bar">${H([{label:i.label,href:`/p/${encodeURIComponent(i.id)}`},{label:s.plural??s.label}])}${be(3)}</div>`;if(u+=`<div class="ox-head"><div class="ox-avatar">${D(s.icon)}</div><div><h1>${k(s.plural??s.label)}</h1><p>${l.length} page${l.length===1?"":"s"}${o?` \xB7 ${k(o)} only`:""}</p></div></div>`,s.id==="event"&&(u+=`<nav class="ox-tabs">${["","major","normal","minor"].map(x=>`<a class="${(o??"")===x?"on":""}" href="${g}${x?`?importance=${x}`:""}">${x||"all"}</a>`).join("")}</nav>`),u+='<section class="ox-card" style="margin-top:16px">'+(l.slice((r-1)*c,r*c).map(({e:x,at:f})=>ne(e,x,x.type==="event"?`<span class="ox-st ${x.importance}">${x.importance}</span>`:"",`${f} \xB7 ${x.pages.map(A=>A.agentId).filter((A,y,v)=>v.indexOf(A)===y).join(", ")}`)).join("")||'<div class="ox-empty">None.</div>')+"</section>",m>1){let x=o?`importance=${o}&`:"";u+=`<div class="ox-pager">${r>1?`<a href="${g}?${x}page=${r-1}">\u2190 previous</a>`:""}<span>page ${r} of ${m}</span>${r<m?`<a href="${g}?${x}page=${r+1}">next \u2192</a>`:""}</div>`}return N(s.plural??s.label,L(e,{pillar:i.id}),u)}function Ia(e,a){let t=a.trim().toLowerCase(),r=[];if(t)for(let o of e.entities.values()){let i=o.title.toLowerCase(),s=i===t?100:i.startsWith(t)?60:i.includes(t)?40:0;!s&&o.pages.some(d=>d.article.content.toLowerCase().includes(t))&&(s=10),s&&r.push({e:o,s})}r.sort((o,i)=>i.s-o.s||i.e.updated.localeCompare(o.e.updated));let n=`<div class="ox-bar">${H([{label:"Search"}])}</div>`;return n+=`<div class="ox-head"><div class="ox-avatar">${D("search")}</div><div><h1>${t?`\u201C${k(a)}\u201D`:"Search"}</h1><p>${r.length} match${r.length===1?"":"es"}</p></div></div>`,n+=`<section class="ox-card">${r.slice(0,60).map(({e:o})=>ne(e,o)).join("")||'<div class="ox-empty">No page matches.</div>'}</section>`,N(`Search: ${a}`,L(e,{}),n,"",a)}function za(e,a,t){let r=e.ontology,n=_e(e),o=`<div class="ox-bar">${H([{label:"Ontology"}])}</div>`;o+=`<div class="ox-head"><div class="ox-avatar">${D("steps")}</div><div><h1>Ontology</h1><p>${t?`Read from ${k(t)}`:"Built-in defaults. Run <code>agentx wiki ontology init</code> to write an ontology.yaml you can edit."}</p></div></div>`,a.length&&(o+=`<div class="ox-err"><b>Problems</b><ul>${a.map(i=>`<li>${k(i)}</li>`).join("")}</ul></div>`),o+=`<section class="ox-card"><div class="ox-card-h"><h2>Types</h2><span class="note">${r.types.length}</span></div>`;for(let i of r.types){let s=r.pillars.find(d=>d.id===i.pillar);o+=`<div class="ox-row"><span class="ox-ic">${D(i.icon)}</span><div class="t"><span class="l">${k(i.label)} <span class="ox-sub">${k(i.id)}</span></span><div class="ox-sub">${k(s?.label??i.pillar)} \xB7 lens: ${k((i.lens??[]).map(d=>d.title??d.panel).join(" \u2192 "))}</div></div><div class="r"><span class="ox-chip">${n.get(i.id)?.length??0}</span></div></div>`}o+=`</section><section class="ox-card" style="margin-top:16px"><div class="ox-card-h"><h2>Relations</h2><span class="note">${r.properties.length}</span></div>`;for(let i of r.properties)o+=`<div class="ox-kv"><span class="k">${k(i.id)}</span><span>${k(i.label)}${i.inverse?` \xB7 inverse: ${k(i.inverse)}`:""}${i.wikidata?` <span class="ox-sub">${k(i.wikidata)}</span>`:""}</span></div>`;return o+=`</section><section class="ox-card" style="margin-top:16px"><div class="ox-card-h"><h2>Event importance</h2></div><div class="ox-kv"><span class="k">default</span><span>${k(r.importance.default)}</span></div><div class="ox-kv"><span class="k">major set by</span><span>${k(r.importance.major_set_by)}</span></div><div class="ox-kv"><span class="k">roll-up</span><span>${r.importance.rollup.min} minor events in ${r.importance.rollup.days} days</span></div></section>`,N("Ontology",L(e,{}),o)}var oe=class{constructor(a,t){this.hub=a;this.wikiDir=t}cache=new Qe;pageAt(a){if(!a.startsWith("/e/"))return null;let{ontology:t}=me(this.wikiDir),n=this.cache.get(this.hub,t).entities.get(a.split("/").filter(Boolean)[1]??"")?.pages[0];return n?{agentId:n.agentId,path:n.article.path,title:n.article.meta.title}:null}handle(a,t){if(!(a==="/"||a===""||a.startsWith("/p/")||a.startsWith("/e/")||a==="/find"||a==="/ontology"))return null;let{ontology:r,errors:n,file:o}=me(this.wikiDir),i=Ve(this.wikiDir,this.hub.listAgents([]),r.agent_names),s=this.cache.get(this.hub,r,i),d=Math.max(1,Number(t.get("page"))||1);if(a==="/"||a==="")return Ca(s,n);if(a==="/find")return Ia(s,t.get("q")??"");if(a==="/ontology")return za(s,n,o);let l=a.split("/").filter(Boolean);if(l[0]==="p")return l.length===2?Aa(s,l[1],t.get("kind")):l.length===3?Ta(s,l[1],l[2],d,t.get("importance")):null;let c=s.entities.get(l[1]??"");if(!c)return null;let m={g:s,readEntries:g=>this.hub.getSharedStore().readEntries(g),versions:(g,u)=>this.hub.getAgentWiki(g).getVersions(u)};return l.length===2?ta(m,c):l.length===3?ra(m,c,l[2],d):l.length===4&&l[2]==="s"?na(m,c,Number(l[3])):null}};var Dt=`
2222
2222
  .wc-root{--wc-bg:#fff;--wc-ink:#1b1f1e;--wc-muted:#5d6664;--wc-edge:#d9dedc;--wc-soft:#f3f5f4;--wc-accent:#2f6fde;--wc-on-accent:#fff;--wc-add:#e6f4ea;--wc-add-ink:#1e6b34;--wc-del:#fbe9e9;--wc-del-ink:#9b2c2c;
2223
2223
  font:14px/1.45 'IBM Plex Sans',system-ui,-apple-system,sans-serif;color:var(--wc-ink)}
2224
2224
  [data-theme=dark] .wc-root{--wc-bg:#181c1b;--wc-ink:#e9eeec;--wc-muted:#a3adab;--wc-edge:#2c3331;--wc-soft:#1f2422;--wc-accent:#6b9cff;--wc-on-accent:#0b1020;--wc-add:#173823;--wc-add-ink:#9be3b0;--wc-del:#3b1d1d;--wc-del-ink:#f3a9a9}
@@ -2889,12 +2889,12 @@ tr:hover td { background: var(--bg-hover); }
2889
2889
  </div>`}o+=d.length}}return o===0&&(n+=`<p style="color:var(--muted);margin-top:24px">No articles tagged <code>${p(a)}</code>.</p>`),C(`Tag: ${a}`,E(r),n)}function Vt(e,a,t,r){let n=r||e.summary(),o;try{o=e.getAgentWiki(a)}catch{return C(`Tag: ${t}`,E(n),`<h1>Agent not found: ${p(a)}</h1>`)}let i=o.findByTags([t],void 0,100),s=`/agent/${encodeURIComponent(a)}`,d=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${s}">${p(a)}</a> <span class="sep">/</span> <span class="current">${p(t)}</span></nav>`;d+=`<div class="page-head"><div><h1>${p(t)}</h1><p class="page-sub">${i.length} article${i.length===1?"":"s"} tagged <code>${p(t)}</code> in <b>${p(a)}</b>.</p></div></div>`;for(let l of i)d+=`<div class="entry-card">
2890
2890
  <div class="meta-line">${j((l.meta.tags||[]).slice(0,6),a)}</div>
2891
2891
  <h3><a href="${s}/article/${encodeURIComponent(l.path)}">${p(l.meta.title)}</a></h3>
2892
- </div>`;return C(`${a} \xB7 ${t}`,E(n),d)}function B(e,a,t){let r=e.rebuildIndex(),n=Ce(r.articles.map(i=>({title:i.title,path:i.path,tags:i.tags}))),o='<div class="nav-section">';o+=`<div class="nav-section-title">${p(a)}</div>`,o+=`<a class="nav-item${t?"":" active"}" href="/">Home</a>`,o+='<a class="nav-item" href="/lint">Health check</a>',o+="</div>";for(let[i,s]of n){o+='<div class="nav-section">',o+=`<div class="nav-section-title">${Ae(i)}</div>`;for(let d of s){let l=d.path===t;o+=`<a class="nav-item${l?" active":""}" href="/article/${encodeURIComponent(d.path)}">${p(d.title)}</a>`}o+="</div>"}return o}function Qt(e){let{wikiDir:a,agentFilter:t,peers:r=[],mode:n="graph",pathPrefix:o=""}=e,i=o.replace(/\/+$/,""),s=new je(a,void 0,n),d=new oe(s,a),l=r.length>0?new re(r):null;return async(c,m)=>{let g=new URL(c.url||"/","http://localhost"),u=decodeURIComponent(g.pathname),x=i&&u.startsWith(i)?u.slice(i.length)||"/":u,f=null,A=200;try{if(x.startsWith("/remote/")&&l){let y=x.slice(8).split("/article/");if(y.length===2){let[v,b]=y,h=v.indexOf("/"),$=decodeURIComponent(v.slice(0,h)),w=v.slice(h+1),S=await l.getRemoteArticle($,w,b);if(S){let O=await l.getRemoteAgents(),J=[...s.summary(),...O.map(I=>({...I,agentId:`${I.agentId} @${I.nodeId}`}))],T=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${p(w)} @ ${p($)}</div>`;T+=`<h1>${p(S.meta.title)}</h1>`,T+='<dl class="meta">',T+=`<dt>Tags</dt><dd>${(S.meta.tags||[]).map(I=>`<span class="tag">${I}</span>`).join(" ")}</dd>`,T+=`<dt>Owner</dt><dd>${p(S.meta.owner)}</dd>`,T+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p($)}</dd>`,T+=`<dt>Updated</dt><dd>${S.meta.lastUpdated}</dd>`,T+="</dl>";let R=new Map;T+=ie(S.content,R),f=C(S.meta.title,E(J),T)}}}if(!f&&t){let y=s.getAgentWiki(t);if(x==="/"||x===""){let v=y.rebuildIndex(),b=s.getAgentEntries(t),h=`<h1>${p(t)}</h1>`;if(h+='<div class="stats">',h+=`<div class="stat-card"><div class="number">${v.articles.length}</div><div class="label">Articles</div></div>`,h+=`<div class="stat-card"><div class="number">${b.length}</div><div class="label">Entries</div></div>`,h+="</div>",v.articles.length>0){h+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let $ of v.articles)h+=`<tr><td><a href="/article/${encodeURIComponent($.path)}">${p($.title)}</a></td><td><span class="tag">${($.tags||[]).slice(0,3).join(", ")}</span></td><td>${$.lastUpdated||""}</td></tr>`;h+="</table>"}f=C(t,B(y,t),h)}else if(x.startsWith("/article/")){let v=x.slice(9),b=y.readArticle(v);if(b){let h=y.rebuildIndex(),$=new Map;for(let S of h.articles)$.set(S.title,S.path);let w=`<h1>${p(b.meta.title)}</h1>`;w+='<dl class="meta">',w+=`<dt>Tags</dt><dd>${(b.meta.tags||[]).map(S=>`<span class="tag">${S}</span>`).join(" ")}</dd>`,w+=`<dt>Updated</dt><dd>${b.meta.lastUpdated}</dd>`,b.meta.sources?.length&&(w+=`<dt>Sources</dt><dd>${b.meta.sources.length} entries</dd>`),w+="</dl>",w+=ie(b.content,$),f=C(b.meta.title,B(y,t,v),w)}}else if(x==="/lint"){let v=y.lint(),b="<h1>Health Check</h1>";if(v.length===0)b+='<p style="color:green;">No issues.</p>';else{b+="<table><tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let h of v)b+=`<tr><td><span class="tag">${h.type}</span></td><td>${p(h.article)}</td><td>${p(h.message)}</td></tr>`;b+="</table>"}f=C("Health Check",B(y,t),b)}else if(x==="/search"){let v=g.searchParams.get("q")||"",b=await y.findRelevantReranked(v,void 0,20),h=`<h1>Search: "${p(v)}"</h1>`;for(let $ of b)h+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent($.path)}">${p($.meta.title)}</a></h3><p>${p($.content.slice(0,200))}...</p></div>`;b.length===0&&(h+="<p>No results.</p>"),f=C(`Search: ${v}`,B(y,t),h)}else if(x.startsWith("/tag/")){let v=decodeURIComponent(x.slice(5)),b=y.findByTags([v],void 0,100),h=`<h1>Tag: <a class="tag" href="#">${p(v)}</a></h1>`;h+=`<p>${b.length} article${b.length===1?"":"s"} tagged <code>${p(v)}</code></p>`;for(let $ of b)h+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent($.path)}">${p($.meta.title)}</a></h3><div class="meta-line">${j(($.meta.tags||[]).slice(0,6))}</div></div>`;b.length===0&&(h+="<p>No articles with this tag.</p>"),f=C(`Tag: ${v}`,B(y,t),h)}}else if(!f&&(f=d.handle(x,g.searchParams))===null){let y=l?await l.getRemoteAgents():[],v=s.summary(),b=new Map(v.map(w=>[w.agentId,w])),h=[],$=new Set;for(let w of v){let S=y.find(O=>O.agentId===w.agentId);S&&S.totalArticles>w.totalArticles?h.push({...S,totalEntries:Math.max(w.totalEntries,S.totalEntries),unabsorbed:Math.max(w.unabsorbed,S.unabsorbed)}):h.push(w),$.add(w.agentId)}for(let w of y)$.has(w.agentId)||(h.push(w),$.add(w.agentId));if(x==="/agents")f=qt(s,h,y);else if(x==="/entries")f=Jt(s,h);else if(x==="/search")f=Xt(s,g.searchParams.get("q")||"",h);else if(x.startsWith("/tag/"))f=Gt(s,decodeURIComponent(x.slice(5)),h);else if(x.match(/^\/agent\/[^/]+\/tag\/.+/)){let w=x.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);f=Vt(s,decodeURIComponent(w[1]),decodeURIComponent(w[2]),h)}else if(x.startsWith("/agent/")){let w=x.slice(7),S=w.indexOf("/article/");if(S===-1)f=Kt(s,w,h);else{let O=w.slice(0,S),J=w.slice(S+9);if(f=Yt(s,O,J,h),!f&&l){let T=y.find(R=>R.agentId===O);if(T){let R=await l.getRemoteArticle(T.peerUrl,O,J);if(R){let I=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${p(T.nodeId)}</span> / ${p(O)}</div>`;I+=`<h1>${p(R.meta.title)}</h1>`,I+='<dl class="meta">',I+=`<dt>Tags</dt><dd>${(R.meta.tags||[]).map(Qa=>`<span class="tag">${Qa}</span>`).join(" ")}</dd>`,I+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p(T.nodeId)}</dd>`,I+=`<dt>Updated</dt><dd>${R.meta.lastUpdated}</dd>`,I+="</dl>",I+=ie(R.content,new Map),f=C(R.meta.title,E(h),I)}}}}}}if(!f){A=404;let y=t?B(s.getAgentWiki(t),t):E(s.summary());f=C("Not Found",y,"<h1>Page not found</h1>")}}catch(y){A=500,f=C("Error","",`<h1>Error</h1><pre>${p(y.message)}</pre>`)}if(A===200&&e.curator){let y=Zt(s,d,x,t);y&&(f=Pa(f,y,e.curatorEndpoint,e.curatorToken?.(c)))}m.writeHead(A,{"Content-Type":"text/html; charset=utf-8"}),m.end(i?er(f,i):f)}}function Zt(e,a,t,r){let n,o;if(r&&t.startsWith("/article/"))n=r,o=t.slice(9);else if(!r&&t.startsWith("/agent/")){let d=t.match(/^\/agent\/([^/]+)\/article\/(.+)$/);d&&(n=d[1],o=d[2])}else if(!r)return a.pageAt(t);if(!n||!o||!e.listAgents([]).includes(n))return null;let i=e.getAgentWiki(n);if(!Fe(i.baseDir,o))return null;let s=i.readArticle(o);return s?{agentId:n,path:o,title:s.meta.title}:null}function er(e,a){e=e.replace(/(\s(?:href|action)=")\/(?!\/)/g,`$1${a}/`),e=e.replace(new RegExp(`(${a})${a}/`,"g"),`${a}/`);let t=`<a href="/hub" style="position:fixed;top:10px;right:14px;z-index:9999;padding:5px 11px;background:rgba(0,0,0,0.55);color:#fff;font:12px/1.2 'IBM Plex Sans',system-ui,sans-serif;text-decoration:none;border-radius:6px;border:1px solid rgba(255,255,255,0.18);backdrop-filter:blur(6px)">\u2190 Dashboard</a>`;return e=e.replace(/<body([^>]*)>/,`<body$1>${t}`),e}function go(e,a=4200,t,r=[],n="graph"){let o=Qt({wikiDir:e,agentFilter:t,peers:r,mode:n});Nt((s,d)=>{o(s,d)}).listen(a)}import{existsSync as ar,readFileSync as tr}from"fs";xe();function vo(e){let a=K(e),t={};if(ar(a))try{t=q(JSON.parse(tr(a,"utf-8")))}catch{t={}}let r=t?.workflows?.required??{},n={};for(let[o,i]of Object.entries(r.agents??{}))typeof i=="boolean"&&(n[o]=i);return{enabled:typeof r.enabled=="boolean"?r.enabled:G.enabled,agents:n,exemptQuestions:typeof r.exemptQuestions=="boolean"?r.exemptQuestions:G.exemptQuestions,retentionDays:Number.isInteger(r.retentionDays)&&r.retentionDays>=0?r.retentionDays:G.retentionDays,engine:t?.workflows?.enabled===!0}}async function wo(e,a={}){return e.retentionDays!==void 0&&!(Number.isInteger(e.retentionDays)&&e.retentionDays>=0&&e.retentionDays<=3650)?{success:!1,error:"retentionDays is a whole number of days from 0 to 3650"}:e.agent&&!/^[A-Za-z0-9_.@-]{1,80}$/.test(e.agent.id)?{success:!1,error:`"${e.agent.id}" is not an agent id`}:X(t=>{let r=t.workflows??={},n=r.required??={};if(e.enabled!==void 0&&(n.enabled=e.enabled),e.exemptQuestions!==void 0&&(n.exemptQuestions=e.exemptQuestions),e.retentionDays!==void 0&&(n.retentionDays=e.retentionDays),e.agent){let o=n.agents??={};e.agent.value===null?delete o[e.agent.id]:o[e.agent.id]=e.agent.value}(e.enabled===!0||e.agent?.value===!0)&&(r.enabled=!0)},{configPath:a.configPath,reload:a.reload})}var rr={"claude-code":{bin:"claude",login:"Install Claude Code (https://claude.com/claude-code) and run `claude` once to log in"},"codex-cli":{bin:"codex",login:"Install Codex CLI and run `codex login`"},opencode:{bin:"opencode",login:"Install OpenCode and run `opencode auth login`"}};function nr(e){if(typeof e!="string")return null;let a=e.match(/^\$\{(\w+)\}$/);return a?a[1]:null}function ko(e){let a=e.rawConfig?.agents?.[e.agentId];if(!a)return{ready:!1,hint:`No agent "${e.agentId}" in agentx.json.`};let t=String(a.tier||""),r=rr[t];if(r)return e.hasBinary(r.bin)?e.cliLoggedIn?.(r.bin)===!1?{ready:!1,need:"cli",cli:r.bin,hint:`${r.bin} is installed but not logged in. In a terminal, run \`${r.bin}\` once and log in, then press Check again.`}:{ready:!0}:{ready:!1,need:"cli",cli:r.bin,hint:`${r.login}, then press Check again.`};if(t==="sdk"||t==="orchestrator"){let n=a.provider||(t==="sdk"?"claude":"claude-code"),o=e.rawConfig?.providers?.[n];if(t==="orchestrator"&&!(o&&"apiKey"in o))return{ready:!0};let i=o?.apiKey,s=nr(i);return s?e.env[s]||e.dotenv[s]?{ready:!0}:{ready:!1,need:"key",envVar:s,hint:`Paste an API key for "${n}". It is saved to .env as ${s} on this computer only.`}:typeof i=="string"&&i.trim()?{ready:!0}:{ready:!1,hint:`Set providers.${n}.apiKey in agentx.json.`}}return{ready:!0}}import{execFileSync as or}from"child_process";function Co(e){if(e!=="claude")return null;let a=Ge(e);if(!a)return null;try{let t=or(a,["auth","status"],{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]});return Ra(t)}catch(t){return typeof t?.stdout=="string"?Ra(t.stdout):null}}function Ra(e){try{let a=JSON.parse(e);return typeof a?.loggedIn=="boolean"?a.loggedIn:null}catch{return null}}import{existsSync as Na,readdirSync as dr}from"fs";import{join as Wa}from"path";import{join as ir}from"path";function Oa(e){return/^[\w@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function U(e){return(a,t)=>`cd ${Oa(t)} && npx -y skills add ${Oa(a)} -a ${e} -y`}var se={tier:"claude-code",skillDirs:e=>[ir(e,".claude","skills")],addSkillCommand:U("claude-code"),instructionsFile:"CLAUDE.md"};import{join as sr}from"path";var Da={tier:"codex-cli",skillDirs:e=>[sr(e,".agents","skills")],addSkillCommand:U("codex"),instructionsFile:"AGENTS.md"};import{join as Te}from"path";var Ma={tier:"opencode",skillDirs:e=>[Te(e,".agents","skills"),Te(e,".opencode","skills"),Te(e,".claude","skills")],addSkillCommand:U("opencode"),instructionsFile:"AGENTS.md"};import{join as Ie}from"path";var ja=e=>({...se,tier:e,skillDirs:a=>[Ie(a,".claude","skills"),Ie(a,".skills"),Ie(a,"skills")]}),Ha=ja("sdk"),La=ja("orchestrator");var lr={"claude-code":se,"codex-cli":Da,opencode:Ma,sdk:Ha,orchestrator:La};function Ba(e){return lr[e??"claude-code"]??null}function Yo(e,a){return Ba(e)?.skillDirs(a)[0]??null}function Jo(e,a){let t=new Map;for(let r of Ba(e)?.skillDirs(a)??[])if(Na(r))for(let n of dr(r))n.startsWith(".")||t.has(n)||Na(Wa(r,n,"SKILL.md"))&&t.set(n,Wa(r,n));return[...t].map(([r,n])=>({name:r,dir:n})).sort((r,n)=>r.name.localeCompare(n.name))}et();function Vo(e,a,t=20){return e.prepare(`SELECT task_id, agent_id, channel, chat_id, status, started_at, finished_at, message_preview
2892
+ </div>`;return C(`${a} \xB7 ${t}`,E(n),d)}function B(e,a,t){let r=e.rebuildIndex(),n=Ce(r.articles.map(i=>({title:i.title,path:i.path,tags:i.tags}))),o='<div class="nav-section">';o+=`<div class="nav-section-title">${p(a)}</div>`,o+=`<a class="nav-item${t?"":" active"}" href="/">Home</a>`,o+='<a class="nav-item" href="/lint">Health check</a>',o+="</div>";for(let[i,s]of n){o+='<div class="nav-section">',o+=`<div class="nav-section-title">${Ae(i)}</div>`;for(let d of s){let l=d.path===t;o+=`<a class="nav-item${l?" active":""}" href="/article/${encodeURIComponent(d.path)}">${p(d.title)}</a>`}o+="</div>"}return o}function Qt(e){let{wikiDir:a,agentFilter:t,peers:r=[],mode:n="graph",pathPrefix:o=""}=e,i=o.replace(/\/+$/,""),s=new He(a,void 0,n),d=new oe(s,a),l=r.length>0?new re(r):null;return async(c,m)=>{let g=new URL(c.url||"/","http://localhost"),u=decodeURIComponent(g.pathname),x=i&&u.startsWith(i)?u.slice(i.length)||"/":u,f=null,A=200;try{if(x.startsWith("/remote/")&&l){let y=x.slice(8).split("/article/");if(y.length===2){let[v,b]=y,h=v.indexOf("/"),$=decodeURIComponent(v.slice(0,h)),w=v.slice(h+1),S=await l.getRemoteArticle($,w,b);if(S){let O=await l.getRemoteAgents(),J=[...s.summary(),...O.map(I=>({...I,agentId:`${I.agentId} @${I.nodeId}`}))],T=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${p(w)} @ ${p($)}</div>`;T+=`<h1>${p(S.meta.title)}</h1>`,T+='<dl class="meta">',T+=`<dt>Tags</dt><dd>${(S.meta.tags||[]).map(I=>`<span class="tag">${I}</span>`).join(" ")}</dd>`,T+=`<dt>Owner</dt><dd>${p(S.meta.owner)}</dd>`,T+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p($)}</dd>`,T+=`<dt>Updated</dt><dd>${S.meta.lastUpdated}</dd>`,T+="</dl>";let R=new Map;T+=ie(S.content,R),f=C(S.meta.title,E(J),T)}}}if(!f&&t){let y=s.getAgentWiki(t);if(x==="/"||x===""){let v=y.rebuildIndex(),b=s.getAgentEntries(t),h=`<h1>${p(t)}</h1>`;if(h+='<div class="stats">',h+=`<div class="stat-card"><div class="number">${v.articles.length}</div><div class="label">Articles</div></div>`,h+=`<div class="stat-card"><div class="number">${b.length}</div><div class="label">Entries</div></div>`,h+="</div>",v.articles.length>0){h+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let $ of v.articles)h+=`<tr><td><a href="/article/${encodeURIComponent($.path)}">${p($.title)}</a></td><td><span class="tag">${($.tags||[]).slice(0,3).join(", ")}</span></td><td>${$.lastUpdated||""}</td></tr>`;h+="</table>"}f=C(t,B(y,t),h)}else if(x.startsWith("/article/")){let v=x.slice(9),b=y.readArticle(v);if(b){let h=y.rebuildIndex(),$=new Map;for(let S of h.articles)$.set(S.title,S.path);let w=`<h1>${p(b.meta.title)}</h1>`;w+='<dl class="meta">',w+=`<dt>Tags</dt><dd>${(b.meta.tags||[]).map(S=>`<span class="tag">${S}</span>`).join(" ")}</dd>`,w+=`<dt>Updated</dt><dd>${b.meta.lastUpdated}</dd>`,b.meta.sources?.length&&(w+=`<dt>Sources</dt><dd>${b.meta.sources.length} entries</dd>`),w+="</dl>",w+=ie(b.content,$),f=C(b.meta.title,B(y,t,v),w)}}else if(x==="/lint"){let v=y.lint(),b="<h1>Health Check</h1>";if(v.length===0)b+='<p style="color:green;">No issues.</p>';else{b+="<table><tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let h of v)b+=`<tr><td><span class="tag">${h.type}</span></td><td>${p(h.article)}</td><td>${p(h.message)}</td></tr>`;b+="</table>"}f=C("Health Check",B(y,t),b)}else if(x==="/search"){let v=g.searchParams.get("q")||"",b=await y.findRelevantReranked(v,void 0,20),h=`<h1>Search: "${p(v)}"</h1>`;for(let $ of b)h+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent($.path)}">${p($.meta.title)}</a></h3><p>${p($.content.slice(0,200))}...</p></div>`;b.length===0&&(h+="<p>No results.</p>"),f=C(`Search: ${v}`,B(y,t),h)}else if(x.startsWith("/tag/")){let v=decodeURIComponent(x.slice(5)),b=y.findByTags([v],void 0,100),h=`<h1>Tag: <a class="tag" href="#">${p(v)}</a></h1>`;h+=`<p>${b.length} article${b.length===1?"":"s"} tagged <code>${p(v)}</code></p>`;for(let $ of b)h+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent($.path)}">${p($.meta.title)}</a></h3><div class="meta-line">${j(($.meta.tags||[]).slice(0,6))}</div></div>`;b.length===0&&(h+="<p>No articles with this tag.</p>"),f=C(`Tag: ${v}`,B(y,t),h)}}else if(!f&&(f=d.handle(x,g.searchParams))===null){let y=l?await l.getRemoteAgents():[],v=s.summary(),b=new Map(v.map(w=>[w.agentId,w])),h=[],$=new Set;for(let w of v){let S=y.find(O=>O.agentId===w.agentId);S&&S.totalArticles>w.totalArticles?h.push({...S,totalEntries:Math.max(w.totalEntries,S.totalEntries),unabsorbed:Math.max(w.unabsorbed,S.unabsorbed)}):h.push(w),$.add(w.agentId)}for(let w of y)$.has(w.agentId)||(h.push(w),$.add(w.agentId));if(x==="/agents")f=qt(s,h,y);else if(x==="/entries")f=Jt(s,h);else if(x==="/search")f=Xt(s,g.searchParams.get("q")||"",h);else if(x.startsWith("/tag/"))f=Gt(s,decodeURIComponent(x.slice(5)),h);else if(x.match(/^\/agent\/[^/]+\/tag\/.+/)){let w=x.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);f=Vt(s,decodeURIComponent(w[1]),decodeURIComponent(w[2]),h)}else if(x.startsWith("/agent/")){let w=x.slice(7),S=w.indexOf("/article/");if(S===-1)f=Kt(s,w,h);else{let O=w.slice(0,S),J=w.slice(S+9);if(f=Yt(s,O,J,h),!f&&l){let T=y.find(R=>R.agentId===O);if(T){let R=await l.getRemoteArticle(T.peerUrl,O,J);if(R){let I=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${p(T.nodeId)}</span> / ${p(O)}</div>`;I+=`<h1>${p(R.meta.title)}</h1>`,I+='<dl class="meta">',I+=`<dt>Tags</dt><dd>${(R.meta.tags||[]).map(Qa=>`<span class="tag">${Qa}</span>`).join(" ")}</dd>`,I+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p(T.nodeId)}</dd>`,I+=`<dt>Updated</dt><dd>${R.meta.lastUpdated}</dd>`,I+="</dl>",I+=ie(R.content,new Map),f=C(R.meta.title,E(h),I)}}}}}}if(!f){A=404;let y=t?B(s.getAgentWiki(t),t):E(s.summary());f=C("Not Found",y,"<h1>Page not found</h1>")}}catch(y){A=500,f=C("Error","",`<h1>Error</h1><pre>${p(y.message)}</pre>`)}if(A===200&&e.curator){let y=Zt(s,d,x,t);y&&(f=Pa(f,y,e.curatorEndpoint,e.curatorToken?.(c)))}m.writeHead(A,{"Content-Type":"text/html; charset=utf-8"}),m.end(i?er(f,i):f)}}function Zt(e,a,t,r){let n,o;if(r&&t.startsWith("/article/"))n=r,o=t.slice(9);else if(!r&&t.startsWith("/agent/")){let d=t.match(/^\/agent\/([^/]+)\/article\/(.+)$/);d&&(n=d[1],o=d[2])}else if(!r)return a.pageAt(t);if(!n||!o||!e.listAgents([]).includes(n))return null;let i=e.getAgentWiki(n);if(!Fe(i.baseDir,o))return null;let s=i.readArticle(o);return s?{agentId:n,path:o,title:s.meta.title}:null}function er(e,a){e=e.replace(/(\s(?:href|action)=")\/(?!\/)/g,`$1${a}/`),e=e.replace(new RegExp(`(${a})${a}/`,"g"),`${a}/`);let t=`<a href="/hub" style="position:fixed;top:10px;right:14px;z-index:9999;padding:5px 11px;background:rgba(0,0,0,0.55);color:#fff;font:12px/1.2 'IBM Plex Sans',system-ui,sans-serif;text-decoration:none;border-radius:6px;border:1px solid rgba(255,255,255,0.18);backdrop-filter:blur(6px)">\u2190 Dashboard</a>`;return e=e.replace(/<body([^>]*)>/,`<body$1>${t}`),e}function go(e,a=4200,t,r=[],n="graph"){let o=Qt({wikiDir:e,agentFilter:t,peers:r,mode:n});Nt((s,d)=>{o(s,d)}).listen(a)}import{existsSync as ar,readFileSync as tr}from"fs";xe();function vo(e){let a=K(e),t={};if(ar(a))try{t=q(JSON.parse(tr(a,"utf-8")))}catch{t={}}let r=t?.workflows?.required??{},n={};for(let[o,i]of Object.entries(r.agents??{}))typeof i=="boolean"&&(n[o]=i);return{enabled:typeof r.enabled=="boolean"?r.enabled:G.enabled,agents:n,exemptQuestions:typeof r.exemptQuestions=="boolean"?r.exemptQuestions:G.exemptQuestions,retentionDays:Number.isInteger(r.retentionDays)&&r.retentionDays>=0?r.retentionDays:G.retentionDays,engine:t?.workflows?.enabled===!0}}async function wo(e,a={}){return e.retentionDays!==void 0&&!(Number.isInteger(e.retentionDays)&&e.retentionDays>=0&&e.retentionDays<=3650)?{success:!1,error:"retentionDays is a whole number of days from 0 to 3650"}:e.agent&&!/^[A-Za-z0-9_.@-]{1,80}$/.test(e.agent.id)?{success:!1,error:`"${e.agent.id}" is not an agent id`}:X(t=>{let r=t.workflows??={},n=r.required??={};if(e.enabled!==void 0&&(n.enabled=e.enabled),e.exemptQuestions!==void 0&&(n.exemptQuestions=e.exemptQuestions),e.retentionDays!==void 0&&(n.retentionDays=e.retentionDays),e.agent){let o=n.agents??={};e.agent.value===null?delete o[e.agent.id]:o[e.agent.id]=e.agent.value}(e.enabled===!0||e.agent?.value===!0)&&(r.enabled=!0)},{configPath:a.configPath,reload:a.reload})}var rr={"claude-code":{bin:"claude",login:"Install Claude Code (https://claude.com/claude-code) and run `claude` once to log in"},"codex-cli":{bin:"codex",login:"Install Codex CLI and run `codex login`"},opencode:{bin:"opencode",login:"Install OpenCode and run `opencode auth login`"}};function nr(e){if(typeof e!="string")return null;let a=e.match(/^\$\{(\w+)\}$/);return a?a[1]:null}function ko(e){let a=e.rawConfig?.agents?.[e.agentId];if(!a)return{ready:!1,hint:`No agent "${e.agentId}" in agentx.json.`};let t=String(a.tier||""),r=rr[t];if(r)return e.hasBinary(r.bin)?e.cliLoggedIn?.(r.bin)===!1?{ready:!1,need:"cli",cli:r.bin,hint:`${r.bin} is installed but not logged in. In a terminal, run \`${r.bin}\` once and log in, then press Check again.`}:{ready:!0}:{ready:!1,need:"cli",cli:r.bin,hint:`${r.login}, then press Check again.`};if(t==="sdk"||t==="orchestrator"){let n=a.provider||(t==="sdk"?"claude":"claude-code"),o=e.rawConfig?.providers?.[n];if(t==="orchestrator"&&!(o&&"apiKey"in o))return{ready:!0};let i=o?.apiKey,s=nr(i);return s?e.env[s]||e.dotenv[s]?{ready:!0}:{ready:!1,need:"key",envVar:s,hint:`Paste an API key for "${n}". It is saved to .env as ${s} on this computer only.`}:typeof i=="string"&&i.trim()?{ready:!0}:{ready:!1,hint:`Set providers.${n}.apiKey in agentx.json.`}}return{ready:!0}}import{execFileSync as or}from"child_process";function Co(e){if(e!=="claude")return null;let a=Ge(e);if(!a)return null;try{let t=or(a,["auth","status"],{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]});return Ra(t)}catch(t){return typeof t?.stdout=="string"?Ra(t.stdout):null}}function Ra(e){try{let a=JSON.parse(e);return typeof a?.loggedIn=="boolean"?a.loggedIn:null}catch{return null}}import{existsSync as Na,readdirSync as dr}from"fs";import{join as Wa}from"path";import{join as ir}from"path";function Oa(e){return/^[\w@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function U(e){return(a,t)=>`cd ${Oa(t)} && npx -y skills add ${Oa(a)} -a ${e} -y`}var se={tier:"claude-code",skillDirs:e=>[ir(e,".claude","skills")],addSkillCommand:U("claude-code"),instructionsFile:"CLAUDE.md"};import{join as sr}from"path";var Da={tier:"codex-cli",skillDirs:e=>[sr(e,".agents","skills")],addSkillCommand:U("codex"),instructionsFile:"AGENTS.md"};import{join as Te}from"path";var Ma={tier:"opencode",skillDirs:e=>[Te(e,".agents","skills"),Te(e,".opencode","skills"),Te(e,".claude","skills")],addSkillCommand:U("opencode"),instructionsFile:"AGENTS.md"};import{join as Ie}from"path";var ja=e=>({...se,tier:e,skillDirs:a=>[Ie(a,".claude","skills"),Ie(a,".skills"),Ie(a,"skills")]}),Ha=ja("sdk"),La=ja("orchestrator");var lr={"claude-code":se,"codex-cli":Da,opencode:Ma,sdk:Ha,orchestrator:La};function Ba(e){return lr[e??"claude-code"]??null}function Yo(e,a){return Ba(e)?.skillDirs(a)[0]??null}function Jo(e,a){let t=new Map;for(let r of Ba(e)?.skillDirs(a)??[])if(Na(r))for(let n of dr(r))n.startsWith(".")||t.has(n)||Na(Wa(r,n,"SKILL.md"))&&t.set(n,Wa(r,n));return[...t].map(([r,n])=>({name:r,dir:n})).sort((r,n)=>r.name.localeCompare(n.name))}et();function Vo(e,a,t=20){return e.prepare(`SELECT task_id, agent_id, channel, chat_id, status, started_at, finished_at, message_preview
2893
2893
  FROM task_traces
2894
2894
  WHERE person = ? AND (channel IS NULL OR channel != 'a2a')
2895
2895
  ORDER BY started_at DESC, rowid DESC LIMIT ?`).all(a,Math.max(1,Math.min(t,500))).map(n=>({taskId:n.task_id,agentId:n.agent_id,channel:n.channel,chatId:n.chat_id,status:n.status,startedAt:n.started_at,finishedAt:n.finished_at??null,messagePreview:n.message_preview}))}function cr(e){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'requests'").get()?e.prepare("PRAGMA table_info(requests)").all().some(r=>r.name==="person"):!1}function Ua(e,a,t,r,...n){return cr(e)?e.prepare(`SELECT id, state, channel, agent_id, text, created_at FROM requests
2896
2896
  WHERE person = ? AND state IN (${t.map(()=>"?").join(",")})
2897
- ${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Qo(e,a){return Ua(e,a,ce,"ORDER BY created_at")}function Zo(e,a,t=50){return Ua(e,a,[...ce,...Pe],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}at();var ze="member:",pr=90,xr="members",gr="tailscale-user-login",ur=400,mr=60*60*1e3;function fr(e){let a=e.scopes.find(t=>t.startsWith(ze));return a?a.slice(ze.length):null}function qa(e,a){if(!e)return null;let t=a.verify(e),r=t?fr(t):null;return t&&r?{rec:t,personId:r}:null}function ii(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${ze}${t.id}`],expiresInDays:pr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var hr=Math.round(Le/6e4);function br(e){return e==="client"?"Your project":"My work"}function si(e){let a=br(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${Ne(e.code)}`,` The code works once, for ${hr} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
2898
- `)}var vr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",wr="Too many machines are waiting for the owner's answer. Try again later.",Fa="That code didn't work. Check it, or ask the person who invited you for a new one.",Ka=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ya(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function yr(e){if(!Ya(e))return null;let a=Ka(e,gr).toLowerCase();return a?a.slice(0,80):null}function kr(e){let a=e.socket?.remoteAddress||"unknown";if(!Ya(e))return a;let t=Ka(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function $r(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function _r(e){return e.identities.map(Ee).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function di(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=kr(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await Q(e,2048);s=b.code,d=$r(b.machine)}catch{}let l=a.codes.redeem(s),c=l?qa(l.token,a.tokens):null;if(await Cr(t,a.minMs??ur),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Fa}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Fa}};let x=yr(e),f=_r(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:vr}};let A=d||"Unnamed machine",y=u.name.slice(0,40),v=We(a.root,{title:`New machine for ${y}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${A}". Let it see their own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:xr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:A,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:A}),n(`[member] ${g} paired "${A}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:A,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:wr}})}var de="this machine is not paired",Sr="waiting for the owner to approve this machine";function Ja(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function li(e,a){return a.state==="pending"&&a.cardId?Ja(ue(e,a.cardId)):null}function ci(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=qa(e,a.tokens);if(!o)return{ok:!1,status:401,error:de};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:de};if(a.people&&!a.people().some(c=>c.id===s))return Xa(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:de};if(d.state==="pending"){let c=d.cardId?ue(a.root,d.cardId):null,m=Ja(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:de}}else return{ok:!1,status:403,error:Sr,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=mr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Xa(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function pi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Xa(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function Cr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Ga=["gitlab","github"];function Ar(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Ga.includes(r))throw new Error(`Request status works on ${Ga.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function ui(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function mi(e){let{summary:a}=Z(t=>Ar(t,e?.channel,!!e?.enabled));return{summary:a}}var hi="https://myaccount.google.com/apppasswords";function bi(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function vi(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function wi(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function $i(e){return`${e.name} <${e.from}> via ${e.host}:${e.port}`}async function _i(e,a){return Be({host:e.host,port:e.port,secure:e.secure,user:e.user,password:e.password},{name:e.name,address:e.from},a,{"Auto-Submitted":"auto-generated"})}function Si(e,a){return{to:e,subject:`${a.name}: test mail`,text:[`This is a test mail from ${a.name}.`,"","If it reached you, AgentX can send mail through this sender.","You can ignore it."].join(`
2899
- `)}}function Ai(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ti(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Ii(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function zi(e,a){if(a){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Tr="https://ntfy.sh";function Ei(e){return{enabled:!!e?.enabled,server:e?.server||Tr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Ri(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}Za();function Va(e){return/^(agent|person):/.test(e)?F(e):`person:${e}`}function ji(e){let a=(e?.projects??[]).filter(t=>t?.id);return a.map(t=>({id:t.id,name:t.name?.trim()||t.id,client:He(t.id,a),...t.pm?{pm:F(t.pm)}:{},...t.lead?{lead:Va(t.lead)}:{},team:[...new Set((t.team??[]).filter(Boolean).map(F))]})).sort((t,r)=>t.client.localeCompare(r.client)||t.name.localeCompare(r.name)||t.id.localeCompare(r.id))}function Hi(e,a,t){if(!t.lead&&!t.team?.length)return;let r=new Set(Object.keys(e.business?.orgChart||{})),n=new Set((e.people||[]).map(i=>String(i.id))),o={id:a,name:a,client:"",...t.lead?{lead:Va(t.lead)}:{},team:(t.team??[]).map(F)};return Ir([o],r,n)}function Ir(e,a,t){let r=n=>{let o=le(n);return o.kind==="agent"?a.has(o.id)?void 0:`"${o.id}", which is not an agent in business.orgChart`:t.has(o.id)?void 0:`"${o.id}", which is not a person in people`};for(let n of e){if(n.lead){if(le(n.lead).kind!=="person")return`Project ${n.name} is led by "${n.lead}"; a lead is a person (person:<id>), the PM is the agent`;let o=r(n.lead);if(o)return`Project ${n.name} is led by ${o}`}for(let o of n.team){let i=r(o);if(i)return`Project ${n.name} has ${i} in its team`}}}export{ve as a,da as b,ye as c,nt as d,ot as e,it as f,ua as g,mt as h,_n as i,Sn as j,Cn as k,ko as l,Co as m,Ba as n,Yo as o,Jo as p,Rn as q,On as r,It as s,Et as t,ke as u,Dn as v,Mn as w,Rt as x,Bn as y,Un as z,Fn as A,Vo as B,Qo as C,Zo as D,pr as E,xr as F,ii as G,hr as H,br as I,si as J,vr as K,wr as L,yr as M,kr as N,$r as O,_r as P,di as Q,Ja as R,li as S,ci as T,Xa as U,pi as V,Ga as W,Ar as X,ui as Y,mi as Z,hi as _,bi as $,vi as aa,wi as ba,$i as ca,_i as da,Si as ea,Ai as fa,Ti as ga,Ii as ha,zi as ia,Ei as ja,Ri as ka,Va as la,ji as ma,Hi as na,Ir as oa,Qt as pa,go as qa,vo as ra,wo as sa};
2900
- //# sourceMappingURL=chunk-KWZ6NMXZ.js.map
2897
+ ${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Qo(e,a){return Ua(e,a,ce,"ORDER BY created_at")}function Zo(e,a,t=50){return Ua(e,a,[...ce,...Pe],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}at();var ze="member:",pr=90,xr="members",gr="tailscale-user-login",ur=400,mr=60*60*1e3;function fr(e){let a=e.scopes.find(t=>t.startsWith(ze));return a?a.slice(ze.length):null}function qa(e,a){if(!e)return null;let t=a.verify(e),r=t?fr(t):null;return t&&r?{rec:t,personId:r}:null}function ii(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${ze}${t.id}`],expiresInDays:pr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var hr=Math.round(Ne/6e4);function br(e){return e==="client"?"Your project":"My work"}function si(e){let a=br(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${We(e.code)}`,` The code works once, for ${hr} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
2898
+ `)}var vr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",wr="Too many machines are waiting for the owner's answer. Try again later.",Fa="That code didn't work. Check it, or ask the person who invited you for a new one.",Ka=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ya(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function yr(e){if(!Ya(e))return null;let a=Ka(e,gr).toLowerCase();return a?a.slice(0,80):null}function kr(e){let a=e.socket?.remoteAddress||"unknown";if(!Ya(e))return a;let t=Ka(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function $r(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function _r(e){return e.identities.map(Ee).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function di(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=kr(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await Q(e,2048);s=b.code,d=$r(b.machine)}catch{}let l=a.codes.redeem(s),c=l?qa(l.token,a.tokens):null;if(await Cr(t,a.minMs??ur),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Fa}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Fa}};let x=yr(e),f=_r(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:vr}};let A=d||"Unnamed machine",y=u.name.slice(0,40),v=Oe(a.root,{title:`New machine for ${y}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${A}". Let it see their own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:xr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:A,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:A}),n(`[member] ${g} paired "${A}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:A,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:wr}})}var de="this machine is not paired",Sr="waiting for the owner to approve this machine";function Ja(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function li(e,a){return a.state==="pending"&&a.cardId?Ja(ge(e,a.cardId)):null}function ci(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=qa(e,a.tokens);if(!o)return{ok:!1,status:401,error:de};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:de};if(a.people&&!a.people().some(c=>c.id===s))return Xa(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:de};if(d.state==="pending"){let c=d.cardId?ge(a.root,d.cardId):null,m=Ja(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:de}}else return{ok:!1,status:403,error:Sr,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=mr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Xa(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function pi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Xa(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function Cr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Ga=["gitlab","github"];function Ar(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Ga.includes(r))throw new Error(`Request status works on ${Ga.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function ui(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function mi(e){let{summary:a}=Z(t=>Ar(t,e?.channel,!!e?.enabled));return{summary:a}}var hi="https://myaccount.google.com/apppasswords";function bi(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function vi(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function wi(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function $i(e){return`${e.name} <${e.from}> via ${e.host}:${e.port}`}async function _i(e,a){return Be({host:e.host,port:e.port,secure:e.secure,user:e.user,password:e.password},{name:e.name,address:e.from},a,{"Auto-Submitted":"auto-generated"})}function Si(e,a){return{to:e,subject:`${a.name}: test mail`,text:[`This is a test mail from ${a.name}.`,"","If it reached you, AgentX can send mail through this sender.","You can ignore it."].join(`
2899
+ `)}}function Ai(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ti(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Ii(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function zi(e,a){if(a){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Tr="https://ntfy.sh";function Ei(e){return{enabled:!!e?.enabled,server:e?.server||Tr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Ri(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}Za();function Va(e){return/^(agent|person):/.test(e)?F(e):`person:${e}`}function ji(e){let a=(e?.projects??[]).filter(t=>t?.id);return a.map(t=>({id:t.id,name:t.name?.trim()||t.id,client:Le(t.id,a),...t.pm?{pm:F(t.pm)}:{},...t.lead?{lead:Va(t.lead)}:{},team:[...new Set((t.team??[]).filter(Boolean).map(F))]})).sort((t,r)=>t.client.localeCompare(r.client)||t.name.localeCompare(r.name)||t.id.localeCompare(r.id))}function Hi(e,a,t){if(!t.lead&&!t.team?.length)return;let r=new Set(Object.keys(e.business?.orgChart||{})),n=new Set((e.people||[]).map(i=>String(i.id))),o={id:a,name:a,client:"",...t.lead?{lead:Va(t.lead)}:{},team:(t.team??[]).map(F)};return Ir([o],r,n)}function Ir(e,a,t){let r=n=>{let o=le(n);return o.kind==="agent"?a.has(o.id)?void 0:`"${o.id}", which is not an agent in business.orgChart`:t.has(o.id)?void 0:`"${o.id}", which is not a person in people`};for(let n of e){if(n.lead){if(le(n.lead).kind!=="person")return`Project ${n.name} is led by "${n.lead}"; a lead is a person (person:<id>), the PM is the agent`;let o=r(n.lead);if(o)return`Project ${n.name} is led by ${o}`}for(let o of n.team){let i=r(o);if(i)return`Project ${n.name} has ${i} in its team`}}}export{ve as a,da as b,ye as c,nt as d,ot as e,it as f,ua as g,mt as h,_n as i,Sn as j,Cn as k,ko as l,Co as m,Ba as n,Yo as o,Jo as p,Rn as q,On as r,It as s,Et as t,ke as u,Dn as v,Mn as w,Rt as x,Bn as y,Un as z,Fn as A,Vo as B,Qo as C,Zo as D,pr as E,xr as F,ii as G,hr as H,br as I,si as J,vr as K,wr as L,yr as M,kr as N,$r as O,_r as P,di as Q,Ja as R,li as S,ci as T,Xa as U,pi as V,Ga as W,Ar as X,ui as Y,mi as Z,hi as _,bi as $,vi as aa,wi as ba,$i as ca,_i as da,Si as ea,Ai as fa,Ti as ga,Ii as ha,zi as ia,Ei as ja,Ri as ka,Va as la,ji as ma,Hi as na,Ir as oa,Qt as pa,go as qa,vo as ra,wo as sa};
2900
+ //# sourceMappingURL=chunk-GCBFLU64.js.map
@@ -1,3 +1,3 @@
1
- import{q as x,s as A}from"./chunk-WDGATQV3.js";import{a as w,e as D}from"./chunk-VQRY4IDI.js";D();var h="guest:",b="guests",P=7,y=365,T=400;function I(e){let t=e.scopes.find(n=>n.startsWith(h));return t?t.slice(h.length):null}function _(e){return`g-${e.toString(36)}-${Math.random().toString(36).slice(2,6)}`}var l=e=>(Array.isArray(e)?e:typeof e=="string"?e.split(","):[]).map(t=>String(t).trim()).filter(Boolean).slice(0,50);function M(e,t){let n=(e.now??Date.now)(),o=String(t.name??"").trim().slice(0,120),s=String(t.guest??"").trim().slice(0,80);if(!o)return{ok:!1,error:'name is required: what you call this grant, e.g. "Support session for company X"'};if(!s)return{ok:!1,error:"guest is required: the other organisation's name"};if(!t.agentId||!e.hasAgent(t.agentId))return{ok:!1,error:`agent must be an agent on this node, got "${t.agentId??""}"`};let a=w.safeParse(t.level??"propose");if(!a.success)return{ok:!1,error:"level must be report, propose or act"};let r=t.days===void 0?P:Number(t.days);if(!Number.isFinite(r)||r<1||r>y)return{ok:!1,error:`days must be between 1 and ${y}`};let d=_(n),{token:u,record:g}=e.tokens.create({name:`guest ${s} (${o})`,scopes:[`${h}${d}`],expiresInDays:Math.ceil(r)}),{code:i,expiresAt:p}=e.codes.create({token:u,tokenId:g.id,name:d}),c={id:d,name:o,guest:s,agentId:t.agentId,folders:l(t.folders),skills:l(t.skills),commands:l(t.commands),level:a.data,state:"pending",tokenId:g.id,createdAt:new Date(n).toISOString(),expiresAt:new Date(n+r*864e5).toISOString(),usage:{turns:0,tokens:0}};return e.guests.add(c),e.guests.log({grant:d,event:"invited",detail:`${s}: ${o}`}),{ok:!0,code:i,codeExpiresAt:p,grant:c}}var j="That code didn't work. Ask the host for a new one.";async function Y(e,t,n){let o=Date.now(),s=n.now??Date.now,a=n.log??(f=>console.log(f)),r=n.limiter.retryAfter(t);if(r>0)return a(`[guests] join refused from ${t}: locked out for ${r}s more`),{status:429,body:{error:"too many attempts",retryAfter:r},retryAfter:r};let d=n.codes.redeem(e.code),u=d?n.tokens.verify(d.token):null,g=u?I(u):null,i=g?n.guests.get(g):null;if(await L(o,n.minMs??T),!d||!u||!i||i.tokenId!==u.id||i.state==="ended")return n.limiter.fail(t),a(`[guests] join failed from ${t}`),{status:401,body:{error:j}};n.limiter.succeed(t);let p=e.node&&typeof e.node=="object"?e.node:{},c=(f,S)=>typeof f=="string"&&f.trim()?f.replace(/\s+/g," ").trim().slice(0,S):void 0,m={id:c(p.id,80),name:c(p.name,80),address:t},$=i.expiresAt.slice(0,10),k=A(n.root,{title:`Guest mesh: ${i.guest} wants to join`,ask:`Let "${m.name??m.id??"a node"}" at ${t} use ${i.agentId} inside "${i.name}" (${i.level}, until ${$})?`,recommend:`Yes if ${i.guest} told you they are joining now. No if you did not expect it.`,if_silent:"discard",raised_by:b},{now:s()});return k.ok?(n.guests.update(i.id,{guestNode:m,cardId:k.card.id}),n.guests.log({grant:i.id,event:"joined",address:t,detail:m.name??m.id}),a(`[guests] ${i.id}: ${i.guest} joined from ${t}; waiting for the owner (card ${k.card.id})`),{status:200,body:{grant:i.id,name:i.name,agentId:i.agentId,level:i.level,expiresAt:i.expiresAt,state:"pending"},token:d.token}):(a(`[guests] ${i.id}: join from ${t} could not raise a card: ${k.error}`),{status:403,body:{error:"The host cannot take a join right now. Try again later."}})}var G="no grant opens this",R="waiting for the host to approve the join",O="the host paused this grant";function N(e,t){let n=e.now??Date.now,o=e.log??(r=>console.log(r));if(t.state==="ended")return t;if(Date.parse(t.expiresAt)<=n())return o(`[guests] ${t.id}: expired`),v({tokens:e.tokens,guests:e.guests,now:n},t.id,"expired")??t;if(t.state!=="pending")return t;let s=t.cardId?x(e.root,t.cardId):null,a=s?s.status==="decided"?s.verdict:s.status==="expired"?"no":null:null;if(a==="yes"){let r=e.guests.update(t.id,{state:"active",approvedAt:new Date(n()).toISOString()})??t;return e.guests.log({grant:t.id,event:"approved",detail:s?.decided_by}),o(`[guests] ${t.id}: join approved`),r}if(a==="no"){let r=s?.status==="expired"?"the host did not answer in time":"the host said no",d=v({tokens:e.tokens,guests:e.guests,now:n},t.id,r)??t;return e.guests.log({grant:t.id,event:"refused",detail:r}),o(`[guests] ${t.id}: join refused: ${r}`),d}return t}function J(e,t){let n=e?t.tokens.verify(e):null,o=n?I(n):null,s=o?t.guests.get(o):null;if(!n||!s||s.tokenId!==n.id)return{ok:!1,status:401,error:G};let a=N(t,s);return a.state==="ended"?{ok:!1,status:401,error:G}:a.state==="pending"?{ok:!1,status:403,error:R,waiting:!0}:a.state==="paused"?{ok:!1,status:403,error:O,paused:!0}:{ok:!0,grant:a}}function C(e){let t=(o,s)=>o.length?o.join(", "):`none named: do not touch ${s} unless the owner's own instructions already allow it for this work`,n=e.level==="report"?"report: read and answer only; change nothing":e.level==="propose"?"propose: you may prepare changes and open a merge request or draft; never merge, deploy or delete":"act: you may act inside the grant without asking";return[`[Guest mesh] You are working for a guest organisation, "${e.guest}", under the grant "${e.name}" that the owner of this node opened.`,`Stay inside it. Folders: ${t(e.folders,"files")}. Skills: ${t(e.skills,"skills")}. Commands: ${t(e.commands,"commands")}. Freedom: ${n}. The grant ends on ${e.expiresAt.slice(0,10)}.`,"Anything outside the grant: say it is not covered and stop. The guest sees only your answers: never reveal other chats, agents, people or files of this node."].join(`
1
+ import{r as x,t as A}from"./chunk-XL7UWG36.js";import{a as w,e as D}from"./chunk-VQRY4IDI.js";D();var h="guest:",b="guests",P=7,y=365,T=400;function I(e){let t=e.scopes.find(n=>n.startsWith(h));return t?t.slice(h.length):null}function _(e){return`g-${e.toString(36)}-${Math.random().toString(36).slice(2,6)}`}var l=e=>(Array.isArray(e)?e:typeof e=="string"?e.split(","):[]).map(t=>String(t).trim()).filter(Boolean).slice(0,50);function M(e,t){let n=(e.now??Date.now)(),o=String(t.name??"").trim().slice(0,120),s=String(t.guest??"").trim().slice(0,80);if(!o)return{ok:!1,error:'name is required: what you call this grant, e.g. "Support session for company X"'};if(!s)return{ok:!1,error:"guest is required: the other organisation's name"};if(!t.agentId||!e.hasAgent(t.agentId))return{ok:!1,error:`agent must be an agent on this node, got "${t.agentId??""}"`};let a=w.safeParse(t.level??"propose");if(!a.success)return{ok:!1,error:"level must be report, propose or act"};let r=t.days===void 0?P:Number(t.days);if(!Number.isFinite(r)||r<1||r>y)return{ok:!1,error:`days must be between 1 and ${y}`};let d=_(n),{token:u,record:g}=e.tokens.create({name:`guest ${s} (${o})`,scopes:[`${h}${d}`],expiresInDays:Math.ceil(r)}),{code:i,expiresAt:p}=e.codes.create({token:u,tokenId:g.id,name:d}),c={id:d,name:o,guest:s,agentId:t.agentId,folders:l(t.folders),skills:l(t.skills),commands:l(t.commands),level:a.data,state:"pending",tokenId:g.id,createdAt:new Date(n).toISOString(),expiresAt:new Date(n+r*864e5).toISOString(),usage:{turns:0,tokens:0}};return e.guests.add(c),e.guests.log({grant:d,event:"invited",detail:`${s}: ${o}`}),{ok:!0,code:i,codeExpiresAt:p,grant:c}}var j="That code didn't work. Ask the host for a new one.";async function Y(e,t,n){let o=Date.now(),s=n.now??Date.now,a=n.log??(f=>console.log(f)),r=n.limiter.retryAfter(t);if(r>0)return a(`[guests] join refused from ${t}: locked out for ${r}s more`),{status:429,body:{error:"too many attempts",retryAfter:r},retryAfter:r};let d=n.codes.redeem(e.code),u=d?n.tokens.verify(d.token):null,g=u?I(u):null,i=g?n.guests.get(g):null;if(await L(o,n.minMs??T),!d||!u||!i||i.tokenId!==u.id||i.state==="ended")return n.limiter.fail(t),a(`[guests] join failed from ${t}`),{status:401,body:{error:j}};n.limiter.succeed(t);let p=e.node&&typeof e.node=="object"?e.node:{},c=(f,S)=>typeof f=="string"&&f.trim()?f.replace(/\s+/g," ").trim().slice(0,S):void 0,m={id:c(p.id,80),name:c(p.name,80),address:t},$=i.expiresAt.slice(0,10),k=A(n.root,{title:`Guest mesh: ${i.guest} wants to join`,ask:`Let "${m.name??m.id??"a node"}" at ${t} use ${i.agentId} inside "${i.name}" (${i.level}, until ${$})?`,recommend:`Yes if ${i.guest} told you they are joining now. No if you did not expect it.`,if_silent:"discard",raised_by:b},{now:s()});return k.ok?(n.guests.update(i.id,{guestNode:m,cardId:k.card.id}),n.guests.log({grant:i.id,event:"joined",address:t,detail:m.name??m.id}),a(`[guests] ${i.id}: ${i.guest} joined from ${t}; waiting for the owner (card ${k.card.id})`),{status:200,body:{grant:i.id,name:i.name,agentId:i.agentId,level:i.level,expiresAt:i.expiresAt,state:"pending"},token:d.token}):(a(`[guests] ${i.id}: join from ${t} could not raise a card: ${k.error}`),{status:403,body:{error:"The host cannot take a join right now. Try again later."}})}var G="no grant opens this",R="waiting for the host to approve the join",O="the host paused this grant";function N(e,t){let n=e.now??Date.now,o=e.log??(r=>console.log(r));if(t.state==="ended")return t;if(Date.parse(t.expiresAt)<=n())return o(`[guests] ${t.id}: expired`),v({tokens:e.tokens,guests:e.guests,now:n},t.id,"expired")??t;if(t.state!=="pending")return t;let s=t.cardId?x(e.root,t.cardId):null,a=s?s.status==="decided"?s.verdict:s.status==="expired"?"no":null:null;if(a==="yes"){let r=e.guests.update(t.id,{state:"active",approvedAt:new Date(n()).toISOString()})??t;return e.guests.log({grant:t.id,event:"approved",detail:s?.decided_by}),o(`[guests] ${t.id}: join approved`),r}if(a==="no"){let r=s?.status==="expired"?"the host did not answer in time":"the host said no",d=v({tokens:e.tokens,guests:e.guests,now:n},t.id,r)??t;return e.guests.log({grant:t.id,event:"refused",detail:r}),o(`[guests] ${t.id}: join refused: ${r}`),d}return t}function J(e,t){let n=e?t.tokens.verify(e):null,o=n?I(n):null,s=o?t.guests.get(o):null;if(!n||!s||s.tokenId!==n.id)return{ok:!1,status:401,error:G};let a=N(t,s);return a.state==="ended"?{ok:!1,status:401,error:G}:a.state==="pending"?{ok:!1,status:403,error:R,waiting:!0}:a.state==="paused"?{ok:!1,status:403,error:O,paused:!0}:{ok:!0,grant:a}}function C(e){let t=(o,s)=>o.length?o.join(", "):`none named: do not touch ${s} unless the owner's own instructions already allow it for this work`,n=e.level==="report"?"report: read and answer only; change nothing":e.level==="propose"?"propose: you may prepare changes and open a merge request or draft; never merge, deploy or delete":"act: you may act inside the grant without asking";return[`[Guest mesh] You are working for a guest organisation, "${e.guest}", under the grant "${e.name}" that the owner of this node opened.`,`Stay inside it. Folders: ${t(e.folders,"files")}. Skills: ${t(e.skills,"skills")}. Commands: ${t(e.commands,"commands")}. Freedom: ${n}. The grant ends on ${e.expiresAt.slice(0,10)}.`,"Anything outside the grant: say it is not covered and stop. The guest sees only your answers: never reveal other chats, agents, people or files of this node."].join(`
2
2
  `)}function q(e,t){return{agentId:e.agentId,message:t,context:{channel:"guest",chatId:`guest:${e.id}`,sender:`guest:${e.guest}`},systemPromptAppend:C(e),...e.level==="act"?{}:{autonomy:e.level}}}function B(e,t){let n=e.guests.get(t);if(!n||n.state!=="active")return null;let o=e.guests.update(t,{state:"paused",pausedAt:new Date((e.now??Date.now)()).toISOString()});return e.guests.log({grant:t,event:"paused"}),o}function U(e,t){let n=e.guests.get(t);if(!n||n.state!=="paused")return null;let o=e.guests.update(t,{state:"active",pausedAt:void 0});return e.guests.log({grant:t,event:"resumed"}),o}function v(e,t,n="ended by the host"){let o=e.guests.get(t);if(!o||o.state==="ended")return null;e.tokens.revoke(o.tokenId);let s=e.guests.update(t,{state:"ended",endedAt:new Date((e.now??Date.now)()).toISOString(),endedReason:n});return e.guests.log({grant:t,event:n==="expired"?"expired":"ended",detail:n}),s}function X(e,t,n){let o=e.guests.get(t);if(!o||o.state==="ended")return{ok:!1,error:`no open grant "${t}"`};let s={};if(n.folders!==void 0&&(s.folders=l(n.folders)),n.skills!==void 0&&(s.skills=l(n.skills)),n.commands!==void 0&&(s.commands=l(n.commands)),n.level!==void 0){let u=w.safeParse(n.level);if(!u.success)return{ok:!1,error:"level must be report, propose or act"};s.level=u.data}if(n.days!==void 0){let u=Number(n.days);if(!Number.isFinite(u)||u<1||u>y)return{ok:!1,error:`days must be between 1 and ${y}`};s.expiresAt=new Date((e.now??Date.now)()+u*864e5).toISOString()}let a=e.guests.update(t,s),r=["report","propose","act"],d=s.level&&r.indexOf(s.level)>r.indexOf(o.level)||s.folders&&s.folders.length>o.folders.length||s.skills&&s.skills.length>o.skills.length||s.commands&&s.commands.length>o.commands.length||s.expiresAt&&s.expiresAt>o.expiresAt;return e.guests.log({grant:t,event:d?"widened":"narrowed",detail:Object.keys(s).join(", ")}),{ok:!0,grant:a}}function W(e){return{grant:e.id,name:e.name,agentId:e.agentId,level:e.level,folders:e.folders,skills:e.skills,commands:e.commands,state:e.state,expiresAt:e.expiresAt,usage:e.usage}}async function L(e,t){let n=e+t-Date.now();n>0&&await new Promise(o=>setTimeout(o,n))}export{h as a,b,P as c,y as d,I as e,_ as f,M as g,j as h,Y as i,G as j,R as k,O as l,N as m,J as n,C as o,q as p,B as q,U as r,v as s,X as t,W as u};
3
- //# sourceMappingURL=chunk-S6YN3IBM.js.map
3
+ //# sourceMappingURL=chunk-GJOKXP5D.js.map