agentix-cli 0.169.0 → 0.171.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +2 -1
  2. package/dist/{App-GK5F6QMB.js → App-56QIEQGH.js} +2 -2
  3. package/dist/{ChatApp-4HHJB4HM.js → ChatApp-JNWIXMDN.js} +2 -2
  4. package/dist/{absorb-eval-PO7TUGT2.js → absorb-eval-BYYFZJCC.js} +2 -2
  5. package/dist/adapter-YQ37MDPV.js +12 -0
  6. package/dist/adapter-YQ37MDPV.js.map +1 -0
  7. package/dist/{agent-6WKET7JZ.js → agent-2SQYGIUD.js} +2 -2
  8. package/dist/{board-dashboard-NEYLE6NJ.js → board-dashboard-QFCOFP7F.js} +552 -352
  9. package/dist/board-dashboard-QFCOFP7F.js.map +1 -0
  10. package/dist/{chunk-E67Z6OYF.js → chunk-2BJ7NIGG.js} +2 -2
  11. package/dist/{chunk-COMJ7R5T.js → chunk-35I76HQS.js} +2 -2
  12. package/dist/{chunk-LXW7H4D4.js → chunk-35R7Y7BT.js} +2 -2
  13. package/dist/{chunk-DCJHCUEQ.js → chunk-5KVTIFRY.js} +2 -2
  14. package/dist/{chunk-5PEXL5LD.js → chunk-74RXD676.js} +2 -2
  15. package/dist/chunk-AQGQLVCD.js +3 -0
  16. package/dist/chunk-AQGQLVCD.js.map +1 -0
  17. package/dist/{chunk-FEA3XMVU.js → chunk-BAAKV4HK.js} +69 -69
  18. package/dist/chunk-BAAKV4HK.js.map +1 -0
  19. package/dist/{chunk-AU3VT7BD.js → chunk-DMCMV4UJ.js} +2 -2
  20. package/dist/{chunk-6JKFJM2D.js → chunk-DOBTHQ32.js} +2 -2
  21. package/dist/{chunk-Z6ZR2ELO.js → chunk-ES236GV6.js} +2 -2
  22. package/dist/{chunk-E7Y4G3FK.js → chunk-FBNU7MMW.js} +94 -94
  23. package/dist/chunk-FBNU7MMW.js.map +1 -0
  24. package/dist/{chunk-5QI7XFTA.js → chunk-FOTAGQEL.js} +2 -2
  25. package/dist/{chunk-S34KFBMJ.js → chunk-GALI5ANI.js} +3 -3
  26. package/dist/{chunk-ZTIOHZIL.js → chunk-HZXLZIB4.js} +2 -2
  27. package/dist/{chunk-CBXPIKPJ.js → chunk-IPHFWU2F.js} +2 -2
  28. package/dist/{chunk-U5SJLLXH.js → chunk-KE3KLMMK.js} +2 -2
  29. package/dist/{chunk-KMPUUH5R.js → chunk-LB55Q3K4.js} +2 -2
  30. package/dist/{chunk-UF5TWOKL.js → chunk-LXRLD4VQ.js} +12 -12
  31. package/dist/chunk-LXRLD4VQ.js.map +1 -0
  32. package/dist/{chunk-YQM6VR6U.js → chunk-MY7C6E4Y.js} +2 -2
  33. package/dist/{chunk-VUEQ4SL5.js → chunk-N6VBEITO.js} +2 -2
  34. package/dist/chunk-N6VBEITO.js.map +1 -0
  35. package/dist/chunk-NGGEGY5K.js +92 -0
  36. package/dist/chunk-NGGEGY5K.js.map +1 -0
  37. package/dist/{chunk-UKKOBMOP.js → chunk-NR5IZJYS.js} +2 -2
  38. package/dist/{chunk-EEM433JK.js → chunk-P3GQPEMU.js} +36 -35
  39. package/dist/chunk-P3GQPEMU.js.map +1 -0
  40. package/dist/{chunk-PIJ6ECBC.js → chunk-TAUXWIYB.js} +2 -2
  41. package/dist/{chunk-HFSPH5WM.js → chunk-TB3ZEMTC.js} +2 -2
  42. package/dist/{chunk-BRK6M6LA.js → chunk-VJ5HC63R.js} +2 -2
  43. package/dist/chunk-VJ5HC63R.js.map +1 -0
  44. package/dist/{chunk-U4PICSLC.js → chunk-WO4XKOMM.js} +2 -2
  45. package/dist/{chunk-JKMFMW3E.js → chunk-WVPFWUR2.js} +2 -2
  46. package/dist/{chunk-TVGVQABC.js → chunk-XCYGF4RB.js} +2 -2
  47. package/dist/{chunk-BRQKV4FC.js → chunk-XUT4RBU6.js} +2 -2
  48. package/dist/{chunk-6VKWJQOX.js → chunk-YE3MGLJF.js} +170 -170
  49. package/dist/chunk-YE3MGLJF.js.map +1 -0
  50. package/dist/{chunk-KWY5IBII.js → chunk-YLQZFV6Y.js} +2 -2
  51. package/dist/cli.js +1 -1
  52. package/dist/{client-DOIYODET.js → client-LP4PURY2.js} +2 -2
  53. package/dist/config-IBOY7BGF.js +2 -0
  54. package/dist/config-mutate-PETOQADF.js +2 -0
  55. package/dist/config-mutator-2NLZ37LL.js +2 -0
  56. package/dist/{contributions-2CJFYRZ7.js → contributions-NQ3OQ4O4.js} +2 -2
  57. package/dist/{doctor-OQZMDL5S.js → doctor-AMX2GRRN.js} +2 -2
  58. package/dist/{facts-ROUMKS7I.js → facts-ALJBF7IA.js} +2 -2
  59. package/dist/{follow-up-tool-PQUPXQQT.js → follow-up-tool-3XSPNZKM.js} +2 -2
  60. package/dist/hub-DRCMPJMQ.js +2 -0
  61. package/dist/index.d.ts +577 -46
  62. package/dist/index.js +1 -1
  63. package/dist/index.js.map +1 -1
  64. package/dist/processes-EWARF6ZW.js +2 -0
  65. package/dist/{program-URGH65VO.js → program-O3BJYC47.js} +298 -296
  66. package/dist/program-O3BJYC47.js.map +1 -0
  67. package/dist/{promote-ZWQAL3RE.js → promote-4F2H3WEB.js} +2 -2
  68. package/dist/{query-N4EJ24LW.js → query-25FU55U6.js} +2 -2
  69. package/dist/{query-settings-RZV5ELLC.js → query-settings-5BLTPQQQ.js} +2 -2
  70. package/dist/{registry-EBYOZK3P.js → registry-MXZBIPE5.js} +2 -2
  71. package/dist/{request-planner-KCG6QB6M.js → request-planner-7JLFVL6Y.js} +2 -2
  72. package/dist/{review-candidates-3GHWVJQ3.js → review-candidates-MHIKLDT7.js} +2 -2
  73. package/dist/routing-ZSGWR6ID.js +2 -0
  74. package/dist/schedule-tool-2VI5IWZD.js +2 -0
  75. package/dist/{scheduler-SCVCNKJC.js → scheduler-J6BGTTMH.js} +2 -2
  76. package/dist/{seat-PD7W3KAN.js → seat-WUEQNCSG.js} +2 -2
  77. package/dist/{select-Z3YXBGUP.js → select-ASFYQYDU.js} +2 -2
  78. package/dist/{set-enabled-NJYJWDWH.js → set-enabled-6NIDVEZF.js} +2 -2
  79. package/dist/{sprint-tool-OLHZZAK3.js → sprint-tool-APMWCQF3.js} +2 -2
  80. package/dist/{tool-XH5QN6JM.js → tool-2CKQKDU5.js} +2 -2
  81. package/dist/{tool-7IKZO33P.js → tool-JPSOIPZZ.js} +2 -2
  82. package/dist/{tool-EVQBMGJV.js → tool-MKUGBNSW.js} +2 -2
  83. package/dist/{wiki-BPOTYAQV.js → wiki-JR6U5PSV.js} +2 -2
  84. package/dist/wiki-enrich-KFVPA2JG.js +2 -0
  85. package/package.json +5 -1
  86. package/dist/board-dashboard-NEYLE6NJ.js.map +0 -1
  87. package/dist/chunk-6VKWJQOX.js.map +0 -1
  88. package/dist/chunk-BRK6M6LA.js.map +0 -1
  89. package/dist/chunk-E7Y4G3FK.js.map +0 -1
  90. package/dist/chunk-EEM433JK.js.map +0 -1
  91. package/dist/chunk-FEA3XMVU.js.map +0 -1
  92. package/dist/chunk-NKCS6EZ7.js +0 -92
  93. package/dist/chunk-NKCS6EZ7.js.map +0 -1
  94. package/dist/chunk-UF5TWOKL.js.map +0 -1
  95. package/dist/chunk-VUEQ4SL5.js.map +0 -1
  96. package/dist/config-3UBJRE5R.js +0 -2
  97. package/dist/config-mutate-ZRPDYJKN.js +0 -2
  98. package/dist/config-mutator-B5MR3V4B.js +0 -2
  99. package/dist/hub-LOW7KS5N.js +0 -2
  100. package/dist/processes-QZWODHBX.js +0 -2
  101. package/dist/program-URGH65VO.js.map +0 -1
  102. package/dist/routing-XULOU6BI.js +0 -2
  103. package/dist/schedule-tool-ALZXDGGC.js +0 -2
  104. package/dist/wiki-enrich-JCNGRYQZ.js +0 -2
  105. /package/dist/{App-GK5F6QMB.js.map → App-56QIEQGH.js.map} +0 -0
  106. /package/dist/{ChatApp-4HHJB4HM.js.map → ChatApp-JNWIXMDN.js.map} +0 -0
  107. /package/dist/{absorb-eval-PO7TUGT2.js.map → absorb-eval-BYYFZJCC.js.map} +0 -0
  108. /package/dist/{agent-6WKET7JZ.js.map → agent-2SQYGIUD.js.map} +0 -0
  109. /package/dist/{chunk-E67Z6OYF.js.map → chunk-2BJ7NIGG.js.map} +0 -0
  110. /package/dist/{chunk-COMJ7R5T.js.map → chunk-35I76HQS.js.map} +0 -0
  111. /package/dist/{chunk-LXW7H4D4.js.map → chunk-35R7Y7BT.js.map} +0 -0
  112. /package/dist/{chunk-DCJHCUEQ.js.map → chunk-5KVTIFRY.js.map} +0 -0
  113. /package/dist/{chunk-5PEXL5LD.js.map → chunk-74RXD676.js.map} +0 -0
  114. /package/dist/{chunk-AU3VT7BD.js.map → chunk-DMCMV4UJ.js.map} +0 -0
  115. /package/dist/{chunk-6JKFJM2D.js.map → chunk-DOBTHQ32.js.map} +0 -0
  116. /package/dist/{chunk-Z6ZR2ELO.js.map → chunk-ES236GV6.js.map} +0 -0
  117. /package/dist/{chunk-5QI7XFTA.js.map → chunk-FOTAGQEL.js.map} +0 -0
  118. /package/dist/{chunk-S34KFBMJ.js.map → chunk-GALI5ANI.js.map} +0 -0
  119. /package/dist/{chunk-ZTIOHZIL.js.map → chunk-HZXLZIB4.js.map} +0 -0
  120. /package/dist/{chunk-CBXPIKPJ.js.map → chunk-IPHFWU2F.js.map} +0 -0
  121. /package/dist/{chunk-U5SJLLXH.js.map → chunk-KE3KLMMK.js.map} +0 -0
  122. /package/dist/{chunk-KMPUUH5R.js.map → chunk-LB55Q3K4.js.map} +0 -0
  123. /package/dist/{chunk-YQM6VR6U.js.map → chunk-MY7C6E4Y.js.map} +0 -0
  124. /package/dist/{chunk-UKKOBMOP.js.map → chunk-NR5IZJYS.js.map} +0 -0
  125. /package/dist/{chunk-PIJ6ECBC.js.map → chunk-TAUXWIYB.js.map} +0 -0
  126. /package/dist/{chunk-HFSPH5WM.js.map → chunk-TB3ZEMTC.js.map} +0 -0
  127. /package/dist/{chunk-U4PICSLC.js.map → chunk-WO4XKOMM.js.map} +0 -0
  128. /package/dist/{chunk-JKMFMW3E.js.map → chunk-WVPFWUR2.js.map} +0 -0
  129. /package/dist/{chunk-TVGVQABC.js.map → chunk-XCYGF4RB.js.map} +0 -0
  130. /package/dist/{chunk-BRQKV4FC.js.map → chunk-XUT4RBU6.js.map} +0 -0
  131. /package/dist/{chunk-KWY5IBII.js.map → chunk-YLQZFV6Y.js.map} +0 -0
  132. /package/dist/{client-DOIYODET.js.map → client-LP4PURY2.js.map} +0 -0
  133. /package/dist/{config-3UBJRE5R.js.map → config-IBOY7BGF.js.map} +0 -0
  134. /package/dist/{config-mutate-ZRPDYJKN.js.map → config-mutate-PETOQADF.js.map} +0 -0
  135. /package/dist/{config-mutator-B5MR3V4B.js.map → config-mutator-2NLZ37LL.js.map} +0 -0
  136. /package/dist/{contributions-2CJFYRZ7.js.map → contributions-NQ3OQ4O4.js.map} +0 -0
  137. /package/dist/{doctor-OQZMDL5S.js.map → doctor-AMX2GRRN.js.map} +0 -0
  138. /package/dist/{facts-ROUMKS7I.js.map → facts-ALJBF7IA.js.map} +0 -0
  139. /package/dist/{follow-up-tool-PQUPXQQT.js.map → follow-up-tool-3XSPNZKM.js.map} +0 -0
  140. /package/dist/{hub-LOW7KS5N.js.map → hub-DRCMPJMQ.js.map} +0 -0
  141. /package/dist/{processes-QZWODHBX.js.map → processes-EWARF6ZW.js.map} +0 -0
  142. /package/dist/{promote-ZWQAL3RE.js.map → promote-4F2H3WEB.js.map} +0 -0
  143. /package/dist/{query-N4EJ24LW.js.map → query-25FU55U6.js.map} +0 -0
  144. /package/dist/{query-settings-RZV5ELLC.js.map → query-settings-5BLTPQQQ.js.map} +0 -0
  145. /package/dist/{registry-EBYOZK3P.js.map → registry-MXZBIPE5.js.map} +0 -0
  146. /package/dist/{request-planner-KCG6QB6M.js.map → request-planner-7JLFVL6Y.js.map} +0 -0
  147. /package/dist/{review-candidates-3GHWVJQ3.js.map → review-candidates-MHIKLDT7.js.map} +0 -0
  148. /package/dist/{routing-XULOU6BI.js.map → routing-ZSGWR6ID.js.map} +0 -0
  149. /package/dist/{schedule-tool-ALZXDGGC.js.map → schedule-tool-2VI5IWZD.js.map} +0 -0
  150. /package/dist/{scheduler-SCVCNKJC.js.map → scheduler-J6BGTTMH.js.map} +0 -0
  151. /package/dist/{seat-PD7W3KAN.js.map → seat-WUEQNCSG.js.map} +0 -0
  152. /package/dist/{select-Z3YXBGUP.js.map → select-ASFYQYDU.js.map} +0 -0
  153. /package/dist/{set-enabled-NJYJWDWH.js.map → set-enabled-6NIDVEZF.js.map} +0 -0
  154. /package/dist/{sprint-tool-OLHZZAK3.js.map → sprint-tool-APMWCQF3.js.map} +0 -0
  155. /package/dist/{tool-XH5QN6JM.js.map → tool-2CKQKDU5.js.map} +0 -0
  156. /package/dist/{tool-7IKZO33P.js.map → tool-JPSOIPZZ.js.map} +0 -0
  157. /package/dist/{tool-EVQBMGJV.js.map → tool-MKUGBNSW.js.map} +0 -0
  158. /package/dist/{wiki-BPOTYAQV.js.map → wiki-JR6U5PSV.js.map} +0 -0
  159. /package/dist/{wiki-enrich-JCNGRYQZ.js.map → wiki-enrich-KFVPA2JG.js.map} +0 -0
