agentix-cli 0.199.0 → 0.200.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 (136) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/AnswerView.swift +11 -2
  2. package/apps/mac-voice/Sources/AgentXVoice/Artifacts.swift +8 -0
  3. package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +12 -1
  4. package/dist/{App-HGCD735J.js → App-AUKNCAVD.js} +2 -2
  5. package/dist/{ChatApp-VVBGBDKU.js → ChatApp-KYQIQZ6Q.js} +2 -2
  6. package/dist/{absorb-eval-2XT7XBH7.js → absorb-eval-TJN5WUYZ.js} +2 -2
  7. package/dist/{adapter-ZGEMORWD.js → adapter-VLNSNP6C.js} +2 -2
  8. package/dist/{agent-4IF72I6E.js → agent-KXHSNUNY.js} +2 -2
  9. package/dist/{board-dashboard-2P77CUM3.js → board-dashboard-QKOJEHXS.js} +453 -372
  10. package/dist/board-dashboard-QKOJEHXS.js.map +1 -0
  11. package/dist/{chunk-BBXB7X25.js → chunk-25U5MNNF.js} +2 -2
  12. package/dist/{chunk-SPZXOCN5.js → chunk-3I3TBJZV.js} +6 -6
  13. package/dist/{chunk-3DAHVUJH.js → chunk-4MJOSO7T.js} +2 -2
  14. package/dist/{chunk-K3QWXVLV.js → chunk-64UGFZPX.js} +2 -2
  15. package/dist/{chunk-OCZVJANH.js → chunk-6QVUXEVK.js} +2 -2
  16. package/dist/{chunk-F6UAAQSU.js → chunk-6RJ7ERGC.js} +2 -2
  17. package/dist/{chunk-YU2JJIQH.js → chunk-7VHE7WLJ.js} +3 -3
  18. package/dist/{chunk-UU7A5DNY.js → chunk-AHJ6FEHW.js} +2 -2
  19. package/dist/{chunk-K2JE5XR4.js → chunk-AKDJGDLN.js} +2 -2
  20. package/dist/{chunk-3SWDVBGA.js → chunk-APULKE2J.js} +2 -2
  21. package/dist/{chunk-XZFBOXFK.js → chunk-BNTN3LKN.js} +2 -2
  22. package/dist/{chunk-I4U2ELEX.js → chunk-EM72LW2F.js} +58 -57
  23. package/dist/chunk-EM72LW2F.js.map +1 -0
  24. package/dist/{chunk-XTBFWRM3.js → chunk-J4AMQF7D.js} +2 -2
  25. package/dist/{chunk-5QK3U7R6.js → chunk-K34LYNGN.js} +2 -2
  26. package/dist/{chunk-L3FCDIJT.js → chunk-KE4SLJTC.js} +2 -2
  27. package/dist/{chunk-DECMCWGN.js → chunk-KOZSBUXJ.js} +2 -2
  28. package/dist/{chunk-7SKUXUIX.js → chunk-LBIU3OWW.js} +5 -5
  29. package/dist/{chunk-RE6N3TRQ.js → chunk-M6EQBW2F.js} +2 -2
  30. package/dist/{chunk-JAS75QDT.js → chunk-O672XL5L.js} +2 -2
  31. package/dist/{chunk-6QU5YWOE.js → chunk-ORAQRC6A.js} +2 -2
  32. package/dist/{chunk-KWU4EOWC.js → chunk-QISI5WM2.js} +2 -2
  33. package/dist/{chunk-5NE26NUO.js → chunk-QMFNIUW7.js} +2 -2
  34. package/dist/{chunk-UPRACUXY.js → chunk-QTOOFB4N.js} +2 -2
  35. package/dist/{chunk-UPRACUXY.js.map → chunk-QTOOFB4N.js.map} +1 -1
  36. package/dist/{chunk-OWL6JA6W.js → chunk-R5TCPLWF.js} +2 -2
  37. package/dist/{chunk-DUVPXHDO.js → chunk-RW2JLP5P.js} +2 -2
  38. package/dist/{chunk-3DX7CKKW.js → chunk-SXL6R3HH.js} +2 -2
  39. package/dist/{chunk-5VRN6JP7.js → chunk-TBSPEM7I.js} +2 -2
  40. package/dist/{chunk-UY25GSQ3.js → chunk-UBLPD6DK.js} +2 -2
  41. package/dist/{chunk-T7HWU7O4.js → chunk-W764F42W.js} +2 -2
  42. package/dist/cli.js +1 -1
  43. package/dist/{client-PNZ3LL72.js → client-FXU56BIM.js} +2 -2
  44. package/dist/{config-HOKADOXX.js → config-IOQKEH47.js} +2 -2
  45. package/dist/{config-mutate-ZR7EM4IB.js → config-mutate-633Q77K3.js} +2 -2
  46. package/dist/{config-mutator-NWTMXBEY.js → config-mutator-LRZHJ3UN.js} +2 -2
  47. package/dist/{contributions-NBKZD7QW.js → contributions-3AE43OSI.js} +2 -2
  48. package/dist/{doctor-K6SPV3GU.js → doctor-KCRL67QL.js} +2 -2
  49. package/dist/{follow-up-tool-NPC3JLOA.js → follow-up-tool-WLDWTZRW.js} +2 -2
  50. package/dist/{hub-NKGZO574.js → hub-PG4OFRIQ.js} +2 -2
  51. package/dist/index.d.ts +31 -0
  52. package/dist/index.js +1 -1
  53. package/dist/{program-DYFXKKJE.js → program-QHE7PH65.js} +201 -202
  54. package/dist/program-QHE7PH65.js.map +1 -0
  55. package/dist/{promote-HIFKFRC4.js → promote-DLM7N6V2.js} +2 -2
  56. package/dist/{query-VXE4AREX.js → query-TBQGAIZG.js} +2 -2
  57. package/dist/{query-settings-NC7FOIRC.js → query-settings-U6XNO5V4.js} +2 -2
  58. package/dist/{registry-NGRLHM7L.js → registry-DGGJJOVA.js} +2 -2
  59. package/dist/{request-planner-I65SRAJI.js → request-planner-YQ4RTZNU.js} +2 -2
  60. package/dist/{review-candidates-7KV34XZR.js → review-candidates-OE5HDVWI.js} +2 -2
  61. package/dist/{routing-MLOSXPVH.js → routing-RAG6I37K.js} +2 -2
  62. package/dist/schedule-tool-O5FJXSKO.js +2 -0
  63. package/dist/{scheduler-WEOQLNIF.js → scheduler-TGP4B5KZ.js} +2 -2
  64. package/dist/{seat-66LQTUIR.js → seat-74G2KLZQ.js} +2 -2
  65. package/dist/{select-JV425OUL.js → select-P7565K5D.js} +2 -2
  66. package/dist/{set-enabled-DWL2MKVS.js → set-enabled-DE3TKKEK.js} +2 -2
  67. package/dist/{sprint-tool-CDO3HLLT.js → sprint-tool-CK3SD4NZ.js} +2 -2
  68. package/dist/{tool-W763BDXL.js → tool-DWKCESVE.js} +2 -2
  69. package/dist/{tool-7EFJJM2A.js → tool-X6DAR3KL.js} +2 -2
  70. package/dist/{tool-U3WQCSUN.js → tool-XGB3PMXA.js} +2 -2
  71. package/dist/{wiki-MIEXBQ5H.js → wiki-E45S2K6F.js} +2 -2
  72. package/dist/wiki-enrich-LREINNTK.js +2 -0
  73. package/package.json +1 -1
  74. package/dist/board-dashboard-2P77CUM3.js.map +0 -1
  75. package/dist/chunk-I4U2ELEX.js.map +0 -1
  76. package/dist/program-DYFXKKJE.js.map +0 -1
  77. package/dist/schedule-tool-7DCB7KJP.js +0 -2
  78. package/dist/wiki-enrich-K4HHTRZN.js +0 -2
  79. /package/dist/{App-HGCD735J.js.map → App-AUKNCAVD.js.map} +0 -0
  80. /package/dist/{ChatApp-VVBGBDKU.js.map → ChatApp-KYQIQZ6Q.js.map} +0 -0
  81. /package/dist/{absorb-eval-2XT7XBH7.js.map → absorb-eval-TJN5WUYZ.js.map} +0 -0
  82. /package/dist/{adapter-ZGEMORWD.js.map → adapter-VLNSNP6C.js.map} +0 -0
  83. /package/dist/{agent-4IF72I6E.js.map → agent-KXHSNUNY.js.map} +0 -0
  84. /package/dist/{chunk-BBXB7X25.js.map → chunk-25U5MNNF.js.map} +0 -0
  85. /package/dist/{chunk-SPZXOCN5.js.map → chunk-3I3TBJZV.js.map} +0 -0
  86. /package/dist/{chunk-3DAHVUJH.js.map → chunk-4MJOSO7T.js.map} +0 -0
  87. /package/dist/{chunk-K3QWXVLV.js.map → chunk-64UGFZPX.js.map} +0 -0
  88. /package/dist/{chunk-OCZVJANH.js.map → chunk-6QVUXEVK.js.map} +0 -0
  89. /package/dist/{chunk-F6UAAQSU.js.map → chunk-6RJ7ERGC.js.map} +0 -0
  90. /package/dist/{chunk-YU2JJIQH.js.map → chunk-7VHE7WLJ.js.map} +0 -0
  91. /package/dist/{chunk-UU7A5DNY.js.map → chunk-AHJ6FEHW.js.map} +0 -0
  92. /package/dist/{chunk-K2JE5XR4.js.map → chunk-AKDJGDLN.js.map} +0 -0
  93. /package/dist/{chunk-3SWDVBGA.js.map → chunk-APULKE2J.js.map} +0 -0
  94. /package/dist/{chunk-XZFBOXFK.js.map → chunk-BNTN3LKN.js.map} +0 -0
  95. /package/dist/{chunk-XTBFWRM3.js.map → chunk-J4AMQF7D.js.map} +0 -0
  96. /package/dist/{chunk-5QK3U7R6.js.map → chunk-K34LYNGN.js.map} +0 -0
  97. /package/dist/{chunk-L3FCDIJT.js.map → chunk-KE4SLJTC.js.map} +0 -0
  98. /package/dist/{chunk-DECMCWGN.js.map → chunk-KOZSBUXJ.js.map} +0 -0
  99. /package/dist/{chunk-7SKUXUIX.js.map → chunk-LBIU3OWW.js.map} +0 -0
  100. /package/dist/{chunk-RE6N3TRQ.js.map → chunk-M6EQBW2F.js.map} +0 -0
  101. /package/dist/{chunk-JAS75QDT.js.map → chunk-O672XL5L.js.map} +0 -0
  102. /package/dist/{chunk-6QU5YWOE.js.map → chunk-ORAQRC6A.js.map} +0 -0
  103. /package/dist/{chunk-KWU4EOWC.js.map → chunk-QISI5WM2.js.map} +0 -0
  104. /package/dist/{chunk-5NE26NUO.js.map → chunk-QMFNIUW7.js.map} +0 -0
  105. /package/dist/{chunk-OWL6JA6W.js.map → chunk-R5TCPLWF.js.map} +0 -0
  106. /package/dist/{chunk-DUVPXHDO.js.map → chunk-RW2JLP5P.js.map} +0 -0
  107. /package/dist/{chunk-3DX7CKKW.js.map → chunk-SXL6R3HH.js.map} +0 -0
  108. /package/dist/{chunk-5VRN6JP7.js.map → chunk-TBSPEM7I.js.map} +0 -0
  109. /package/dist/{chunk-UY25GSQ3.js.map → chunk-UBLPD6DK.js.map} +0 -0
  110. /package/dist/{chunk-T7HWU7O4.js.map → chunk-W764F42W.js.map} +0 -0
  111. /package/dist/{client-PNZ3LL72.js.map → client-FXU56BIM.js.map} +0 -0
  112. /package/dist/{config-HOKADOXX.js.map → config-IOQKEH47.js.map} +0 -0
  113. /package/dist/{config-mutate-ZR7EM4IB.js.map → config-mutate-633Q77K3.js.map} +0 -0
  114. /package/dist/{config-mutator-NWTMXBEY.js.map → config-mutator-LRZHJ3UN.js.map} +0 -0
  115. /package/dist/{contributions-NBKZD7QW.js.map → contributions-3AE43OSI.js.map} +0 -0
  116. /package/dist/{doctor-K6SPV3GU.js.map → doctor-KCRL67QL.js.map} +0 -0
  117. /package/dist/{follow-up-tool-NPC3JLOA.js.map → follow-up-tool-WLDWTZRW.js.map} +0 -0
  118. /package/dist/{hub-NKGZO574.js.map → hub-PG4OFRIQ.js.map} +0 -0
  119. /package/dist/{promote-HIFKFRC4.js.map → promote-DLM7N6V2.js.map} +0 -0
  120. /package/dist/{query-VXE4AREX.js.map → query-TBQGAIZG.js.map} +0 -0
  121. /package/dist/{query-settings-NC7FOIRC.js.map → query-settings-U6XNO5V4.js.map} +0 -0
  122. /package/dist/{registry-NGRLHM7L.js.map → registry-DGGJJOVA.js.map} +0 -0
  123. /package/dist/{request-planner-I65SRAJI.js.map → request-planner-YQ4RTZNU.js.map} +0 -0
  124. /package/dist/{review-candidates-7KV34XZR.js.map → review-candidates-OE5HDVWI.js.map} +0 -0
  125. /package/dist/{routing-MLOSXPVH.js.map → routing-RAG6I37K.js.map} +0 -0
  126. /package/dist/{schedule-tool-7DCB7KJP.js.map → schedule-tool-O5FJXSKO.js.map} +0 -0
  127. /package/dist/{scheduler-WEOQLNIF.js.map → scheduler-TGP4B5KZ.js.map} +0 -0
  128. /package/dist/{seat-66LQTUIR.js.map → seat-74G2KLZQ.js.map} +0 -0
  129. /package/dist/{select-JV425OUL.js.map → select-P7565K5D.js.map} +0 -0
  130. /package/dist/{set-enabled-DWL2MKVS.js.map → set-enabled-DE3TKKEK.js.map} +0 -0
  131. /package/dist/{sprint-tool-CDO3HLLT.js.map → sprint-tool-CK3SD4NZ.js.map} +0 -0
  132. /package/dist/{tool-W763BDXL.js.map → tool-DWKCESVE.js.map} +0 -0
  133. /package/dist/{tool-7EFJJM2A.js.map → tool-X6DAR3KL.js.map} +0 -0
  134. /package/dist/{tool-U3WQCSUN.js.map → tool-XGB3PMXA.js.map} +0 -0
  135. /package/dist/{wiki-MIEXBQ5H.js.map → wiki-E45S2K6F.js.map} +0 -0
  136. /package/dist/{wiki-enrich-K4HHTRZN.js.map → wiki-enrich-LREINNTK.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as Ge,b as k,c as D,d as Ve,e as ue,f as me,g as L,h as fe,i as N,j,n as Qe,o as Ze,p as ea,q as aa}from"./chunk-EFGAPAYZ.js";import{e as Je,i as Xe}from"./chunk-QAWKN2N4.js";import{b as ge}from"./chunk-DODL5POT.js";import{a as Q,b as Ye}from"./chunk-3DAHVUJH.js";import{Ja as Be,Ka as Ue,La as Fe,Na as qe,ja as $,oa as We,xb as Ke}from"./chunk-K2JE5XR4.js";import{a as G}from"./chunk-IMLAPB7G.js";import{b as V}from"./chunk-2VDO2HEK.js";import{c as He,e as Le}from"./chunk-LQE73AZR.js";import{b as je}from"./chunk-MRIVENBY.js";import{q as xe,s as Ne}from"./chunk-XPZSEDE3.js";import{ga as X}from"./chunk-5QK3U7R6.js";import{b as pe}from"./chunk-7AB3QUGH.js";import{a as q,b as J}from"./chunk-DUVPXHDO.js";import{a as Me}from"./chunk-OWL6JA6W.js";import{c as Re,d as Oe}from"./chunk-OWNQ2FD4.js";import{a as De}from"./chunk-ROLSSYXE.js";import{a as Pe}from"./chunk-QUFIUXMQ.js";import{Ab as le,Db as F,Eb as Ee,Ob as ce,Za as ze,eb as Qa,ja as de,ka as Ie,ua as Va}from"./chunk-UPRACUXY.js";import{existsSync as K,readFileSync as la,writeFileSync as ca,appendFileSync as it,mkdirSync as st}from"fs";import{dirname as dt,resolve as M}from"path";import{fileURLToPath as lt}from"url";import{hostname as ct}from"os";import{spawn as pt}from"child_process";var he=`:root {
1
+ import{a as Ve,b as k,c as D,d as Qe,e as ue,f as me,g as L,h as fe,i as N,j,n as Ze,o as ea,p as aa,q as ta}from"./chunk-EFGAPAYZ.js";import{e as Xe,i as Ge}from"./chunk-QAWKN2N4.js";import{b as ge}from"./chunk-DODL5POT.js";import{a as Q,b as Je}from"./chunk-4MJOSO7T.js";import{Ja as Ue,Ka as Fe,La as qe,Na as Ke,ja as _,oa as Be,xb as Ye}from"./chunk-AKDJGDLN.js";import{a as G}from"./chunk-IMLAPB7G.js";import{k as je}from"./chunk-KOZSBUXJ.js";import{b as V}from"./chunk-2VDO2HEK.js";import{c as He,e as Le}from"./chunk-LQE73AZR.js";import{b as We}from"./chunk-MRIVENBY.js";import{q as xe,s as Ne}from"./chunk-XPZSEDE3.js";import{ga as X}from"./chunk-K34LYNGN.js";import{b as pe}from"./chunk-7AB3QUGH.js";import{a as q,b as J}from"./chunk-RW2JLP5P.js";import{a as Me}from"./chunk-R5TCPLWF.js";import{c as Re,d as Oe}from"./chunk-OWNQ2FD4.js";import{a as De}from"./chunk-ROLSSYXE.js";import{a as Pe}from"./chunk-QUFIUXMQ.js";import{Ab as le,Db as F,Eb as Ee,Ob as ce,Za as ze,eb as Za,ja as de,ka as Ie,ua as Qa}from"./chunk-QTOOFB4N.js";import{existsSync as K,readFileSync as ca,writeFileSync as pa,appendFileSync as st,mkdirSync as dt}from"fs";import{dirname as lt,resolve as M}from"path";import{fileURLToPath as ct}from"url";import{hostname as pt}from"os";import{spawn as xt}from"child_process";var he=`:root {
2
2
  /* --- Brand (agentina) --------------------------------------------- */
3
3
  --ax-blue: #2979FF;
4
4
  --ax-blue-d: #1B5FD9;
@@ -1608,7 +1608,7 @@ textarea.ax-builder__inp { min-height: 80px; line-height: 1.5; resize: vertical;
1608
1608
  .ax-log-head, .ax-log-row { grid-template-columns: 8px 80px 1fr auto; }
1609
1609
  .ax-log-head span:nth-child(3), .ax-log-row .ax-who { display: none; }
1610
1610
  .ax-grid-2, .ax-grid-3 { grid-template-columns: 1fr; }
1611
- }`;var ta=`
1611
+ }`;var ra=`
1612
1612
  .ax-as-dock{position:fixed;bottom:0;left:50%;transform:translateX(-50%);z-index:59;
1613
1613
  display:flex;flex-direction:column;align-items:center;
1614
1614
  width:min(620px,calc(100vw - 36px));transition:transform 160ms ease}
@@ -1720,7 +1720,7 @@ body.ax-as-open{padding-right:var(--ax-as-w)}
1720
1720
  .ax-as__foot textarea{flex:1;resize:none;font:inherit;font-size:13px;padding:8px 10px;
1721
1721
  min-height:38px;max-height:140px;border-radius:var(--ax-radius-sm);
1722
1722
  border:var(--ax-border-w) solid var(--ax-border-2);background:var(--ax-bg);color:var(--ax-text)}
1723
- `,ra=`
1723
+ `,na=`
1724
1724
  <div class="ax-as-dock" id="ax-as-dock">
1725
1725
  <button class="ax-as-dock__grip" id="ax-as-bar-toggle" type="button"
1726
1726
  aria-expanded="true" aria-controls="ax-as-bar" title="Hide the composer"></button>
@@ -1751,7 +1751,7 @@ body.ax-as-open{padding-right:var(--ax-as-w)}
1751
1751
  <div class="ax-as__log" id="ax-as-log">
1752
1752
  <p class="ax-as__empty">Ask about what is on this page. What you are looking at &mdash; the page, its filters and the rows in view &mdash; goes with the question.</p>
1753
1753
  </div>
1754
- </aside>`,na=String.raw`
1754
+ </aside>`,oa=String.raw`
1755
1755
  (function(){
1756
1756
  const $=id=>document.getElementById(id);
1757
1757
  const panel=$('ax-as'), handle=$('ax-as-handle');
@@ -1993,50 +1993,50 @@ if(threadId&&!userHid()&&$('ax-as-log').querySelector('.ax-as__pending'))open(tr
1993
1993
  });
1994
1994
  loadHistory();
1995
1995
  })();
1996
- `;function oa(e){return"globalThis.__axBind=globalThis.__axBind||((n,f)=>{globalThis[f.name]=f;globalThis[n]=f;return f});"+Object.entries(e).map(([t,r])=>`const ${t}=globalThis.__axBind(${JSON.stringify(t)},${r.toString()});`).join("")}function ve(e){let a=`${he}
1996
+ `;function ia(e){return"globalThis.__axBind=globalThis.__axBind||((n,f)=>{globalThis[f.name]=f;globalThis[n]=f;return f});"+Object.entries(e).map(([t,r])=>`const ${t}=globalThis.__axBind(${JSON.stringify(t)},${r.toString()});`).join("")}function ve(e){let a=`${he}
1997
1997
  ${be}
1998
- ${Ue}
1999
- ${ta}${e.css?`
2000
- `+e.css:""}`,t=e.customHeader??(e.activeTab==="custom"?"":qe({activeTab:e.activeTab,subtitle:e.subtitle,subheader:e.subheader,peers:e.peers,currentPeerId:e.currentPeerId})),r=e.noMain?e.body:`<main>${e.body}</main>`;return`<!DOCTYPE html>
1998
+ ${Fe}
1999
+ ${ra}${e.css?`
2000
+ `+e.css:""}`,t=e.customHeader??(e.activeTab==="custom"?"":Ke({activeTab:e.activeTab,subtitle:e.subtitle,subheader:e.subheader,peers:e.peers,currentPeerId:e.currentPeerId})),r=e.noMain?e.body:`<main>${e.body}</main>`;return`<!DOCTYPE html>
2001
2001
  <html lang="en">
2002
2002
  <head>
2003
2003
  <meta charset="utf-8">
2004
2004
  <meta name="viewport" content="width=device-width, initial-scale=1">
2005
- <title>${et(e.title)}</title>
2006
- ${Be}
2005
+ <title>${at(e.title)}</title>
2006
+ ${Ue}
2007
2007
  ${e.headExtras||""}
2008
2008
  <style>${a}</style>
2009
2009
  </head>
2010
2010
  <body>
2011
2011
  ${t}
2012
2012
  ${r}
2013
- ${e.noAssistant?"":ra}
2014
- ${e.localToken?`<script>window.AX_LOCAL_TOKEN = ${Za(e.localToken)};</script>`:""}
2015
- ${Fe}
2013
+ ${e.noAssistant?"":na}
2014
+ ${e.localToken?`<script>window.AX_LOCAL_TOKEN = ${et(e.localToken)};</script>`:""}
2015
+ ${qe}
2016
2016
  ${e.scripts||""}
2017
- ${e.noAssistant?"":`<script>${oa({markdownToHtml:G})}${na}</script>`}
2017
+ ${e.noAssistant?"":`<script>${ia({markdownToHtml:G})}${oa}</script>`}
2018
2018
  </body>
2019
- </html>`}function Za(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function et(e){return String(e||"").replace(/[<>&]/g,a=>({"<":"&lt;",">":"&gt;","&":"&amp;"})[a])}function Z(e,a={}){let t=["ax-btn",a.primary?"ax-btn--primary":"",a.ghost?"ax-btn--ghost":"",a.danger?"ax-btn--danger":"",a.extraClass||""].filter(Boolean).join(" ");return`<button ${[`type="${a.type||"button"}"`,`class="${t}"`,a.id?`id="${$(a.id)}"`:"",a.disabled?"disabled":"",a.onclick?`onclick="${$(a.onclick)}"`:""].filter(Boolean).join(" ")}>${$(e)}</button>`}function z(e){let a=`<label>${$(e.label)}${e.hint?` <span class="ax-hint">${e.hint}</span>`:""}</label>`,t="",r=[`name="${$(e.name)}"`,e.required?"required":"",e.readonly?"readonly":"",e.placeholder?`placeholder="${$(e.placeholder)}"`:"",e.extraAttrs||""].filter(Boolean).join(" ");if(e.type==="textarea")t=`<textarea ${r} rows="${e.rows||3}">${$(e.value||"")}</textarea>`;else if(e.type==="select"&&e.options){let n=e.options.map(o=>`<option value="${$(o.value)}"${o.selected?" selected":""}>${$(o.label)}</option>`).join("");t=`<select ${r}>${n}</select>`}else t=`<input type="${e.type||"text"}" ${r}`+(e.value!==void 0?` value="${$(e.value)}"`:"")+(e.pattern?` pattern="${$(e.pattern)}"`:"")+" />";return`<div class="ax-field">${a}${t}</div>`}function ee(e){return`<div class="ax-row">${e.join("")}</div>`}function W(e,a,t){return`<section class="ax-step">
2020
- <div class="ax-step__head"><span class="ax-step__num">${$(String(e))}</span>${$(a)}</div>
2019
+ </html>`}function et(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function at(e){return String(e||"").replace(/[<>&]/g,a=>({"<":"&lt;",">":"&gt;","&":"&amp;"})[a])}function Z(e,a={}){let t=["ax-btn",a.primary?"ax-btn--primary":"",a.ghost?"ax-btn--ghost":"",a.danger?"ax-btn--danger":"",a.extraClass||""].filter(Boolean).join(" ");return`<button ${[`type="${a.type||"button"}"`,`class="${t}"`,a.id?`id="${_(a.id)}"`:"",a.disabled?"disabled":"",a.onclick?`onclick="${_(a.onclick)}"`:""].filter(Boolean).join(" ")}>${_(e)}</button>`}function z(e){let a=`<label>${_(e.label)}${e.hint?` <span class="ax-hint">${e.hint}</span>`:""}</label>`,t="",r=[`name="${_(e.name)}"`,e.required?"required":"",e.readonly?"readonly":"",e.placeholder?`placeholder="${_(e.placeholder)}"`:"",e.extraAttrs||""].filter(Boolean).join(" ");if(e.type==="textarea")t=`<textarea ${r} rows="${e.rows||3}">${_(e.value||"")}</textarea>`;else if(e.type==="select"&&e.options){let n=e.options.map(o=>`<option value="${_(o.value)}"${o.selected?" selected":""}>${_(o.label)}</option>`).join("");t=`<select ${r}>${n}</select>`}else t=`<input type="${e.type||"text"}" ${r}`+(e.value!==void 0?` value="${_(e.value)}"`:"")+(e.pattern?` pattern="${_(e.pattern)}"`:"")+" />";return`<div class="ax-field">${a}${t}</div>`}function ee(e){return`<div class="ax-row">${e.join("")}</div>`}function W(e,a,t){return`<section class="ax-step">
2020
+ <div class="ax-step__head"><span class="ax-step__num">${_(String(e))}</span>${_(a)}</div>
2021
2021
  ${t}