@@ -1,5 +1,5 @@
1
- import{lb as m,ub as b}from"./chunk-NKCS6EZ7.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
1
+ import{mb as m,vb as b}from"./chunk-NGGEGY5K.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
2
2
 
3
3
  `))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
4
4
  `))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
5
- //# sourceMappingURL=chunk-5QI7XFTA.js.map
5
+ //# sourceMappingURL=chunk-FOTAGQEL.js.map
@@ -1,4 +1,4 @@
1
- import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-JKMFMW3E.js";import{a as H}from"./chunk-LUOW2YHY.js";import{y as N,z as ot}from"./chunk-Z6ZR2ELO.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{b as E,c as L}from"./chunk-QOYAX2FT.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
1
+ import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-WVPFWUR2.js";import{a as H}from"./chunk-LUOW2YHY.js";import{y as N,z as ot}from"./chunk-ES236GV6.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{b as E,c as L}from"./chunk-QOYAX2FT.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
2
2
 
3
3
  ## Shared wiki (other agents' articles)
4
4
 
@@ -51,5 +51,5 @@ ${o}
51
51
 
52
52
  Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
53
53
 
54
- Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-3UBJRE5R.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
- //# sourceMappingURL=chunk-S34KFBMJ.js.map
54
+ Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-IBOY7BGF.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
+ //# sourceMappingURL=chunk-GALI5ANI.js.map
@@ -1,4 +1,4 @@
1
- import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-TVGVQABC.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
1
+ import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-XCYGF4RB.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
2
2
  ## Worldview
3
3
 
4
4
  ${r}
@@ -249,4 +249,4 @@ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
249
249
  Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let m=[{role:"user",content:n}];s&&(m.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),m.push({role:"user",content:`Your previous response failed validation: ${s}
250
250
  Re-emit the FULL corrected JSON object.`}));let u=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:m}),signal:i.signal});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`anthropic API ${u.status}: ${a.slice(0,500)}`)}let d=await u.json(),e=(Array.isArray(d.content)?d.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
251
251
  `).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...l)=>t(l.map(String).join(" "))),p=c.rebuildIndex(),m=z(r),u=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(u,p,m,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let d=p.articles.map(l=>({title:l.title,path:l.path,type:l.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,d,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,d,g);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(l=>l.candidates),w=new Set(y.map(l=>l.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(l=>[l.stamp,l]));for(let l of f.articles){let A=c.readArticle(l.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${l.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(l.promotedFrom,T),S={id:Y(o,l.path),createdAt:v,status:"pending",article:l,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:l.path,title:l.title,type:l.type,stamps:l.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of l.promotedFrom)k.push({stamp:X,decision:"proposed",article:l.path,proposal:S.id,at:v})}for(let l of f.skipped)k.push({stamp:l.stamp,decision:"skipped",reason:l.reason,at:v}),i.skipped.push(l);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let m=s.now??Date.now(),u=new Date(m).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??u,lastUpdated:u,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let g=new Date(m).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:g}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:g};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
252
- //# sourceMappingURL=chunk-ZTIOHZIL.js.map
252
+ //# sourceMappingURL=chunk-HZXLZIB4.js.map
@@ -1,4 +1,4 @@
1
- import{lb as l,ub as m}from"./chunk-NKCS6EZ7.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
1
+ import{mb as l,vb as m}from"./chunk-NGGEGY5K.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
2
2
  `,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
4
- //# sourceMappingURL=chunk-CBXPIKPJ.js.map
4
+ //# sourceMappingURL=chunk-IPHFWU2F.js.map
@@ -1,4 +1,4 @@
1
- import{c as w}from"./chunk-COMJ7R5T.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
1
+ import{c as w}from"./chunk-35I76HQS.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
2
2
  ${a.content}`),t.previous??""].join(`
3
3
  `),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
4
4
  `).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