2022
- </section>`}function at(e){return`<div class="ax-page-head">
2023
- ${e.kicker?`<div class="ax-kicker">${$(e.kicker)}</div>`:""}
2024
- <h1>${$(e.title)}</h1>
2022
+ </section>`}function tt(e){return`<div class="ax-page-head">
2023
+ ${e.kicker?`<div class="ax-kicker">${_(e.kicker)}</div>`:""}
2024
+ <h1>${_(e.title)}</h1>
2025
2025
  ${e.lead?`<p class="ax-lead">${e.lead}</p>`:""}
2026
- </div>`}function ia(e){return`<div class="ax-health-card">
2026
+ </div>`}function sa(e){return`<div class="ax-health-card">
2027
2027
  <div class="ax-hc-dot ax-hc-dot--${e.kind||"off"}"></div>
2028
2028
  <div class="ax-hc-txt">
2029
- <div class="ax-hc-num">${$(e.num)}</div>
2030
- <div class="ax-hc-lbl">${$(e.label)}</div>
2029
+ <div class="ax-hc-num">${_(e.num)}</div>
2030
+ <div class="ax-hc-lbl">${_(e.label)}</div>
2031
2031
  </div>
2032
- </div>`}function tt(e){return`<div class="ax-health-strip">${e.map(ia).join("")}</div>`}function rt(e){return`<div class="ax-section-head">
2032
+ </div>`}function rt(e){return`<div class="ax-health-strip">${e.map(sa).join("")}</div>`}function nt(e){return`<div class="ax-section-head">
2033
2033
  <div class="ax-section-head__icon">${e.icon}</div>
2034
2034
  <div class="ax-section-head__text">
2035
- <h2>${$(e.title)}</h2>
2036
- ${e.lead?`<p class="ax-lead">${$(e.lead)}</p>`:""}
2035
+ <h2>${_(e.title)}</h2>
2036
+ ${e.lead?`<p class="ax-lead">${_(e.lead)}</p>`:""}
2037
2037
  </div>
2038
2038
  ${e.actionHtml||""}