33
33
  {"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
34
34
  `)+`
35
35
  `}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
36
- //# sourceMappingURL=chunk-U5SJLLXH.js.map
36
+ //# sourceMappingURL=chunk-KE3KLMMK.js.map
@@ -1,4 +1,4 @@
1
- import{b as $,c as w}from"./chunk-HFSPH5WM.js";import{h as G,j as Y}from"./chunk-3UOTLMXD.js";import{a as I,b as J}from"./chunk-FCPTN6NF.js";import{a as U,b as Ee}from"./chunk-7I7IEX4S.js";import{d as B}from"./chunk-QIJLFPWE.js";import{execFile as Ve}from"child_process";import{writeFileSync as de,mkdirSync as C,existsSync as D,readFileSync as We}from"fs";import{resolve as _}from"path";var ve=["off","shadow","authoritative"],_e={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},ye="INTENT_LEDGER_MODE";function V(n,e=process.env){let t=H(e[_e[n]]);if(t)return t;let r=H(e[ye]);return r||"off"}function H(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return ve.includes(e)?e:null}J();import Te from"better-sqlite3";import{existsSync as tt,mkdirSync as Ie}from"fs";import{dirname as Re,resolve as be}from"path";var R=class{db;path;constructor(e={}){this.path=be(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),Ie(Re(this.path),{recursive:!0}),this.db=new Te(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Se(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let r=this.findEventBySourceId(e.source,e.sourceEventId);if(r)return r}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
1
+ import{b as $,c as w}from"./chunk-TB3ZEMTC.js";import{h as G,j as Y}from"./chunk-3UOTLMXD.js";import{a as I,b as J}from"./chunk-FCPTN6NF.js";import{a as U,b as Ee}from"./chunk-7I7IEX4S.js";import{d as B}from"./chunk-QIJLFPWE.js";import{execFile as Ve}from"child_process";import{writeFileSync as de,mkdirSync as C,existsSync as D,readFileSync as We}from"fs";import{resolve as _}from"path";var ve=["off","shadow","authoritative"],_e={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},ye="INTENT_LEDGER_MODE";function V(n,e=process.env){let t=H(e[_e[n]]);if(t)return t;let r=H(e[ye]);return r||"off"}function H(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return ve.includes(e)?e:null}J();import Te from"better-sqlite3";import{existsSync as tt,mkdirSync as Ie}from"fs";import{dirname as Re,resolve as be}from"path";var R=class{db;path;constructor(e={}){this.path=be(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),Ie(Re(this.path),{recursive:!0}),this.db=new Te(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Se(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let r=this.findEventBySourceId(e.source,e.sourceEventId);if(r)return r}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
2
2
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let r=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
3
3
  FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return r?W(r):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
4
4
  FROM intent_events WHERE id = ?`).get(e);return t?W(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
@@ -134,4 +134,4 @@ ${A(ge(a.block,i.prompt),i.report)}`,i.maxOutputTokens),agentId:i.agent,autonomy
134
134
  `);return t.length<=e?t.join(`
135
135
  `):t.slice(-e).join(`
136
136
  `)}function qe(n,e,t){return new Promise((r,i)=>{Ve("/bin/sh",["-c",n],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(s,o,a)=>{if(s&&s.killed){i(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}r({stdout:String(o??""),stderr:String(a??""),code:s?typeof s.code=="number"?s.code:1:0})})})}export{R as a,z as b,_t as c,Me as d,yt as e,Tt as f,x as g,ie as h,V as i,at as j,j as k,ee as l,bt as m,He as n,Ke as o,me as p,he as q,fe as r,P as s,X as t};
137
- //# sourceMappingURL=chunk-KMPUUH5R.js.map
137
+ //# sourceMappingURL=chunk-LB55Q3K4.js.map
@@ -1,4 +1,4 @@
1
- import{a as He,b as w,c as z,d as qe,e as pe,f as ue,g as W,h as ge,i as O,j as U,n as Fe,o as Ke,p as Ge,q as Je}from"./chunk-XVTD6I34.js";import{e as Be,i as je}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Le}from"./chunk-CBXPIKPJ.js";import{c as Ue,d as le,e as P,f as de,g as q}from"./chunk-AU3VT7BD.js";import{lb as Oe,na as We}from"./chunk-FEA3XMVU.js";import{a as Ne}from"./chunk-VUEQ4SL5.js";import{a as Te}from"./chunk-IMLAPB7G.js";import{b as Y}from"./chunk-2VDO2HEK.js";import{c as De,e as _e}from"./chunk-LQE73AZR.js";import{b as Me}from"./chunk-MRIVENBY.js";import{n as se,p as ze}from"./chunk-LQS27HSV.js";import{$ as J}from"./chunk-EEM433JK.js";import{a as H,b as G}from"./chunk-HFSPH5WM.js";import{a as Re}from"./chunk-U4PICSLC.js";import{c as Ie,d as Ee}from"./chunk-OWNQ2FD4.js";import{a as Pe}from"./chunk-ROLSSYXE.js";import{a as Ce}from"./chunk-QUFIUXMQ.js";import{Ia as Ae,Pa as Lt,Y as ae,Z as $e,fa as Ut,hb as oe,kb as j,lb as Se,ub as ie}from"./chunk-NKCS6EZ7.js";import{existsSync as F,readFileSync as Ve,writeFileSync as Qe,appendFileSync as Ht,mkdirSync as qt}from"fs";import{dirname as Ft,resolve as M}from"path";import{fileURLToPath as Kt}from"url";import{hostname as Gt}from"os";import{spawn as Jt}from"child_process";function Ye(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
1
+ import{a as He,b as w,c as z,d as qe,e as pe,f as ue,g as N,h as ge,i as O,j as U,n as Fe,o as Ke,p as Ge,q as Je}from"./chunk-XVTD6I34.js";import{e as Be,i as je}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Le}from"./chunk-IPHFWU2F.js";import{c as Ue,d as le,e as P,f as de,g as q}from"./chunk-DMCMV4UJ.js";import{lb as Oe,na as Ne}from"./chunk-BAAKV4HK.js";import{a as We}from"./chunk-N6VBEITO.js";import{a as Te}from"./chunk-IMLAPB7G.js";import{b as Y}from"./chunk-2VDO2HEK.js";import{c as De,e as _e}from"./chunk-LQE73AZR.js";import{b as Me}from"./chunk-MRIVENBY.js";import{n as se,p as ze}from"./chunk-LQS27HSV.js";import{fa as J}from"./chunk-P3GQPEMU.js";import{a as H,b as G}from"./chunk-TB3ZEMTC.js";import{a as Re}from"./chunk-WO4XKOMM.js";import{c as Ie,d as Ee}from"./chunk-OWNQ2FD4.js";import{a as Pe}from"./chunk-ROLSSYXE.js";import{a as Ce}from"./chunk-QUFIUXMQ.js";import{Ia as Ae,Pa as Lt,Y as ae,Z as $e,fa as Ut,ib as oe,lb as j,mb as Se,vb as ie}from"./chunk-NGGEGY5K.js";import{existsSync as F,readFileSync as Ve,writeFileSync as Qe,appendFileSync as Ht,mkdirSync as qt}from"fs";import{dirname as Ft,resolve as M}from"path";import{fileURLToPath as Kt}from"url";import{hostname as Gt}from"os";import{spawn as Jt}from"child_process";function Ye(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
2
2
  <div class="ax-topbar__left">
3
3
  <div class="ax-brand">
4
4
  <span class="ax-brand__mark">AX</span>
@@ -24,7 +24,7 @@ import{a as He,b as w,c as z,d as qe,e as pe,f as ue,g as W,h as ge,i as O,j as
24
24
  `),s=q(4,"Anthropic API key",P({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">
25
25
  The key is stored in <code>.env</code> as <code>ANTHROPIC_API_KEY</code> and used to authenticate requests to Anthropic. Keep it private.
26
26
  </div>`),l=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>`:"",d=`<div class="ax-wizard">
27
- <h1 class="ax-wizard__h1">${Ne(n)}</h1>
27
+ <h1 class="ax-wizard__h1">${We(n)}</h1>
28
28
  <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>
29
29
 
30
30
  ${l}
@@ -181,7 +181,7 @@ ${g}
181
181
  `;Ht(e,o+a.join(`
182
182
  `)+`
183
183
  `)}}function Ar(e,t){let n=Ze(),r=n.nodeName||Gt().replace(/\.local$/,""),a=Ye(n,r);t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(a)}async function Sr(e,t){let n="";await new Promise(a=>{e.on("data",o=>{n+=o}),e.on("end",()=>a())});let r;try{r=JSON.parse(n)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON"}));return}try{let a=Yt(r);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(a))}catch(a){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:a.message||"wizard failed"}))}}async function Cr(e,t){t.setHeader("Content-Type","application/json");let n;try{n=Se().node?.bind||"127.0.0.1:18800"}catch(i){t.writeHead(400),t.end(JSON.stringify({ok:!1,error:`Config validation failed: ${i.message}`}));return}let r=`http://${n.replace(/^0\.0\.0\.0/,"127.0.0.1")}`;if(await Xe(r)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!0}));return}let a=process.argv[1]||M(Ft(Kt(import.meta.url)),"cli.js");try{Jt(process.execPath,[a,"daemon","start"],{detached:!0,stdio:"ignore",cwd:process.cwd()}).unref()}catch(i){t.writeHead(500),t.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 Xe(r)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!1}));return}t.writeHead(504),t.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 Xe(e){try{let t=await fetch(e,{method:"GET",signal:AbortSignal.timeout(800)});return t.status>0&&t.status<600}catch{return!1}}import{mkdirSync as Zt,readFileSync as en,renameSync as tn,writeFileSync as nn}from"fs";import{dirname as rn,isAbsolute as an,resolve as on}from"path";import{createHash as sn,randomBytes as ln}from"crypto";var _r=".agentx/app-pins.json",zr=12,rt=40,at=2e3,dn=/^pin_[a-z0-9]{6,32}$/;function cn(e,t){return an(t)?t:on(e,t)}function V(e){let t=typeof e=="string"?e.trim().replace(/\s+/g," "):"";return t?/[\p{Cc}\p{Cf}]/u.test(t)?{ok:!1,error:"Use only letters, numbers, spaces and punctuation in the name."}:[...t].length>rt?{ok:!1,error:`Keep the name under ${rt} characters.`}:{ok:!0,value:t}:{ok:!1,error:"Give the button a name."}}function fe(e){let t=typeof e=="string"?e.trim():"";if(!t)return{ok:!1,error:"Give the page's address."};if(t.length>at)return{ok:!1,error:`Keep the address under ${at} characters.`};let n;try{n=new URL(t)}catch{return{ok:!1,error:"That is not a web address. It should start with https://"}}return n.protocol!=="https:"||!n.hostname?{ok:!1,error:"Only https:// pages can be pinned."}:n.username||n.password?{ok:!1,error:"Leave the user name and password out of the address."}:{ok:!0,value:n.href}}function pn(e){return`cfg_${sn("sha256").update(e).digest("hex").slice(0,12)}`}function un(e){let t=[];for(let n of e){let r=V(n.label),a=fe(n.url);!r.ok||!a.ok||t.some(o=>o.url===a.value||o.label.toLowerCase()===r.value.toLowerCase())||t.push({id:pn(a.value),label:r.value,url:a.value,source:"config"})}return t}var ot="This button is set in agentx.json (app.pins.pages). Change or remove it there.";function gn(e){let t=V(e.label);if(!t.ok)return t;let n=fe(e.url);return n.ok?{ok:!0,value:{label:t.value,url:n.value}}:n}var me=class{constructor(t,n=Date.now,r=[]){this.path=t;this.now=n;this.fixed=r}list(){return[...this.fixed,...this.load().pins.filter(t=>!this.shadowed(t))]}shadowed(t){return this.fixed.some(n=>n.url===t.url||n.label.toLowerCase()===t.label.toLowerCase())}isFixed(t){return this.fixed.some(n=>n.id===t)}load(){let t;try{t=en(this.path,"utf-8")}catch(o){return{pins:[],damaged:o?.code!=="ENOENT"}}let n;try{n=JSON.parse(t)}catch{return{pins:[],damaged:!0}}let r=Array.isArray(n?.pins)?n.pins:[],a=r.filter(o=>{let i=o;return!!i&&typeof i.id=="string"&&dn.test(i.id)&&V(i.label).ok&&fe(i.url).ok});return{pins:a,damaged:!Array.isArray(n?.pins)||a.length!==r.length}}locked(t){try{return Ee(this.path,t,{what:"The pinned pages file"})}catch(n){if(n instanceof Ie)return{ok:!1,status:409,error:n.message};throw n}}editable(){let{pins:t,damaged:n}=this.load();return n?{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:t}}write(t){Zt(rn(this.path),{recursive:!0});let n=`${this.path}.${process.pid}.tmp`;nn(n,JSON.stringify({pins:t},null,2)+`
184
- `,{mode:384}),tn(n,this.path)}add(t,n){return this.locked(()=>this.addUnlocked(t,n))}addUnlocked(t,n){let r=this.editable();if(!r.ok)return r;let a=r.pins;if(a.filter(i=>!this.shadowed(i)).length+this.fixed.length>=n)return{ok:!1,status:409,error:`You already have ${n} pinned pages, the most allowed (app.pins.max). Remove one first.`};if([...this.fixed,...a].some(i=>i.label.toLowerCase()===t.label.toLowerCase()))return{ok:!1,status:409,error:`You already have a button called ${t.label}.`};if(this.fixed.some(i=>i.url===t.url))return{ok:!1,status:409,error:"This page is already a button, set in agentx.json (app.pins.pages)."};let o={id:`pin_${ln(6).toString("hex")}`,...t,createdAt:new Date(this.now()).toISOString()};return a.push(o),this.write(a),{ok:!0,pin:o}}rename(t,n){return this.locked(()=>this.renameUnlocked(t,n))}renameUnlocked(t,n){if(this.isFixed(t))return{ok:!1,status:409,error:ot};let r=this.editable();if(!r.ok)return r;let a=r.pins,o=a.find(i=>i.id===t);return o?[...this.fixed,...a].some(i=>i.id!==t&&i.label.toLowerCase()===n.toLowerCase())?{ok:!1,status:409,error:`You already have a button called ${n}.`}:(o.label=n,this.write(a),{ok:!0,pin:o}):{ok:!1,status:404,error:"No such pinned page."}}remove(t){return this.locked(()=>this.removeUnlocked(t))}removeUnlocked(t){if(this.isFixed(t))return{ok:!1,status:409,error:ot};let n=this.editable();if(!n.ok)return n;let r=n.pins.filter(a=>a.id!==t);return r.length===n.pins.length?{ok:!1,status:404,error:"No such pinned page."}:(this.write(r),{ok:!0})}};function Mr(e,t){let n=e.app.pins;return{store:new me(cn(t,n.file),Date.now,un(n.pages)),max:n.max}}async function Nr(e,t,n,r,a){if(n!=="/api/app/pins"&&!n.startsWith("/api/app/pins/"))return!1;let o=n.slice(13);if(r==="GET"&&o==="")return R(t,200,{pins:a.store.list(),max:a.max});if(r!=="POST")return R(t,404,{error:"not found"});let i;try{i=await Y(e,4096)}catch(l){return R(t,400,{error:l.message})}let s=typeof i.id=="string"?i.id:"";if(o==="/add"){let l=gn(i);if(!l.ok)return R(t,400,{error:l.error});let d=a.store.add(l.value,a.max);return d.ok?R(t,200,{ok:!0,pin:d.pin}):R(t,d.status,{error:d.error})}if(o==="/rename"){let l=V(i.label);if(!l.ok)return R(t,400,{error:l.error});let d=a.store.rename(s,l.value);return d.ok?R(t,200,{ok:!0,pin:d.pin}):R(t,d.status,{error:d.error})}if(o==="/remove"){let l=a.store.remove(s);return l.ok?R(t,200,{ok:!0}):R(t,l.status,{error:l.error})}return R(t,404,{error:"not found"})}function R(e,t,n){return e.writeHead(t,{"Content-Type":"application/json","Cache-Control":"no-store"}),e.end(JSON.stringify(n)),!0}import{existsSync as it,readFileSync as st}from"fs";ie();function mn(e){let t=H(e),n={};if(it(t))try{n=j(JSON.parse(st(t,"utf-8")))}catch{n={}}let r=oe.safeParse(n?.approvals);return r.success?r.data:oe.parse(void 0)}function jr(e){let t=H(e),n={};if(it(t))try{n=j(JSON.parse(st(t,"utf-8")))}catch{n={}}return We({desk:n?.notifications?.desk,popupEnabled:!!mn(e).popup?.enabled})}function Hr(e){let t=e.indexOf(":");return t<=0||t===e.length-1?null:{channel:e.slice(0,t).trim(),chatId:e.slice(t+1).trim()}}async function qr(e,t={}){return G(n=>{let r=n.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 d=Array.isArray(n.mesh?.peers)?n.mesh.peers:[];if(!d.some(c=>c.name===e.forwardTo))throw new Error(`"${e.forwardTo}" is not in mesh.peers${d.length?` (known: ${d.map(c=>c.name).join(", ")})`:""}; pair the machines first`);r.forwardTo=e.forwardTo}let a=r.digest??={};e.digestEnabled!==void 0&&(a.enabled=e.digestEnabled),e.digestTime!==void 0&&(a.time=e.digestTime),e.digestTimezone===null?delete a.timezone:e.digestTimezone!==void 0&&(a.timezone=e.digestTimezone),e.destination===null?delete a.destination:e.destination!==void 0&&(a.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 d=(n.notifications??={}).desk??={};e.deskPhone!==void 0&&(d.phone=e.deskPhone),e.deskComputer!==void 0&&(d.computer=e.deskComputer)}let s=r.defaultExpiryDays??3,l=r.maxExpiryDays??30;if(s>l)throw new Error(`defaultExpiryDays (${s}) can't be more than maxExpiryDays (${l})`)},{configPath:t.configPath,reload:t.reload})}import{createServer as kn}from"http";var Q=class{peers;cache=new Map;ttl=3e4;constructor(t){this.peers=t.map(n=>({...n,url:n.url.replace(/\/$/,"")}))}async getRemoteAgents(){let t=[];return await Promise.all(this.peers.map(async n=>{try{let r=await this.fetchJson(`${n.url}/wiki/agents`);n.nodeId=r.nodeId;for(let a of r.agents||[])(a.totalEntries>0||a.totalArticles>0)&&t.push({...a,nodeId:r.nodeId,peerUrl:n.url})}catch{}})),t}async getRemoteArticles(t,n){try{return(await this.fetchJson(`${t}/wiki/articles?agent=${encodeURIComponent(n)}`)).articles||[]}catch{return[]}}async getRemoteArticle(t,n,r){try{let a=await this.fetchJson(`${t}/wiki/article?agent=${encodeURIComponent(n)}&path=${encodeURIComponent(r)}`);return{meta:{title:a.title,tags:a.tags||[],owner:a.owner,access:"public",created:a.created,lastUpdated:a.lastUpdated,sources:a.sources||[]},content:a.content,path:a.path}}catch{return null}}async fetchJson(t){let n=this.cache.get(t);if(n&&Date.now()-n.ts<this.ttl)return n.data;let r=this.peers.find(i=>t.startsWith(`${i.url}/`))?.token,a=await fetch(t,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(5e3)});if(!a.ok)throw new Error(`HTTP ${a.status}`);let o=await a.json();return this.cache.set(t,{data:o,ts:Date.now()}),o}};var lt=864e5;function he(e){let t=new Map;for(let n of e.entities.values()){let r=t.get(n.type)??[];r.push(n),t.set(n.type,r)}return t}function ve(e,t){if(t.type==="event")return t.date||t.updated;let n=He(e,t,new Set(["event"]))[0],r=t.updated||t.date;return n&&n.date>r?n.date:r}function dt(e,t,n=Date.now()){let r=[],a=new Date(n+14*lt).toISOString().slice(0,10),o=new Date(n).toISOString().slice(0,10);for(let s of t){let l=s.statements.find(c=>c.property==="due"&&/^\d{4}-\d{2}-\d{2}/.test(c.value)),d=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"}):l&&!d&&l.value<o?r.push({e:s,chip:"late",why:`was due ${l.value}`}):l&&!d&&l.value<=a?r.push({e:s,chip:"due",why:`due ${l.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&&n-Date.parse(s.date)<=30*lt&&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,l)=>i[s.chip]-i[l.chip])}function Z(e,t,n="",r){return`<div class="ox-row"><span class="ox-ic">${qe(e.ontology,t.type)}</span><div class="t"><a href="${ue(t.id)}">${w(t.title)}</a><div class="ox-sub">${w(r??`${pe(e.ontology,t.type).toLowerCase()} \xB7 ${ve(e,t)}`)}</div></div><div class="r">${n}</div></div>`}function ct(e,t){let n=t.slice(0,6).map(r=>Z(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">${t.length}</span></div>${n||'<div class="ox-empty">Nothing waits on a person.</div>'}</section>`}function fn(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 pt(e,t){let n=he(e),r=`<div class="ox-bar">${W([])}</div>`;r+=`<div class="ox-head"><div class="ox-avatar">${z("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+=fn(t),r+='<div class="ox-grid3">';for(let o of e.ontology.pillars){let i=e.ontology.types.filter(d=>d.pillar===o.id),s=i.reduce((d,c)=>d+(n.get(c.id)?.length??0),0),l=i.filter(d=>n.get(d.id)?.length).map(d=>`${d.plural??d.label} ${n.get(d.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">${z(o.icon)}</span><h2>${w(o.label)}</h2><span class="zin">${s}</span></div><div class="ox-sub" style="white-space:normal">${w(o.description??"")}</div><div class="ox-sub" style="margin-top:6px;white-space:normal">${w(l||"nothing yet")}</div></a>`}r+='</div><div class="ox-grid2">';let a=(n.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>'+(a.map(o=>`<div class="ox-ev"><span class="d">${w(o.date)}</span><span class="ox-st ${o.importance}">${o.importance}</span><a href="${ue(o.id)}">${w(o.title)}</a></div>`).join("")||'<div class="ox-empty">No events yet.</div>')+"</section>",r+=ct(e,dt(e,[...e.entities.values()])),r+="</div>",U("Wiki",O(e,{home:!0}),r)}function ut(e,t,n){let r=e.ontology.pillars.find(c=>c.id===t);if(!r)return null;let a=he(e),o=e.ontology.types.filter(c=>c.pillar===r.id),i=o.find(c=>c.id===n)??o.find(c=>a.get(c.id)?.length)??o[0],s=`<div class="ox-bar">${W([{label:r.label}])}${ge(1)}</div>`;s+=`<div class="ox-head"><div class="ox-avatar">${z(r.icon)}</div><div><h1>${w(r.label)}</h1><p>${w(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)}">${w(c.plural??c.label)}<small>${a.get(c.id)?.length??0}</small></a>`).join("")}</nav>`;let l=i?(a.get(i.id)??[]).map(c=>({e:c,at:ve(e,c)})).sort((c,f)=>f.at.localeCompare(c.at)):[];s+='<div class="ox-grid2">',s+=`<section class="ox-card"><div class="ox-card-h"><h2>${w(i?.plural??i?.label??"")}</h2><span class="note">${l.length} \xB7 most active first</span>`+(i?`<a class="zin" href="/p/${encodeURIComponent(r.id)}/${encodeURIComponent(i.id)}">open list (Z3) \u2192</a>`:"")+"</div>"+(l.slice(0,5).map(({e:c,at:f})=>Z(e,c,c.type==="event"?`<span class="ox-st ${c.importance}">${c.importance}</span>`:"",`${Fe(c,90)||pe(e.ontology,c.type).toLowerCase()} \xB7 ${f}`)).join("")||`<div class="ox-empty">No ${w((i?.plural??"pages").toLowerCase())} yet.</div>`)+"</section>";let d=o.flatMap(c=>a.get(c.id)??[]);return s+=ct(e,dt(e,d)),s+="</div>",U(r.label,O(e,{pillar:r.id}),s)}function gt(e,t,n,r,a){let o=a&&Pe.includes(a)?a:null,i=e.ontology.pillars.find(u=>u.id===t),s=e.ontology.types.find(u=>u.id===n&&u.pillar===t);if(!i||!s)return null;let l=[...e.entities.values()].filter(u=>u.type===s.id);o&&(l=l.filter(u=>u.importance===o));let d=l.map(u=>({e:u,at:ve(e,u)})).sort((u,h)=>h.at.localeCompare(u.at)),c=50,f=Math.max(1,Math.ceil(d.length/c)),g=`/p/${encodeURIComponent(i.id)}/${encodeURIComponent(s.id)}`,m=`<div class="ox-bar">${W([{label:i.label,href:`/p/${encodeURIComponent(i.id)}`},{label:s.plural??s.label}])}${ge(3)}</div>`;if(m+=`<div class="ox-head"><div class="ox-avatar">${z(s.icon)}</div><div><h1>${w(s.plural??s.label)}</h1><p>${d.length} page${d.length===1?"":"s"}${o?` \xB7 ${w(o)} only`:""}</p></div></div>`,s.id==="event"&&(m+=`<nav class="ox-tabs">${["","major","normal","minor"].map(u=>`<a class="${(o??"")===u?"on":""}" href="${g}${u?`?importance=${u}`:""}">${u||"all"}</a>`).join("")}</nav>`),m+='<section class="ox-card" style="margin-top:16px">'+(d.slice((r-1)*c,r*c).map(({e:u,at:h})=>Z(e,u,u.type==="event"?`<span class="ox-st ${u.importance}">${u.importance}</span>`:"",`${h} \xB7 ${u.pages.map(C=>C.agentId).filter((C,y,x)=>x.indexOf(C)===y).join(", ")}`)).join("")||'<div class="ox-empty">None.</div>')+"</section>",f>1){let u=o?`importance=${o}&`:"";m+=`<div class="ox-pager">${r>1?`<a href="${g}?${u}page=${r-1}">\u2190 previous</a>`:""}<span>page ${r} of ${f}</span>${r<f?`<a href="${g}?${u}page=${r+1}">next \u2192</a>`:""}</div>`}return U(s.plural??s.label,O(e,{pillar:i.id}),m)}function mt(e,t){let n=t.trim().toLowerCase(),r=[];if(n)for(let o of e.entities.values()){let i=o.title.toLowerCase(),s=i===n?100:i.startsWith(n)?60:i.includes(n)?40:0;!s&&o.pages.some(l=>l.article.content.toLowerCase().includes(n))&&(s=10),s&&r.push({e:o,s})}r.sort((o,i)=>i.s-o.s||i.e.updated.localeCompare(o.e.updated));let a=`<div class="ox-bar">${W([{label:"Search"}])}</div>`;return a+=`<div class="ox-head"><div class="ox-avatar">${z("search")}</div><div><h1>${n?`\u201C${w(t)}\u201D`:"Search"}</h1><p>${r.length} match${r.length===1?"":"es"}</p></div></div>`,a+=`<section class="ox-card">${r.slice(0,60).map(({e:o})=>Z(e,o)).join("")||'<div class="ox-empty">No page matches.</div>'}</section>`,U(`Search: ${t}`,O(e,{}),a,"",t)}function ft(e,t,n){let r=e.ontology,a=he(e),o=`<div class="ox-bar">${W([{label:"Ontology"}])}</div>`;o+=`<div class="ox-head"><div class="ox-avatar">${z("steps")}</div><div><h1>Ontology</h1><p>${n?`Read from ${w(n)}`:"Built-in defaults. Run <code>agentx wiki ontology init</code> to write an ontology.yaml you can edit."}</p></div></div>`,t.length&&(o+=`<div class="ox-err"><b>Problems</b><ul>${t.map(i=>`<li>${w(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(l=>l.id===i.pillar);o+=`<div class="ox-row"><span class="ox-ic">${z(i.icon)}</span><div class="t"><span class="l">${w(i.label)} <span class="ox-sub">${w(i.id)}</span></span><div class="ox-sub">${w(s?.label??i.pillar)} \xB7 lens: ${w((i.lens??[]).map(l=>l.title??l.panel).join(" \u2192 "))}</div></div><div class="r"><span class="ox-chip">${a.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">${w(i.id)}</span><span>${w(i.label)}${i.inverse?` \xB7 inverse: ${w(i.inverse)}`:""}${i.wikidata?` <span class="ox-sub">${w(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>${w(r.importance.default)}</span></div><div class="ox-kv"><span class="k">major set by</span><span>${w(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>`,U("Ontology",O(e,{}),o)}var ee=class{constructor(t,n){this.hub=t;this.wikiDir=n}cache=new je;pageAt(t){if(!t.startsWith("/e/"))return null;let{ontology:n}=ce(this.wikiDir),a=this.cache.get(this.hub,n).entities.get(t.split("/").filter(Boolean)[1]??"")?.pages[0];return a?{agentId:a.agentId,path:a.article.path,title:a.article.meta.title}:null}handle(t,n){if(!(t==="/"||t===""||t.startsWith("/p/")||t.startsWith("/e/")||t==="/find"||t==="/ontology"))return null;let{ontology:r,errors:a,file:o}=ce(this.wikiDir),i=Be(this.wikiDir,this.hub.listAgents([]),r.agent_names),s=this.cache.get(this.hub,r,i),l=Math.max(1,Number(n.get("page"))||1);if(t==="/"||t==="")return pt(s,a);if(t==="/find")return mt(s,n.get("q")??"");if(t==="/ontology")return ft(s,a,o);let d=t.split("/").filter(Boolean);if(d[0]==="p")return d.length===2?ut(s,d[1],n.get("kind")):d.length===3?gt(s,d[1],d[2],l,n.get("importance")):null;let c=s.entities.get(d[1]??"");if(!c)return null;let f={g:s,readEntries:g=>this.hub.getSharedStore().readEntries(g),versions:(g,m)=>this.hub.getAgentWiki(g).getVersions(m)};return d.length===2?Ke(f,c):d.length===3?Ge(f,c,d[2],l):d.length===4&&d[2]==="s"?Je(f,c,Number(d[3])):null}};var hn=`
184
+ `,{mode:384}),tn(n,this.path)}add(t,n){return this.locked(()=>this.addUnlocked(t,n))}addUnlocked(t,n){let r=this.editable();if(!r.ok)return r;let a=r.pins;if(a.filter(i=>!this.shadowed(i)).length+this.fixed.length>=n)return{ok:!1,status:409,error:`You already have ${n} pinned pages, the most allowed (app.pins.max). Remove one first.`};if([...this.fixed,...a].some(i=>i.label.toLowerCase()===t.label.toLowerCase()))return{ok:!1,status:409,error:`You already have a button called ${t.label}.`};if(this.fixed.some(i=>i.url===t.url))return{ok:!1,status:409,error:"This page is already a button, set in agentx.json (app.pins.pages)."};let o={id:`pin_${ln(6).toString("hex")}`,...t,createdAt:new Date(this.now()).toISOString()};return a.push(o),this.write(a),{ok:!0,pin:o}}rename(t,n){return this.locked(()=>this.renameUnlocked(t,n))}renameUnlocked(t,n){if(this.isFixed(t))return{ok:!1,status:409,error:ot};let r=this.editable();if(!r.ok)return r;let a=r.pins,o=a.find(i=>i.id===t);return o?[...this.fixed,...a].some(i=>i.id!==t&&i.label.toLowerCase()===n.toLowerCase())?{ok:!1,status:409,error:`You already have a button called ${n}.`}:(o.label=n,this.write(a),{ok:!0,pin:o}):{ok:!1,status:404,error:"No such pinned page."}}remove(t){return this.locked(()=>this.removeUnlocked(t))}removeUnlocked(t){if(this.isFixed(t))return{ok:!1,status:409,error:ot};let n=this.editable();if(!n.ok)return n;let r=n.pins.filter(a=>a.id!==t);return r.length===n.pins.length?{ok:!1,status:404,error:"No such pinned page."}:(this.write(r),{ok:!0})}};function Mr(e,t){let n=e.app.pins;return{store:new me(cn(t,n.file),Date.now,un(n.pages)),max:n.max}}async function Wr(e,t,n,r,a){if(n!=="/api/app/pins"&&!n.startsWith("/api/app/pins/"))return!1;let o=n.slice(13);if(r==="GET"&&o==="")return R(t,200,{pins:a.store.list(),max:a.max});if(r!=="POST")return R(t,404,{error:"not found"});let i;try{i=await Y(e,4096)}catch(l){return R(t,400,{error:l.message})}let s=typeof i.id=="string"?i.id:"";if(o==="/add"){let l=gn(i);if(!l.ok)return R(t,400,{error:l.error});let d=a.store.add(l.value,a.max);return d.ok?R(t,200,{ok:!0,pin:d.pin}):R(t,d.status,{error:d.error})}if(o==="/rename"){let l=V(i.label);if(!l.ok)return R(t,400,{error:l.error});let d=a.store.rename(s,l.value);return d.ok?R(t,200,{ok:!0,pin:d.pin}):R(t,d.status,{error:d.error})}if(o==="/remove"){let l=a.store.remove(s);return l.ok?R(t,200,{ok:!0}):R(t,l.status,{error:l.error})}return R(t,404,{error:"not found"})}function R(e,t,n){return e.writeHead(t,{"Content-Type":"application/json","Cache-Control":"no-store"}),e.end(JSON.stringify(n)),!0}import{existsSync as it,readFileSync as st}from"fs";ie();function mn(e){let t=H(e),n={};if(it(t))try{n=j(JSON.parse(st(t,"utf-8")))}catch{n={}}let r=oe.safeParse(n?.approvals);return r.success?r.data:oe.parse(void 0)}function jr(e){let t=H(e),n={};if(it(t))try{n=j(JSON.parse(st(t,"utf-8")))}catch{n={}}return Ne({desk:n?.notifications?.desk,popupEnabled:!!mn(e).popup?.enabled})}function Hr(e){let t=e.indexOf(":");return t<=0||t===e.length-1?null:{channel:e.slice(0,t).trim(),chatId:e.slice(t+1).trim()}}async function qr(e,t={}){return G(n=>{let r=n.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 d=Array.isArray(n.mesh?.peers)?n.mesh.peers:[];if(!d.some(c=>c.name===e.forwardTo))throw new Error(`"${e.forwardTo}" is not in mesh.peers${d.length?` (known: ${d.map(c=>c.name).join(", ")})`:""}; pair the machines first`);r.forwardTo=e.forwardTo}let a=r.digest??={};e.digestEnabled!==void 0&&(a.enabled=e.digestEnabled),e.digestTime!==void 0&&(a.time=e.digestTime),e.digestTimezone===null?delete a.timezone:e.digestTimezone!==void 0&&(a.timezone=e.digestTimezone),e.destination===null?delete a.destination:e.destination!==void 0&&(a.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 d=(n.notifications??={}).desk??={};e.deskPhone!==void 0&&(d.phone=e.deskPhone),e.deskComputer!==void 0&&(d.computer=e.deskComputer)}let s=r.defaultExpiryDays??3,l=r.maxExpiryDays??30;if(s>l)throw new Error(`defaultExpiryDays (${s}) can't be more than maxExpiryDays (${l})`)},{configPath:t.configPath,reload:t.reload})}import{createServer as kn}from"http";var Q=class{peers;cache=new Map;ttl=3e4;constructor(t){this.peers=t.map(n=>({...n,url:n.url.replace(/\/$/,"")}))}async getRemoteAgents(){let t=[];return await Promise.all(this.peers.map(async n=>{try{let r=await this.fetchJson(`${n.url}/wiki/agents`);n.nodeId=r.nodeId;for(let a of r.agents||[])(a.totalEntries>0||a.totalArticles>0)&&t.push({...a,nodeId:r.nodeId,peerUrl:n.url})}catch{}})),t}async getRemoteArticles(t,n){try{return(await this.fetchJson(`${t}/wiki/articles?agent=${encodeURIComponent(n)}`)).articles||[]}catch{return[]}}async getRemoteArticle(t,n,r){try{let a=await this.fetchJson(`${t}/wiki/article?agent=${encodeURIComponent(n)}&path=${encodeURIComponent(r)}`);return{meta:{title:a.title,tags:a.tags||[],owner:a.owner,access:"public",created:a.created,lastUpdated:a.lastUpdated,sources:a.sources||[]},content:a.content,path:a.path}}catch{return null}}async fetchJson(t){let n=this.cache.get(t);if(n&&Date.now()-n.ts<this.ttl)return n.data;let r=this.peers.find(i=>t.startsWith(`${i.url}/`))?.token,a=await fetch(t,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(5e3)});if(!a.ok)throw new Error(`HTTP ${a.status}`);let o=await a.json();return this.cache.set(t,{data:o,ts:Date.now()}),o}};var lt=864e5;function he(e){let t=new Map;for(let n of e.entities.values()){let r=t.get(n.type)??[];r.push(n),t.set(n.type,r)}return t}function ve(e,t){if(t.type==="event")return t.date||t.updated;let n=He(e,t,new Set(["event"]))[0],r=t.updated||t.date;return n&&n.date>r?n.date:r}function dt(e,t,n=Date.now()){let r=[],a=new Date(n+14*lt).toISOString().slice(0,10),o=new Date(n).toISOString().slice(0,10);for(let s of t){let l=s.statements.find(c=>c.property==="due"&&/^\d{4}-\d{2}-\d{2}/.test(c.value)),d=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"}):l&&!d&&l.value<o?r.push({e:s,chip:"late",why:`was due ${l.value}`}):l&&!d&&l.value<=a?r.push({e:s,chip:"due",why:`due ${l.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&&n-Date.parse(s.date)<=30*lt&&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,l)=>i[s.chip]-i[l.chip])}function Z(e,t,n="",r){return`<div class="ox-row"><span class="ox-ic">${qe(e.ontology,t.type)}</span><div class="t"><a href="${ue(t.id)}">${w(t.title)}</a><div class="ox-sub">${w(r??`${pe(e.ontology,t.type).toLowerCase()} \xB7 ${ve(e,t)}`)}</div></div><div class="r">${n}</div></div>`}function ct(e,t){let n=t.slice(0,6).map(r=>Z(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">${t.length}</span></div>${n||'<div class="ox-empty">Nothing waits on a person.</div>'}</section>`}function fn(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 pt(e,t){let n=he(e),r=`<div class="ox-bar">${N([])}</div>`;r+=`<div class="ox-head"><div class="ox-avatar">${z("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+=fn(t),r+='<div class="ox-grid3">';for(let o of e.ontology.pillars){let i=e.ontology.types.filter(d=>d.pillar===o.id),s=i.reduce((d,c)=>d+(n.get(c.id)?.length??0),0),l=i.filter(d=>n.get(d.id)?.length).map(d=>`${d.plural??d.label} ${n.get(d.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">${z(o.icon)}</span><h2>${w(o.label)}</h2><span class="zin">${s}</span></div><div class="ox-sub" style="white-space:normal">${w(o.description??"")}</div><div class="ox-sub" style="margin-top:6px;white-space:normal">${w(l||"nothing yet")}</div></a>`}r+='</div><div class="ox-grid2">';let a=(n.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>'+(a.map(o=>`<div class="ox-ev"><span class="d">${w(o.date)}</span><span class="ox-st ${o.importance}">${o.importance}</span><a href="${ue(o.id)}">${w(o.title)}</a></div>`).join("")||'<div class="ox-empty">No events yet.</div>')+"</section>",r+=ct(e,dt(e,[...e.entities.values()])),r+="</div>",U("Wiki",O(e,{home:!0}),r)}function ut(e,t,n){let r=e.ontology.pillars.find(c=>c.id===t);if(!r)return null;let a=he(e),o=e.ontology.types.filter(c=>c.pillar===r.id),i=o.find(c=>c.id===n)??o.find(c=>a.get(c.id)?.length)??o[0],s=`<div class="ox-bar">${N([{label:r.label}])}${ge(1)}</div>`;s+=`<div class="ox-head"><div class="ox-avatar">${z(r.icon)}</div><div><h1>${w(r.label)}</h1><p>${w(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)}">${w(c.plural??c.label)}<small>${a.get(c.id)?.length??0}</small></a>`).join("")}</nav>`;let l=i?(a.get(i.id)??[]).map(c=>({e:c,at:ve(e,c)})).sort((c,f)=>f.at.localeCompare(c.at)):[];s+='<div class="ox-grid2">',s+=`<section class="ox-card"><div class="ox-card-h"><h2>${w(i?.plural??i?.label??"")}</h2><span class="note">${l.length} \xB7 most active first</span>`+(i?`<a class="zin" href="/p/${encodeURIComponent(r.id)}/${encodeURIComponent(i.id)}">open list (Z3) \u2192</a>`:"")+"</div>"+(l.slice(0,5).map(({e:c,at:f})=>Z(e,c,c.type==="event"?`<span class="ox-st ${c.importance}">${c.importance}</span>`:"",`${Fe(c,90)||pe(e.ontology,c.type).toLowerCase()} \xB7 ${f}`)).join("")||`<div class="ox-empty">No ${w((i?.plural??"pages").toLowerCase())} yet.</div>`)+"</section>";let d=o.flatMap(c=>a.get(c.id)??[]);return s+=ct(e,dt(e,d)),s+="</div>",U(r.label,O(e,{pillar:r.id}),s)}function gt(e,t,n,r,a){let o=a&&Pe.includes(a)?a:null,i=e.ontology.pillars.find(u=>u.id===t),s=e.ontology.types.find(u=>u.id===n&&u.pillar===t);if(!i||!s)return null;let l=[...e.entities.values()].filter(u=>u.type===s.id);o&&(l=l.filter(u=>u.importance===o));let d=l.map(u=>({e:u,at:ve(e,u)})).sort((u,h)=>h.at.localeCompare(u.at)),c=50,f=Math.max(1,Math.ceil(d.length/c)),g=`/p/${encodeURIComponent(i.id)}/${encodeURIComponent(s.id)}`,m=`<div class="ox-bar">${N([{label:i.label,href:`/p/${encodeURIComponent(i.id)}`},{label:s.plural??s.label}])}${ge(3)}</div>`;if(m+=`<div class="ox-head"><div class="ox-avatar">${z(s.icon)}</div><div><h1>${w(s.plural??s.label)}</h1><p>${d.length} page${d.length===1?"":"s"}${o?` \xB7 ${w(o)} only`:""}</p></div></div>`,s.id==="event"&&(m+=`<nav class="ox-tabs">${["","major","normal","minor"].map(u=>`<a class="${(o??"")===u?"on":""}" href="${g}${u?`?importance=${u}`:""}">${u||"all"}</a>`).join("")}</nav>`),m+='<section class="ox-card" style="margin-top:16px">'+(d.slice((r-1)*c,r*c).map(({e:u,at:h})=>Z(e,u,u.type==="event"?`<span class="ox-st ${u.importance}">${u.importance}</span>`:"",`${h} \xB7 ${u.pages.map(C=>C.agentId).filter((C,y,x)=>x.indexOf(C)===y).join(", ")}`)).join("")||'<div class="ox-empty">None.</div>')+"</section>",f>1){let u=o?`importance=${o}&`:"";m+=`<div class="ox-pager">${r>1?`<a href="${g}?${u}page=${r-1}">\u2190 previous</a>`:""}<span>page ${r} of ${f}</span>${r<f?`<a href="${g}?${u}page=${r+1}">next \u2192</a>`:""}</div>`}return U(s.plural??s.label,O(e,{pillar:i.id}),m)}function mt(e,t){let n=t.trim().toLowerCase(),r=[];if(n)for(let o of e.entities.values()){let i=o.title.toLowerCase(),s=i===n?100:i.startsWith(n)?60:i.includes(n)?40:0;!s&&o.pages.some(l=>l.article.content.toLowerCase().includes(n))&&(s=10),s&&r.push({e:o,s})}r.sort((o,i)=>i.s-o.s||i.e.updated.localeCompare(o.e.updated));let a=`<div class="ox-bar">${N([{label:"Search"}])}</div>`;return a+=`<div class="ox-head"><div class="ox-avatar">${z("search")}</div><div><h1>${n?`\u201C${w(t)}\u201D`:"Search"}</h1><p>${r.length} match${r.length===1?"":"es"}</p></div></div>`,a+=`<section class="ox-card">${r.slice(0,60).map(({e:o})=>Z(e,o)).join("")||'<div class="ox-empty">No page matches.</div>'}</section>`,U(`Search: ${t}`,O(e,{}),a,"",t)}function ft(e,t,n){let r=e.ontology,a=he(e),o=`<div class="ox-bar">${N([{label:"Ontology"}])}</div>`;o+=`<div class="ox-head"><div class="ox-avatar">${z("steps")}</div><div><h1>Ontology</h1><p>${n?`Read from ${w(n)}`:"Built-in defaults. Run <code>agentx wiki ontology init</code> to write an ontology.yaml you can edit."}</p></div></div>`,t.length&&(o+=`<div class="ox-err"><b>Problems</b><ul>${t.map(i=>`<li>${w(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(l=>l.id===i.pillar);o+=`<div class="ox-row"><span class="ox-ic">${z(i.icon)}</span><div class="t"><span class="l">${w(i.label)} <span class="ox-sub">${w(i.id)}</span></span><div class="ox-sub">${w(s?.label??i.pillar)} \xB7 lens: ${w((i.lens??[]).map(l=>l.title??l.panel).join(" \u2192 "))}</div></div><div class="r"><span class="ox-chip">${a.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">${w(i.id)}</span><span>${w(i.label)}${i.inverse?` \xB7 inverse: ${w(i.inverse)}`:""}${i.wikidata?` <span class="ox-sub">${w(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>${w(r.importance.default)}</span></div><div class="ox-kv"><span class="k">major set by</span><span>${w(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>`,U("Ontology",O(e,{}),o)}var ee=class{constructor(t,n){this.hub=t;this.wikiDir=n}cache=new je;pageAt(t){if(!t.startsWith("/e/"))return null;let{ontology:n}=ce(this.wikiDir),a=this.cache.get(this.hub,n).entities.get(t.split("/").filter(Boolean)[1]??"")?.pages[0];return a?{agentId:a.agentId,path:a.article.path,title:a.article.meta.title}:null}handle(t,n){if(!(t==="/"||t===""||t.startsWith("/p/")||t.startsWith("/e/")||t==="/find"||t==="/ontology"))return null;let{ontology:r,errors:a,file:o}=ce(this.wikiDir),i=Be(this.wikiDir,this.hub.listAgents([]),r.agent_names),s=this.cache.get(this.hub,r,i),l=Math.max(1,Number(n.get("page"))||1);if(t==="/"||t==="")return pt(s,a);if(t==="/find")return mt(s,n.get("q")??"");if(t==="/ontology")return ft(s,a,o);let d=t.split("/").filter(Boolean);if(d[0]==="p")return d.length===2?ut(s,d[1],n.get("kind")):d.length===3?gt(s,d[1],d[2],l,n.get("importance")):null;let c=s.entities.get(d[1]??"");if(!c)return null;let f={g:s,readEntries:g=>this.hub.getSharedStore().readEntries(g),versions:(g,m)=>this.hub.getAgentWiki(g).getVersions(m)};return d.length===2?Ke(f,c):d.length===3?Ge(f,c,d[2],l):d.length===4&&d[2]==="s"?Je(f,c,Number(d[3])):null}};var hn=`
185
185
  .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;
186
186
  font:14px/1.45 'IBM Plex Sans',system-ui,-apple-system,sans-serif;color:var(--wc-ink)}
187
187
  [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}
@@ -299,7 +299,7 @@ ${g}
299
299
  </div>
300
300
  <script type="application/json" id="wc-data">${r}</script>
301
301
  <script>${vn}</script>`}function ht(e,t,n,r){let a=yn(t,n,r);return e.includes("</body>")?e.replace(/<\/body>(?![\s\S]*<\/body>)/,()=>`${a}
302
- </body>`):e+a}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function wn(e){return e.replace(/<!--\s*tags?:[^>]*-->\s*\n?/gi,"")}function vt(e,t){return`<a href="${t?`/agent/${encodeURIComponent(t)}/tag/${encodeURIComponent(e)}`:`/tag/${encodeURIComponent(e)}`}" class="tag">${p(e)}</a>`}function N(e,t){return(e||[]).map(n=>vt(n,t)).join(" ")}function $n(e,t){if(!e)return;let n=t.get(e);if(n)return n;let r=new Set(t.values());if(r.has(e))return e;let a=e.endsWith(".md")?e:`${e}.md`;if(r.has(a))return a;let o=e.toLowerCase();for(let[i,s]of t)if(i.toLowerCase()===o)return s}function te(e,t,n=""){return Te(wn(e),{wikilink:(r,a)=>{let o=$n(r,t);return o?`<a href="${n}/article/${encodeURIComponent(o)}" class="wikilink">${a}</a>`:`<a href="${n}/search?q=${encodeURIComponent(r)}" class="wikilink broken" title="Not found \u2014 click to search">${a}</a>`}})}var An=`<link rel="preconnect" href="https://fonts.googleapis.com">
302
+ </body>`):e+a}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function wn(e){return e.replace(/<!--\s*tags?:[^>]*-->\s*\n?/gi,"")}function vt(e,t){return`<a href="${t?`/agent/${encodeURIComponent(t)}/tag/${encodeURIComponent(e)}`:`/tag/${encodeURIComponent(e)}`}" class="tag">${p(e)}</a>`}function W(e,t){return(e||[]).map(n=>vt(n,t)).join(" ")}function $n(e,t){if(!e)return;let n=t.get(e);if(n)return n;let r=new Set(t.values());if(r.has(e))return e;let a=e.endsWith(".md")?e:`${e}.md`;if(r.has(a))return a;let o=e.toLowerCase();for(let[i,s]of t)if(i.toLowerCase()===o)return s}function te(e,t,n=""){return Te(wn(e),{wikilink:(r,a)=>{let o=$n(r,t);return o?`<a href="${n}/article/${encodeURIComponent(o)}" class="wikilink">${a}</a>`:`<a href="${n}/search?q=${encodeURIComponent(r)}" class="wikilink broken" title="Not found \u2014 click to search">${a}</a>`}})}var An=`<link rel="preconnect" href="https://fonts.googleapis.com">
303
303
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
304
304
  <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">`,Sn=`
305
305
  :root {
@@ -829,30 +829,30 @@ tr:hover td { background: var(--bg-hover); }
829
829
  <span><strong>${c.totalArticles}</strong> articles</span>
830
830
  <span><strong>${c.totalEntries}</strong> entries</span>
831
831
  ${f}
832
- </div>`,c.articles.length>0){d+='<div class="article-list">';for(let u of c.articles.slice(0,6)){let h=N((u.tags||[]).slice(0,2),c.agentId);d+=`<div class="article-row">${h} <a class="article-title" href="/agent/${encodeURIComponent(c.agentId)}/article/${encodeURIComponent(u.path)}">${p(u.title)}</a></div>`}c.articles.length>6&&(d+=`<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>`),d+="</div>"}d+="</div>"}return d+="</div>",S("Hub",T(r),d)}function In(e,t,n){let r=n||e.summary(),a=r.find(g=>g.agentId===t);if(!a)return S("Not Found",T(r),"<h1>Agent not found</h1>");let o=a.peerUrl!==void 0,i=e.getAgentEntries(t),s=a.articles||[],l=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">${p(t)}</span></nav>`;if(l+=`<div class="page-head"><div><h1>${p(t)}</h1>`,o&&(l+=`<p class="page-sub"><span class="tag" style="color:var(--cool);background:var(--cool-soft)">remote @ ${p(a.nodeId)}</span></p>`),l+="</div></div>",l+='<div class="stat-strip">',l+=`<div class="stat-cell"><div class="label">Articles</div><div class="number">${a.totalArticles}</div></div>`,l+=`<div class="stat-cell"><div class="label">Entries</div><div class="number">${a.totalEntries}</div></div>`,l+=`<div class="stat-cell"><div class="label">Unabsorbed</div><div class="number">${a.unabsorbed}</div></div>`,l+="</div>",s.length>0){l+='<div class="section-head"><h2>Articles</h2><span class="mono" style="font-size:12px;color:var(--muted)">'+s.length+" total</span></div>";let g=be(s);for(let[m,u]of g){l+=`<h3 class="display" style="font-size:17px;color:var(--muted);font-weight:500;margin:20px 0 8px">${xe(m)}</h3>`,l+='<div class="agent-card" style="padding:4px 14px"><div class="article-list">';for(let h of u)l+=`<div class="article-row">${N((h.tags||[]).slice(0,3),t)} <a class="article-title" href="/agent/${encodeURIComponent(t)}/article/${encodeURIComponent(h.path)}">${p(h.title)}</a></div>`;l+="</div></div>"}}let d=i.slice(-5).reverse();if(d.length>0){l+='<div class="section-head"><h2>Recent entries</h2><a class="btn ghost" href="/entries">See all \u2192</a></div>';for(let g of d)l+=`<div class="entry-card">
832
+ </div>`,c.articles.length>0){d+='<div class="article-list">';for(let u of c.articles.slice(0,6)){let h=W((u.tags||[]).slice(0,2),c.agentId);d+=`<div class="article-row">${h} <a class="article-title" href="/agent/${encodeURIComponent(c.agentId)}/article/${encodeURIComponent(u.path)}">${p(u.title)}</a></div>`}c.articles.length>6&&(d+=`<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>`),d+="</div>"}d+="</div>"}return d+="</div>",S("Hub",T(r),d)}function In(e,t,n){let r=n||e.summary(),a=r.find(g=>g.agentId===t);if(!a)return S("Not Found",T(r),"<h1>Agent not found</h1>");let o=a.peerUrl!==void 0,i=e.getAgentEntries(t),s=a.articles||[],l=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">${p(t)}</span></nav>`;if(l+=`<div class="page-head"><div><h1>${p(t)}</h1>`,o&&(l+=`<p class="page-sub"><span class="tag" style="color:var(--cool);background:var(--cool-soft)">remote @ ${p(a.nodeId)}</span></p>`),l+="</div></div>",l+='<div class="stat-strip">',l+=`<div class="stat-cell"><div class="label">Articles</div><div class="number">${a.totalArticles}</div></div>`,l+=`<div class="stat-cell"><div class="label">Entries</div><div class="number">${a.totalEntries}</div></div>`,l+=`<div class="stat-cell"><div class="label">Unabsorbed</div><div class="number">${a.unabsorbed}</div></div>`,l+="</div>",s.length>0){l+='<div class="section-head"><h2>Articles</h2><span class="mono" style="font-size:12px;color:var(--muted)">'+s.length+" total</span></div>";let g=be(s);for(let[m,u]of g){l+=`<h3 class="display" style="font-size:17px;color:var(--muted);font-weight:500;margin:20px 0 8px">${xe(m)}</h3>`,l+='<div class="agent-card" style="padding:4px 14px"><div class="article-list">';for(let h of u)l+=`<div class="article-row">${W((h.tags||[]).slice(0,3),t)} <a class="article-title" href="/agent/${encodeURIComponent(t)}/article/${encodeURIComponent(h.path)}">${p(h.title)}</a></div>`;l+="</div></div>"}}let d=i.slice(-5).reverse();if(d.length>0){l+='<div class="section-head"><h2>Recent entries</h2><a class="btn ghost" href="/entries">See all \u2192</a></div>';for(let g of d)l+=`<div class="entry-card">
833
833
  <div class="meta-line">${g.date} \xB7 via ${p(g.source)} \xB7 <code>${p(g.id)}</code></div>
834
834
  <p>${p(g.content.slice(0,300))}${g.content.length>300?"\u2026":""}</p>
835
835
  </div>`}let f=e.getAgentWiki(t).lint();if(f.length>0){l+=`<div class="section-head"><h2>Health issues</h2><span class="mono" style="font-size:12px;color:var(--warn)">${f.length}</span></div>`,l+='<div class="health-list">';for(let g of f)l+=`<div class="health-row">
836
836
  <span class="kind">${p(g.type)}</span>
837
837
  <span class="article">${p(g.article)}</span>
838
838
  <span class="msg">${p(g.message)}</span>
839
- </div>`;l+="</div>"}return S(t,T(r,t),l)}function En(e,t,n,r){let a=e.getAgentWiki(t),o=a.readArticle(n);if(!o)return null;let i=r||e.summary(),s=a.rebuildIndex(),l=new Map;for(let m of s.articles)l.set(m.title,m.path);let d=`/agent/${encodeURIComponent(t)}`,f=a.buildBacklinks()[o.meta.title]||[],g=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${d}">${p(t)}</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>${vt(o.meta.type,t)}</dd>`),o.meta.tags?.length&&(g+=`<dt>Tags</dt><dd>${N(o.meta.tags,t)}</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+=te(o.content,l,d),f.length>0){g+='<div class="backlinks"><h4>Pages that link here</h4><ul>';for(let m of f){let u=a.readArticle(m);g+=`<li><a href="${d}/article/${encodeURIComponent(m)}">${p(u?.meta.title||m)}</a></li>`}g+="</ul></div>"}return g+="</article>",S(o.meta.title,T(i,`${t}/${n}`),g)}function Pn(e,t){let n=t||e.summary(),a=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 a){let l=i.get(s.date)||[];l.push(s),i.set(s.date,l)}for(let[s,l]of[...i].reverse()){o+=`<div class="section-head"><h2>${s}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${l.length} entries</span></div>`;for(let d of l)o+=`<div class="entry-card">
839
+ </div>`;l+="</div>"}return S(t,T(r,t),l)}function En(e,t,n,r){let a=e.getAgentWiki(t),o=a.readArticle(n);if(!o)return null;let i=r||e.summary(),s=a.rebuildIndex(),l=new Map;for(let m of s.articles)l.set(m.title,m.path);let d=`/agent/${encodeURIComponent(t)}`,f=a.buildBacklinks()[o.meta.title]||[],g=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${d}">${p(t)}</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>${vt(o.meta.type,t)}</dd>`),o.meta.tags?.length&&(g+=`<dt>Tags</dt><dd>${W(o.meta.tags,t)}</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+=te(o.content,l,d),f.length>0){g+='<div class="backlinks"><h4>Pages that link here</h4><ul>';for(let m of f){let u=a.readArticle(m);g+=`<li><a href="${d}/article/${encodeURIComponent(m)}">${p(u?.meta.title||m)}</a></li>`}g+="</ul></div>"}return g+="</article>",S(o.meta.title,T(i,`${t}/${n}`),g)}function Pn(e,t){let n=t||e.summary(),a=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 a){let l=i.get(s.date)||[];l.push(s),i.set(s.date,l)}for(let[s,l]of[...i].reverse()){o+=`<div class="section-head"><h2>${s}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${l.length} entries</span></div>`;for(let d of l)o+=`<div class="entry-card">
840
840
  <div class="meta-line">
841
841
  <a href="/agent/${encodeURIComponent(d.agentId)}">${p(d.agentId)}</a>
842
842
  \xB7 via ${p(d.source)} \xB7 <code>${p(d.id)}</code>
843
843
  </div>
844
844
  <p>${p(d.content.slice(0,400))}${d.content.length>400?"\u2026":""}</p>
845
845
  </div>`}return S("All Entries",T(n),o)}function Rn(e,t,n){let r=n||e.summary(),a='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Search</span></nav>';a+=`<div class="page-head"><div><h1>\u201C${p(t)}\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 d=e.getAgentWiki(s.agentId).findRelevant(t,void 0,10);if(d.length>0){i.push(`<div class="section-head"><h2>${p(s.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${d.length} match${d.length===1?"":"es"}</span></div>`);for(let c of d){let f=`/agent/${encodeURIComponent(s.agentId)}`;i.push(`<div class="entry-card">
846
- <div class="meta-line">${N((c.meta.tags||[]).slice(0,3),s.agentId)}</div>
846
+ <div class="meta-line">${W((c.meta.tags||[]).slice(0,3),s.agentId)}</div>
847
847
  <h3><a href="${f}/article/${encodeURIComponent(c.path)}">${p(c.meta.title)}</a></h3>
848
848
  <p>${p(c.content.slice(0,240))}\u2026</p>
849
849
  </div>`)}o+=d.length}}return a+=i.join(""),o===0&&(a+='<p style="color:var(--muted);margin-top:24px">No matching articles found.</p>'),S(`Search: ${t}`,T(r),a,t)}function Tn(e,t,n){let r=n||e.summary(),a='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Tag</span></nav>';a+=`<div class="page-head"><div><h1>${p(t)}</h1><p class="page-sub">All articles tagged <span class="tag">${p(t)}</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 l=s.findByTags([t],void 0,100);if(l.length!==0){a+=`<div class="section-head"><h2>${p(i.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${l.length}</span></div>`;for(let d of l){let c=`/agent/${encodeURIComponent(i.agentId)}`;a+=`<div class="entry-card">
850
- <div class="meta-line">${N((d.meta.tags||[]).slice(0,6),i.agentId)}</div>
850
+ <div class="meta-line">${W((d.meta.tags||[]).slice(0,6),i.agentId)}</div>
851
851
  <h3><a href="${c}/article/${encodeURIComponent(d.path)}">${p(d.meta.title)}</a></h3>
852
852
  </div>`}o+=l.length}}return o===0&&(a+=`<p style="color:var(--muted);margin-top:24px">No articles tagged <code>${p(t)}</code>.</p>`),S(`Tag: ${t}`,T(r),a)}function Dn(e,t,n,r){let a=r||e.summary(),o;try{o=e.getAgentWiki(t)}catch{return S(`Tag: ${n}`,T(a),`<h1>Agent not found: ${p(t)}</h1>`)}let i=o.findByTags([n],void 0,100),s=`/agent/${encodeURIComponent(t)}`,l=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${s}">${p(t)}</a> <span class="sep">/</span> <span class="current">${p(n)}</span></nav>`;l+=`<div class="page-head"><div><h1>${p(n)}</h1><p class="page-sub">${i.length} article${i.length===1?"":"s"} tagged <code>${p(n)}</code> in <b>${p(t)}</b>.</p></div></div>`;for(let d of i)l+=`<div class="entry-card">
853
- <div class="meta-line">${N((d.meta.tags||[]).slice(0,6),t)}</div>
853
+ <div class="meta-line">${W((d.meta.tags||[]).slice(0,6),t)}</div>
854
854
  <h3><a href="${s}/article/${encodeURIComponent(d.path)}">${p(d.meta.title)}</a></h3>
855
- </div>`;return S(`${t} \xB7 ${n}`,T(a),l)}function L(e,t,n){let r=e.rebuildIndex(),a=be(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(t)}</div>`,o+=`<a class="nav-item${n?"":" active"}" href="/">Home</a>`,o+='<a class="nav-item" href="/lint">Health check</a>',o+="</div>";for(let[i,s]of a){o+='<div class="nav-section">',o+=`<div class="nav-section-title">${xe(i)}</div>`;for(let l of s){let d=l.path===n;o+=`<a class="nav-item${d?" active":""}" href="/article/${encodeURIComponent(l.path)}">${p(l.title)}</a>`}o+="</div>"}return o}function _n(e){let{wikiDir:t,agentFilter:n,peers:r=[],mode:a="graph",pathPrefix:o=""}=e,i=o.replace(/\/+$/,""),s=new Re(t,void 0,a),l=new ee(s,t),d=r.length>0?new Q(r):null;return async(c,f)=>{let g=new URL(c.url||"/","http://localhost"),m=decodeURIComponent(g.pathname),u=i&&m.startsWith(i)?m.slice(i.length)||"/":m,h=null,C=200;try{if(u.startsWith("/remote/")&&d){let y=u.slice(8).split("/article/");if(y.length===2){let[x,b]=y,v=x.indexOf("/"),$=decodeURIComponent(x.slice(0,v)),k=x.slice(v+1),A=await d.getRemoteArticle($,k,b);if(A){let _=await d.getRemoteAgents(),K=[...s.summary(),..._.map(E=>({...E,agentId:`${E.agentId} @${E.nodeId}`}))],I=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${p(k)} @ ${p($)}</div>`;I+=`<h1>${p(A.meta.title)}</h1>`,I+='<dl class="meta">',I+=`<dt>Tags</dt><dd>${(A.meta.tags||[]).map(E=>`<span class="tag">${E}</span>`).join(" ")}</dd>`,I+=`<dt>Owner</dt><dd>${p(A.meta.owner)}</dd>`,I+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p($)}</dd>`,I+=`<dt>Updated</dt><dd>${A.meta.lastUpdated}</dd>`,I+="</dl>";let D=new Map;I+=te(A.content,D),h=S(A.meta.title,T(K),I)}}}if(!h&&n){let y=s.getAgentWiki(n);if(u==="/"||u===""){let x=y.rebuildIndex(),b=s.getAgentEntries(n),v=`<h1>${p(n)}</h1>`;if(v+='<div class="stats">',v+=`<div class="stat-card"><div class="number">${x.articles.length}</div><div class="label">Articles</div></div>`,v+=`<div class="stat-card"><div class="number">${b.length}</div><div class="label">Entries</div></div>`,v+="</div>",x.articles.length>0){v+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let $ of x.articles)v+=`<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>`;v+="</table>"}h=S(n,L(y,n),v)}else if(u.startsWith("/article/")){let x=u.slice(9),b=y.readArticle(x);if(b){let v=y.rebuildIndex(),$=new Map;for(let A of v.articles)$.set(A.title,A.path);let k=`<h1>${p(b.meta.title)}</h1>`;k+='<dl class="meta">',k+=`<dt>Tags</dt><dd>${(b.meta.tags||[]).map(A=>`<span class="tag">${A}</span>`).join(" ")}</dd>`,k+=`<dt>Updated</dt><dd>${b.meta.lastUpdated}</dd>`,b.meta.sources?.length&&(k+=`<dt>Sources</dt><dd>${b.meta.sources.length} entries</dd>`),k+="</dl>",k+=te(b.content,$),h=S(b.meta.title,L(y,n,x),k)}}else if(u==="/lint"){let x=y.lint(),b="<h1>Health Check</h1>";if(x.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 v of x)b+=`<tr><td><span class="tag">${v.type}</span></td><td>${p(v.article)}</td><td>${p(v.message)}</td></tr>`;b+="</table>"}h=S("Health Check",L(y,n),b)}else if(u==="/search"){let x=g.searchParams.get("q")||"",b=await y.findRelevantReranked(x,void 0,20),v=`<h1>Search: "${p(x)}"</h1>`;for(let $ of b)v+=`<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&&(v+="<p>No results.</p>"),h=S(`Search: ${x}`,L(y,n),v)}else if(u.startsWith("/tag/")){let x=decodeURIComponent(u.slice(5)),b=y.findByTags([x],void 0,100),v=`<h1>Tag: <a class="tag" href="#">${p(x)}</a></h1>`;v+=`<p>${b.length} article${b.length===1?"":"s"} tagged <code>${p(x)}</code></p>`;for(let $ of b)v+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent($.path)}">${p($.meta.title)}</a></h3><div class="meta-line">${N(($.meta.tags||[]).slice(0,6))}</div></div>`;b.length===0&&(v+="<p>No articles with this tag.</p>"),h=S(`Tag: ${x}`,L(y,n),v)}}else if(!h&&(h=l.handle(u,g.searchParams))===null){let y=d?await d.getRemoteAgents():[],x=s.summary(),b=new Map(x.map(k=>[k.agentId,k])),v=[],$=new Set;for(let k of x){let A=y.find(_=>_.agentId===k.agentId);A&&A.totalArticles>k.totalArticles?v.push({...A,totalEntries:Math.max(k.totalEntries,A.totalEntries),unabsorbed:Math.max(k.unabsorbed,A.unabsorbed)}):v.push(k),$.add(k.agentId)}for(let k of y)$.has(k.agentId)||(v.push(k),$.add(k.agentId));if(u==="/agents")h=Cn(s,v,y);else if(u==="/entries")h=Pn(s,v);else if(u==="/search")h=Rn(s,g.searchParams.get("q")||"",v);else if(u.startsWith("/tag/"))h=Tn(s,decodeURIComponent(u.slice(5)),v);else if(u.match(/^\/agent\/[^/]+\/tag\/.+/)){let k=u.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);h=Dn(s,decodeURIComponent(k[1]),decodeURIComponent(k[2]),v)}else if(u.startsWith("/agent/")){let k=u.slice(7),A=k.indexOf("/article/");if(A===-1)h=In(s,k,v);else{let _=k.slice(0,A),K=k.slice(A+9);if(h=En(s,_,K,v),!h&&d){let I=y.find(D=>D.agentId===_);if(I){let D=await d.getRemoteArticle(I.peerUrl,_,K);if(D){let E=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${p(I.nodeId)}</span> / ${p(_)}</div>`;E+=`<h1>${p(D.meta.title)}</h1>`,E+='<dl class="meta">',E+=`<dt>Tags</dt><dd>${(D.meta.tags||[]).map(Ot=>`<span class="tag">${Ot}</span>`).join(" ")}</dd>`,E+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p(I.nodeId)}</dd>`,E+=`<dt>Updated</dt><dd>${D.meta.lastUpdated}</dd>`,E+="</dl>",E+=te(D.content,new Map),h=S(D.meta.title,T(v),E)}}}}}}if(!h){C=404;let y=n?L(s.getAgentWiki(n),n):T(s.summary());h=S("Not Found",y,"<h1>Page not found</h1>")}}catch(y){C=500,h=S("Error","",`<h1>Error</h1><pre>${p(y.message)}</pre>`)}if(C===200&&e.curator){let y=zn(s,l,u,n);y&&(h=ht(h,y,e.curatorEndpoint,e.curatorToken?.(c)))}f.writeHead(C,{"Content-Type":"text/html; charset=utf-8"}),f.end(i?Mn(h,i):h)}}function zn(e,t,n,r){let a,o;if(r&&n.startsWith("/article/"))a=r,o=n.slice(9);else if(!r&&n.startsWith("/agent/")){let l=n.match(/^\/agent\/([^/]+)\/article\/(.+)$/);l&&(a=l[1],o=l[2])}else if(!r)return t.pageAt(n);if(!a||!o||!e.listAgents([]).includes(a))return null;let i=e.getAgentWiki(a);if(!Me(i.baseDir,o))return null;let s=i.readArticle(o);return s?{agentId:a,path:o,title:s.meta.title}:null}function Mn(e,t){e=e.replace(/(\s(?:href|action)=")\/(?!\/)/g,`$1${t}/`),e=e.replace(new RegExp(`(${t})${t}/`,"g"),`${t}/`);let n=`<a href="/admin" 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>${n}`),e}function ua(e,t=4200,n,r=[],a="graph"){let o=_n({wikiDir:e,agentFilter:n,peers:r,mode:a});kn((s,l)=>{o(s,l)}).listen(t)}import{existsSync as Nn,readFileSync as Wn}from"fs";ie();function ba(e){let t=H(e),n={};if(Nn(t))try{n=j(JSON.parse(Wn(t,"utf-8")))}catch{n={}}let r=n?.workflows?.required??{},a={};for(let[o,i]of Object.entries(r.agents??{}))typeof i=="boolean"&&(a[o]=i);return{enabled:typeof r.enabled=="boolean"?r.enabled:J.enabled,agents:a,exemptQuestions:typeof r.exemptQuestions=="boolean"?r.exemptQuestions:J.exemptQuestions,retentionDays:Number.isInteger(r.retentionDays)&&r.retentionDays>=0?r.retentionDays:J.retentionDays,engine:n?.workflows?.enabled===!0}}async function xa(e,t={}){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`}:G(n=>{let r=n.workflows??={},a=r.required??={};if(e.enabled!==void 0&&(a.enabled=e.enabled),e.exemptQuestions!==void 0&&(a.exemptQuestions=e.exemptQuestions),e.retentionDays!==void 0&&(a.retentionDays=e.retentionDays),e.agent){let o=a.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:t.configPath,reload:t.reload})}var On={"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 Un(e){if(typeof e!="string")return null;let t=e.match(/^\$\{(\w+)\}$/);return t?t[1]:null}function ka(e){let t=e.rawConfig?.agents?.[e.agentId];if(!t)return{ready:!1,hint:`No agent "${e.agentId}" in agentx.json.`};let n=String(t.tier||""),r=On[n];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(n==="sdk"||n==="orchestrator"){let a=t.provider||(n==="sdk"?"claude":"claude-code"),o=e.rawConfig?.providers?.[a];if(n==="orchestrator"&&!(o&&"apiKey"in o))return{ready:!0};let i=o?.apiKey,s=Un(i);return s?e.env[s]||e.dotenv[s]?{ready:!0}:{ready:!1,need:"key",envVar:s,hint:`Paste an API key for "${a}". It is saved to .env as ${s} on this computer only.`}:typeof i=="string"&&i.trim()?{ready:!0}:{ready:!1,hint:`Set providers.${a}.apiKey in agentx.json.`}}return{ready:!0}}import{appendFileSync as Ln,chmodSync as Bn,existsSync as bt,readFileSync as xt,writeFileSync as jn}from"fs";function Hn(e){return bt(e)?Object.fromEntries(Ce(xt(e,"utf-8"))):{}}function Sa(e,t,n){if(!/^[A-Z_][A-Z0-9_]*$/.test(t))throw new Error(`not an environment variable name: ${t}`);if(!n||/[\r\n]/.test(n))throw new Error("the value must be one non-empty line");if(Hn(e)[t])return!1;if(!bt(e))return jn(e,`# AgentX environment variables
855
+ </div>`;return S(`${t} \xB7 ${n}`,T(a),l)}function L(e,t,n){let r=e.rebuildIndex(),a=be(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(t)}</div>`,o+=`<a class="nav-item${n?"":" active"}" href="/">Home</a>`,o+='<a class="nav-item" href="/lint">Health check</a>',o+="</div>";for(let[i,s]of a){o+='<div class="nav-section">',o+=`<div class="nav-section-title">${xe(i)}</div>`;for(let l of s){let d=l.path===n;o+=`<a class="nav-item${d?" active":""}" href="/article/${encodeURIComponent(l.path)}">${p(l.title)}</a>`}o+="</div>"}return o}function _n(e){let{wikiDir:t,agentFilter:n,peers:r=[],mode:a="graph",pathPrefix:o=""}=e,i=o.replace(/\/+$/,""),s=new Re(t,void 0,a),l=new ee(s,t),d=r.length>0?new Q(r):null;return async(c,f)=>{let g=new URL(c.url||"/","http://localhost"),m=decodeURIComponent(g.pathname),u=i&&m.startsWith(i)?m.slice(i.length)||"/":m,h=null,C=200;try{if(u.startsWith("/remote/")&&d){let y=u.slice(8).split("/article/");if(y.length===2){let[x,b]=y,v=x.indexOf("/"),$=decodeURIComponent(x.slice(0,v)),k=x.slice(v+1),A=await d.getRemoteArticle($,k,b);if(A){let _=await d.getRemoteAgents(),K=[...s.summary(),..._.map(E=>({...E,agentId:`${E.agentId} @${E.nodeId}`}))],I=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${p(k)} @ ${p($)}</div>`;I+=`<h1>${p(A.meta.title)}</h1>`,I+='<dl class="meta">',I+=`<dt>Tags</dt><dd>${(A.meta.tags||[]).map(E=>`<span class="tag">${E}</span>`).join(" ")}</dd>`,I+=`<dt>Owner</dt><dd>${p(A.meta.owner)}</dd>`,I+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p($)}</dd>`,I+=`<dt>Updated</dt><dd>${A.meta.lastUpdated}</dd>`,I+="</dl>";let D=new Map;I+=te(A.content,D),h=S(A.meta.title,T(K),I)}}}if(!h&&n){let y=s.getAgentWiki(n);if(u==="/"||u===""){let x=y.rebuildIndex(),b=s.getAgentEntries(n),v=`<h1>${p(n)}</h1>`;if(v+='<div class="stats">',v+=`<div class="stat-card"><div class="number">${x.articles.length}</div><div class="label">Articles</div></div>`,v+=`<div class="stat-card"><div class="number">${b.length}</div><div class="label">Entries</div></div>`,v+="</div>",x.articles.length>0){v+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let $ of x.articles)v+=`<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>`;v+="</table>"}h=S(n,L(y,n),v)}else if(u.startsWith("/article/")){let x=u.slice(9),b=y.readArticle(x);if(b){let v=y.rebuildIndex(),$=new Map;for(let A of v.articles)$.set(A.title,A.path);let k=`<h1>${p(b.meta.title)}</h1>`;k+='<dl class="meta">',k+=`<dt>Tags</dt><dd>${(b.meta.tags||[]).map(A=>`<span class="tag">${A}</span>`).join(" ")}</dd>`,k+=`<dt>Updated</dt><dd>${b.meta.lastUpdated}</dd>`,b.meta.sources?.length&&(k+=`<dt>Sources</dt><dd>${b.meta.sources.length} entries</dd>`),k+="</dl>",k+=te(b.content,$),h=S(b.meta.title,L(y,n,x),k)}}else if(u==="/lint"){let x=y.lint(),b="<h1>Health Check</h1>";if(x.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 v of x)b+=`<tr><td><span class="tag">${v.type}</span></td><td>${p(v.article)}</td><td>${p(v.message)}</td></tr>`;b+="</table>"}h=S("Health Check",L(y,n),b)}else if(u==="/search"){let x=g.searchParams.get("q")||"",b=await y.findRelevantReranked(x,void 0,20),v=`<h1>Search: "${p(x)}"</h1>`;for(let $ of b)v+=`<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&&(v+="<p>No results.</p>"),h=S(`Search: ${x}`,L(y,n),v)}else if(u.startsWith("/tag/")){let x=decodeURIComponent(u.slice(5)),b=y.findByTags([x],void 0,100),v=`<h1>Tag: <a class="tag" href="#">${p(x)}</a></h1>`;v+=`<p>${b.length} article${b.length===1?"":"s"} tagged <code>${p(x)}</code></p>`;for(let $ of b)v+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent($.path)}">${p($.meta.title)}</a></h3><div class="meta-line">${W(($.meta.tags||[]).slice(0,6))}</div></div>`;b.length===0&&(v+="<p>No articles with this tag.</p>"),h=S(`Tag: ${x}`,L(y,n),v)}}else if(!h&&(h=l.handle(u,g.searchParams))===null){let y=d?await d.getRemoteAgents():[],x=s.summary(),b=new Map(x.map(k=>[k.agentId,k])),v=[],$=new Set;for(let k of x){let A=y.find(_=>_.agentId===k.agentId);A&&A.totalArticles>k.totalArticles?v.push({...A,totalEntries:Math.max(k.totalEntries,A.totalEntries),unabsorbed:Math.max(k.unabsorbed,A.unabsorbed)}):v.push(k),$.add(k.agentId)}for(let k of y)$.has(k.agentId)||(v.push(k),$.add(k.agentId));if(u==="/agents")h=Cn(s,v,y);else if(u==="/entries")h=Pn(s,v);else if(u==="/search")h=Rn(s,g.searchParams.get("q")||"",v);else if(u.startsWith("/tag/"))h=Tn(s,decodeURIComponent(u.slice(5)),v);else if(u.match(/^\/agent\/[^/]+\/tag\/.+/)){let k=u.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);h=Dn(s,decodeURIComponent(k[1]),decodeURIComponent(k[2]),v)}else if(u.startsWith("/agent/")){let k=u.slice(7),A=k.indexOf("/article/");if(A===-1)h=In(s,k,v);else{let _=k.slice(0,A),K=k.slice(A+9);if(h=En(s,_,K,v),!h&&d){let I=y.find(D=>D.agentId===_);if(I){let D=await d.getRemoteArticle(I.peerUrl,_,K);if(D){let E=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${p(I.nodeId)}</span> / ${p(_)}</div>`;E+=`<h1>${p(D.meta.title)}</h1>`,E+='<dl class="meta">',E+=`<dt>Tags</dt><dd>${(D.meta.tags||[]).map(Ot=>`<span class="tag">${Ot}</span>`).join(" ")}</dd>`,E+=`<dt>Source</dt><dd><span class="tag">remote</span> ${p(I.nodeId)}</dd>`,E+=`<dt>Updated</dt><dd>${D.meta.lastUpdated}</dd>`,E+="</dl>",E+=te(D.content,new Map),h=S(D.meta.title,T(v),E)}}}}}}if(!h){C=404;let y=n?L(s.getAgentWiki(n),n):T(s.summary());h=S("Not Found",y,"<h1>Page not found</h1>")}}catch(y){C=500,h=S("Error","",`<h1>Error</h1><pre>${p(y.message)}</pre>`)}if(C===200&&e.curator){let y=zn(s,l,u,n);y&&(h=ht(h,y,e.curatorEndpoint,e.curatorToken?.(c)))}f.writeHead(C,{"Content-Type":"text/html; charset=utf-8"}),f.end(i?Mn(h,i):h)}}function zn(e,t,n,r){let a,o;if(r&&n.startsWith("/article/"))a=r,o=n.slice(9);else if(!r&&n.startsWith("/agent/")){let l=n.match(/^\/agent\/([^/]+)\/article\/(.+)$/);l&&(a=l[1],o=l[2])}else if(!r)return t.pageAt(n);if(!a||!o||!e.listAgents([]).includes(a))return null;let i=e.getAgentWiki(a);if(!Me(i.baseDir,o))return null;let s=i.readArticle(o);return s?{agentId:a,path:o,title:s.meta.title}:null}function Mn(e,t){e=e.replace(/(\s(?:href|action)=")\/(?!\/)/g,`$1${t}/`),e=e.replace(new RegExp(`(${t})${t}/`,"g"),`${t}/`);let n=`<a href="/admin" 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>${n}`),e}function ua(e,t=4200,n,r=[],a="graph"){let o=_n({wikiDir:e,agentFilter:n,peers:r,mode:a});kn((s,l)=>{o(s,l)}).listen(t)}import{existsSync as Wn,readFileSync as Nn}from"fs";ie();function ba(e){let t=H(e),n={};if(Wn(t))try{n=j(JSON.parse(Nn(t,"utf-8")))}catch{n={}}let r=n?.workflows?.required??{},a={};for(let[o,i]of Object.entries(r.agents??{}))typeof i=="boolean"&&(a[o]=i);return{enabled:typeof r.enabled=="boolean"?r.enabled:J.enabled,agents:a,exemptQuestions:typeof r.exemptQuestions=="boolean"?r.exemptQuestions:J.exemptQuestions,retentionDays:Number.isInteger(r.retentionDays)&&r.retentionDays>=0?r.retentionDays:J.retentionDays,engine:n?.workflows?.enabled===!0}}async function xa(e,t={}){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`}:G(n=>{let r=n.workflows??={},a=r.required??={};if(e.enabled!==void 0&&(a.enabled=e.enabled),e.exemptQuestions!==void 0&&(a.exemptQuestions=e.exemptQuestions),e.retentionDays!==void 0&&(a.retentionDays=e.retentionDays),e.agent){let o=a.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:t.configPath,reload:t.reload})}var On={"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 Un(e){if(typeof e!="string")return null;let t=e.match(/^\$\{(\w+)\}$/);return t?t[1]:null}function ka(e){let t=e.rawConfig?.agents?.[e.agentId];if(!t)return{ready:!1,hint:`No agent "${e.agentId}" in agentx.json.`};let n=String(t.tier||""),r=On[n];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(n==="sdk"||n==="orchestrator"){let a=t.provider||(n==="sdk"?"claude":"claude-code"),o=e.rawConfig?.providers?.[a];if(n==="orchestrator"&&!(o&&"apiKey"in o))return{ready:!0};let i=o?.apiKey,s=Un(i);return s?e.env[s]||e.dotenv[s]?{ready:!0}:{ready:!1,need:"key",envVar:s,hint:`Paste an API key for "${a}". It is saved to .env as ${s} on this computer only.`}:typeof i=="string"&&i.trim()?{ready:!0}:{ready:!1,hint:`Set providers.${a}.apiKey in agentx.json.`}}return{ready:!0}}import{appendFileSync as Ln,chmodSync as Bn,existsSync as bt,readFileSync as xt,writeFileSync as jn}from"fs";function Hn(e){return bt(e)?Object.fromEntries(Ce(xt(e,"utf-8"))):{}}function Sa(e,t,n){if(!/^[A-Z_][A-Z0-9_]*$/.test(t))throw new Error(`not an environment variable name: ${t}`);if(!n||/[\r\n]/.test(n))throw new Error("the value must be one non-empty line");if(Hn(e)[t])return!1;if(!bt(e))return jn(e,`# AgentX environment variables
856
856
  # (Never commit this file: it contains secrets.)
857
857
 
858
858
  ${t}=${n}
@@ -865,5 +865,5 @@ ${t}=${n}
865
865
  ORDER BY started_at DESC, rowid DESC LIMIT ?`).all(t,Math.max(1,Math.min(n,500))).map(a=>({taskId:a.task_id,agentId:a.agent_id,channel:a.channel,chatId:a.chat_id,status:a.status,startedAt:a.started_at,finishedAt:a.finished_at??null,messagePreview:a.message_preview}))}function Yn(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 Rt(e,t,n,r,...a){return Yn(e)?e.prepare(`SELECT id, state, channel, agent_id, text, created_at FROM requests
866
866
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
867
867
  ${r}`).all(t,...n,...a).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function to(e,t){return Rt(e,t,ae,"ORDER BY created_at")}function no(e,t,n=50){return Rt(e,t,[...ae,...$e],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}Lt();var we="member:",Xn=90,Vn="members",Qn="tailscale-user-login",Zn=400,er=60*60*1e3;function tr(e){let t=e.scopes.find(n=>n.startsWith(we));return t?t.slice(we.length):null}function Dt(e,t){if(!e)return null;let n=t.verify(e),r=n?tr(n):null;return n&&r?{rec:n,personId:r}:null}function co(e,t){let n=e.people().find(s=>s.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:r,record:a}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${we}${n.id}`],expiresInDays:Xn}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:a.id,name:n.id});return e.members.log({person:n.id,device:a.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:a.id,person:n}}var nr=Math.round(De/6e4);function rr(e){return e==="client"?"Your project":"My work"}function po(e){let t=rr(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": 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, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","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: ${_e(e.code)}`,` The code works once, for ${nr} 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(`
868
- `)}var ar="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",or="Too many machines are waiting for the owner's answer. Try again later.",Tt="That code didn't work. Check it, or ask the person who invited you for a new one.",_t=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function zt(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function ir(e){if(!zt(e))return null;let t=_t(e,Qn).toLowerCase();return t?t.slice(0,80):null}function sr(e){let t=e.socket?.remoteAddress||"unknown";if(!zt(e))return t;let n=_t(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function lr(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function dr(e){return e.identities.map(Ae).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function uo(e,t){let n=Date.now(),r=t.now??Date.now,a=t.log??(b=>console.log(b)),o=sr(e),i=t.limiter.retryAfter(o);if(i>0)return a(`[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,l="";try{let b=await Y(e,2048);s=b.code,l=lr(b.machine)}catch{}let d=t.codes.redeem(s),c=d?Dt(d.token,t.tokens):null;if(await pr(n,t.minMs??Zn),!d||!c)return t.limiter.fail(o),a(`[member] pair-code failed from ${o}`),{status:401,body:{error:Tt}};t.limiter.succeed(o);let{rec:f,personId:g}=c,m=t.people().find(b=>b.id===g);if(!m)return t.tokens.revoke(f.id),t.members.log({person:g,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),a(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Tt}};let u=ir(e),h=dr(m);if(h.length&&(!u||!h.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:g,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${h.join(" or ")}`}),a(`[member] ${g}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${h.join(" or ")}`),{status:403,body:{error:ar}};let C=l||"Unnamed machine",y=m.name.slice(0,40),x=ze(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${y}'s 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:Vn},{now:r()});return x.ok?(t.members.add({tokenId:f.id,personId:g,name:C,state:"pending",cardId:x.card.id,address:o,...u?{network:u}:{},createdAt:new Date(r()).toISOString()}),t.members.log({person:g,device:f.id,event:"paired",address:o,detail:C}),a(`[member] ${g} paired "${C}" from ${o}; waiting for the owner (card ${x.card.id})`),{status:200,body:{person:g,name:C,state:"pending"},token:d.token}):(t.tokens.revoke(f.id),t.members.log({person:g,device:f.id,event:"refused",address:o,detail:x.error}),a(`[member] ${g}: pairing from ${o} refused: ${x.error}`),{status:503,body:{error:or}})}var re="this machine is not paired",cr="waiting for the owner to approve this machine";function Mt(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function go(e,t){return t.state==="pending"&&t.cardId?Mt(se(e,t.cardId)):null}function mo(e,t,n){let r=t.now??Date.now,a=t.log??(c=>console.log(c)),o=Dt(e,t.tokens);if(!o)return{ok:!1,status:401,error:re};let{rec:i,personId:s}=o,l=t.members.byToken(i.id);if(!l||l.state==="removed"||l.personId!==s)return{ok:!1,status:401,error:re};if(t.people&&!t.people().some(c=>c.id===s))return Nt(t,i.id,"person no longer listed"),a(`[member] ${s}: "${l.name}" ended: person no longer listed`),{ok:!1,status:401,error:re};if(l.state==="pending"){let c=l.cardId?se(t.root,l.cardId):null,f=Mt(c);if(f==="yes")l=t.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??l,t.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),a(`[member] ${s}: "${l.name}" approved`);else if(f==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(i.id),t.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),t.members.log({person:s,device:i.id,event:"refused",detail:g}),a(`[member] ${s}: "${l.name}" refused: ${g}`),{ok:!1,status:401,error:re}}else return{ok:!1,status:403,error:cr,waiting:!0}}let d=l.lastSeenAt?Date.parse(l.lastSeenAt):0;return n&&(r()-d>=er||l.lastAddress!==n)&&(l=t.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:n})??l,t.members.log({person:s,device:i.id,event:"signed-in",address:n})),{ok:!0,device:l,personId:s,rec:i}}function Nt(e,t,n="removed by the owner"){let r=e.members.byToken(t);if(!r)return null;e.tokens.revoke(t);let a=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:r.personId,device:t,event:"removed",detail:n}),a}function fo(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Nt(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function pr(e,t){let n=e+t-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}var Wt=["gitlab","github"];function ur(e,t,n){let r=String(t||"").trim().toLowerCase();if(!Wt.includes(r))throw new Error(`Request status works on ${Wt.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let a=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...a,r])]:a.filter(o=>o!==r),`request status on ${r} is ${n?"on":"off"}`}function bo(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function xo(e){let{summary:t}=X(n=>ur(n,e?.channel,!!e?.enabled));return{summary:t}}function ko(e){return new Set(Object.entries(e).filter(([,t])=>t?.wiki?.absorb?.enabled===!1).map(([t])=>t))}function wo(e,t){return t.only?{agents:[t.only],skipped:[]}:{agents:e.filter(n=>!t.off.has(n)),skipped:e.filter(n=>t.off.has(n))}}function $o(e,t){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===t?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Ao(e,t){if(t){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 gr="https://ntfy.sh";function Co(e){return{enabled:!!e?.enabled,server:e?.server||gr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Io(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let r=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");n.server=r}if("topic"in t){let r=String(t.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");n.topic=r}if("token"in t){let r=String(t.token??"").trim();r?n.token=r:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{Ze as a,Yt as b,Ar as c,Sr as d,Cr as e,ka as f,Hn as g,Sa as h,Pa as i,_r as j,zr as k,cn as l,gn as m,me as n,Mr as o,Nr as p,Pt as q,Xa as r,Va as s,mn as t,jr as u,Hr as v,qr as w,eo as x,to as y,no as z,Xn as A,co as B,nr as C,rr as D,po as E,sr as F,uo as G,go as H,mo as I,Nt as J,fo as K,Wt as L,ur as M,bo as N,xo as O,ko as P,wo as Q,$o as R,Ao as S,Co as T,Io as U,_n as V,ua as W,ba as X,xa as Y};
869
- //# sourceMappingURL=chunk-UF5TWOKL.js.map
868
+ `)}var ar="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",or="Too many machines are waiting for the owner's answer. Try again later.",Tt="That code didn't work. Check it, or ask the person who invited you for a new one.",_t=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function zt(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function ir(e){if(!zt(e))return null;let t=_t(e,Qn).toLowerCase();return t?t.slice(0,80):null}function sr(e){let t=e.socket?.remoteAddress||"unknown";if(!zt(e))return t;let n=_t(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function lr(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function dr(e){return e.identities.map(Ae).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function uo(e,t){let n=Date.now(),r=t.now??Date.now,a=t.log??(b=>console.log(b)),o=sr(e),i=t.limiter.retryAfter(o);if(i>0)return a(`[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,l="";try{let b=await Y(e,2048);s=b.code,l=lr(b.machine)}catch{}let d=t.codes.redeem(s),c=d?Dt(d.token,t.tokens):null;if(await pr(n,t.minMs??Zn),!d||!c)return t.limiter.fail(o),a(`[member] pair-code failed from ${o}`),{status:401,body:{error:Tt}};t.limiter.succeed(o);let{rec:f,personId:g}=c,m=t.people().find(b=>b.id===g);if(!m)return t.tokens.revoke(f.id),t.members.log({person:g,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),a(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Tt}};let u=ir(e),h=dr(m);if(h.length&&(!u||!h.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:g,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${h.join(" or ")}`}),a(`[member] ${g}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${h.join(" or ")}`),{status:403,body:{error:ar}};let C=l||"Unnamed machine",y=m.name.slice(0,40),x=ze(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${y}'s 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:Vn},{now:r()});return x.ok?(t.members.add({tokenId:f.id,personId:g,name:C,state:"pending",cardId:x.card.id,address:o,...u?{network:u}:{},createdAt:new Date(r()).toISOString()}),t.members.log({person:g,device:f.id,event:"paired",address:o,detail:C}),a(`[member] ${g} paired "${C}" from ${o}; waiting for the owner (card ${x.card.id})`),{status:200,body:{person:g,name:C,state:"pending"},token:d.token}):(t.tokens.revoke(f.id),t.members.log({person:g,device:f.id,event:"refused",address:o,detail:x.error}),a(`[member] ${g}: pairing from ${o} refused: ${x.error}`),{status:503,body:{error:or}})}var re="this machine is not paired",cr="waiting for the owner to approve this machine";function Mt(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function go(e,t){return t.state==="pending"&&t.cardId?Mt(se(e,t.cardId)):null}function mo(e,t,n){let r=t.now??Date.now,a=t.log??(c=>console.log(c)),o=Dt(e,t.tokens);if(!o)return{ok:!1,status:401,error:re};let{rec:i,personId:s}=o,l=t.members.byToken(i.id);if(!l||l.state==="removed"||l.personId!==s)return{ok:!1,status:401,error:re};if(t.people&&!t.people().some(c=>c.id===s))return Wt(t,i.id,"person no longer listed"),a(`[member] ${s}: "${l.name}" ended: person no longer listed`),{ok:!1,status:401,error:re};if(l.state==="pending"){let c=l.cardId?se(t.root,l.cardId):null,f=Mt(c);if(f==="yes")l=t.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??l,t.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),a(`[member] ${s}: "${l.name}" approved`);else if(f==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(i.id),t.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),t.members.log({person:s,device:i.id,event:"refused",detail:g}),a(`[member] ${s}: "${l.name}" refused: ${g}`),{ok:!1,status:401,error:re}}else return{ok:!1,status:403,error:cr,waiting:!0}}let d=l.lastSeenAt?Date.parse(l.lastSeenAt):0;return n&&(r()-d>=er||l.lastAddress!==n)&&(l=t.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:n})??l,t.members.log({person:s,device:i.id,event:"signed-in",address:n})),{ok:!0,device:l,personId:s,rec:i}}function Wt(e,t,n="removed by the owner"){let r=e.members.byToken(t);if(!r)return null;e.tokens.revoke(t);let a=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:r.personId,device:t,event:"removed",detail:n}),a}function fo(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Wt(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function pr(e,t){let n=e+t-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}var Nt=["gitlab","github"];function ur(e,t,n){let r=String(t||"").trim().toLowerCase();if(!Nt.includes(r))throw new Error(`Request status works on ${Nt.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let a=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...a,r])]:a.filter(o=>o!==r),`request status on ${r} is ${n?"on":"off"}`}function bo(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function xo(e){let{summary:t}=X(n=>ur(n,e?.channel,!!e?.enabled));return{summary:t}}var ko="https://myaccount.google.com/apppasswords";function wo(e){let t=e.split("@")[1]?.toLowerCase()??"";if(t==="gmail.com"||t==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function $o(e){let t=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,...t,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function Ao(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function Co(e){return new Set(Object.entries(e).filter(([,t])=>t?.wiki?.absorb?.enabled===!1).map(([t])=>t))}function Io(e,t){return t.only?{agents:[t.only],skipped:[]}:{agents:e.filter(n=>!t.off.has(n)),skipped:e.filter(n=>t.off.has(n))}}function Eo(e,t){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===t?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Po(e,t){if(t){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 gr="https://ntfy.sh";function To(e){return{enabled:!!e?.enabled,server:e?.server||gr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Do(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let r=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");n.server=r}if("topic"in t){let r=String(t.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");n.topic=r}if("token"in t){let r=String(t.token??"").trim();r?n.token=r:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{Ze as a,Yt as b,Ar as c,Sr as d,Cr as e,ka as f,Hn as g,Sa as h,Pa as i,Pt as j,Xa as k,Va as l,_r as m,zr as n,cn as o,gn as p,me as q,Mr as r,Wr as s,mn as t,jr as u,Hr as v,qr as w,eo as x,to as y,no as z,Xn as A,co as B,nr as C,rr as D,po as E,sr as F,uo as G,go as H,mo as I,Wt as J,fo as K,Nt as L,ur as M,bo as N,xo as O,ko as P,wo as Q,$o as R,Ao as S,Co as T,Io as U,Eo as V,Po as W,To as X,Do as Y,_n as Z,ua as _,ba as $,xa as aa};
869
+ //# sourceMappingURL=chunk-LXRLD4VQ.js.map