2039
- </div>`}function sa(e,a){let t=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
2039
+ </div>`}function da(e,a){let t=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
2040
2040
  <div class="ax-topbar__left">
2041
2041
  <div class="ax-brand">
2042
2042
  <span class="ax-brand__mark">AX</span>
@@ -2061,7 +2061,7 @@ ${e.noAssistant?"":`<script>${oa({markdownToHtml:G})}${na}</script>`}
2061
2061
  `),s=W(4,"Anthropic API key",z({name:"anthropicApiKey",label:"API key",hint:"(optional \u2014 skip if you're using Claude Code)",type:"password",placeholder:"sk-ant-\u2026",extraAttrs:'autocomplete="off"'})+`<div class="ax-hint-block">
2062
2062
  The key is stored in <code>.env</code> as <code>ANTHROPIC_API_KEY</code> and used to authenticate requests to Anthropic. Keep it private.
2063
2063
  </div>`),d=e.configExists?`<div class="ax-banner">Existing install: <b>${e.agentCount}</b> agent(s), <b>${e.channelCount}</b> channel(s) already configured. This wizard will add to it.</div>`:"",l=`<div class="ax-wizard">
2064
- <h1 class="ax-wizard__h1">${$(t)}</h1>
2064
+ <h1 class="ax-wizard__h1">${_(t)}</h1>
2065
2065
  <p class="ax-wizard__lead">Fill in the basics below. We'll write <code>agentx.json</code>, set up a folder for your first agent, and point you at the next step.</p>
2066
2066
 
2067
2067
  ${d}
@@ -2078,7 +2078,7 @@ ${e.noAssistant?"":`<script>${oa({markdownToHtml:G})}${na}</script>`}
2078
2078
  ${Z("Skip, I'll do it later",{onclick:`window.location.href='${pe}#page=live'`})}
2079
2079
  </footer>
2080
2080
  </form>
2081
- </div>`;return ve({title:"AgentX \u2014 Setup",activeTab:"custom",subtitle:"Setup",customHeader:r,noMain:!0,noAssistant:!0,body:l,css:nt,scripts:ot})}var nt=`
2081
+ </div>`;return ve({title:"AgentX \u2014 Setup",activeTab:"custom",subtitle:"Setup",customHeader:r,noMain:!0,noAssistant:!0,body:l,css:ot,scripts:it})}var ot=`
2082
2082
  /* Pre-dashboard topbar variant \u2014 no tab nav, the pills are the only chrome. */
2083
2083
  .ax-topbar__right a.ax-skip {
2084
2084
  padding: 4px 10px; border: 1px solid var(--ax-border-2); border-radius: 4px;
@@ -2135,7 +2135,7 @@ ${e.noAssistant?"":`<script>${oa({markdownToHtml:G})}${na}</script>`}
2135
2135
  .ax-next-steps code { background: var(--ax-surface-2); padding: 1px 6px; border-radius: 3px; color: var(--ax-text); font-family: var(--ax-mono); font-size: var(--ax-fs-sm); }
2136
2136
  .ax-startd { margin-top: 14px; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
2137
2137
  .ax-startd__status { color: var(--ax-text-2); font-size: var(--ax-fs-sm); }
2138
- .ax-startd__status a { color: var(--ax-accent); }`,ot=`<script>
2138
+ .ax-startd__status a { color: var(--ax-accent); }`,it=`<script>
2139
2139
  document.getElementById('enableTelegram').addEventListener('change', (e) => {
2140
2140
  document.getElementById('telegramFields').classList.toggle('is-show', e.target.checked);
2141
2141
  });
@@ -2209,16 +2209,16 @@ document.getElementById('wizard').addEventListener('submit', async (e) => {
2209
2209
  btn.disabled = false; btn.textContent = 'Save and continue';
2210
2210
  }
2211
2211
  });
2212
- </script>`;ce();function pa(e=process.cwd()){let a=M(e,"agentx.json");if(!K(a))return{configExists:!1,agentCount:0,channelCount:0};try{let t=JSON.parse(la(a,"utf-8")),r=t.agents?Object.keys(t.agents).length:0,n=t.channels?Object.values(t.channels).filter(o=>o&&o.enabled).length:0;return{configExists:!0,agentCount:r,channelCount:n,nodeName:t.node?.name}}catch{return{configExists:!1,agentCount:0,channelCount:0}}}function xt(e,a=process.cwd(),t={}){if(!e.nodeName?.trim())throw new Error("Team name is required.");if(!e.agent?.id?.trim())throw new Error("Agent id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(e.agent.id))throw new Error("Agent id must be lowercase (letters, digits, -, _) and start with a letter or digit.");if(!e.agent.name?.trim())throw new Error("Agent name is required.");let r=gt(e.agent.triggerWords);if(r.length===0)throw new Error("At least one trigger word is required.");if(e.agent.tier!=="claude-code"&&e.agent.tier!=="codex-cli"&&e.agent.tier!=="opencode"&&e.agent.tier!=="sdk"&&e.agent.tier!=="orchestrator")throw new Error("AI engine must be claude-code, codex-cli, opencode, sdk, or orchestrator.");let n=M(a,"agentx.json"),o=M(a,".env"),i=M(a,"agents",e.agent.id),s=pa(a);st(i,{recursive:!0});let d=M(i,"CLAUDE.md");if(!K(d)){let g=e.agent.personality?.trim()||`You are ${e.agent.name}, an assistant on the ${e.nodeName} team.`;ca(d,`# ${e.agent.name}
2212
+ </script>`;ce();function xa(e=process.cwd()){let a=M(e,"agentx.json");if(!K(a))return{configExists:!1,agentCount:0,channelCount:0};try{let t=JSON.parse(ca(a,"utf-8")),r=t.agents?Object.keys(t.agents).length:0,n=t.channels?Object.values(t.channels).filter(o=>o&&o.enabled).length:0;return{configExists:!0,agentCount:r,channelCount:n,nodeName:t.node?.name}}catch{return{configExists:!1,agentCount:0,channelCount:0}}}function gt(e,a=process.cwd(),t={}){if(!e.nodeName?.trim())throw new Error("Team name is required.");if(!e.agent?.id?.trim())throw new Error("Agent id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(e.agent.id))throw new Error("Agent id must be lowercase (letters, digits, -, _) and start with a letter or digit.");if(!e.agent.name?.trim())throw new Error("Agent name is required.");let r=ut(e.agent.triggerWords);if(r.length===0)throw new Error("At least one trigger word is required.");if(e.agent.tier!=="claude-code"&&e.agent.tier!=="codex-cli"&&e.agent.tier!=="opencode"&&e.agent.tier!=="sdk"&&e.agent.tier!=="orchestrator")throw new Error("AI engine must be claude-code, codex-cli, opencode, sdk, or orchestrator.");let n=M(a,"agentx.json"),o=M(a,".env"),i=M(a,"agents",e.agent.id),s=xa(a);dt(i,{recursive:!0});let d=M(i,"CLAUDE.md");if(!K(d)){let g=e.agent.personality?.trim()||`You are ${e.agent.name}, an assistant on the ${e.nodeName} team.`;pa(d,`# ${e.agent.name}
2213
2213
 
2214
2214
  ${g}
2215
- `)}let l=e.telegram?`TG_${e.agent.id.toUpperCase()}_BOT_TOKEN`:void 0,c;if(s.configExists)c=Q(u=>{if(u.node=u.node||{},u.node.name||(u.node.name=e.nodeName),u.node.id||(u.node.id=xa(e.nodeName)||"team"),u.node.bind||(u.node.bind="127.0.0.1:18800"),u.node.defaultAgent=u.node.defaultAgent||e.agent.id,u.providers=u.providers||{},u.providers.claude||(u.providers.claude={apiKey:"${ANTHROPIC_API_KEY}"}),u.agents=u.agents||{},u.agents[e.agent.id])throw new Error(`Agent "${e.agent.id}" already exists.`);return u.agents[e.agent.id]=ga(e,i,r),e.telegram&&(u.channels=u.channels||{},u.channels.telegram=u.channels.telegram||{enabled:!0,accounts:{},policy:{dm:"pair",group:"mention-required"}},u.channels.telegram.enabled=!0,u.channels.telegram.accounts=u.channels.telegram.accounts||{},u.channels.telegram.accounts[e.telegram.accountId]=ua(e,l)),{summary:`added agent "${e.agent.id}"`+(e.telegram?" + telegram account":"")}},{configPath:n}).backupPath;else{let g=ut(e,i,r,l,t);Ye(g,{configPath:n})}mt(o,e,l);let m=[];return(e.anthropicApiKey||!K(M(a,".env")))&&m.push("Double-check the API keys in .env"),e.agent.tier==="claude-code"&&m.push("Run claude --version to confirm Claude Code is installed (needed for the claude-code engine)"),e.agent.tier==="codex-cli"&&m.push("Run codex --version to confirm Codex CLI is installed (needed for the codex-cli engine)"),e.agent.tier==="opencode"&&m.push("Run opencode --version to confirm OpenCode is installed and authenticated"),m.push("Start the daemon: agentx daemon start"),m.push("Open the dashboard: http://127.0.0.1:4202"),{summary:s.configExists?`Added agent "${e.agent.id}" to your team.`:`Initialized your team with first agent "${e.agent.id}".`,nextSteps:m,backupPath:c}}function gt(e){return(e||"").split(/[,\s]+/).map(a=>a.trim()).filter(Boolean).filter((a,t,r)=>r.indexOf(a)===t)}function xa(e){return(e||"").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")}function ut(e,a,t,r,n={}){let o=xa(e.nodeName)||"team",i=n.daemonPort??18800,s={node:{id:o,name:e.nodeName,bind:`127.0.0.1:${i}`,defaultAgent:e.agent.id},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{[e.agent.id]:ga(e,a,t)},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},dashboard:{enabled:!0,port:n.dashboardPort??4202,bind:"127.0.0.1",daemonUrl:`http://localhost:${i}`},boards:[]};return e.telegram&&r?s.channels.telegram={enabled:!0,accounts:{[e.telegram.accountId]:ua(e,r)},policy:{dm:"pair",group:"mention-required"}}:s.channels.telegram={enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},s}function ga(e,a,t){let r={name:e.agent.name,workspace:a,tier:e.agent.tier,mentions:t,maxConcurrent:2,permissionMode:"default"};return e.agent.model&&(r.model=e.agent.model),e.agent.provider&&(r.provider=e.agent.provider),e.agent.personality?.trim()&&(r.systemPrompt=e.agent.personality.trim().slice(0,400)),r}function ua(e,a){return e.telegram?.botUsername,{token:"${"+a+"}",agentBinding:e.agent.id}}function mt(e,a,t){let r=K(e)?la(e,"utf-8"):"",n=[];if(a.anthropicApiKey&&!r.includes("ANTHROPIC_API_KEY=")&&n.push(`ANTHROPIC_API_KEY=${a.anthropicApiKey}`),a.telegram&&t&&!r.includes(`${t}=`)&&n.push(`${t}=${a.telegram.botToken}`),!K(e)){ca(e,[...["# AgentX environment variables","# (Never commit this file \u2014 it contains secrets.)",""],...n,""].join(`
2215
+ `)}let l=e.telegram?`TG_${e.agent.id.toUpperCase()}_BOT_TOKEN`:void 0,c;if(s.configExists)c=Q(u=>{if(u.node=u.node||{},u.node.name||(u.node.name=e.nodeName),u.node.id||(u.node.id=ga(e.nodeName)||"team"),u.node.bind||(u.node.bind="127.0.0.1:18800"),u.node.defaultAgent=u.node.defaultAgent||e.agent.id,u.providers=u.providers||{},u.providers.claude||(u.providers.claude={apiKey:"${ANTHROPIC_API_KEY}"}),u.agents=u.agents||{},u.agents[e.agent.id])throw new Error(`Agent "${e.agent.id}" already exists.`);return u.agents[e.agent.id]=ua(e,i,r),e.telegram&&(u.channels=u.channels||{},u.channels.telegram=u.channels.telegram||{enabled:!0,accounts:{},policy:{dm:"pair",group:"mention-required"}},u.channels.telegram.enabled=!0,u.channels.telegram.accounts=u.channels.telegram.accounts||{},u.channels.telegram.accounts[e.telegram.accountId]=ma(e,l)),{summary:`added agent "${e.agent.id}"`+(e.telegram?" + telegram account":"")}},{configPath:n}).backupPath;else{let g=mt(e,i,r,l,t);Je(g,{configPath:n})}ft(o,e,l);let m=[];return(e.anthropicApiKey||!K(M(a,".env")))&&m.push("Double-check the API keys in .env"),e.agent.tier==="claude-code"&&m.push("Run claude --version to confirm Claude Code is installed (needed for the claude-code engine)"),e.agent.tier==="codex-cli"&&m.push("Run codex --version to confirm Codex CLI is installed (needed for the codex-cli engine)"),e.agent.tier==="opencode"&&m.push("Run opencode --version to confirm OpenCode is installed and authenticated"),m.push("Start the daemon: agentx daemon start"),m.push("Open the dashboard: http://127.0.0.1:4202"),{summary:s.configExists?`Added agent "${e.agent.id}" to your team.`:`Initialized your team with first agent "${e.agent.id}".`,nextSteps:m,backupPath:c}}function ut(e){return(e||"").split(/[,\s]+/).map(a=>a.trim()).filter(Boolean).filter((a,t,r)=>r.indexOf(a)===t)}function ga(e){return(e||"").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")}function mt(e,a,t,r,n={}){let o=ga(e.nodeName)||"team",i=n.daemonPort??18800,s={node:{id:o,name:e.nodeName,bind:`127.0.0.1:${i}`,defaultAgent:e.agent.id},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{[e.agent.id]:ua(e,a,t)},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},dashboard:{enabled:!0,port:n.dashboardPort??4202,bind:"127.0.0.1",daemonUrl:`http://localhost:${i}`},boards:[]};return e.telegram&&r?s.channels.telegram={enabled:!0,accounts:{[e.telegram.accountId]:ma(e,r)},policy:{dm:"pair",group:"mention-required"}}:s.channels.telegram={enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},s}function ua(e,a,t){let r={name:e.agent.name,workspace:a,tier:e.agent.tier,mentions:t,maxConcurrent:2,permissionMode:"default"};return e.agent.model&&(r.model=e.agent.model),e.agent.provider&&(r.provider=e.agent.provider),e.agent.personality?.trim()&&(r.systemPrompt=e.agent.personality.trim().slice(0,400)),r}function ma(e,a){return e.telegram?.botUsername,{token:"${"+a+"}",agentBinding:e.agent.id}}function ft(e,a,t){let r=K(e)?ca(e,"utf-8"):"",n=[];if(a.anthropicApiKey&&!r.includes("ANTHROPIC_API_KEY=")&&n.push(`ANTHROPIC_API_KEY=${a.anthropicApiKey}`),a.telegram&&t&&!r.includes(`${t}=`)&&n.push(`${t}=${a.telegram.botToken}`),!K(e)){pa(e,[...["# AgentX environment variables","# (Never commit this file \u2014 it contains secrets.)",""],...n,""].join(`
2216
2216
  `),{mode:384});return}if(n.length>0){let o=r.endsWith(`
2217
2217
  `)?"":`
2218
- `;it(e,o+n.join(`
2218
+ `;st(e,o+n.join(`
2219
2219
  `)+`
2220
- `)}}function $n(e,a){let t=pa(),r=t.nodeName||ct().replace(/\.local$/,""),n=sa(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=xt(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 An(e,a){a.setHeader("Content-Type","application/json");let t;try{t=Ee().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 da(r)){a.writeHead(200),a.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!0}));return}let n=process.argv[1]||M(dt(lt(import.meta.url)),"cli.js");try{pt(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 da(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 da(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 ft,readFileSync as ht,renameSync as bt,writeFileSync as vt}from"fs";import{dirname as wt,isAbsolute as yt,resolve as kt}from"path";import{createHash as _t,randomBytes as $t}from"crypto";var Rn=".agentx/app-pins.json",On=12,ma=40,fa=2e3,St=/^pin_[a-z0-9]{6,32}$/;function At(e,a){return yt(a)?a:kt(e,a)}function ae(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>ma?{ok:!1,error:`Keep the name under ${ma} characters.`}:{ok:!0,value:a}:{ok:!1,error:"Give the button a name."}}function ye(e){let a=typeof e=="string"?e.trim():"";if(!a)return{ok:!1,error:"Give the page's address."};if(a.length>fa)return{ok:!1,error:`Keep the address under ${fa} 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 Ct(e){return`cfg_${_t("sha256").update(e).digest("hex").slice(0,12)}`}function Tt(e){let a=[];for(let t of e){let r=ae(t.label),n=ye(t.url);!r.ok||!n.ok||a.some(o=>o.url===n.value||o.label.toLowerCase()===r.value.toLowerCase())||a.push({id:Ct(n.value),label:r.value,url:n.value,source:"config"})}return a}var ha="This button is set in agentx.json (app.pins.pages). Change or remove it there.";function It(e){let a=ae(e.label);if(!a.ok)return a;let t=ye(e.url);return t.ok?{ok:!0,value:{label:a.value,url:t.value}}:t}var we=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=ht(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"&&St.test(i.id)&&ae(i.label).ok&&ye(i.url).ok});return{pins:n,damaged:!Array.isArray(t?.pins)||n.length!==r.length}}locked(a){try{return Oe(this.path,a,{what:"The pinned pages file"})}catch(t){if(t instanceof Re)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){ft(wt(this.path),{recursive:!0});let t=`${this.path}.${process.pid}.tmp`;vt(t,JSON.stringify({pins:a},null,2)+`
2221
- `,{mode:384}),bt(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_${$t(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:ha};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:ha};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 we(At(a,t.file),Date.now,Tt(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 E(a,200,{pins:n.store.list(),max:n.max});if(r!=="POST")return E(a,404,{error:"not found"});let i;try{i=await V(e,4096)}catch(d){return E(a,400,{error:d.message})}let s=typeof i.id=="string"?i.id:"";if(o==="/add"){let d=It(i);if(!d.ok)return E(a,400,{error:d.error});let l=n.store.add(d.value,n.max);return l.ok?E(a,200,{ok:!0,pin:l.pin}):E(a,l.status,{error:l.error})}if(o==="/rename"){let d=ae(i.label);if(!d.ok)return E(a,400,{error:d.error});let l=n.store.rename(s,d.value);return l.ok?E(a,200,{ok:!0,pin:l.pin}):E(a,l.status,{error:l.error})}if(o==="/remove"){let d=n.store.remove(s);return d.ok?E(a,200,{ok:!0}):E(a,d.status,{error:d.error})}return E(a,404,{error:"not found"})}function E(e,a,t){return e.writeHead(a,{"Content-Type":"application/json","Cache-Control":"no-store"}),e.end(JSON.stringify(t)),!0}import{existsSync as ba,readFileSync as va}from"fs";ce();function zt(e){let a=q(e),t={};if(ba(a))try{t=F(JSON.parse(va(a,"utf-8")))}catch{t={}}let r=le.safeParse(t?.approvals);return r.success?r.data:le.parse(void 0)}function Bn(e){let a=q(e),t={};if(ba(a))try{t=F(JSON.parse(va(a,"utf-8")))}catch{t={}}return We({desk:t?.notifications?.desk,popupEnabled:!!zt(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 J(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 Ht}from"http";var te=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 wa=864e5;function ke(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 _e(e,a){if(a.type==="event")return a.date||a.updated;let t=Ge(e,a,new Set(["event"]))[0],r=a.updated||a.date;return t&&t.date>r?t.date:r}function ya(e,a,t=Date.now()){let r=[],n=new Date(t+14*wa).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*wa&&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 re(e,a,t="",r){return`<div class="ox-row"><span class="ox-ic">${Ve(e.ontology,a.type)}</span><div class="t"><a href="${me(a.id)}">${k(a.title)}</a><div class="ox-sub">${k(r??`${ue(e.ontology,a.type).toLowerCase()} \xB7 ${_e(e,a)}`)}</div></div><div class="r">${t}</div></div>`}function ka(e,a){let t=a.slice(0,6).map(r=>re(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 Et(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 _a(e,a){let t=ke(e),r=`<div class="ox-bar">${L([])}</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+=Et(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="${me(o.id)}">${k(o.title)}</a></div>`).join("")||'<div class="ox-empty">No events yet.</div>')+"</section>",r+=ka(e,ya(e,[...e.entities.values()])),r+="</div>",j("Wiki",N(e,{home:!0}),r)}function $a(e,a,t){let r=e.ontology.pillars.find(c=>c.id===a);if(!r)return null;let n=ke(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">${L([{label:r.label}])}${fe(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:_e(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})=>re(e,c,c.type==="event"?`<span class="ox-st ${c.importance}">${c.importance}</span>`:"",`${Qe(c,90)||ue(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+=ka(e,ya(e,l)),s+="</div>",j(r.label,N(e,{pillar:r.id}),s)}function Sa(e,a,t,r,n){let o=n&&De.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:_e(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">${L([{label:i.label,href:`/p/${encodeURIComponent(i.id)}`},{label:s.plural??s.label}])}${fe(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})=>re(e,x,x.type==="event"?`<span class="ox-st ${x.importance}">${x.importance}</span>`:"",`${f} \xB7 ${x.pages.map(C=>C.agentId).filter((C,w,v)=>v.indexOf(C)===w).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 j(s.plural??s.label,N(e,{pillar:i.id}),u)}function Aa(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">${L([{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})=>re(e,o)).join("")||'<div class="ox-empty">No page matches.</div>'}</section>`,j(`Search: ${a}`,N(e,{}),n,"",a)}function Ca(e,a,t){let r=e.ontology,n=ke(e),o=`<div class="ox-bar">${L([{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>`,j("Ontology",N(e,{}),o)}var ne=class{constructor(a,t){this.hub=a;this.wikiDir=t}cache=new Xe;pageAt(a){if(!a.startsWith("/e/"))return null;let{ontology:t}=ge(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}=ge(this.wikiDir),i=Je(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 _a(s,n);if(a==="/find")return Aa(s,t.get("q")??"");if(a==="/ontology")return Ca(s,n,o);let l=a.split("/").filter(Boolean);if(l[0]==="p")return l.length===2?$a(s,l[1],t.get("kind")):l.length===3?Sa(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?Ze(m,c):l.length===3?ea(m,c,l[2],d):l.length===4&&l[2]==="s"?aa(m,c,Number(l[3])):null}};var Pt=`
2220
+ `)}}function Sn(e,a){let t=xa(),r=t.nodeName||pt().replace(/\.local$/,""),n=da(t,r);a.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),a.end(n)}async function An(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=gt(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=Ee().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 la(r)){a.writeHead(200),a.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!0}));return}let n=process.argv[1]||M(lt(ct(import.meta.url)),"cli.js");try{xt(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 la(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 la(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 ht,readFileSync as bt,renameSync as vt,writeFileSync as wt}from"fs";import{dirname as yt,isAbsolute as kt,resolve as $t}from"path";import{createHash as _t,randomBytes as St}from"crypto";var On=".agentx/app-pins.json",Dn=12,fa=40,ha=2e3,At=/^pin_[a-z0-9]{6,32}$/;function Ct(e,a){return kt(a)?a:$t(e,a)}function ae(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>fa?{ok:!1,error:`Keep the name under ${fa} characters.`}:{ok:!0,value:a}:{ok:!1,error:"Give the button a name."}}function ye(e){let a=typeof e=="string"?e.trim():"";if(!a)return{ok:!1,error:"Give the page's address."};if(a.length>ha)return{ok:!1,error:`Keep the address under ${ha} 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 Tt(e){return`cfg_${_t("sha256").update(e).digest("hex").slice(0,12)}`}function It(e){let a=[];for(let t of e){let r=ae(t.label),n=ye(t.url);!r.ok||!n.ok||a.some(o=>o.url===n.value||o.label.toLowerCase()===r.value.toLowerCase())||a.push({id:Tt(n.value),label:r.value,url:n.value,source:"config"})}return a}var ba="This button is set in agentx.json (app.pins.pages). Change or remove it there.";function zt(e){let a=ae(e.label);if(!a.ok)return a;let t=ye(e.url);return t.ok?{ok:!0,value:{label:a.value,url:t.value}}:t}var we=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=bt(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"&&At.test(i.id)&&ae(i.label).ok&&ye(i.url).ok});return{pins:n,damaged:!Array.isArray(t?.pins)||n.length!==r.length}}locked(a){try{return Oe(this.path,a,{what:"The pinned pages file"})}catch(t){if(t instanceof Re)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){ht(yt(this.path),{recursive:!0});let t=`${this.path}.${process.pid}.tmp`;wt(t,JSON.stringify({pins:a},null,2)+`
2221
+ `,{mode:384}),vt(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_${St(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:ba};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:ba};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 Mn(e,a){let t=e.app.pins;return{store:new we(Ct(a,t.file),Date.now,It(t.pages)),max:t.max}}async function Hn(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 E(a,200,{pins:n.store.list(),max:n.max});if(r!=="POST")return E(a,404,{error:"not found"});let i;try{i=await V(e,4096)}catch(d){return E(a,400,{error:d.message})}let s=typeof i.id=="string"?i.id:"";if(o==="/add"){let d=zt(i);if(!d.ok)return E(a,400,{error:d.error});let l=n.store.add(d.value,n.max);return l.ok?E(a,200,{ok:!0,pin:l.pin}):E(a,l.status,{error:l.error})}if(o==="/rename"){let d=ae(i.label);if(!d.ok)return E(a,400,{error:d.error});let l=n.store.rename(s,d.value);return l.ok?E(a,200,{ok:!0,pin:l.pin}):E(a,l.status,{error:l.error})}if(o==="/remove"){let d=n.store.remove(s);return d.ok?E(a,200,{ok:!0}):E(a,d.status,{error:d.error})}return E(a,404,{error:"not found"})}function E(e,a,t){return e.writeHead(a,{"Content-Type":"application/json","Cache-Control":"no-store"}),e.end(JSON.stringify(t)),!0}import{existsSync as va,readFileSync as wa}from"fs";ce();function Et(e){let a=q(e),t={};if(va(a))try{t=F(JSON.parse(wa(a,"utf-8")))}catch{t={}}let r=le.safeParse(t?.approvals);return r.success?r.data:le.parse(void 0)}function Un(e){let a=q(e),t={};if(va(a))try{t=F(JSON.parse(wa(a,"utf-8")))}catch{t={}}return Be({desk:t?.notifications?.desk,popupEnabled:!!Et(e).popup?.enabled})}function Fn(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 qn(e,a={}){return J(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 Lt}from"http";var te=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 ya=864e5;function ke(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 $e(e,a){if(a.type==="event")return a.date||a.updated;let t=Ve(e,a,new Set(["event"]))[0],r=a.updated||a.date;return t&&t.date>r?t.date:r}function ka(e,a,t=Date.now()){let r=[],n=new Date(t+14*ya).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*ya&&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 re(e,a,t="",r){return`<div class="ox-row"><span class="ox-ic">${Qe(e.ontology,a.type)}</span><div class="t"><a href="${me(a.id)}">${k(a.title)}</a><div class="ox-sub">${k(r??`${ue(e.ontology,a.type).toLowerCase()} \xB7 ${$e(e,a)}`)}</div></div><div class="r">${t}</div></div>`}function $a(e,a){let t=a.slice(0,6).map(r=>re(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 Pt(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 _a(e,a){let t=ke(e),r=`<div class="ox-bar">${L([])}</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+=Pt(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="${me(o.id)}">${k(o.title)}</a></div>`).join("")||'<div class="ox-empty">No events yet.</div>')+"</section>",r+=$a(e,ka(e,[...e.entities.values()])),r+="</div>",j("Wiki",N(e,{home:!0}),r)}function Sa(e,a,t){let r=e.ontology.pillars.find(c=>c.id===a);if(!r)return null;let n=ke(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">${L([{label:r.label}])}${fe(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:$e(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})=>re(e,c,c.type==="event"?`<span class="ox-st ${c.importance}">${c.importance}</span>`:"",`${Ze(c,90)||ue(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+=$a(e,ka(e,l)),s+="</div>",j(r.label,N(e,{pillar:r.id}),s)}function Aa(e,a,t,r,n){let o=n&&De.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:$e(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">${L([{label:i.label,href:`/p/${encodeURIComponent(i.id)}`},{label:s.plural??s.label}])}${fe(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})=>re(e,x,x.type==="event"?`<span class="ox-st ${x.importance}">${x.importance}</span>`:"",`${f} \xB7 ${x.pages.map(C=>C.agentId).filter((C,y,v)=>v.indexOf(C)===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 j(s.plural??s.label,N(e,{pillar:i.id}),u)}function Ca(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">${L([{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})=>re(e,o)).join("")||'<div class="ox-empty">No page matches.</div>'}</section>`,j(`Search: ${a}`,N(e,{}),n,"",a)}function Ta(e,a,t){let r=e.ontology,n=ke(e),o=`<div class="ox-bar">${L([{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>`,j("Ontology",N(e,{}),o)}var ne=class{constructor(a,t){this.hub=a;this.wikiDir=t}cache=new Ge;pageAt(a){if(!a.startsWith("/e/"))return null;let{ontology:t}=ge(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}=ge(this.wikiDir),i=Xe(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 _a(s,n);if(a==="/find")return Ca(s,t.get("q")??"");if(a==="/ontology")return Ta(s,n,o);let l=a.split("/").filter(Boolean);if(l[0]==="p")return l.length===2?Sa(s,l[1],t.get("kind")):l.length===3?Aa(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?ea(m,c):l.length===3?aa(m,c,l[2],d):l.length===4&&l[2]==="s"?ta(m,c,Number(l[3])):null}};var Rt=`
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}
@@ -2257,7 +2257,7 @@ ${g}
2257
2257
  @keyframes wc-blink{0%{content:''}25%{content:'.'}50%{content:'..'}75%{content:'\u2026'}}
2258
2258
  @media (max-width:600px){.wc-panel{right:8px;left:8px;bottom:80px;width:auto;max-height:calc(100vh - 100px)}.wc-fab{right:14px;bottom:14px}}
2259
2259
  @media (prefers-reduced-motion:reduce){.wc-dots::after{animation:none;content:'\u2026'}}
2260
- `,Rt=`
2260
+ `,Ot=`
2261
2261
  (function(){
2262
2262
  var root=document.getElementById('wc-root'); if(!root) return;
2263
2263
  var cfg=JSON.parse(document.getElementById('wc-data').textContent);
@@ -2325,20 +2325,20 @@ ${g}
2325
2325
  api('GET',q()).then(function(state){if(state.enabled===false)return;fab.hidden=false;
2326
2326
  try{if(sessionStorage.getItem(openKey))setOpen(true)}catch(e){}}).catch(function(){});
2327
2327
  })();
2328
- `,Ot='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"/><path d="M12 8.5l.9 2.1 2.1.9-2.1.9-.9 2.1-.9-2.1-2.1-.9 2.1-.9z"/></svg>';function Dt(e){return e.replace(/[&<>"']/g,a=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[a])}function Mt(e,a="/api/wiki/curate",t){let r=JSON.stringify({agent:e.agentId,path:e.path,title:e.title,endpoint:a,...t?{token:t}:{}}).replace(/</g,"\\u003c");return`<style>${Pt}</style>
2328
+ `,Dt='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"/><path d="M12 8.5l.9 2.1 2.1.9-2.1.9-.9 2.1-.9-2.1-2.1-.9 2.1-.9z"/></svg>';function Mt(e){return e.replace(/[&<>"']/g,a=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[a])}function Ht(e,a="/api/wiki/curate",t){let r=JSON.stringify({agent:e.agentId,path:e.path,title:e.title,endpoint:a,...t?{token:t}:{}}).replace(/</g,"\\u003c");return`<style>${Rt}</style>
2329
2329
  <div class="wc-root" id="wc-root">
2330
- <button class="wc-fab" type="button" hidden aria-label="Ask an agent to curate this page" aria-expanded="false" aria-controls="wc-panel" title="Curate this page">${Ot}</button>
2330
+ <button class="wc-fab" type="button" hidden aria-label="Ask an agent to curate this page" aria-expanded="false" aria-controls="wc-panel" title="Curate this page">${Dt}</button>
2331
2331
  <section class="wc-panel" id="wc-panel" role="dialog" aria-label="Curate this page" hidden>
2332
- <div class="wc-head"><div><h2>Curate this page</h2><p class="wc-sub">${Dt(e.title)}</p></div><button class="wc-x" type="button" aria-label="Close">\xD7</button></div>
2332
+ <div class="wc-head"><div><h2>Curate this page</h2><p class="wc-sub">${Mt(e.title)}</p></div><button class="wc-x" type="button" aria-label="Close">\xD7</button></div>
2333
2333
  <div class="wc-log" aria-live="polite"></div>
2334
2334
  <form class="wc-form"><textarea rows="2" aria-label="Instruction for the agent" placeholder="What should change on this page?"></textarea><button class="wc-send" type="submit">Send</button></form>
2335
2335
  </section>
2336
2336
  </div>
2337
2337
  <script type="application/json" id="wc-data">${r}</script>
2338
- <script>${Rt}</script>`}function Ta(e,a,t,r){let n=Mt(a,t,r);return e.includes("</body>")?e.replace(/<\/body>(?![\s\S]*<\/body>)/,()=>`${n}
2339
- </body>`):e+n}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Lt(e){return e.replace(/<!--\s*tags?:[^>]*-->\s*\n?/gi,"")}function Ia(e,a){return`<a href="${a?`/agent/${encodeURIComponent(a)}/tag/${encodeURIComponent(e)}`:`/tag/${encodeURIComponent(e)}`}" class="tag">${p(e)}</a>`}function H(e,a){return(e||[]).map(t=>Ia(t,a)).join(" ")}function Nt(e,a){if(!e)return;let t=a.get(e);if(t)return t;let r=new Set(a.values());if(r.has(e))return e;let n=e.endsWith(".md")?e:`${e}.md`;if(r.has(n))return n;let o=e.toLowerCase();for(let[i,s]of a)if(i.toLowerCase()===o)return s}function oe(e,a,t=""){return G(Lt(e),{wikilink:(r,n)=>{let o=Nt(r,a);return o?`<a href="${t}/article/${encodeURIComponent(o)}" class="wikilink">${n}</a>`:`<a href="${t}/search?q=${encodeURIComponent(r)}" class="wikilink broken" title="Not found \u2014 click to search">${n}</a>`}})}var jt=`<link rel="preconnect" href="https://fonts.googleapis.com">
2338
+ <script>${Ot}</script>`}function Ia(e,a,t,r){let n=Ht(a,t,r);return e.includes("</body>")?e.replace(/<\/body>(?![\s\S]*<\/body>)/,()=>`${n}
2339
+ </body>`):e+n}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Nt(e){return e.replace(/<!--\s*tags?:[^>]*-->\s*\n?/gi,"")}function za(e,a){return`<a href="${a?`/agent/${encodeURIComponent(a)}/tag/${encodeURIComponent(e)}`:`/tag/${encodeURIComponent(e)}`}" class="tag">${p(e)}</a>`}function H(e,a){return(e||[]).map(t=>za(t,a)).join(" ")}function jt(e,a){if(!e)return;let t=a.get(e);if(t)return t;let r=new Set(a.values());if(r.has(e))return e;let n=e.endsWith(".md")?e:`${e}.md`;if(r.has(n))return n;let o=e.toLowerCase();for(let[i,s]of a)if(i.toLowerCase()===o)return s}function oe(e,a,t=""){return G(Nt(e),{wikilink:(r,n)=>{let o=jt(r,a);return o?`<a href="${t}/article/${encodeURIComponent(o)}" class="wikilink">${n}</a>`:`<a href="${t}/search?q=${encodeURIComponent(r)}" class="wikilink broken" title="Not found \u2014 click to search">${n}</a>`}})}var Wt=`<link rel="preconnect" href="https://fonts.googleapis.com">
2340
2340
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
2341
- <link href="https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,300..600;1,6..72,300..600&family=Inter+Tight:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">`,Wt=`
2341
+ <link href="https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,300..600;1,6..72,300..600&family=Inter+Tight:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">`,Bt=`
2342
2342
  :root {
2343
2343
  --bg: #FAF8F3;
2344
2344
  --bg-raised: #FFFFFF;
@@ -2811,8 +2811,8 @@ tr:hover td { background: var(--bg-hover); }
2811
2811
  <meta charset="utf-8">
2812
2812
  <meta name="viewport" content="width=device-width, initial-scale=1">
2813
2813
  <title>${p(e)} \u2014 AgentX Wiki</title>
2814
- ${jt}
2815
- <style>${Wt}</style>
2814
+ ${Wt}
2815
+ <style>${Bt}</style>
2816
2816
  <script>(function(){try{var t=localStorage.getItem('wiki-theme');if(t)document.documentElement.setAttribute('data-theme',t)}catch(e){}})();</script>
2817
2817
  </head>
2818
2818
  <body>
@@ -2857,7 +2857,7 @@ tr:hover td { background: var(--bg-hover); }
2857
2857
  })();
2858
2858
  </script>
2859
2859
  </body>
2860
- </html>`}function $e(e){let a=new Map;for(let t of e){let r=t.path.includes("/")?t.path.split("/").slice(0,-1).join("/"):"/",n=a.get(r)||[];n.push(t),a.set(r,n)}return new Map([...a].sort((t,r)=>t[0].localeCompare(r[0])))}function Se(e){return e==="/"?"Root":e.split("/").pop().replace(/-/g," ")}function P(e,a){let t='<div class="nav-section">';t+=`<a class="nav-item${a?"":" active"}" href="/">Home</a>`,t+='<a class="nav-item" href="/entries">All entries</a>',t+="</div>";for(let r of e){let n=`/agent/${encodeURIComponent(r.agentId)}`;t+='<div class="nav-section">',t+=`<a class="nav-agent-header" href="${n}">`,t+=`<span class="name">${p(r.agentId)}</span>`,t+=`<span class="badge">${r.totalArticles}</span>`,t+="</a>",t+='<div class="nav-agent-children">';let o=$e(r.articles);for(let[i,s]of o){t+=`<div class="nav-agent-type-label">${Se(i)}</div>`;for(let d of s){let c=`${r.agentId}/${d.path}`===a;t+=`<a class="nav-item${c?" active":""}" href="${n}/article/${encodeURIComponent(d.path)}">${p(d.title)}</a>`}}t+="</div>",t+="</div>"}return t}function Bt(e,a,t){let r=a||e.summary(),o=e.getSharedStore().listEntries().length,i=r.reduce((c,m)=>c+m.totalArticles,0),s=r.reduce((c,m)=>c+m.unabsorbed,0),d=new Set((t||[]).map(c=>c.agentId)),l=`<div class="page-head">
2860
+ </html>`}function _e(e){let a=new Map;for(let t of e){let r=t.path.includes("/")?t.path.split("/").slice(0,-1).join("/"):"/",n=a.get(r)||[];n.push(t),a.set(r,n)}return new Map([...a].sort((t,r)=>t[0].localeCompare(r[0])))}function Se(e){return e==="/"?"Root":e.split("/").pop().replace(/-/g," ")}function P(e,a){let t='<div class="nav-section">';t+=`<a class="nav-item${a?"":" active"}" href="/">Home</a>`,t+='<a class="nav-item" href="/entries">All entries</a>',t+="</div>";for(let r of e){let n=`/agent/${encodeURIComponent(r.agentId)}`;t+='<div class="nav-section">',t+=`<a class="nav-agent-header" href="${n}">`,t+=`<span class="name">${p(r.agentId)}</span>`,t+=`<span class="badge">${r.totalArticles}</span>`,t+="</a>",t+='<div class="nav-agent-children">';let o=_e(r.articles);for(let[i,s]of o){t+=`<div class="nav-agent-type-label">${Se(i)}</div>`;for(let d of s){let c=`${r.agentId}/${d.path}`===a;t+=`<a class="nav-item${c?" active":""}" href="${n}/article/${encodeURIComponent(d.path)}">${p(d.title)}</a>`}}t+="</div>",t+="</div>"}return t}function Ut(e,a,t){let r=a||e.summary(),o=e.getSharedStore().listEntries().length,i=r.reduce((c,m)=>c+m.totalArticles,0),s=r.reduce((c,m)=>c+m.unabsorbed,0),d=new Set((t||[]).map(c=>c.agentId)),l=`<div class="page-head">
2861
2861
  <div>
2862
2862
  <h1>AgentX Wiki</h1>
2863
2863
  <p class="page-sub">Agent-owned institutional knowledge, typed and cross-referenced. Everything here compiles from raw conversation entries through the nightly absorb pass.</p>
@@ -2866,41 +2866,42 @@ tr:hover td { background: var(--bg-hover); }
2866
2866
  <span><strong>${c.totalArticles}</strong> articles</span>
2867
2867
  <span><strong>${c.totalEntries}</strong> entries</span>
2868
2868
  ${m}
2869
- </div>`,c.articles.length>0){l+='<div class="article-list">';for(let x of c.articles.slice(0,6)){let f=H((x.tags||[]).slice(0,2),c.agentId);l+=`<div class="article-row">${f} <a class="article-title" href="/agent/${encodeURIComponent(c.agentId)}/article/${encodeURIComponent(x.path)}">${p(x.title)}</a></div>`}c.articles.length>6&&(l+=`<div class="article-row"><a class="article-title" style="color:var(--muted)" href="/agent/${encodeURIComponent(c.agentId)}">+ ${c.articles.length-6} more \u2192</a></div>`),l+="</div>"}l+="</div>"}return l+="</div>",A("Hub",P(r),l)}function Ut(e,a,t){let r=t||e.summary(),n=r.find(g=>g.agentId===a);if(!n)return A("Not Found",P(r),"<h1>Agent not found</h1>");let o=n.peerUrl!==void 0,i=e.getAgentEntries(a),s=n.articles||[],d=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">${p(a)}</span></nav>`;if(d+=`<div class="page-head"><div><h1>${p(a)}</h1>`,o&&(d+=`<p class="page-sub"><span class="tag" style="color:var(--cool);background:var(--cool-soft)">remote @ ${p(n.nodeId)}</span></p>`),d+="</div></div>",d+='<div class="stat-strip">',d+=`<div class="stat-cell"><div class="label">Articles</div><div class="number">${n.totalArticles}</div></div>`,d+=`<div class="stat-cell"><div class="label">Entries</div><div class="number">${n.totalEntries}</div></div>`,d+=`<div class="stat-cell"><div class="label">Unabsorbed</div><div class="number">${n.unabsorbed}</div></div>`,d+="</div>",s.length>0){d+='<div class="section-head"><h2>Articles</h2><span class="mono" style="font-size:12px;color:var(--muted)">'+s.length+" total</span></div>";let g=$e(s);for(let[u,x]of g){d+=`<h3 class="display" style="font-size:17px;color:var(--muted);font-weight:500;margin:20px 0 8px">${Se(u)}</h3>`,d+='<div class="agent-card" style="padding:4px 14px"><div class="article-list">';for(let f of x)d+=`<div class="article-row">${H((f.tags||[]).slice(0,3),a)} <a class="article-title" href="/agent/${encodeURIComponent(a)}/article/${encodeURIComponent(f.path)}">${p(f.title)}</a></div>`;d+="</div></div>"}}let l=i.slice(-5).reverse();if(l.length>0){d+='<div class="section-head"><h2>Recent entries</h2><a class="btn ghost" href="/entries">See all \u2192</a></div>';for(let g of l)d+=`<div class="entry-card">
2869
+ </div>`,c.articles.length>0){l+='<div class="article-list">';for(let x of c.articles.slice(0,6)){let f=H((x.tags||[]).slice(0,2),c.agentId);l+=`<div class="article-row">${f} <a class="article-title" href="/agent/${encodeURIComponent(c.agentId)}/article/${encodeURIComponent(x.path)}">${p(x.title)}</a></div>`}c.articles.length>6&&(l+=`<div class="article-row"><a class="article-title" style="color:var(--muted)" href="/agent/${encodeURIComponent(c.agentId)}">+ ${c.articles.length-6} more \u2192</a></div>`),l+="</div>"}l+="</div>"}return l+="</div>",A("Hub",P(r),l)}function Ft(e,a,t){let r=t||e.summary(),n=r.find(g=>g.agentId===a);if(!n)return A("Not Found",P(r),"<h1>Agent not found</h1>");let o=n.peerUrl!==void 0,i=e.getAgentEntries(a),s=n.articles||[],d=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">${p(a)}</span></nav>`;if(d+=`<div class="page-head"><div><h1>${p(a)}</h1>`,o&&(d+=`<p class="page-sub"><span class="tag" style="color:var(--cool);background:var(--cool-soft)">remote @ ${p(n.nodeId)}</span></p>`),d+="</div></div>",d+='<div class="stat-strip">',d+=`<div class="stat-cell"><div class="label">Articles</div><div class="number">${n.totalArticles}</div></div>`,d+=`<div class="stat-cell"><div class="label">Entries</div><div class="number">${n.totalEntries}</div></div>`,d+=`<div class="stat-cell"><div class="label">Unabsorbed</div><div class="number">${n.unabsorbed}</div></div>`,d+="</div>",s.length>0){d+='<div class="section-head"><h2>Articles</h2><span class="mono" style="font-size:12px;color:var(--muted)">'+s.length+" total</span></div>";let g=_e(s);for(let[u,x]of g){d+=`<h3 class="display" style="font-size:17px;color:var(--muted);font-weight:500;margin:20px 0 8px">${Se(u)}</h3>`,d+='<div class="agent-card" style="padding:4px 14px"><div class="article-list">';for(let f of x)d+=`<div class="article-row">${H((f.tags||[]).slice(0,3),a)} <a class="article-title" href="/agent/${encodeURIComponent(a)}/article/${encodeURIComponent(f.path)}">${p(f.title)}</a></div>`;d+="</div></div>"}}let l=i.slice(-5).reverse();if(l.length>0){d+='<div class="section-head"><h2>Recent entries</h2><a class="btn ghost" href="/entries">See all \u2192</a></div>';for(let g of l)d+=`<div class="entry-card">
2870
2870
  <div class="meta-line">${g.date} \xB7 via ${p(g.source)} \xB7 <code>${p(g.id)}</code></div>
2871
2871
  <p>${p(g.content.slice(0,300))}${g.content.length>300?"\u2026":""}</p>
2872
2872
  </div>`}let m=e.getAgentWiki(a).lint();if(m.length>0){d+=`<div class="section-head"><h2>Health issues</h2><span class="mono" style="font-size:12px;color:var(--warn)">${m.length}</span></div>`,d+='<div class="health-list">';for(let g of m)d+=`<div class="health-row">
2873
2873
  <span class="kind">${p(g.type)}</span>
2874
2874
  <span class="article">${p(g.article)}</span>
2875
2875
  <span class="msg">${p(g.message)}</span>
2876
- </div>`;d+="</div>"}return A(a,P(r,a),d)}function Ft(e,a,t,r){let n=e.getAgentWiki(a),o=n.readArticle(t);if(!o)return null;let i=r||e.summary(),s=n.rebuildIndex(),d=new Map;for(let u of s.articles)d.set(u.title,u.path);let l=`/agent/${encodeURIComponent(a)}`,m=n.buildBacklinks()[o.meta.title]||[],g=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${l}">${p(a)}</a> <span class="sep">/</span> <span class="current">${p(o.meta.title)}</span></nav>`;if(g+=`<article class="prose"><h1>${p(o.meta.title)}</h1>`,g+='<dl class="meta">',o.meta.type&&(g+=`<dt>Type</dt><dd>${Ia(o.meta.type,a)}</dd>`),o.meta.tags?.length&&(g+=`<dt>Tags</dt><dd>${H(o.meta.tags,a)}</dd>`),o.meta.owner&&(g+=`<dt>Owner</dt><dd>${p(o.meta.owner)}</dd>`),g+=`<dt>Created</dt><dd>${p(o.meta.created||"\u2014")}</dd>`,g+=`<dt>Updated</dt><dd>${p(o.meta.lastUpdated||"\u2014")}</dd>`,o.meta.sources?.length&&(g+=`<dt>Sources</dt><dd>${o.meta.sources.length} entries</dd>`),g+="</dl>",g+=oe(o.content,d,l),m.length>0){g+='<div class="backlinks"><h4>Pages that link here</h4><ul>';for(let u of m){let x=n.readArticle(u);g+=`<li><a href="${l}/article/${encodeURIComponent(u)}">${p(x?.meta.title||u)}</a></li>`}g+="</ul></div>"}return g+="</article>",A(o.meta.title,P(i,`${a}/${t}`),g)}function qt(e,a){let t=a||e.summary(),n=e.getSharedStore().listEntries(),o='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Entries</span></nav>';o+='<div class="page-head"><div><h1>All raw entries</h1><p class="page-sub">Every conversation line that the ingest pipeline captured. Absorb compiles these into typed articles nightly.</p></div></div>';let i=new Map;for(let s of n){let d=i.get(s.date)||[];d.push(s),i.set(s.date,d)}for(let[s,d]of[...i].reverse()){o+=`<div class="section-head"><h2>${s}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${d.length} entries</span></div>`;for(let l of d)o+=`<div class="entry-card">
2876
+ </div>`;d+="</div>"}return A(a,P(r,a),d)}function qt(e,a,t,r){let n=e.getAgentWiki(a),o=n.readArticle(t);if(!o)return null;let i=r||e.summary(),s=n.rebuildIndex(),d=new Map;for(let u of s.articles)d.set(u.title,u.path);let l=`/agent/${encodeURIComponent(a)}`,m=n.buildBacklinks()[o.meta.title]||[],g=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${l}">${p(a)}</a> <span class="sep">/</span> <span class="current">${p(o.meta.title)}</span></nav>`;if(g+=`<article class="prose"><h1>${p(o.meta.title)}</h1>`,g+='<dl class="meta">',o.meta.type&&(g+=`<dt>Type</dt><dd>${za(o.meta.type,a)}</dd>`),o.meta.tags?.length&&(g+=`<dt>Tags</dt><dd>${H(o.meta.tags,a)}</dd>`),o.meta.owner&&(g+=`<dt>Owner</dt><dd>${p(o.meta.owner)}</dd>`),g+=`<dt>Created</dt><dd>${p(o.meta.created||"\u2014")}</dd>`,g+=`<dt>Updated</dt><dd>${p(o.meta.lastUpdated||"\u2014")}</dd>`,o.meta.sources?.length&&(g+=`<dt>Sources</dt><dd>${o.meta.sources.length} entries</dd>`),g+="</dl>",g+=oe(o.content,d,l),m.length>0){g+='<div class="backlinks"><h4>Pages that link here</h4><ul>';for(let u of m){let x=n.readArticle(u);g+=`<li><a href="${l}/article/${encodeURIComponent(u)}">${p(x?.meta.title||u)}</a></li>`}g+="</ul></div>"}return g+="</article>",A(o.meta.title,P(i,`${a}/${t}`),g)}function Kt(e,a){let t=a||e.summary(),n=e.getSharedStore().listEntries(),o='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Entries</span></nav>';o+='<div class="page-head"><div><h1>All raw entries</h1><p class="page-sub">Every conversation line that the ingest pipeline captured. Absorb compiles these into typed articles nightly.</p></div></div>';let i=new Map;for(let s of n){let d=i.get(s.date)||[];d.push(s),i.set(s.date,d)}for(let[s,d]of[...i].reverse()){o+=`<div class="section-head"><h2>${s}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${d.length} entries</span></div>`;for(let l of d)o+=`<div class="entry-card">
2877
2877
  <div class="meta-line">
2878
2878
  <a href="/agent/${encodeURIComponent(l.agentId)}">${p(l.agentId)}</a>
2879
2879
  \xB7 via ${p(l.source)} \xB7 <code>${p(l.id)}</code>
2880
2880
  </div>
2881
2881
  <p>${p(l.content.slice(0,400))}${l.content.length>400?"\u2026":""}</p>
2882
- </div>`}return A("All Entries",P(t),o)}function Kt(e,a,t){let r=t||e.summary(),n='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Search</span></nav>';n+=`<div class="page-head"><div><h1>\u201C${p(a)}\u201D</h1><p class="page-sub">Full-text search across every agent's wiki.</p></div></div>`;let o=0,i=[];for(let s of r){let l=e.getAgentWiki(s.agentId).findRelevant(a,void 0,10);if(l.length>0){i.push(`<div class="section-head"><h2>${p(s.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${l.length} match${l.length===1?"":"es"}</span></div>`);for(let c of l){let m=`/agent/${encodeURIComponent(s.agentId)}`;i.push(`<div class="entry-card">
2882
+ </div>`}return A("All Entries",P(t),o)}function Yt(e,a,t){let r=t||e.summary(),n='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Search</span></nav>';n+=`<div class="page-head"><div><h1>\u201C${p(a)}\u201D</h1><p class="page-sub">Full-text search across every agent's wiki.</p></div></div>`;let o=0,i=[];for(let s of r){let l=e.getAgentWiki(s.agentId).findRelevant(a,void 0,10);if(l.length>0){i.push(`<div class="section-head"><h2>${p(s.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${l.length} match${l.length===1?"":"es"}</span></div>`);for(let c of l){let m=`/agent/${encodeURIComponent(s.agentId)}`;i.push(`<div class="entry-card">
2883
2883
  <div class="meta-line">${H((c.meta.tags||[]).slice(0,3),s.agentId)}</div>
2884
2884
  <h3><a href="${m}/article/${encodeURIComponent(c.path)}">${p(c.meta.title)}</a></h3>
2885
2885
  <p>${p(c.content.slice(0,240))}\u2026</p>
2886
- </div>`)}o+=l.length}}return n+=i.join(""),o===0&&(n+='<p style="color:var(--muted);margin-top:24px">No matching articles found.</p>'),A(`Search: ${a}`,P(r),n,a)}function Yt(e,a,t){let r=t||e.summary(),n='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Tag</span></nav>';n+=`<div class="page-head"><div><h1>${p(a)}</h1><p class="page-sub">All articles tagged <span class="tag">${p(a)}</span>, across every agent.</p></div></div>`;let o=0;for(let i of r){let s;try{s=e.getAgentWiki(i.agentId)}catch{continue}let d=s.findByTags([a],void 0,100);if(d.length!==0){n+=`<div class="section-head"><h2>${p(i.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${d.length}</span></div>`;for(let l of d){let c=`/agent/${encodeURIComponent(i.agentId)}`;n+=`<div class="entry-card">
2886
+ </div>`)}o+=l.length}}return n+=i.join(""),o===0&&(n+='<p style="color:var(--muted);margin-top:24px">No matching articles found.</p>'),A(`Search: ${a}`,P(r),n,a)}function Jt(e,a,t){let r=t||e.summary(),n='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Tag</span></nav>';n+=`<div class="page-head"><div><h1>${p(a)}</h1><p class="page-sub">All articles tagged <span class="tag">${p(a)}</span>, across every agent.</p></div></div>`;let o=0;for(let i of r){let s;try{s=e.getAgentWiki(i.agentId)}catch{continue}let d=s.findByTags([a],void 0,100);if(d.length!==0){n+=`<div class="section-head"><h2>${p(i.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${d.length}</span></div>`;for(let l of d){let c=`/agent/${encodeURIComponent(i.agentId)}`;n+=`<div class="entry-card">
2887
2887
  <div class="meta-line">${H((l.meta.tags||[]).slice(0,6),i.agentId)}</div>
2888
2888
  <h3><a href="${c}/article/${encodeURIComponent(l.path)}">${p(l.meta.title)}</a></h3>
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>`),A(`Tag: ${a}`,P(r),n)}function Jt(e,a,t,r){let n=r||e.summary(),o;try{o=e.getAgentWiki(a)}catch{return A(`Tag: ${t}`,P(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">
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>`),A(`Tag: ${a}`,P(r),n)}function Xt(e,a,t,r){let n=r||e.summary(),o;try{o=e.getAgentWiki(a)}catch{return A(`Tag: ${t}`,P(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">${H((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 A(`${a} \xB7 ${t}`,P(n),d)}function B(e,a,t){let r=e.rebuildIndex(),n=$e(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">${Se(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 Xt(e){let{wikiDir:a,agentFilter:t,peers:r=[],mode:n="graph",pathPrefix:o=""}=e,i=o.replace(/\/+$/,""),s=new Me(a,void 0,n),d=new ne(s,a),l=r.length>0?new te(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,C=200;try{if(x.startsWith("/remote/")&&l){let w=x.slice(8).split("/article/");if(w.length===2){let[v,b]=w,h=v.indexOf("/"),_=decodeURIComponent(v.slice(0,h)),y=v.slice(h+1),S=await l.getRemoteArticle(_,y,b);if(S){let O=await l.getRemoteAgents(),Y=[...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(y)} @ ${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+=oe(S.content,R),f=A(S.meta.title,P(Y),T)}}}if(!f&&t){let w=s.getAgentWiki(t);if(x==="/"||x===""){let v=w.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=A(t,B(w,t),h)}else if(x.startsWith("/article/")){let v=x.slice(9),b=w.readArticle(v);if(b){let h=w.rebuildIndex(),_=new Map;for(let S of h.articles)_.set(S.title,S.path);let y=`<h1>${p(b.meta.title)}</h1>`;y+='<dl class="meta">',y+=`<dt>Tags</dt><dd>${(b.meta.tags||[]).map(S=>`<span class="tag">${S}</span>`).join(" ")}</dd>`,y+=`<dt>Updated</dt><dd>${b.meta.lastUpdated}</dd>`,b.meta.sources?.length&&(y+=`<dt>Sources</dt><dd>${b.meta.sources.length} entries</dd>`),y+="</dl>",y+=oe(b.content,_),f=A(b.meta.title,B(w,t,v),y)}}else if(x==="/lint"){let v=w.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=A("Health Check",B(w,t),b)}else if(x==="/search"){let v=g.searchParams.get("q")||"",b=await w.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=A(`Search: ${v}`,B(w,t),h)}else if(x.startsWith("/tag/")){let v=decodeURIComponent(x.slice(5)),b=w.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">${H((_.meta.tags||[]).slice(0,6))}</div></div>`;b.length===0&&(h+="<p>No articles with this tag.</p>"),f=A(`Tag: ${v}`,B(w,t),h)}}else if(!f&&(f=d.handle(x,g.searchParams))===null){let w=l?await l.getRemoteAgents():[],v=s.summary(),b=new Map(v.map(y=>[y.agentId,y])),h=[],_=new Set;for(let y of v){let S=w.find(O=>O.agentId===y.agentId);S&&S.totalArticles>y.totalArticles?h.push({...S,totalEntries:Math.max(y.totalEntries,S.totalEntries),unabsorbed:Math.max(y.unabsorbed,S.unabsorbed)}):h.push(y),_.add(y.agentId)}for(let y of w)_.has(y.agentId)||(h.push(y),_.add(y.agentId));if(x==="/agents")f=Bt(s,h,w);else if(x==="/entries")f=qt(s,h);else if(x==="/search")f=Kt(s,g.searchParams.get("q")||"",h);else if(x.startsWith("/tag/"))f=Yt(s,decodeURIComponent(x.slice(5)),h);else if(x.match(/^\/agent\/[^/]+\/tag\/.+/)){let y=x.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);f=Jt(s,decodeURIComponent(y[1]),decodeURIComponent(y[2]),h)}else if(x.startsWith("/agent/")){let y=x.slice(7),S=y.indexOf("/article/");if(S===-1)f=Ut(s,y,h);else{let O=y.slice(0,S),Y=y.slice(S+9);if(f=Ft(s,O,Y,h),!f&&l){let T=w.find(R=>R.agentId===O);if(T){let R=await l.getRemoteArticle(T.peerUrl,O,Y);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(Ga=>`<span class="tag">${Ga}</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+=oe(R.content,new Map),f=A(R.meta.title,P(h),I)}}}}}}if(!f){C=404;let w=t?B(s.getAgentWiki(t),t):P(s.summary());f=A("Not Found",w,"<h1>Page not found</h1>")}}catch(w){C=500,f=A("Error","",`<h1>Error</h1><pre>${p(w.message)}</pre>`)}if(C===200&&e.curator){let w=Gt(s,d,x,t);w&&(f=Ta(f,w,e.curatorEndpoint,e.curatorToken?.(c)))}m.writeHead(C,{"Content-Type":"text/html; charset=utf-8"}),m.end(i?Vt(f,i):f)}}function Gt(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(!je(i.baseDir,o))return null;let s=i.readArticle(o);return s?{agentId:n,path:o,title:s.meta.title}:null}function Vt(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=Xt({wikiDir:e,agentFilter:t,peers:r,mode:n});Ht((s,d)=>{o(s,d)}).listen(a)}import{existsSync as Qt,readFileSync as Zt}from"fs";ce();function vo(e){let a=q(e),t={};if(Qt(a))try{t=F(JSON.parse(Zt(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:X.enabled,agents:n,exemptQuestions:typeof r.exemptQuestions=="boolean"?r.exemptQuestions:X.exemptQuestions,retentionDays:Number.isInteger(r.retentionDays)&&r.retentionDays>=0?r.retentionDays:X.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`}:J(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 er={"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 ar(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=er[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=ar(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{appendFileSync as tr,chmodSync as rr,existsSync as za,readFileSync as Ea,writeFileSync as nr}from"fs";function or(e){return za(e)?Object.fromEntries(Pe(Ea(e,"utf-8"))):{}}function Ao(e,a,t){if(!/^[A-Z_][A-Z0-9_]*$/.test(a))throw new Error(`not an environment variable name: ${a}`);if(!t||/[\r\n]/.test(t))throw new Error("the value must be one non-empty line");if(or(e)[a])return!1;if(!za(e))return nr(e,`# AgentX environment variables
2892
+ </div>`;return A(`${a} \xB7 ${t}`,P(n),d)}function B(e,a,t){let r=e.rebuildIndex(),n=_e(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">${Se(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 Gt(e){let{wikiDir:a,agentFilter:t,peers:r=[],mode:n="graph",pathPrefix:o=""}=e,i=o.replace(/\/+$/,""),s=new Me(a,void 0,n),d=new ne(s,a),l=r.length>0?new te(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,C=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(),Y=[...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+=oe(S.content,R),f=A(S.meta.title,P(Y),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=A(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+=oe(b.content,$),f=A(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=A("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=A(`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">${H(($.meta.tags||[]).slice(0,6))}</div></div>`;b.length===0&&(h+="<p>No articles with this tag.</p>"),f=A(`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=Ut(s,h,y);else if(x==="/entries")f=Kt(s,h);else if(x==="/search")f=Yt(s,g.searchParams.get("q")||"",h);else if(x.startsWith("/tag/"))f=Jt(s,decodeURIComponent(x.slice(5)),h);else if(x.match(/^\/agent\/[^/]+\/tag\/.+/)){let w=x.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);f=Xt(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=Ft(s,w,h);else{let O=w.slice(0,S),Y=w.slice(S+9);if(f=qt(s,O,Y,h),!f&&l){let T=y.find(R=>R.agentId===O);if(T){let R=await l.getRemoteArticle(T.peerUrl,O,Y);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(Va=>`<span class="tag">${Va}</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+=oe(R.content,new Map),f=A(R.meta.title,P(h),I)}}}}}}if(!f){C=404;let y=t?B(s.getAgentWiki(t),t):P(s.summary());f=A("Not Found",y,"<h1>Page not found</h1>")}}catch(y){C=500,f=A("Error","",`<h1>Error</h1><pre>${p(y.message)}</pre>`)}if(C===200&&e.curator){let y=Vt(s,d,x,t);y&&(f=Ia(f,y,e.curatorEndpoint,e.curatorToken?.(c)))}m.writeHead(C,{"Content-Type":"text/html; charset=utf-8"}),m.end(i?Qt(f,i):f)}}function Vt(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(!We(i.baseDir,o))return null;let s=i.readArticle(o);return s?{agentId:n,path:o,title:s.meta.title}:null}function Qt(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 uo(e,a=4200,t,r=[],n="graph"){let o=Gt({wikiDir:e,agentFilter:t,peers:r,mode:n});Lt((s,d)=>{o(s,d)}).listen(a)}import{existsSync as Zt,readFileSync as er}from"fs";ce();function wo(e){let a=q(e),t={};if(Zt(a))try{t=F(JSON.parse(er(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:X.enabled,agents:n,exemptQuestions:typeof r.exemptQuestions=="boolean"?r.exemptQuestions:X.exemptQuestions,retentionDays:Number.isInteger(r.retentionDays)&&r.retentionDays>=0?r.retentionDays:X.retentionDays,engine:t?.workflows?.enabled===!0}}async function yo(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`}:J(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 ar={"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 tr(e){if(typeof e!="string")return null;let a=e.match(/^\$\{(\w+)\}$/);return a?a[1]:null}function $o(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=ar[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=tr(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{appendFileSync as rr,chmodSync as nr,existsSync as Ea,readFileSync as Pa,writeFileSync as or}from"fs";function ir(e){return Ea(e)?Object.fromEntries(Pe(Pa(e,"utf-8"))):{}}function Co(e,a,t){if(!/^[A-Z_][A-Z0-9_]*$/.test(a))throw new Error(`not an environment variable name: ${a}`);if(!t||/[\r\n]/.test(t))throw new Error("the value must be one non-empty line");if(ir(e)[a])return!1;if(!Ea(e))return or(e,`# AgentX environment variables
2893
2893
  # (Never commit this file: it contains secrets.)
2894
2894
 
2895
2895
  ${a}=${t}
2896
- `,{mode:384}),!0;try{rr(e,384)}catch{}let r=Ea(e,"utf-8"),n=r===""||r.endsWith(`
2896
+ `,{mode:384}),!0;try{nr(e,384)}catch{}let r=Pa(e,"utf-8"),n=r===""||r.endsWith(`
2897
2897
  `)?"":`
2898
- `;return tr(e,`${n}${a}=${t}
2899
- `),!0}import{execFileSync as ir}from"child_process";function zo(e){if(e!=="claude")return null;let a=Ke(e);if(!a)return null;try{let t=ir(a,["auth","status"],{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]});return Pa(t)}catch(t){return typeof t?.stdout=="string"?Pa(t.stdout):null}}function Pa(e){try{let a=JSON.parse(e);return typeof a?.loggedIn=="boolean"?a.loggedIn:null}catch{return null}}import{existsSync as Na,readdirSync as lr}from"fs";import{join as ja}from"path";import{join as sr}from"path";function Ra(e){return/^[\w@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function U(e){return(a,t)=>`cd ${Ra(t)} && npx -y skills add ${Ra(a)} -a ${e} -y`}var ie={tier:"claude-code",skillDirs:e=>[sr(e,".claude","skills")],addSkillCommand:U("claude-code"),instructionsFile:"CLAUDE.md"};import{join as dr}from"path";var Oa={tier:"codex-cli",skillDirs:e=>[dr(e,".agents","skills")],addSkillCommand:U("codex"),instructionsFile:"AGENTS.md"};import{join as Ae}from"path";var Da={tier:"opencode",skillDirs:e=>[Ae(e,".agents","skills"),Ae(e,".opencode","skills"),Ae(e,".claude","skills")],addSkillCommand:U("opencode"),instructionsFile:"AGENTS.md"};import{join as Ce}from"path";var Ma=e=>({...ie,tier:e,skillDirs:a=>[Ce(a,".claude","skills"),Ce(a,".skills"),Ce(a,"skills")]}),Ha=Ma("sdk"),La=Ma("orchestrator");var cr={"claude-code":ie,"codex-cli":Oa,opencode:Da,sdk:Ha,orchestrator:La};function Wa(e){return cr[e??"claude-code"]??null}function Vo(e,a){return Wa(e)?.skillDirs(a)[0]??null}function Qo(e,a){let t=new Map;for(let r of Wa(e)?.skillDirs(a)??[])if(Na(r))for(let n of lr(r))n.startsWith(".")||t.has(n)||Na(ja(r,n,"SKILL.md"))&&t.set(n,ja(r,n));return[...t].map(([r,n])=>({name:r,dir:n})).sort((r,n)=>r.name.localeCompare(n.name))}Va();function ai(e,a,t=20){return e.prepare(`SELECT task_id, agent_id, channel, chat_id, status, started_at, finished_at, message_preview
2898
+ `;return rr(e,`${n}${a}=${t}
2899
+ `),!0}import{execFileSync as sr}from"child_process";function Eo(e){if(e!=="claude")return null;let a=Ye(e);if(!a)return null;try{let t=sr(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 ja,readdirSync as cr}from"fs";import{join as Wa}from"path";import{join as dr}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 ie={tier:"claude-code",skillDirs:e=>[dr(e,".claude","skills")],addSkillCommand:U("claude-code"),instructionsFile:"CLAUDE.md"};import{join as lr}from"path";var Da={tier:"codex-cli",skillDirs:e=>[lr(e,".agents","skills")],addSkillCommand:U("codex"),instructionsFile:"AGENTS.md"};import{join as Ae}from"path";var Ma={tier:"opencode",skillDirs:e=>[Ae(e,".agents","skills"),Ae(e,".opencode","skills"),Ae(e,".claude","skills")],addSkillCommand:U("opencode"),instructionsFile:"AGENTS.md"};import{join as Ce}from"path";var Ha=e=>({...ie,tier:e,skillDirs:a=>[Ce(a,".claude","skills"),Ce(a,".skills"),Ce(a,"skills")]}),La=Ha("sdk"),Na=Ha("orchestrator");var pr={"claude-code":ie,"codex-cli":Da,opencode:Ma,sdk:La,orchestrator:Na};function Ba(e){return pr[e??"claude-code"]??null}function Qo(e,a){return Ba(e)?.skillDirs(a)[0]??null}function Zo(e,a){let t=new Map;for(let r of Ba(e)?.skillDirs(a)??[])if(ja(r))for(let n of cr(r))n.startsWith(".")||t.has(n)||ja(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))}Qa();function ti(e,a,t=20){return e.prepare(`SELECT task_id, agent_id, channel, chat_id, status, started_at, finished_at, message_preview
2900
2900
  FROM task_traces
2901
2901
  WHERE person = ? AND (channel IS NULL OR channel != 'a2a')
2902
- 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 pr(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 Ba(e,a,t,r,...n){return pr(e)?e.prepare(`SELECT id, state, channel, agent_id, text, created_at FROM requests
2902
+ 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 xr(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 xr(e)?e.prepare(`SELECT id, state, channel, agent_id, text, created_at FROM requests
2903
2903
  WHERE person = ? AND state IN (${t.map(()=>"?").join(",")})
2904
- ${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 ti(e,a){return Ba(e,a,de,"ORDER BY created_at")}function ri(e,a,t=50){return Ba(e,a,[...de,...Ie],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}Qa();var Te="member:",xr=90,gr="members",ur="tailscale-user-login",mr=400,fr=60*60*1e3;function hr(e){let a=e.scopes.find(t=>t.startsWith(Te));return a?a.slice(Te.length):null}function Fa(e,a){if(!e)return null;let t=a.verify(e),r=t?hr(t):null;return t&&r?{rec:t,personId:r}:null}function ci(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:[`${Te}${t.id}`],expiresInDays:xr}),{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 br=Math.round(He/6e4);function vr(e){return e==="client"?"Your project":"My work"}function pi(e){let a=vr(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: ${Le(e.code)}`,` The code works once, for ${br} 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(`
2905
- `)}var wr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",yr="Too many machines are waiting for the owner's answer. Try again later.",Ua="That code didn't work. Check it, or ask the person who invited you for a new one.",qa=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ka(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function kr(e){if(!Ka(e))return null;let a=qa(e,ur).toLowerCase();return a?a.slice(0,80):null}function _r(e){let a=e.socket?.remoteAddress||"unknown";if(!Ka(e))return a;let t=qa(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 Sr(e){return e.identities.map(ze).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function xi(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=_r(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 V(e,2048);s=b.code,d=$r(b.machine)}catch{}let l=a.codes.redeem(s),c=l?Fa(l.token,a.tokens):null;if(await Cr(t,a.minMs??mr),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Ua}};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:Ua}};let x=kr(e),f=Sr(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:wr}};let C=d||"Unnamed machine",w=u.name.slice(0,40),v=Ne(a.root,{title:`New machine for ${w}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${w}'s own work?`,recommend:`Yes if ${w} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:gr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:C,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:C}),n(`[member] ${g} paired "${C}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:C,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:yr}})}var se="this machine is not paired",Ar="waiting for the owner to approve this machine";function Ya(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function gi(e,a){return a.state==="pending"&&a.cardId?Ya(xe(e,a.cardId)):null}function ui(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=Fa(e,a.tokens);if(!o)return{ok:!1,status:401,error:se};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:se};if(a.people&&!a.people().some(c=>c.id===s))return Ja(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:se};if(d.state==="pending"){let c=d.cardId?xe(a.root,d.cardId):null,m=Ya(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:se}}else return{ok:!1,status:403,error:Ar,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=fr||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 Ja(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 mi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Ja(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 Xa=["gitlab","github"];function Tr(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Xa.includes(r))throw new Error(`Request status works on ${Xa.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 bi(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function vi(e){let{summary:a}=Q(t=>Tr(t,e?.channel,!!e?.enabled));return{summary:a}}var yi="https://myaccount.google.com/apppasswords";function ki(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 _i(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 $i(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function Ai(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ci(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 Ti(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 Ii(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 Ir="https://ntfy.sh";function Ei(e){return{enabled:!!e?.enabled,server:e?.server||Ir,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Pi(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}export{he as a,oa as b,ve as c,at as d,tt as e,rt as f,pa as g,xt as h,$n as i,Sn as j,An as k,ko as l,or as m,Ao as n,zo as o,Wa as p,Vo as q,Qo as r,Rn as s,On as t,At as u,It as v,we as w,Dn as x,Mn as y,zt as z,Bn as A,Un as B,Fn as C,ai as D,ti as E,ri as F,xr as G,ci as H,br as I,vr as J,pi as K,_r as L,xi as M,gi as N,ui as O,Ja as P,mi as Q,Xa as R,Tr as S,bi as T,vi as U,yi as V,ki as W,_i as X,$i as Y,Ai as Z,Ci as _,Ti as $,Ii as aa,Ei as ba,Pi as ca,Xt as da,go as ea,vo as fa,wo as ga};
2906
- //# sourceMappingURL=chunk-I4U2ELEX.js.map
2904
+ ${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 ri(e,a){return Ua(e,a,de,"ORDER BY created_at")}function ni(e,a,t=50){return Ua(e,a,[...de,...Ie],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}Za();var Te="member:",gr=90,ur="members",mr="tailscale-user-login",fr=400,hr=60*60*1e3;function br(e){let a=e.scopes.find(t=>t.startsWith(Te));return a?a.slice(Te.length):null}function qa(e,a){if(!e)return null;let t=a.verify(e),r=t?br(t):null;return t&&r?{rec:t,personId:r}:null}function pi(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:[`${Te}${t.id}`],expiresInDays:gr}),{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 vr=Math.round(He/6e4);function wr(e){return e==="client"?"Your project":"My work"}function xi(e){let a=wr(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: ${Le(e.code)}`,` The code works once, for ${vr} 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(`
2905
+ `)}var yr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",kr="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 $r(e){if(!Ya(e))return null;let a=Ka(e,mr).toLowerCase();return a?a.slice(0,80):null}function _r(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 Sr(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function Ar(e){return e.identities.map(ze).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function gi(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=_r(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 V(e,2048);s=b.code,d=Sr(b.machine)}catch{}let l=a.codes.redeem(s),c=l?qa(l.token,a.tokens):null;if(await Tr(t,a.minMs??fr),!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=$r(e),f=Ar(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:yr}};let C=d||"Unnamed machine",y=u.name.slice(0,40),v=Ne(a.root,{title:`New machine for ${y}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${C}". 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:ur},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:C,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:C}),n(`[member] ${g} paired "${C}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:C,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:kr}})}var se="this machine is not paired",Cr="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 ui(e,a){return a.state==="pending"&&a.cardId?Ja(xe(e,a.cardId)):null}function mi(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:se};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:se};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:se};if(d.state==="pending"){let c=d.cardId?xe(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:se}}else return{ok:!1,status:403,error:Cr,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=hr||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 fi(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 Tr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Ga=["gitlab","github"];function Ir(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 vi(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function wi(e){let{summary:a}=Q(t=>Ir(t,e?.channel,!!e?.enabled));return{summary:a}}var ki="https://myaccount.google.com/apppasswords";function $i(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 _i(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 Si(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function Ti(e){return`${e.name} <${e.from}> via ${e.host}:${e.port}`}async function Ii(e,a){return je({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 zi(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(`
2906
+ `)}}function Pi(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ri(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 Oi(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 Di(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 zr="https://ntfy.sh";function Hi(e){return{enabled:!!e?.enabled,server:e?.server||zr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Li(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}export{he as a,ia as b,ve as c,tt as d,rt as e,nt as f,xa as g,gt as h,Sn as i,An as j,Cn as k,$o as l,ir as m,Co as n,Eo as o,Ba as p,Qo as q,Zo as r,On as s,Dn as t,Ct as u,zt as v,we as w,Mn as x,Hn as y,Et as z,Un as A,Fn as B,qn as C,ti as D,ri as E,ni as F,gr as G,ur as H,pi as I,vr as J,wr as K,xi as L,yr as M,kr as N,$r as O,_r as P,Sr as Q,Ar as R,gi as S,Ja as T,ui as U,mi as V,Xa as W,fi as X,Ga as Y,Ir as Z,vi as _,wi as $,ki as aa,$i as ba,_i as ca,Si as da,Ti as ea,Ii as fa,zi as ga,Pi as ha,Ri as ia,Oi as ja,Di as ka,Hi as la,Li as ma,Gt as na,uo as oa,wo as pa,yo as qa};
2907
+ //# sourceMappingURL=chunk-EM72LW2F.js.map