agentix-cli 0.134.0 → 0.135.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 (110) hide show
  1. package/dist/{absorb-eval-WU7JR3BT.js → absorb-eval-WY3YMLS4.js} +2 -2
  2. package/dist/{agent-2GPJGHHG.js → agent-3R5NY7I3.js} +2 -2
  3. package/dist/{board-dashboard-PUQPL4AX.js → board-dashboard-U3ZSCO62.js} +2 -2
  4. package/dist/{chunk-AHO4CQRK.js → chunk-5NT44FKL.js} +2 -2
  5. package/dist/{chunk-RJOA7QBB.js → chunk-6WF56ME6.js} +2 -2
  6. package/dist/{chunk-MCBTVNPX.js → chunk-BQIWMQNU.js} +2 -2
  7. package/dist/{chunk-MM3F74K4.js → chunk-EEBK4F6E.js} +3 -3
  8. package/dist/chunk-EEBK4F6E.js.map +1 -0
  9. package/dist/{chunk-YSXE65O7.js → chunk-GSKJ57XY.js} +4 -4
  10. package/dist/{chunk-VQYVL72V.js → chunk-H6VWU2HN.js} +2 -2
  11. package/dist/chunk-JRS5QRZG.js +2 -0
  12. package/dist/chunk-JRS5QRZG.js.map +1 -0
  13. package/dist/{chunk-5BI2T3WD.js → chunk-JTDUTCUE.js} +3 -3
  14. package/dist/chunk-JTDUTCUE.js.map +1 -0
  15. package/dist/{chunk-4VVHGR7H.js → chunk-KEXBEUSU.js} +1 -1
  16. package/dist/{chunk-4VVHGR7H.js.map → chunk-KEXBEUSU.js.map} +1 -1
  17. package/dist/chunk-L5UGH4T4.js +160 -0
  18. package/dist/chunk-L5UGH4T4.js.map +1 -0
  19. package/dist/{chunk-RDEFA6Y6.js → chunk-LU7GDHGD.js} +2 -2
  20. package/dist/chunk-MI7WOGH6.js +4 -0
  21. package/dist/chunk-MI7WOGH6.js.map +1 -0
  22. package/dist/chunk-NY7NHGVT.js +105 -0
  23. package/dist/chunk-NY7NHGVT.js.map +1 -0
  24. package/dist/chunk-QAWKN2N4.js +3 -0
  25. package/dist/chunk-QAWKN2N4.js.map +1 -0
  26. package/dist/{chunk-FEEXOWK5.js → chunk-QDWEM4DG.js} +2 -2
  27. package/dist/{chunk-JP5OAMWQ.js → chunk-RGZARSHV.js} +1 -1
  28. package/dist/{chunk-JP5OAMWQ.js.map → chunk-RGZARSHV.js.map} +1 -1
  29. package/dist/{chunk-TDGDH4RA.js → chunk-RVEMX5MJ.js} +2 -2
  30. package/dist/{chunk-TDGDH4RA.js.map → chunk-RVEMX5MJ.js.map} +1 -1
  31. package/dist/{chunk-URN74FTP.js → chunk-WWDYDLY2.js} +2 -2
  32. package/dist/{chunk-G4HDRJVN.js → chunk-YA3P77LV.js} +2 -2
  33. package/dist/{chunk-XWO6ALJQ.js → chunk-ZFRXFUP7.js} +2 -2
  34. package/dist/{chunk-NXRSIWQA.js → chunk-ZGVVYJIK.js} +2 -2
  35. package/dist/cli.js +1 -1
  36. package/dist/{contributions-74M6YOCZ.js → contributions-KLRJ4ZXV.js} +2 -2
  37. package/dist/{enrich-NH3WHKD6.js → enrich-ZB5I7KHN.js} +2 -2
  38. package/dist/event-levels-CQWHSLMT.js +3 -0
  39. package/dist/event-levels-CQWHSLMT.js.map +1 -0
  40. package/dist/graph-ZVKV3JBD.js +2 -0
  41. package/dist/{hub-VTDFUAEH.js → hub-TILTOOSS.js} +2 -2
  42. package/dist/index.d.ts +2 -0
  43. package/dist/index.js +1 -1
  44. package/dist/load-EOZUZK7U.js +2 -0
  45. package/dist/model-call-PKV5UAQ7.js +2 -0
  46. package/dist/{program-3URNCVEZ.js → program-U3HJY7E5.js} +272 -274
  47. package/dist/program-U3HJY7E5.js.map +1 -0
  48. package/dist/{promote-B2BADAEP.js → promote-RHVZB2QZ.js} +2 -2
  49. package/dist/push-bridge-325SXDGN.js +1 -1
  50. package/dist/{query-2VIIGGDS.js → query-OZXZVLO7.js} +2 -2
  51. package/dist/query-runs-7VX3YAC3.js +4 -0
  52. package/dist/query-runs-7VX3YAC3.js.map +1 -0
  53. package/dist/{query-settings-VJ3POZS3.js → query-settings-2MGUS6AY.js} +2 -2
  54. package/dist/registry-LZLIPP7N.js +2 -0
  55. package/dist/roster-BZGKG2ZA.js +2 -0
  56. package/dist/score-DZGPLHCL.js +3 -0
  57. package/dist/score-DZGPLHCL.js.map +1 -0
  58. package/dist/types-ARP27T6T.js +2 -0
  59. package/dist/types-LJZ2YY5W.js +2 -0
  60. package/dist/{wiki-SXWJ5NJQ.js → wiki-GCRRINW3.js} +2 -2
  61. package/dist/wiki-GCRRINW3.js.map +1 -0
  62. package/dist/wiki-enrich-P5TNWACZ.js +2 -0
  63. package/dist/wiki-enrich-P5TNWACZ.js.map +1 -0
  64. package/package.json +1 -1
  65. package/dist/chunk-5BI2T3WD.js.map +0 -1
  66. package/dist/chunk-7VLLZQ3N.js +0 -2
  67. package/dist/chunk-7VLLZQ3N.js.map +0 -1
  68. package/dist/chunk-DDEDSYLF.js +0 -105
  69. package/dist/chunk-DDEDSYLF.js.map +0 -1
  70. package/dist/chunk-KFIJDLQ5.js +0 -3
  71. package/dist/chunk-KFIJDLQ5.js.map +0 -1
  72. package/dist/chunk-MM3F74K4.js.map +0 -1
  73. package/dist/chunk-SFVDQNTY.js +0 -156
  74. package/dist/chunk-SFVDQNTY.js.map +0 -1
  75. package/dist/graph-EXDH7EPZ.js +0 -2
  76. package/dist/load-5DNMGHFW.js +0 -2
  77. package/dist/model-call-BGTDPWZD.js +0 -2
  78. package/dist/program-3URNCVEZ.js.map +0 -1
  79. package/dist/registry-PRCISYBO.js +0 -2
  80. package/dist/roster-IRXP32XF.js +0 -2
  81. package/dist/score-KDNIUTNV.js +0 -3
  82. package/dist/score-KDNIUTNV.js.map +0 -1
  83. package/dist/types-ROL44T62.js +0 -2
  84. /package/dist/{absorb-eval-WU7JR3BT.js.map → absorb-eval-WY3YMLS4.js.map} +0 -0
  85. /package/dist/{agent-2GPJGHHG.js.map → agent-3R5NY7I3.js.map} +0 -0
  86. /package/dist/{board-dashboard-PUQPL4AX.js.map → board-dashboard-U3ZSCO62.js.map} +0 -0
  87. /package/dist/{chunk-AHO4CQRK.js.map → chunk-5NT44FKL.js.map} +0 -0
  88. /package/dist/{chunk-RJOA7QBB.js.map → chunk-6WF56ME6.js.map} +0 -0
  89. /package/dist/{chunk-MCBTVNPX.js.map → chunk-BQIWMQNU.js.map} +0 -0
  90. /package/dist/{chunk-YSXE65O7.js.map → chunk-GSKJ57XY.js.map} +0 -0
  91. /package/dist/{chunk-VQYVL72V.js.map → chunk-H6VWU2HN.js.map} +0 -0
  92. /package/dist/{chunk-RDEFA6Y6.js.map → chunk-LU7GDHGD.js.map} +0 -0
  93. /package/dist/{chunk-FEEXOWK5.js.map → chunk-QDWEM4DG.js.map} +0 -0
  94. /package/dist/{chunk-URN74FTP.js.map → chunk-WWDYDLY2.js.map} +0 -0
  95. /package/dist/{chunk-G4HDRJVN.js.map → chunk-YA3P77LV.js.map} +0 -0
  96. /package/dist/{chunk-XWO6ALJQ.js.map → chunk-ZFRXFUP7.js.map} +0 -0
  97. /package/dist/{chunk-NXRSIWQA.js.map → chunk-ZGVVYJIK.js.map} +0 -0
  98. /package/dist/{contributions-74M6YOCZ.js.map → contributions-KLRJ4ZXV.js.map} +0 -0
  99. /package/dist/{enrich-NH3WHKD6.js.map → enrich-ZB5I7KHN.js.map} +0 -0
  100. /package/dist/{graph-EXDH7EPZ.js.map → graph-ZVKV3JBD.js.map} +0 -0
  101. /package/dist/{hub-VTDFUAEH.js.map → hub-TILTOOSS.js.map} +0 -0
  102. /package/dist/{load-5DNMGHFW.js.map → load-EOZUZK7U.js.map} +0 -0
  103. /package/dist/{model-call-BGTDPWZD.js.map → model-call-PKV5UAQ7.js.map} +0 -0
  104. /package/dist/{promote-B2BADAEP.js.map → promote-RHVZB2QZ.js.map} +0 -0
  105. /package/dist/{query-2VIIGGDS.js.map → query-OZXZVLO7.js.map} +0 -0
  106. /package/dist/{query-settings-VJ3POZS3.js.map → query-settings-2MGUS6AY.js.map} +0 -0
  107. /package/dist/{registry-PRCISYBO.js.map → registry-LZLIPP7N.js.map} +0 -0
  108. /package/dist/{roster-IRXP32XF.js.map → roster-BZGKG2ZA.js.map} +0 -0
  109. /package/dist/{types-ROL44T62.js.map → types-ARP27T6T.js.map} +0 -0
  110. /package/dist/{wiki-SXWJ5NJQ.js.map → types-LJZ2YY5W.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{Aa as Nu,D as Xn,Ea as ju,F as ou,Fa as Zn,Ga as Oi,Ha as Lu,Ia as Fu,J as au,Ja as Uu,Ka as Gu,L as cu,Ma as Wu,N as lu,O as Ei,P as du,Q as Be,R as uu,S as Kn,Ta as Hu,U as Ci,Ua as Bu,V as hu,W as _i,X as tt,Y as vu,Z as Su,a as vd,aa as nt,b as vi,ba as $u,bb as Di,ca as Iu,cb as Ni,da as Tu,ea as xu,eb as qu,f as Si,fa as Au,g as Sd,ga as Ru,h as $d,i as We,ia as we,j as Id,ja as zn,k as Td,ka as Mi,la as Eu,m as xd,ma as zt,na as Cu,o as Ad,oa as Pe,p as Fd,pa as Pu,q as Ud,qa as _u,r as Gd,ra as Mu,s as Wd,sa as Yn,t as Hd,ta as Qn,u as Bd,ua as Ou,v as qd,va as Du,w as Vd,x as Jd,y as Ai}from"./chunk-NXRSIWQA.js";import{d as wd,g as kd,h as bd}from"./chunk-XOUO4XNA.js";import{a as Rd}from"./chunk-ZVP6GB4G.js";import{m as Ed,n as Cd,o as Ii,p as Ce,r as Pd,s as ye}from"./chunk-S2GAEH2F.js";import{b as gu,c as pu,d as Pi,e as fu,f as mu,g as yu,h as wu,i as ku}from"./chunk-EKJG63EJ.js";import{b as bu}from"./chunk-7LN4VKDU.js";import{d as _d}from"./chunk-XGOBZCYC.js";import{g as Md}from"./chunk-LQE73AZR.js";import{b as Od,c as Dd}from"./chunk-2D3RYIDU.js";import{b as Xd}from"./chunk-MRIVENBY.js";import{i as Kd,m as Ri,n as zd,p as Yd,q as Qd,r as Zd,s as eu,t as tu,u as nu}from"./chunk-WEPON4FP.js";import{f as Ti,g as Nd,h as Vn,i as St,k as He,m as jd,n as Ld,o as xi,p as Jn}from"./chunk-AKLZ4YO2.js";import{a as su}from"./chunk-PPUN7YHA.js";import{a as ru,b as iu}from"./chunk-VZLIBDLH.js";import{o as $i}from"./chunk-AHO4CQRK.js";import{b as qn}from"./chunk-EMGB23H5.js";import{A as ll,B as dl,C as ul,D as de,E as gl,F as pl,G as fl,H as ml,I as yl,J as wl,K as kl,L as sd,M as rd,N as id,O as od,P as ad,Q as cd,U as ud,a as Nc,b as di,c as Lc,ca as hd,d as Vc,e as Jc,f as Jt,h as hi,i as gi,j as pi,k as fi,l as Xc,s as Kc,t as Qc,u as Ze,v as Zc,w as nl,x as J,z as cl}from"./chunk-SFVDQNTY.js";import{A as Vl,B as Jl,C as Xl,D as Kl,E as zl,F as Yl,H as Ql,K as Zl,P as ed,Q as td,T as nd,X as ld,a as zc,ba as dd,c as el,d as tl,e as et,f as je,l as bl,n as vl,p as Dl,q as Nl,r as Ul,s as Gl,t as Wl,u as Hl,w as bi,x as Hn,y as Bl,z as ql}from"./chunk-FEEXOWK5.js";import{b as El,c as Cl,d as wi,f as Gn,g as Pl,h as _l,i as Ml,j as Xt,k as Wn,l as Ol}from"./chunk-QSKG754X.js";import{a as mi,b as Yc}from"./chunk-MEFPXHQJ.js";import{A as gd,B as Bn,C as pd,h as tc,n as nc,o as zr}from"./chunk-VQYVL72V.js";import{b as Qa}from"./chunk-SFQUP3BP.js";import{a as Ge}from"./chunk-Y4CYQV7G.js";import{a as fd,b as Kt,c as md,d as yd}from"./chunk-LLNPKE7H.js";import{a as bt,b as vt}from"./chunk-SHEUCITK.js";import{a as Sl,b as yi,c as $l,d as Il,e as Tl,i as xl,j as Al}from"./chunk-HF5EF335.js";import{b as hl}from"./chunk-W4YR2RO2.js";import{b as le,d as kt,f as Le,g as Fn,i as ue,j as Rl,k as Fe,l as Ue,m as Fl,s as ki}from"./chunk-SSQMFHSM.js";import{a as jl,b as Ll}from"./chunk-LUYN6RAC.js";import{d as sl,e as rl,f as il,g as ol,h as al,j as Un}from"./chunk-X5C5W3E4.js";import{d as rc,e as tk,m as _c,n as uk,q as Mc,v as Oc,y as wt,z as jn}from"./chunk-4XMALK7X.js";import{a as Qe,b as Vt,f as li}from"./chunk-72SZI2UW.js";import{a as Bt,b as sc}from"./chunk-FCPTN6NF.js";import{c as Dc}from"./chunk-MYVHVJWZ.js";import{e as jc}from"./chunk-6TURWSMN.js";import{d as Fc,e as Uc,f as ui,g as Ln,h as Gc,i as Wc,j as Hc,k as Bc,q as qc}from"./chunk-AV7T3SYT.js";import{a as _n,b as ek}from"./chunk-7I7IEX4S.js";import{b as Za,e as ec}from"./chunk-JHCI6XCJ.js";import{e as Ke}from"./chunk-DSYKYZMT.js";import{$ as ai,A as vc,B as ri,C as ii,E as oi,G as Sc,H as $c,J as qt,K as Ic,L as Tc,M as xc,N as Ac,O as ak,R as Rc,U as Ec,V as Cc,Z as ck,ba as lk,d as yt,e as oc,f as Qr,g as nk,h as Mn,i as Zr,j as On,l as ze,m as ei,n as ac,o as sk,p as Dn,pa as ci,q as rk,qa as Pc,r as Nn,s as cc,t as ik,w as kc,x as bc,xa as dk}from"./chunk-DYGQF3MI.js";import{e as Ye,f as lc,g as dc,h as ti}from"./chunk-BRK6M6LA.js";import{a as uc,b as hc,c as gc,e as pc,f as ni,g as fc,h as mc,i as si,j as yc,k as wc,n as ok}from"./chunk-UIBUZ2N3.js";import{b as Yr,e as ic}from"./chunk-2QNT5JDS.js";import{d as mt}from"./chunk-QIJLFPWE.js";import{existsSync as Gi,readFileSync as Wi}from"fs";var Vu=["answer","narration","line"];function Ju(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Xu(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!Vu.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${Vu.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:g,done:m}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:g}}:{status:200,body:{item:g,played:await m}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:ji(i);case"front":return r.front(i)?{status:200,body:r.view()}:ji(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:ji(i)}default:return{status:404,body:{error:"Not found"}}}}function Ku(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{Aa as Nu,D as Xn,Ea as ju,F as ou,Fa as Zn,Ga as Oi,Ha as Lu,Ia as Fu,J as au,Ja as Uu,Ka as Gu,L as cu,Ma as Wu,N as lu,O as Ei,P as du,Q as Be,R as uu,S as Kn,Ta as Hu,U as Ci,Ua as Bu,V as hu,W as _i,X as tt,Y as vu,Z as Su,a as vd,aa as nt,b as vi,ba as $u,bb as Di,ca as Iu,cb as Ni,da as Tu,ea as xu,eb as qu,f as Si,fa as Au,g as Sd,ga as Ru,h as $d,i as We,ia as we,j as Id,ja as zn,k as Td,ka as Mi,la as Eu,m as xd,ma as zt,na as Cu,o as Ad,oa as Pe,p as Fd,pa as Pu,q as Ud,qa as _u,r as Gd,ra as Mu,s as Wd,sa as Yn,t as Hd,ta as Qn,u as Bd,ua as Ou,v as qd,va as Du,w as Vd,x as Jd,y as Ai}from"./chunk-ZGVVYJIK.js";import{d as wd,g as kd,h as bd}from"./chunk-XOUO4XNA.js";import{a as Rd}from"./chunk-ZVP6GB4G.js";import{m as Ed,n as Cd,o as Ii,p as Ce,r as Pd,s as ye}from"./chunk-S2GAEH2F.js";import{a as ru,b as iu}from"./chunk-VZLIBDLH.js";import{b as gu,c as pu,d as Pi,e as fu,f as mu,g as yu,h as wu,i as ku}from"./chunk-EKJG63EJ.js";import{b as bu}from"./chunk-7LN4VKDU.js";import{d as _d}from"./chunk-XGOBZCYC.js";import{g as Md}from"./chunk-LQE73AZR.js";import{b as Od,c as Dd}from"./chunk-2D3RYIDU.js";import{b as Xd}from"./chunk-MRIVENBY.js";import{i as Kd,m as Ri,n as zd,p as Yd,q as Qd,r as Zd,s as eu,t as tu,u as nu}from"./chunk-WEPON4FP.js";import{f as Ti,g as Nd,h as Vn,i as St,k as He,m as jd,n as Ld,o as xi,p as Jn}from"./chunk-AKLZ4YO2.js";import{a as su}from"./chunk-PPUN7YHA.js";import{o as $i}from"./chunk-5NT44FKL.js";import{b as qn}from"./chunk-EMGB23H5.js";import{A as ll,B as dl,C as ul,D as de,E as gl,F as pl,G as fl,H as ml,I as yl,J as wl,K as kl,L as sd,M as rd,N as id,O as od,P as ad,Q as cd,U as ud,a as Nc,b as di,c as Lc,ca as hd,d as Vc,e as Jc,f as Jt,h as hi,i as gi,j as pi,k as fi,l as Xc,s as Kc,t as Qc,u as Ze,v as Zc,w as nl,x as J,z as cl}from"./chunk-L5UGH4T4.js";import{A as Vl,B as Jl,C as Xl,D as Kl,E as zl,F as Yl,H as Ql,K as Zl,P as ed,Q as td,T as nd,X as ld,a as zc,ba as dd,c as el,d as tl,e as et,f as je,l as bl,n as vl,p as Dl,q as Nl,r as Ul,s as Gl,t as Wl,u as Hl,w as bi,x as Hn,y as Bl,z as ql}from"./chunk-QDWEM4DG.js";import{b as El,c as Cl,d as wi,f as Gn,g as Pl,h as _l,i as Ml,j as Xt,k as Wn,l as Ol}from"./chunk-QSKG754X.js";import{a as mi,b as Yc}from"./chunk-MEFPXHQJ.js";import{A as gd,B as Bn,C as pd,h as tc,n as nc,o as zr}from"./chunk-H6VWU2HN.js";import{b as Qa}from"./chunk-SFQUP3BP.js";import{a as Ge}from"./chunk-Y4CYQV7G.js";import{a as fd,b as Kt,c as md,d as yd}from"./chunk-LLNPKE7H.js";import{a as bt,b as vt}from"./chunk-SHEUCITK.js";import{a as Sl,b as yi,c as $l,d as Il,e as Tl,i as xl,j as Al}from"./chunk-HF5EF335.js";import{b as hl}from"./chunk-W4YR2RO2.js";import{b as le,d as kt,f as Le,g as Fn,i as ue,j as Rl,k as Fe,l as Ue,m as Fl,s as ki}from"./chunk-SSQMFHSM.js";import{a as jl,b as Ll}from"./chunk-LUYN6RAC.js";import{d as sl,e as rl,f as il,g as ol,h as al,j as Un}from"./chunk-X5C5W3E4.js";import{d as rc,e as tk,m as _c,n as uk,q as Mc,v as Oc,y as wt,z as jn}from"./chunk-4XMALK7X.js";import{a as Qe,b as Vt,f as li}from"./chunk-72SZI2UW.js";import{a as Bt,b as sc}from"./chunk-FCPTN6NF.js";import{c as Dc}from"./chunk-MYVHVJWZ.js";import{e as jc}from"./chunk-6TURWSMN.js";import{d as Fc,e as Uc,f as ui,g as Ln,h as Gc,i as Wc,j as Hc,k as Bc,q as qc}from"./chunk-AV7T3SYT.js";import{a as _n,b as ek}from"./chunk-7I7IEX4S.js";import{b as Za,e as ec}from"./chunk-JHCI6XCJ.js";import{e as Ke}from"./chunk-DSYKYZMT.js";import{$ as ai,A as vc,B as ri,C as ii,E as oi,G as Sc,H as $c,J as qt,K as Ic,L as Tc,M as xc,N as Ac,O as ak,R as Rc,U as Ec,V as Cc,Z as ck,ba as lk,d as yt,e as oc,f as Qr,g as nk,h as Mn,i as Zr,j as On,l as ze,m as ei,n as ac,o as sk,p as Dn,pa as ci,q as rk,qa as Pc,r as Nn,s as cc,t as ik,w as kc,x as bc,xa as dk}from"./chunk-DYGQF3MI.js";import{e as Ye,f as lc,g as dc,h as ti}from"./chunk-BRK6M6LA.js";import{a as uc,b as hc,c as gc,e as pc,f as ni,g as fc,h as mc,i as si,j as yc,k as wc,n as ok}from"./chunk-UIBUZ2N3.js";import{b as Yr,e as ic}from"./chunk-2QNT5JDS.js";import{d as mt}from"./chunk-QIJLFPWE.js";import{existsSync as Gi,readFileSync as Wi}from"fs";var Vu=["answer","narration","line"];function Ju(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Xu(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!Vu.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${Vu.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:g,done:m}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:g}}:{status:200,body:{item:g,played:await m}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:ji(i);case"front":return r.front(i)?{status:200,body:r.view()}:ji(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:ji(i)}default:return{status:404,body:{error:"Not found"}}}}function Ku(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var ji=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});import{resolve as Hi}from"path";lk();var hk={name:"agentx",version:"0.1.0"},gk=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],pk="2024-11-05";function fk(r){return typeof r=="string"&&gk.includes(r)?r:pk}var mk={tools:{},elicitation:{form:{}}},yk=0;async function zu(r,e){let t=++yk;return st({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Yt.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Yt.has(`elicit-${t}`)&&(Yt.delete(`elicit-${t}`),n(null))},6e4)})}var Yt=new Map,wk="http://localhost:18800",Li;function kk(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=Hi(process.cwd(),r);if(!Gi(e))continue;let t=JSON.parse(Wi(e,"utf-8"))?.node?.bind;if(typeof t!="string"||!t.includes(":"))continue;{let n=t.lastIndexOf(":"),s=t.slice(0,n),i=t.slice(n+1),o=!s||s==="0.0.0.0"||s==="::"||s==="*"?"127.0.0.1":s;if(i)return`http://${o}:${i}`}}catch{}return wk}function X(){return Li===void 0&&(Li=kk()),Li}var Fi;function bk(r){try{let e=Hi(process.cwd(),".env");if(!Gi(e))return"";for(let t of Wi(e,"utf-8").split(`
3
3
  `)){let n=t.trim().replace(/^export\s+/,"");if(!n.startsWith(`${r}=`))continue;let s=n.slice(r.length+1).trim();return/^(["']).*\1$/.test(s)?s.slice(1,-1):s}}catch{}return""}function vk(r=process.env){if(r.AGENTX_TOKEN)return r.AGENTX_TOKEN;if(r.MESH_TOKEN)return r.MESH_TOKEN;let e=bk("MESH_TOKEN");if(e)return e;for(let t of["agentx.json",".agentx/config.json"])try{let n=Hi(process.cwd(),t);if(!Gi(n))continue;let s=JSON.parse(Wi(n,"utf-8"))?.dashboard?.token;if(typeof s=="string"&&s)return s}catch{}return""}function Sk(){return Fi===void 0&&(Fi=vk()),Fi}var K=(r,e)=>{let t=Sk();if(!t)return fetch(r,e);let n=new Headers(e?.headers);return n.has("Authorization")||n.set("Authorization",`Bearer ${t}`),fetch(r,{...e,headers:n})};function Ui(r=process.env){let e={};return r.AGENTX_TASK_ID&&(e.callerTaskId=r.AGENTX_TASK_ID),r.AGENTX_CHANNEL&&(e.callerChannel=r.AGENTX_CHANNEL),r.AGENTX_CHAT_ID&&(e.callerChatId=r.AGENTX_CHAT_ID),e}async function $k(){let r=process.env.AGENTX_AGENT_ID,e=Ui();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await K(`${X()}/agents/${encodeURIComponent(r)}/intent-path?${t}`,{signal:AbortSignal.timeout(2e3)});if(!n.ok)return;let s=await n.json();return{...Array.isArray(s.path)&&s.path.length?{path:s.path}:{},...typeof s.graphWeight=="number"?{graphWeight:s.graphWeight}:{}}}catch{return}}var Ik=1e4,Tk=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH"]);function xk(r,e){let t=e,n=t?.cause?.code??t?.code;if(n&&Tk.has(n))return`Error: the AgentX daemon could not be reached (${n}); the message to ${r} was not sent.`;let s=t?.name==="TimeoutError"||t?.name==="AbortError"?"no answer in time":t?.message||String(e);return`Probably delivered to ${r}: the daemon did not confirm (${s}), but the request was sent and is most likely queued. Do not treat this as a failure. If unsure, send the same message again: within 10 minutes a repeat returns the existing task id instead of a second task, and delivers it if the first never arrived. A busy ${r} shows no trace until its turn starts; later, \`agentx trace list --agent ${r} --since 1h\` or the daemon log ("[send/agent]") shows it.`}var Ak=/\x1B\[[0-9;]*[A-Za-z]/g;function $t(r){return r.replace(Ak,"")}async function Rk(r,e,t){let n=await K(`${X()}/recall`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r,channel:e,limit:Math.min(Math.max(t??30,1),100)})}),s=await n.json().catch(()=>({}));if(!n.ok)return{content:[{type:"text",text:`Error: ${s.error||n.statusText}`}]};let i=s.turns||[],o=e?`on ${e}`:"on any channel";return i.length===0?{content:[{type:"text",text:`No other messages ${o} today for ${r}.`}]}:{content:[{type:"text",text:Ek(i,!!s.hasMore)}]}}function Ek(r,e){let t=new Map;for(let s of r){let i=`${s.channel}/${s.chatId}`;t.has(i)||t.set(i,[]),t.get(i).push(s)}let n=[];for(let[s,i]of t){let o=[...i].sort((a,c)=>a.ts.localeCompare(c.ts)).map(a=>{let c=a.role==="agent"?"you":a.senderName||"user";return` [${a.ts.slice(11,16)}] ${c}: ${a.content.slice(0,300)}`});n.push(`From ${s}:
4
4
  ${o.join(`
@@ -40,7 +40,7 @@ ${String(b.plan.text).split(`
40
40
  `)}]}:{content:[{type:"text",text:"No stopped tasks."}]}}if(n!=="stop"&&n!=="resume")return{content:[{type:"text",text:"Error: action must be stop, resume or list."}]};let a=n==="stop"?{taskId:o(e.taskId),agentId:o(e.agentId),channel:o(e.channel),chatId:o(e.chatId),reason:o(e.reason),node:o(e.node),from:s}:{id:o(e.id),reason:o(e.reason),node:o(e.node),from:s},c=await K(`${X()}/api/signals/${n}`,{method:"POST",headers:{"Content-Type":"application/json",...i},body:JSON.stringify(a),signal:AbortSignal.timeout(3e4)}),l=await c.json().catch(()=>({}));return c.ok?{content:[{type:"text",text:n==="stop"?`Stopped task ${l.id} of ${l.agentId}. It is writing its resume plan; resume it with agentx_signal action=resume id=${l.id}.`:`Resumed task ${l.id} of ${l.agentId}. Its answer goes to ${l.delivery??"the chat it came from"}.`}]}:{content:[{type:"text",text:`Signal not sent: ${l.error||`HTTP ${c.status}`}`}]}}case"agentx_crons":{let s=await(await K(`${X()}/crons/health`)).json(),i=`Healthy: ${s.healthy}, Failing: ${s.failing}, Disabled: ${s.disabled}, Missed: ${s.missed}`,o=(s.jobs||[]).map(a=>` ${a.id}: ${a.status}${a.consecutiveErrors?` (${a.consecutiveErrors} errors)`:""}${a.lastError?` \u2014 ${a.lastError.slice(0,100)}`:""}`).join(`
41
41
  `);return{content:[{type:"text",text:`${i}
42
42
 
43
- ${o}`}]}}case"agentx_schedule":{let{runScheduleTool:n,resolveScheduleCaller:s}=await import("./schedule-tool-KPVTMYL3.js");return{content:[{type:"text",text:await n(e,s(e),{notifyOperator:async(o,a)=>{let c=await K(`${X()}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:o.channel,chatId:o.chatId,accountId:o.accountId,text:a}),signal:AbortSignal.timeout(1e4)});if(!c.ok){let l=await c.json().catch(()=>({}));throw new Error(l?.error||`HTTP ${c.status}`)}}})}]}}case"agentx_approval":{let{runApprovalTool:n}=await import("./tool-XLWLXGB5.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:K})}]}}case"agentx_request":{let{runRequestTool:n}=await import("./tool-HUSCHORN.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:K})}]}}case"agentx_workflow":{let{runWorkflowTool:n}=await import("./follow-up-tool-EARVITTS.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X()})}]}}case"agentx_wiki_query":{let n=String(e.question||"").trim();if(!n)return{content:[{type:"text",text:"Error: `question` is required."}]};let{WikiHub:s}=await import("./wiki-SXWJ5NJQ.js"),{agenticQuery:i,sharedQueryEnabled:o}=await import("./query-2VIIGGDS.js"),{loadQuerySettings:a,toolNoteSourceFor:c}=await import("./query-settings-VJ3POZS3.js"),{resolve:l}=await import("path"),d=e.wiki_dir||l(process.cwd(),".agentx/wiki"),u=new s(d,void 0,"graph"),g=e.agent||process.env.AGENTX_AGENT_ID||"";if(!g){let{existsSync:x}=await import("fs");for(let _ of u.listAgents()){let N=l(u.getAgentWiki(_).baseDir,"_index.md");if(x(N)){g=_;break}}}if(!g)return{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let m=u.getAgentWiki(g),f=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,w=await $k(),b=await a(),y=await i(n,m,g,{maxHops:f,shared:await o()?u.sharedScope(g):void 0,messagePath:w?.path,...w?.graphWeight!==void 0?{graphWeight:w.graphWeight}:{},method:b.method,summaries:b.summaries,notes:c(b,g)});if(y.status!=="ok")return{content:[{type:"text",text:`Query returned status "${y.status}"${y.error?`: ${y.error}`:""}`}]};let S=y.citations.map(x=>` - ${x.title} [${x.type||"?"}] (${x.path})`).join(`
43
+ ${o}`}]}}case"agentx_schedule":{let{runScheduleTool:n,resolveScheduleCaller:s}=await import("./schedule-tool-KPVTMYL3.js");return{content:[{type:"text",text:await n(e,s(e),{notifyOperator:async(o,a)=>{let c=await K(`${X()}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:o.channel,chatId:o.chatId,accountId:o.accountId,text:a}),signal:AbortSignal.timeout(1e4)});if(!c.ok){let l=await c.json().catch(()=>({}));throw new Error(l?.error||`HTTP ${c.status}`)}}})}]}}case"agentx_approval":{let{runApprovalTool:n}=await import("./tool-XLWLXGB5.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:K})}]}}case"agentx_request":{let{runRequestTool:n}=await import("./tool-HUSCHORN.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X(),fetch:K})}]}}case"agentx_workflow":{let{runWorkflowTool:n}=await import("./follow-up-tool-EARVITTS.js");return{content:[{type:"text",text:await n(e,{daemonUrl:X()})}]}}case"agentx_wiki_query":{let n=String(e.question||"").trim();if(!n)return{content:[{type:"text",text:"Error: `question` is required."}]};let{WikiHub:s}=await import("./wiki-GCRRINW3.js"),{agenticQuery:i,sharedQueryEnabled:o}=await import("./query-OZXZVLO7.js"),{loadQuerySettings:a,toolNoteSourceFor:c}=await import("./query-settings-2MGUS6AY.js"),{resolve:l}=await import("path"),d=e.wiki_dir||l(process.cwd(),".agentx/wiki"),u=new s(d,void 0,"graph"),g=e.agent||process.env.AGENTX_AGENT_ID||"";if(!g){let{existsSync:x}=await import("fs");for(let _ of u.listAgents()){let N=l(u.getAgentWiki(_).baseDir,"_index.md");if(x(N)){g=_;break}}}if(!g)return{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let m=u.getAgentWiki(g),f=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,w=await $k(),b=await a(),y=await i(n,m,g,{maxHops:f,shared:await o()?u.sharedScope(g):void 0,messagePath:w?.path,...w?.graphWeight!==void 0?{graphWeight:w.graphWeight}:{},method:b.method,summaries:b.summaries,notes:c(b,g)});if(y.status!=="ok")return{content:[{type:"text",text:`Query returned status "${y.status}"${y.error?`: ${y.error}`:""}`}]};let S=y.citations.map(x=>` - ${x.title} [${x.type||"?"}] (${x.path})`).join(`
44
44
  `),I=y.walked.length,P=y.live?.length?`
45
45
 
46
46
  Read live at the source just now:
@@ -530,7 +530,7 @@ ${l}`)}let S={agentId:o,message:y,context:{channel:w,sender:f?"opencode":"openai
530
530
 
531
531
  `)}}function hg(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function gg(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
532
532
 
533
- `)}function pg(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);fo(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function fo(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var cn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new cn(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(cn.levelOrder[e]<cn.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},an=cn;mt(an,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Ov,statSync as Dv}from"fs";var Ct={version:"0.134.0",commit:"3b6ddfe",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Nv(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function mg(){let r=null;try{r=Dv(Ov(process.argv[1])).mtimeMs}catch{}let e=jh().version;return Nv(Ct,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as jv}from"crypto";var As=class{constructor(e=new nl){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Lv.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Uv(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:jv(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Fv(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},Lv=["run","task","signal","mesh","channel","status"];function Fv(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function Uv(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function yg(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Rs,timingSafeEqual as wg}from"crypto";var Es=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[y,S]of Object.entries(e.headers))(y.startsWith("x-hubspot")||y.startsWith("x-hub")||y.startsWith("x-github")||y.startsWith("x-gitlab")||y.startsWith("stripe")||y.startsWith("sentry")||y.startsWith("x-vercel")||y.startsWith("x-odoo")||y.startsWith("x-webhook")||y==="user-agent"||y==="content-type"||y==="host"||y==="x-forwarded-host"||y==="x-forwarded-proto"||y==="x-forwarded-for")&&(b[y]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(b)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let g=this.extractEventType(l,c,e.headers),m=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),f=g&&m?.triggers?.[g]||m?.defaultWorkflow||null;if(await this.fireHookSafe(l,g,i,c),f&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:f,entityRef:{kind:"webhook",id:`${l}:${i}:${g??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:g,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${g??"\u2014"}] -> workflow=${f} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:g,workflow:f,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${g}/${f}]: ${b.message}`)}let w=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(w?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:w.node,status:"accepted"}),this.mesh.sendTask(w.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${w.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${w.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:l,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
533
+ `)}function pg(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);fo(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function fo(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var cn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new cn(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(cn.levelOrder[e]<cn.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},an=cn;mt(an,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Ov,statSync as Dv}from"fs";var Ct={version:"0.135.0",commit:"e4aa315",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Nv(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function mg(){let r=null;try{r=Dv(Ov(process.argv[1])).mtimeMs}catch{}let e=jh().version;return Nv(Ct,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as jv}from"crypto";var As=class{constructor(e=new nl){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Lv.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Uv(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:jv(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Fv(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},Lv=["run","task","signal","mesh","channel","status"];function Fv(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function Uv(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function yg(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Rs,timingSafeEqual as wg}from"crypto";var Es=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[y,S]of Object.entries(e.headers))(y.startsWith("x-hubspot")||y.startsWith("x-hub")||y.startsWith("x-github")||y.startsWith("x-gitlab")||y.startsWith("stripe")||y.startsWith("sentry")||y.startsWith("x-vercel")||y.startsWith("x-odoo")||y.startsWith("x-webhook")||y==="user-agent"||y==="content-type"||y==="host"||y==="x-forwarded-host"||y==="x-forwarded-proto"||y==="x-forwarded-for")&&(b[y]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(b)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let g=this.extractEventType(l,c,e.headers),m=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),f=g&&m?.triggers?.[g]||m?.defaultWorkflow||null;if(await this.fireHookSafe(l,g,i,c),f&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:f,entityRef:{kind:"webhook",id:`${l}:${i}:${g??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:g,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${g??"\u2014"}] -> workflow=${f} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:g,workflow:f,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${g}/${f}]: ${b.message}`)}let w=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(w?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:w.node,status:"accepted"}),this.mesh.sendTask(w.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${w.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${w.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:l,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
534
534
  `)[0]||"no message"} (${d.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
535
535
  `)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",g=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${g?`, ${g}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
536
536
  `)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(d=>d.enabled&&d.agentId===s&&d.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=d=>{let u=e[d.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let d=c("x-hub-signature-256");if(!d)return"missing X-Hub-Signature-256";let u="sha256="+Rs("sha256",a).update(t).digest("hex");return Pt(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?Pt(a,d):"missing X-Gitlab-Token"}if(n==="stripe"){let d=c("stripe-signature");if(!d)return"missing Stripe-Signature";let u=Object.fromEntries(d.split(",").map(m=>m.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let g=Rs("sha256",a).update(`${u.t}.${t}`).digest("hex");return Pt(g,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let g=parseInt(u,10);if(!Number.isFinite(g))return"malformed X-HubSpot-Request-Timestamp";let m=Date.now()-g;if(m>5*6e4)return`HubSpot webhook is ${Math.floor(m/1e3)}s old (>5min replay window)`;let f="POST",w=i||e["x-original-uri"]||e["x-forwarded-path"]||"",b=e["x-forwarded-host"],y=e.host,S=e["x-forwarded-proto"]||"https",I=new Set;b&&w&&I.add(`${S}://${b}${w}`),y&&w&&I.add(`https://${y}${w}`),y&&w&&I.add(`http://${y}${w}`),w&&I.add(w),I.add("");for(let P of I){let D=Rs("sha256",a).update(`${f}${P}${t}${u}`).digest("base64");if(d.length===D.length&&wg(Buffer.from(d),Buffer.from(D)))return null}return`signature mismatch (tried ${I.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let g=Rs("sha256",a).update(t).digest("hex"),m=d.startsWith("sha256=")?d.slice(7):d;return Pt(g,m)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?Pt(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?Pt(a,l):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function Pt(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return wg(t,n)?null:"signature mismatch"}ok();sc();pc();function Gv(r){return{insertTaskHistory:r.prepare(`
@@ -1176,4 +1176,4 @@ data: ${JSON.stringify(F)}
1176
1176
  `)}catch{}},j=setInterval(()=>{try{t.write(`: ping
1177
1177
 
1178
1178
  `)}catch{}},15e3);j.unref?.();let L=new AbortController;t.on("close",()=>{t.writableEnded||L.abort()});try{for await(let U of this.mesh.sendTaskStream(h.peer,h.message,h.agent,{context:h.context,signal:L.signal,vouchOwner:v}))C(U.event,U.data)}catch(U){C("error",{error:U?.message??String(U)})}finally{clearInterval(j);try{t.end()}catch{}}break}let A=h.context,O=typeof h.senderAgentId=="string"?h.senderAgentId:void 0;if(Rw(h,!0)==="callback"){let C=this.delegationGate(e,h,{callee:h.agent,peer:h.peer,message:h.message,calleeContext:A});if(!("track"in C)){let j=jr(C);this.json(t,j.status,j.body);break}}if(h.async===!0){let C=A?.channel,j=A?.chatId;if(!C||!j){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let L=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:L,deliverTo:`${C}:${j}`,note:"result will be delivered to the originating chat when the peer finishes"});let U=h.peer,F=h.agent,ee=this.mesh;(async()=>{let W=Date.now(),q;try{q=await ee.sendTask(U,h.message,F,{vouchOwner:v,context:A,senderAgentId:O}),this.log(`[mesh/task async ${L}] ${U}/${F??"default"} finished in ${Date.now()-W}ms`)}catch(V){q=`Delegation to ${U}/${F??"default"} failed: ${V?.message??V}`,this.log(`[mesh/task async ${L}] failed: ${V?.message??V}`)}try{await this.router.sendOutbound({channel:C,chatId:j,text:q,agentId:A?.agentId??O,accountId:A?.accountId})}catch(V){this.log(`[mesh/task async ${L}] delivery failed: ${V?.message??V}`)}})();break}let M=await this.mesh.sendTask(h.peer,h.message,h.agent,{context:A,senderAgentId:O,vouchOwner:v});this.json(t,200,{response:M});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let p=await B(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let k=await this.webrtc.handleOutgoing(p);this.json(t,k.ok?200:400,k);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let p=await B(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let k=this.webrtc.handleIncoming(p);this.json(t,k.ok?200:400,k);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let h=await B(e),p=h.callId,k=h.target,v=h.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!p||!k||!v){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let $=await this.botManager.invite({callId:p,target:k,agentId:v});this.json(t,$.ok?200:500,$);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let h=this.config.channels.webrtc;if(!h?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...h.stunServers.map(p=>({urls:p})),...h.turnServers],peers:this.mesh?.directory().map(p=>({name:p.peer,healthy:p.healthy}))||[],camera:h.camera,agents:this.registry.list().map(p=>({id:p.id,name:p.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(h=>{let p=this.config.agents[h.id]||{},k=typeof p.description=="string"&&p.description.trim()||tA(p.systemPrompt)||`Agent "${h.name}" (${h.tier})`,v=Array.isArray(p.mentions)?p.mentions.slice(0,4):[];return{id:h.id,name:h.name,description:k,tags:[h.tier,...v],color:fe(h.id,p).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let h=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:h.summary()});break}case"GET /wiki/entries":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent")||void 0,k=n.searchParams.get("after")||void 0,v=p?h.getAgentEntries(p):h.getSharedStore().listEntries({after:k});this.json(t,200,{nodeId:this.config.node.id,count:v.length,entries:v.map($=>({id:$.id,date:$.date,agentId:$.agentId,source:$.source,sourceContext:$.sourceContext,content:$.content}))});break}case"GET /wiki/articles":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent");if(!p){this.json(t,400,{error:"?agent= required"});break}let v=h.getAgentWiki(p).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:p,articles:v.articles});break}case"GET /wiki/article":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent"),k=n.searchParams.get("path");if(!p||!k){this.json(t,400,{error:"?agent= and ?path= required"});break}let $=h.getAgentWiki(p).readArticle(k);if(!$){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:p,path:$.path,title:$.meta.title,tags:$.meta.tags,owner:$.meta.owner,created:$.meta.created,lastUpdated:$.meta.lastUpdated,sources:$.meta.sources,content:$.content});break}case"GET /wiki/notes":{let{NoteStore:h}=await import("./notes-WJJEJ4CJ.js"),p=n.searchParams.get("status")||"waiting";if(!["waiting","open","patched","rejected","deferred","expired","all"].includes(p)){this.json(t,400,{error:"status must be waiting, open, patched, rejected, deferred, expired or all"});break}let k=Math.max(1,Math.min(200,parseInt(n.searchParams.get("limit")||"50",10)||50)),$=new h(this.registry.getWikiHub().getBaseDir()).list(p==="all"?void 0:p);this.json(t,200,{nodeId:this.config.node.id,enabled:this.config.wikiNotes.enabled,inbox:this.config.wikiNotes.inbox??null,crons:this.config.wikiNotes.crons,absorbAgent:this.config.wikiNotes.absorbAgent??null,total:$.length,notes:$.slice(-k).reverse()});break}case"POST /wiki/notes":{let{NoteStore:h,validateNote:p}=await import("./notes-WJJEJ4CJ.js"),k=this.config.wikiNotes;if(!k.enabled||!k.inbox){this.json(t,409,{error:"wiki notes are off on this node: set wikiNotes.enabled and wikiNotes.inbox"});break}let v=await B(e),$=p({...v,to:k.inbox});if("error"in $){this.json(t,400,{error:$.error});break}let T=$.note;if(this.registry.getAgent(k.inbox)){try{let{note:M,added:C}=new h(this.registry.getWikiHub().getBaseDir()).add(T);this.json(t,C?201:200,{ok:!0,added:C,note:M,node:this.config.node.id})}catch(M){this.json(t,507,{error:M?.message??String(M)})}break}if(v.forwarded===!0){this.json(t,404,{error:`inbox agent "${k.inbox}" is not on this node`});break}let A=this.mesh?.findAgentPeer(k.inbox);if(!A){this.json(t,404,{error:`inbox agent "${k.inbox}" is not on this node or any known peer`});break}let O=this.mesh.directory().find(M=>M.peer===A.peer)?.peerUrl;if(!A.healthy||!O){this.json(t,503,{error:`the node hosting "${k.inbox}" (${A.peer}) is unreachable; try again later`});break}try{let M=await fetch(`${O.replace(/\/$/,"")}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(A.peer)},body:JSON.stringify({...T,fromNode:T.fromNode||this.config.node.id,forwarded:!0}),signal:AbortSignal.timeout(1e4)}),C=await M.json().catch(()=>({}));this.json(t,M.status,{...C,peer:A.peer})}catch(M){this.json(t,502,{error:`forward to ${A.peer} failed: ${M?.message??M}`,peer:A.peer})}break}case"GET /graph/schema":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:h.loadSchema()});break}case"GET /graph/nodes":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...h.loadNodes()});break}case"GET /graph/classifications":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}let p=n.searchParams.get("status")||"approved",k=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),v=h.listByStatus(p,k);this.json(t,200,{nodeId:this.config.node.id,status:p,count:v.length,classifications:v});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /wiki/notes[?status=waiting|open|patched|rejected|deferred|expired|all&limit=N]","POST /wiki/notes { from, change, source, date? } \u2014 a note for the wiki observe/sweep run","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/watch/:id/stream { seconds, note? } \u2014 the agent keeps watching for a while (0 stops)","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await B(e);await fg(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let l=this.registry.list().find(d=>d.id===i)?.runningTasks.filter(d=>d.channel===o&&d.chatId===a)||[];for(let d of l)this.registry.cancelRunningTask(d.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){if(!e)return{token:this.config.channels.gitlab?.token,source:"global"};let t=(this.config.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);if(t?.token)return{token:t.token,source:"agentMappings"};let n=lm(this.config,e,"gitlab-user","tokenEnv");return n.status==="ok"&&n.value?{token:n.value,source:`integrations(${n.envVar})`}:this.config.channels.gitlab?.token?{token:this.config.channels.gitlab.token,source:"global"}:{token:void 0,source:n.status}}resolveTodayUsage(){let e=Wg();if(e==="json")return this.registry.getTodayUsage();let t=Gg(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){let e=parseInt(this.config.node.bind.split(":")[1]||"18800",10);for(let t of this.registry.list()){let n=t.workspace;if(!(!n||!Ht(n)))try{let s=ne(n,".claude","skills");Yw(s,{recursive:!0});let i=ne(s,dm);if(!Ht(i))Xa(i,zo(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=hm(Pn(i,"utf-8"),e);o&&(Xa(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n,this.config.session.memoryIndexMaxChars)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!Ht(n))continue;let s=this.config.workflows.enabled&&(this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0)||Ql(this.config.workflows,e)),i=wl(Fc(t),this.config.requests.enabled||s?yl():null);try{switch(kl(n,i)){case"installed":this.log(` mcp: installed ${Object.keys(i).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(i).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(i).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(o){this.log(` mcp: ${e} install failed \u2014 ${o?.message??o}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return Wf(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let g=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${g}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let m=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:g}});this.log(`[workflows/mesh] dispatched broadcast: matched=${m.claimed.length} ${m.claimed.length?`(${m.claimed.map(f=>f.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:m.claimed.map(f=>f.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(g=>g.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async postToPushHost(e,t,n){let s=e.toLowerCase(),i=this.mesh?.directory().find(c=>c.peer.toLowerCase()===s);if(!i)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let o=await fetch(`${i.peerUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(i.peer)},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`push: ${i.peer} ${t} -> ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`);let a=await o.json().catch(()=>({}));if(t==="/channel/send")return a.messageId??void 0;if(typeof a.status!="number")throw new Error(`push: ${i.peer} ${t} gave no answer`);return{status:a.status,body:a.body??{}}}async handlePushApp(e,t){let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-325SXDGN.js"),o=this.config.channels.push;if(!o?.enabled){this.json(t,200,{status:503,body:{error:`Notifications are off on ${this.config.node.name}.`}});return}if(o.relayTo){if(n?.origin!==void 0){this.json(t,200,{status:409,body:{error:`${this.config.node.name} relays its notifications too (channels.push.relayTo = ${o.relayTo})`}});return}if(n?.op!=="app"){this.json(t,400,{error:"op must be app"});return}try{this.json(t,200,await this.postToPushHost(o.relayTo,"/push/app",{op:"app",origin:i(this.config.node.name),call:n.call}))}catch(c){this.log(`[push] /push/app to ${o.relayTo} failed: ${c.message}`),this.json(t,502,{error:c.message})}return}let a=this.pushBridgeCaller(e);"error"in a&&n?.op!=="roster"&&this.log(`[push] /push/app from ${e.socket?.remoteAddress||"?"} refused: ${a.error}`),this.json(t,200,s(n,a,this.pushHost??null,this.pushHost?void 0:`Notifications are not running on ${this.config.node.name}. Check channels.push.subject and the database there.`))}pushBridgeCaller(e){return _d(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await se(e)}catch(l){this.json(t,400,{error:"invalid JSON body",message:l.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}let c;if(n.relayed===!0&&n.origin!==void 0){let l=this.pushBridgeCaller(e);if("origin"in l)c=l.origin;else if(i!=="default"){this.json(t,403,{error:l.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:l}=await import("./push-bridge-325SXDGN.js"),d=l(i,this.pushBridgeCaller(e));if("error"in d){this.json(t,403,{error:d.error});return}}try{let l=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0,origin:c},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:l??null})}catch(l){this.log(`[mesh] /channel/send "${s}" failed: ${l.message}`),this.json(t,500,{error:l.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let g of l)!g.id||s.has(g.id)||(s.add(g.id),i.push({...g,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let g=await u.json();Array.isArray(g.chats)&&a(g.chats.map(m=>({id:m.id,name:m.name,kind:m.kind??"dm",accountId:m.accountId})),`mesh:${d.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await se(e)}catch{s={}}try{let i=await cm({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(o),startRun:o=>this.workflowDispatcher.startRun(o)},n,s);this.json(t,i.status,i.body)}catch(i){this.log(`[workflows] manual run "${n}" failed: ${i.message}`),this.json(t,500,{error:i.message})}}},Ka=za;mt(Ka,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/push/app","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function tA(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function se(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function nA(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function B(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}ek();function nU(r){typeof r=="string"&&(_n.error(r),process.exit(1)),r instanceof Error&&(_n.error(r.message),process.exit(1)),_n.error("Something went wrong. Please try again."),process.exit(1)}export{mA as a,Bi as b,rt as c,Zt as d,nn as e,ct as f,ds as g,jh as h,Pg as i,Yv as j,Qv as k,Ng as l,qe as m,dt as n,Fg as o,ut as p,sP as q,rP as r,Gs as s,s_ as t,J0 as u,Ho as v,$M as w,IM as x,TM as y,Yf as z,T$ as A,CM as B,PM as C,mn as D,Nt as E,yn as F,sO as G,Em as H,mI as I,KO as J,lr as K,la as L,da as M,pr as N,fe as O,wy as P,yr as Q,gT as R,Py as S,fT as T,Dy as U,br as V,Tn as W,Ir as X,xr as Y,Gy as Z,Ia as _,Xe as $,Re as aa,Ky as ba,zy as ca,Yy as da,Qy as ea,Vr as fa,Ww as ga,qa as ha,Bw as ia,Hx as ja,mL as ka,Ka as la,nU as ma};
1179
- //# sourceMappingURL=chunk-YSXE65O7.js.map
1179
+ //# sourceMappingURL=chunk-GSKJ57XY.js.map
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-PRCISYBO.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-LZLIPP7N.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-VQYVL72V.js.map
126
+ //# sourceMappingURL=chunk-H6VWU2HN.js.map
@@ -0,0 +1,2 @@
1
+ import{g as m}from"./chunk-6TURWSMN.js";import{spawn as f}from"child_process";var b=async(r,n,e)=>(await p(r,n,e)).text;function w(r){return async(n,e,c)=>{r.calls++;let{text:l,costUsd:t}=await p(n,e,c);return t===void 0?r.unpriced++:r.usd+=t,l}}async function p(r,n,e){let c=["-p","-","--output-format","json","--max-turns","1","--model",n,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],l=await new Promise((t,s)=>{let i=f("claude",c,{env:m(),stdio:["pipe","pipe","pipe"]}),u="",a="",d=setTimeout(()=>i.kill("SIGTERM"),e);i.stdout.on("data",o=>{u+=o}),i.stderr.on("data",o=>{a+=o}),i.on("error",o=>{clearTimeout(d),s(o)}),i.on("close",o=>{clearTimeout(d),o===0?t(u):s(new Error(`claude exited ${o}: ${a.trim().slice(0,200)}`))}),i.stdin.end(r)});try{let t=JSON.parse(l);if(t.is_error)throw new Error(`model error: ${String(t.result).slice(0,200)}`);let s=t.total_cost_usd;return{text:String(t.result??""),costUsd:typeof s=="number"&&Number.isFinite(s)?s:void 0}}catch(t){if(t instanceof SyntaxError)return{text:l};throw t}}function y(r){let n=r.match(/\{[\s\S]*\}/);if(!n)return null;try{let e=JSON.parse(n[0]);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}export{b as a,w as b,y as c};
2
+ //# sourceMappingURL=chunk-JRS5QRZG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/model-call.ts"],"sourcesContent":["import { spawn } from \"child_process\"\nimport { claudeCliEnv } from \"@/utils/workspace-env\"\n\n/** One model call: prompt in, text out. Tests pass their own. */\nexport type ModelCall = (prompt: string, model: string, timeoutMs: number) => Promise<string>\n\n/**\n * One `claude -p` call with no tools. The prompt carries wiki text and\n * lines read from outside systems, so no built-in tool, MCP server, hook\n * or settings file is loaded: an instruction hidden in that text has\n * nothing to run, write or send with. No shell either: the prompt goes\n * in on stdin.\n */\nexport const claudeModelCall: ModelCall = async (prompt, model, timeoutMs) => (await claudeCall(prompt, model, timeoutMs)).text\n\n/** What the calls of a metered ModelCall spent. */\nexport interface ModelSpend {\n calls: number\n usd: number\n /** Calls whose reply named no cost: `usd` then counts low. */\n unpriced: number\n}\n\n/** claudeModelCall, adding each call's reported cost to `spend`. */\nexport function meteredModelCall(spend: ModelSpend): ModelCall {\n return async (prompt, model, timeoutMs) => {\n spend.calls++\n const { text, costUsd } = await claudeCall(prompt, model, timeoutMs)\n if (costUsd === undefined) spend.unpriced++\n else spend.usd += costUsd\n return text\n }\n}\n\nasync function claudeCall(prompt: string, model: string, timeoutMs: number): Promise<{ text: string; costUsd?: number }> {\n const args = [\"-p\", \"-\", \"--output-format\", \"json\", \"--max-turns\", \"1\", \"--model\", model,\n \"--tools\", \"\", \"--strict-mcp-config\", \"--mcp-config\", '{\"mcpServers\":{}}',\n \"--settings\", '{\"disableAllHooks\":true}', \"--setting-sources\", \"\", \"--no-session-persistence\"]\n const out = await new Promise<string>((ok, fail) => {\n const child = spawn(\"claude\", args, { env: claudeCliEnv(), stdio: [\"pipe\", \"pipe\", \"pipe\"] })\n let stdout = \"\"\n let stderr = \"\"\n const timer = setTimeout(() => child.kill(\"SIGTERM\"), timeoutMs)\n child.stdout.on(\"data\", (d) => { stdout += d })\n child.stderr.on(\"data\", (d) => { stderr += d })\n child.on(\"error\", (err) => { clearTimeout(timer); fail(err) })\n child.on(\"close\", (code) => {\n clearTimeout(timer)\n if (code === 0) ok(stdout)\n else fail(new Error(`claude exited ${code}: ${stderr.trim().slice(0, 200)}`))\n })\n child.stdin.end(prompt)\n })\n try {\n const envelope = JSON.parse(out) as { result?: string; is_error?: boolean; total_cost_usd?: unknown }\n if (envelope.is_error) throw new Error(`model error: ${String(envelope.result).slice(0, 200)}`)\n const cost = envelope.total_cost_usd\n return { text: String(envelope.result ?? \"\"), costUsd: typeof cost === \"number\" && Number.isFinite(cost) ? cost : undefined }\n } catch (err) {\n if (err instanceof SyntaxError) return { text: out }\n throw err\n }\n}\n\n/** The first JSON object in a model reply, or null. */\nexport function firstJsonObject(reply: string): Record<string, unknown> | null {\n const m = reply.match(/\\{[\\s\\S]*\\}/)\n if (!m) return null\n try {\n const parsed = JSON.parse(m[0])\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null\n } catch {\n return null\n }\n}\n"],"mappings":"wCAAA,OAAS,SAAAA,MAAa,gBAaf,IAAMC,EAA6B,MAAOC,EAAQC,EAAOC,KAAe,MAAMC,EAAWH,EAAQC,EAAOC,CAAS,GAAG,KAWpH,SAASE,EAAiBC,EAA8B,CAC7D,MAAO,OAAOL,EAAQC,EAAOC,IAAc,CACzCG,EAAM,QACN,GAAM,CAAE,KAAAC,EAAM,QAAAC,CAAQ,EAAI,MAAMJ,EAAWH,EAAQC,EAAOC,CAAS,EACnE,OAAIK,I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IA,EAAO,MAAU,CAC9H,OAASH,EAAP,CACA,GAAIA,aAAe,YAAa,MAAO,CAAE,KAAMV,CAAI,EACnD,MAAMU,CACR,CACF,CAGO,SAASI,EAAgBC,EAA+C,CAC7E,IAAMC,EAAID,EAAM,MAAM,aAAa,EACnC,GAAI,CAACC,EAAG,OAAO,KACf,GAAI,CACF,IAAMC,EAAS,KAAK,MAAMD,EAAE,CAAC,CAAC,EAC9B,OAAOC,GAAU,OAAOA,GAAW,UAAY,CAAC,MAAM,QAAQA,CAAM,EAAIA,EAAoC,IAC9G,MAAE,CACA,OAAO,IACT,CACF","names":["spawn","claudeModelCall","prompt","model","timeoutMs","claudeCall","meteredModelCall","spend","text","costUsd","args","out","ok","fail","child","spawn","claudeCliEnv","stdout","stderr","timer","d","err","code","envelope","cost","firstJsonObject","reply","m","parsed"]}
@@ -1,3 +1,3 @@
1
- import{a as f}from"./chunk-JP5OAMWQ.js";import{existsSync as g,readFileSync as k,statSync as P,writeFileSync as O}from"fs";import{resolve as b}from"path";import h from"js-yaml";var l=(e=5)=>({panel:"history",title:"History",source:"history",show:e,importance:["major","normal"],fold:"minor",rollup:{min:5,days:30}}),c={panel:"discussed",title:"Discussed",source:"discussed",show:3,access:"owner"},s=(e=1)=>({panel:"notes",title:"Notes",source:"notes",show:e}),_=["device","server","app","domain","account","agent"],v=[{id:"person",label:"Person",plural:"People",pillar:"parties",schema:"Person",icon:"person",lens:[{panel:"roles",title:"Roles over time",from:["role_at","member_of","founded"],show:6,display:"timeline"},{panel:"relations",title:"Relations",from:["works_with","reports_to","client_of","works_on","related"],types:["person","organization","project"],show:5,group_by:"role"},{panel:"belongings",title:"Belongings",from:["owns","uses","related"],types:_.filter(e=>e!=="agent"),show:5},{panel:"obligations",title:"Obligations they carry",from:["subject_to"],show:3},l(),c,s()]},{id:"organization",label:"Organization",plural:"Organizations",pillar:"parties",schema:"Organization",icon:"org",lens:[{panel:"people",title:"People and roles",from:["role_at","member_of","founded"],show:6,group_by:"role"},{panel:"facts",title:"Key facts",from:["registered_with","located_in","identifier","legal_form"],show:6},{panel:"obligations",title:"Obligations and next due dates",from:["subject_to"],show:4},{panel:"agreements",title:"Agreements",source:"linked",types:["contract"],show:4},{panel:"decisions",title:"Decisions",source:"linked",types:["decision","policy"],show:4},l(),c,s()]},{id:"place",label:"Place",plural:"Places",pillar:"places",schema:"Place",icon:"pin",lens:[{panel:"here",title:"What is here",from:["located_in","related"],show:6},{panel:"laws",title:"Laws that apply here",from:["applies_in"],show:5},l(),s()]},{id:"jurisdiction",label:"Jurisdiction",plural:"Jurisdictions",pillar:"places",schema:"AdministrativeArea",icon:"pin",lens:[{panel:"laws",title:"Laws in force",from:["applies_in"],show:6},{panel:"authorities",title:"Authorities with reach",from:["jurisdiction_of"],show:5},{panel:"here",title:"What is here",from:["located_in"],show:5},s()]},{id:"device",label:"Device",plural:"Devices",pillar:"assets",schema:"Product",icon:"device",lens:[{panel:"state",title:"State now",source:"readings",latest:!0,show:6},l(),{panel:"apps",title:"Installed apps",from:["installed_on"],show:5},c,{panel:"parties",title:"Owner, user, location",from:["owns","uses","located_in","related"],types:["person","organization","place"],show:5},s()]},{id:"server",label:"Server",plural:"Servers",pillar:"assets",schema:"Product",icon:"server",lens:[{panel:"state",title:"State now",source:"readings",latest:!0,show:6},l(),{panel:"hosts",title:"Hosted services",from:["installed_on","runs_on"],show:6},c,{panel:"parties",title:"Owner and location",from:["owns","uses","located_in"],show:4},s()]},{id:"app",label:"App or system",plural:"Apps",pillar:"assets",schema:"SoftwareApplication",icon:"app",lens:[{panel:"installs",title:"Where it runs",from:["installed_on","runs_on"],show:5},{panel:"licence",title:"Licence or subscription",from:["party_to","licensed_by"],show:3},l(),c,s()]},{id:"domain",label:"Domain",plural:"Domains",pillar:"assets",schema:"WebSite",icon:"globe",lens:[{panel:"holder",title:"Holder",from:["owns","registrar"],show:3},{panel:"dues",title:"Renewal and due dates",source:"linked",types:["due_date"],show:4},{panel:"services",title:"Linked services",from:["related"],show:5},l(),s()]},{id:"account",label:"Account",plural:"Accounts",pillar:"assets",schema:"Service",icon:"key",lens:[{panel:"holder",title:"Holder",from:["owns","uses"],show:3},{panel:"dues",title:"Renewal and due dates",source:"linked",types:["due_date"],show:4},l(),s()]},{id:"agent",label:"Agent",plural:"Agents",pillar:"assets",schema:"SoftwareApplication",icon:"agent",lens:[{panel:"runs",title:"Where it runs",from:["runs_on","installed_on","related"],types:["server","device"],show:4},{panel:"works",title:"Works for",from:["works_for","uses","related"],types:["person","organization","project"],show:5},l(),c,s()]},{id:"project",label:"Project",plural:"Projects",pillar:"offerings",schema:"Project",icon:"project",lens:[{panel:"people",title:"Client and people",from:["client","client_of","works_on","related"],types:["person","organization","agent"],show:6,group_by:"role"},{panel:"agreements",title:"Agreements",source:"linked",types:["contract"],show:3},{panel:"decisions",title:"Decisions",source:"linked",types:["decision","policy"],show:4},l(6),c,s()]},{id:"offering",label:"Offering",plural:"Offerings",pillar:"offerings",schema:"Offer",icon:"project",lens:[{panel:"clients",title:"Clients",from:["client_of","related"],types:["organization","person"],show:5},l(),s()]},{id:"contract",label:"Agreement",plural:"Agreements",pillar:"agreements",schema:"Contract",icon:"contract",lens:[{panel:"parties",title:"Parties and roles",from:["party_to"],show:5,group_by:"role"},{panel:"terms",title:"Key terms and dates",from:["starts","renews","notice","amount"],show:6},{panel:"obligations",title:"Obligations it creates",from:["creates"],show:5},{panel:"amendments",title:"Amendments",from:["amends"],show:4},l(),s()]},{id:"legal_source",label:"Legal source",plural:"Legal sources",pillar:"law",schema:"Legislation",icon:"law",lens:[{panel:"reference",title:"Gazette reference and dates",from:["identifier","published_in","in_force_from","legal_force","issued_by"],show:6},{panel:"creates",title:"Obligations, penalties and reliefs it creates",from:["creates","created_by"],show:6},{panel:"amends",title:"Amends and amended by",from:["amends","repeals","implements"],show:5},{panel:"applies",title:"Where it applies",from:["applies_in"],show:3},s()]},{id:"obligation",label:"Obligation",plural:"Obligations",pillar:"law",schema:"LegalRuleML Obligation",icon:"law",lens:[{panel:"rule",title:"Who must do what, by when",from:["action","bearer","due_rule","amount_rule","authority","status"],show:6},{panel:"dues",title:"Next due dates",source:"linked",types:["due_date"],show:4},{panel:"sources",title:"Source articles",from:["created_by","changed_by"],show:4},{panel:"penalties",title:"Penalties and reliefs",from:["penalty_for","relieves"],show:4},{panel:"procedure",title:"Procedure",from:["procedure"],show:2},{panel:"bearers",title:"Who carries it",from:["subject_to"],show:5},l(4),s()]},{id:"penalty",label:"Penalty",plural:"Penalties",pillar:"law",schema:"LegalRuleML Penalty",icon:"law",lens:[{panel:"rule",title:"For which failure, how much",from:["penalty_for","kind","amount_rule","created_by"],show:6},s()]},{id:"relief",label:"Relief",plural:"Reliefs",pillar:"law",schema:"LegalRuleML Permission",icon:"law",lens:[{panel:"rule",title:"What it relieves, for whom, until when",from:["relieves","bearer","condition","created_by"],show:6},s()]},{id:"due_date",label:"Due date",plural:"Due dates",pillar:"law",schema:"Event",icon:"calendar",lens:[{panel:"due",title:"Due",from:["due_for","bearer","due","status","fulfilled_by"],show:6},s()]},{id:"event",label:"Event",plural:"Events",pillar:"events",schema:"Event",icon:"calendar",lens:[s(1),{panel:"involved",title:"Who and what was involved",from:["involves","affects","related"],show:8},{panel:"followed",title:"What followed",source:"linked",types:["event","decision"],show:4},c]},{id:"decision",label:"Decision",plural:"Decisions",pillar:"decisions",schema:"ChooseAction",icon:"decision",lens:[s(1),{panel:"affects",title:"What it affects",from:["affects","creates","related"],show:6},{panel:"replaced",title:"Replaced by",from:["replaced_by"],show:2},c]},{id:"policy",label:"Policy",plural:"Policies",pillar:"decisions",schema:"LegalRuleML Obligation",icon:"decision",lens:[{panel:"rule",title:"Rule",from:["action","bearer","creates","created_by"],show:6},{panel:"affects",title:"What it affects",from:["affects","related"],show:6},s()]},{id:"procedure",label:"Procedure",plural:"Procedures",pillar:"procedures",schema:"HowTo",icon:"steps",lens:[s(1),{panel:"triggers",title:"What triggers it",from:["procedure","triggered_by","related"],show:5},{panel:"runs",title:"Last runs",source:"linked",types:["event"],show:4}]},{id:"topic",label:"Topic",plural:"Topics",pillar:"topics",schema:"skos:Concept",icon:"topic",lens:[s(1),{panel:"related",title:"Related",from:["related"],show:8},l(4)]}],d={version:1,pillars:[{id:"parties",label:"Parties",description:"People and organisations, and the roles between them",icon:"person"},{id:"places",label:"Places & Jurisdictions",description:"Where things are, and whose rules apply there",icon:"pin"},{id:"assets",label:"Assets",description:"What is owned or run: devices, servers, apps, domains, accounts, agents",icon:"server"},{id:"offerings",label:"Offerings & Projects",description:"What is sold, built or delivered",icon:"project"},{id:"agreements",label:"Agreements",description:"Contracts, subscriptions and their terms",icon:"contract"},{id:"law",label:"Law & Obligations",description:"Legal sources, the obligations they create, penalties, reliefs and due dates",icon:"law"},{id:"events",label:"Events",description:"What happened, by importance",icon:"calendar"},{id:"decisions",label:"Decisions & Policies",description:"Why things are the way they are",icon:"decision"},{id:"procedures",label:"Procedures",description:"How things are done",icon:"steps"},{id:"topics",label:"Topics",description:"Pages no type fits yet. A growing count means a type is missing.",icon:"topic",sidebar:!1}],types:v,properties:[{id:"related",label:"related to",inverse:"related to"},{id:"role_at",label:"role at",inverse:"people",wikidata:"P108",range:["organization"],domain:["person"]},{id:"member_of",label:"member of",inverse:"members",wikidata:"P463",range:["organization"],domain:["person","organization"]},{id:"founded",label:"founded",inverse:"founded by",wikidata:"P112",domain:["person","organization"]},{id:"works_with",label:"works with",inverse:"works with",domain:["person","organization"]},{id:"reports_to",label:"reports to",inverse:"manages",domain:["person"]},{id:"client_of",label:"client of",inverse:"clients",wikidata:"P1972",domain:["person","organization"]},{id:"client",label:"is for client",inverse:"projects",range:["organization","person"],domain:["project","offering","contract"]},{id:"works_on",label:"works on",inverse:"people",range:["project"],domain:["person","organization","agent"]},{id:"works_for",label:"works for",inverse:"agents",wikidata:"P108",domain:["agent","person"]},{id:"owns",label:"owns",inverse:"owned by",wikidata:"P1830"},{id:"uses",label:"uses",inverse:"used by",wikidata:"P2283"},{id:"located_in",label:"located in",inverse:"here",wikidata:"P276"},{id:"installed_on",label:"installed on",inverse:"installed apps",range:["device","server"]},{id:"runs_on",label:"runs on",inverse:"hosts"},{id:"registered_with",label:"registered with",inverse:"registered"},{id:"identifier",label:"identifier",wikidata:"P1448"},{id:"legal_form",label:"legal form",wikidata:"P1454"},{id:"registrar",label:"registrar"},{id:"licensed_by",label:"licensed by",inverse:"licences"},{id:"party_to",label:"party to",inverse:"parties"},{id:"starts",label:"starts"},{id:"renews",label:"renews"},{id:"notice",label:"notice period"},{id:"amount",label:"amount"},{id:"creates",label:"creates",inverse:"created by"},{id:"created_by",label:"created by",inverse:"creates"},{id:"changed_by",label:"changed by",inverse:"changes"},{id:"amends",label:"amends",inverse:"amended by",wikidata:"P144"},{id:"repeals",label:"repeals",inverse:"repealed by"},{id:"implements",label:"implements",inverse:"implemented by"},{id:"issued_by",label:"issued by",inverse:"issues"},{id:"published_in",label:"published in",wikidata:"P1433"},{id:"in_force_from",label:"in force from",wikidata:"P7588"},{id:"legal_force",label:"legal force"},{id:"applies_in",label:"applies in",inverse:"laws that apply",wikidata:"P1001"},{id:"jurisdiction_of",label:"authority in",inverse:"authorities"},{id:"subject_to",label:"subject to",inverse:"carried by"},{id:"action",label:"action"},{id:"bearer",label:"bearer"},{id:"due_rule",label:"due"},{id:"amount_rule",label:"amount"},{id:"authority",label:"authority",inverse:"collects"},{id:"status",label:"status"},{id:"penalty_for",label:"penalty for",inverse:"penalties"},{id:"relieves",label:"relieves",inverse:"reliefs"},{id:"condition",label:"condition"},{id:"kind",label:"kind"},{id:"procedure",label:"procedure",inverse:"carries out"},{id:"due_for",label:"due for",inverse:"due dates"},{id:"due",label:"due on"},{id:"fulfilled_by",label:"fulfilled by",inverse:"fulfils"},{id:"involves",label:"involves",inverse:"events",wikidata:"P710"},{id:"affects",label:"affects",inverse:"affected by"},{id:"replaced_by",label:"replaced by",inverse:"replaces",wikidata:"P1366"},{id:"triggered_by",label:"triggered by",inverse:"triggers"},{id:"mentions",label:"mentions",inverse:"discussed in"},{id:"reading",label:"reading"}],importance:{default:"normal",major_set_by:"owner",rollup:{min:5,days:30}},sidebar:{pins_max:5,pins:[]},classify:[{type:"agent",legacy:["person","concept","project"],title:"\\bagents?\\b|\\bbot\\b"},{type:"server",legacy:["place","concept"],title:"\\b(server|vps|host|node)\\b"},{type:"device",legacy:["place","concept"],title:"\\b(laptop|macbook|desktop|phone|tablet|printer|router)\\b"},{type:"person",legacy:["person"]},{type:"event",legacy:["event"]},{type:"decision",legacy:["decision"]},{type:"procedure",legacy:["pattern"]},{type:"place",legacy:["place"]},{type:"project",legacy:["project"]},{type:"organization",path:["clients","customers","vendors","suppliers","organizations","orgs","companies"]},{type:"organization",tags:["organization","company","client","vendor","supplier","agency","bank"]},{type:"server",path:["servers","hosts","infrastructure"]},{type:"server",tags:["server","vps","host"]},{type:"device",path:["devices"]},{type:"device",tags:["device","laptop","phone","printer"]},{type:"agent",tags:["agent"],title:"\\bagent\\b"},{type:"app",path:["apps","systems","services"]},{type:"domain",tags:["domain","dns"]},{type:"contract",path:["contracts","agreements"]},{type:"contract",tags:["contract","agreement","subscription"]},{type:"legal_source",path:["laws","legislation"]},{type:"legal_source",tags:["law","legislation","decree"]},{type:"obligation",path:["obligations","compliance"]},{type:"obligation",tags:["obligation","compliance"]},{type:"policy",path:["policies"]},{type:"policy",tags:["policy"]},{type:"procedure",path:["runbooks","procedures"]},{type:"procedure",tags:["runbook","procedure","how-to"]}],fallback_type:"topic"};var y="ontology.yaml",m=new Map;function E(e){let t=b(e,y);if(!g(t))return{ontology:d,errors:[],file:null};let r=P(t).mtimeMs,a=m.get(t);if(a&&a.mtimeMs===r)return a.loaded;let n,i=[];try{n=h.load(k(t,"utf-8"))}catch(w){i.push(`${y} is not valid YAML: ${w.message}`),n={}}let o=A(d,u(n)?n:{},i);i.push(...j(o));let p={ontology:o,errors:i,file:t};return m.set(t,{mtimeMs:r,loaded:p}),p}function T(e){let t=b(e,y);if(g(t))throw new Error(`${t} already exists`);let r=["# Wiki ontology: pillars, types, typed relations, event importance and lenses.","# Edit any section; what you leave out falls back to the built-in defaults.","# Check it with: agentx wiki ontology check",""].join(`
2
- `);return O(t,r+h.dump(d,{lineWidth:120,noRefs:!0})),t}function A(e,t,r=[]){let a=structuredClone(e);typeof t.version=="number"&&(a.version=t.version);for(let n of["pillars","types","properties"]){let i=t[n];if(i!==void 0){if(!Array.isArray(i)){r.push(`${n} must be a list`);continue}a[n]=L(a[n],i,n,r)}}return u(t.importance)&&(a.importance={...a.importance,...t.importance}),u(t.sidebar)&&(a.sidebar={...a.sidebar,...t.sidebar}),t.classify!==void 0&&(Array.isArray(t.classify)?a.classify=t.classify:r.push("classify must be a list")),typeof t.fallback_type=="string"&&(a.fallback_type=t.fallback_type),t.agent_names!==void 0&&(Array.isArray(t.agent_names)?a.agent_names=t.agent_names.filter(n=>typeof n=="string"&&!!n.trim()):r.push("agent_names must be a list")),a}function L(e,t,r,a){let n=e.map(i=>({...i}));for(let i of t){if(!u(i)||typeof i.id!="string"){a.push(`every item in ${r} needs an id`);continue}let o=n.findIndex(p=>p.id===i.id);o===-1?n.push(i):n[o]={...n[o],...i}}return n}function j(e){let t=[],r=new Set(e.pillars.map(i=>i.id)),a=new Set(e.types.map(i=>i.id)),n=new Set(e.properties.map(i=>i.id));for(let i of e.types){r.has(i.pillar)||t.push(`type ${i.id}: unknown pillar "${i.pillar}"`);for(let o of i.lens??[]){for(let p of S(o))n.has(p)||t.push(`type ${i.id}, panel ${o.panel}: unknown property "${p}"`);for(let p of o.types??[])a.has(p)||t.push(`type ${i.id}, panel ${o.panel}: unknown type "${p}"`);for(let p of o.importance??[])f.includes(p)||t.push(`type ${i.id}, panel ${o.panel}: unknown importance "${p}"`)}}for(let i of e.classify)if(a.has(i.type)||t.push(`classify: unknown type "${i.type}"`),i.title)try{new RegExp(i.title,"i")}catch{t.push(`classify: bad title pattern "${i.title}"`)}return a.has(e.fallback_type)||t.push(`fallback_type: unknown type "${e.fallback_type}"`),f.includes(e.importance.default)||t.push(`importance.default: unknown level "${e.importance.default}"`),e.sidebar.pins.length>e.sidebar.pins_max&&t.push(`sidebar.pins: ${e.sidebar.pins.length} pins, only the first ${e.sidebar.pins_max} are shown`),t}function S(e){return e.from?Array.isArray(e.from)?e.from:[e.from]:[]}function M(e){return e.source?e.source:e.panel==="history"||e.panel==="discussed"||e.panel==="notes"?e.panel:e.latest?"readings":e.from?"statements":"linked"}function u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}export{y as a,E as b,T as c,A as d,j as e,S as f,M as g};
3
- //# sourceMappingURL=chunk-5BI2T3WD.js.map
1
+ import{a as d}from"./chunk-RGZARSHV.js";import{existsSync as b,readFileSync as k,statSync as P,writeFileSync as O}from"fs";import{resolve as g}from"path";import h from"js-yaml";var n=(e=5)=>({panel:"history",title:"History",source:"history",show:e,importance:["major","normal"],fold:"minor",rollup:{min:5,days:30}}),c={panel:"discussed",title:"Discussed",source:"discussed",show:3,access:"owner"},s=(e=1)=>({panel:"notes",title:"Notes",source:"notes",show:e}),_=["device","server","app","domain","account","agent"],v=[{id:"person",label:"Person",plural:"People",pillar:"parties",schema:"Person",icon:"person",lens:[{panel:"roles",title:"Roles over time",from:["role_at","member_of","founded"],show:6,display:"timeline"},{panel:"relations",title:"Relations",from:["works_with","reports_to","client_of","works_on","related"],types:["person","organization","project"],show:5,group_by:"role"},{panel:"belongings",title:"Belongings",from:["owns","uses","related"],types:_.filter(e=>e!=="agent"),show:5},{panel:"obligations",title:"Obligations they carry",from:["subject_to"],show:3},n(),c,s()]},{id:"organization",label:"Organization",plural:"Organizations",pillar:"parties",schema:"Organization",icon:"org",lens:[{panel:"people",title:"People and roles",from:["role_at","member_of","founded"],show:6,group_by:"role"},{panel:"facts",title:"Key facts",from:["registered_with","located_in","identifier","legal_form"],show:6},{panel:"obligations",title:"Obligations and next due dates",from:["subject_to"],show:4},{panel:"agreements",title:"Agreements",source:"linked",types:["contract"],show:4},{panel:"decisions",title:"Decisions",source:"linked",types:["decision","policy"],show:4},n(),c,s()]},{id:"place",label:"Place",plural:"Places",pillar:"places",schema:"Place",icon:"pin",lens:[{panel:"here",title:"What is here",from:["located_in","related"],show:6},{panel:"laws",title:"Laws that apply here",from:["applies_in"],show:5},n(),s()]},{id:"jurisdiction",label:"Jurisdiction",plural:"Jurisdictions",pillar:"places",schema:"AdministrativeArea",icon:"pin",lens:[{panel:"laws",title:"Laws in force",from:["applies_in"],show:6},{panel:"authorities",title:"Authorities with reach",from:["jurisdiction_of"],show:5},{panel:"here",title:"What is here",from:["located_in"],show:5},s()]},{id:"device",label:"Device",plural:"Devices",pillar:"assets",schema:"Product",icon:"device",lens:[{panel:"state",title:"State now",source:"readings",latest:!0,show:6},n(),{panel:"apps",title:"Installed apps",from:["installed_on"],show:5},c,{panel:"parties",title:"Owner, user, location",from:["owns","uses","located_in","related"],types:["person","organization","place"],show:5},s()]},{id:"server",label:"Server",plural:"Servers",pillar:"assets",schema:"Product",icon:"server",lens:[{panel:"state",title:"State now",source:"readings",latest:!0,show:6},n(),{panel:"hosts",title:"Hosted services",from:["installed_on","runs_on"],show:6},c,{panel:"parties",title:"Owner and location",from:["owns","uses","located_in"],show:4},s()]},{id:"app",label:"App or system",plural:"Apps",pillar:"assets",schema:"SoftwareApplication",icon:"app",lens:[{panel:"installs",title:"Where it runs",from:["installed_on","runs_on"],show:5},{panel:"licence",title:"Licence or subscription",from:["party_to","licensed_by"],show:3},n(),c,s()]},{id:"domain",label:"Domain",plural:"Domains",pillar:"assets",schema:"WebSite",icon:"globe",lens:[{panel:"holder",title:"Holder",from:["owns","registrar"],show:3},{panel:"dues",title:"Renewal and due dates",source:"linked",types:["due_date"],show:4},{panel:"services",title:"Linked services",from:["related"],show:5},n(),s()]},{id:"account",label:"Account",plural:"Accounts",pillar:"assets",schema:"Service",icon:"key",lens:[{panel:"holder",title:"Holder",from:["owns","uses"],show:3},{panel:"dues",title:"Renewal and due dates",source:"linked",types:["due_date"],show:4},n(),s()]},{id:"agent",label:"Agent",plural:"Agents",pillar:"assets",schema:"SoftwareApplication",icon:"agent",lens:[{panel:"runs",title:"Where it runs",from:["runs_on","installed_on","related"],types:["server","device"],show:4},{panel:"works",title:"Works for",from:["works_for","uses","related"],types:["person","organization","project"],show:5},n(),c,s()]},{id:"project",label:"Project",plural:"Projects",pillar:"offerings",schema:"Project",icon:"project",lens:[{panel:"people",title:"Client and people",from:["client","client_of","works_on","related"],types:["person","organization","agent"],show:6,group_by:"role"},{panel:"agreements",title:"Agreements",source:"linked",types:["contract"],show:3},{panel:"decisions",title:"Decisions",source:"linked",types:["decision","policy"],show:4},n(6),c,s()]},{id:"offering",label:"Offering",plural:"Offerings",pillar:"offerings",schema:"Offer",icon:"project",lens:[{panel:"clients",title:"Clients",from:["client_of","related"],types:["organization","person"],show:5},n(),s()]},{id:"contract",label:"Agreement",plural:"Agreements",pillar:"agreements",schema:"Contract",icon:"contract",lens:[{panel:"parties",title:"Parties and roles",from:["party_to"],show:5,group_by:"role"},{panel:"terms",title:"Key terms and dates",from:["starts","renews","notice","amount"],show:6},{panel:"obligations",title:"Obligations it creates",from:["creates"],show:5},{panel:"amendments",title:"Amendments",from:["amends"],show:4},n(),s()]},{id:"legal_source",label:"Legal source",plural:"Legal sources",pillar:"law",schema:"Legislation",icon:"law",lens:[{panel:"reference",title:"Gazette reference and dates",from:["identifier","published_in","in_force_from","legal_force","issued_by"],show:6},{panel:"creates",title:"Obligations, penalties and reliefs it creates",from:["creates","created_by"],show:6},{panel:"amends",title:"Amends and amended by",from:["amends","repeals","implements"],show:5},{panel:"applies",title:"Where it applies",from:["applies_in"],show:3},s()]},{id:"obligation",label:"Obligation",plural:"Obligations",pillar:"law",schema:"LegalRuleML Obligation",icon:"law",lens:[{panel:"rule",title:"Who must do what, by when",from:["action","bearer","due_rule","amount_rule","authority","status"],show:6},{panel:"dues",title:"Next due dates",source:"linked",types:["due_date"],show:4},{panel:"sources",title:"Source articles",from:["created_by","changed_by"],show:4},{panel:"penalties",title:"Penalties and reliefs",from:["penalty_for","relieves"],show:4},{panel:"procedure",title:"Procedure",from:["procedure"],show:2},{panel:"bearers",title:"Who carries it",from:["subject_to"],show:5},n(4),s()]},{id:"penalty",label:"Penalty",plural:"Penalties",pillar:"law",schema:"LegalRuleML Penalty",icon:"law",lens:[{panel:"rule",title:"For which failure, how much",from:["penalty_for","kind","amount_rule","created_by"],show:6},s()]},{id:"relief",label:"Relief",plural:"Reliefs",pillar:"law",schema:"LegalRuleML Permission",icon:"law",lens:[{panel:"rule",title:"What it relieves, for whom, until when",from:["relieves","bearer","condition","created_by"],show:6},s()]},{id:"due_date",label:"Due date",plural:"Due dates",pillar:"law",schema:"Event",icon:"calendar",lens:[{panel:"due",title:"Due",from:["due_for","bearer","due","status","fulfilled_by"],show:6},s()]},{id:"event",label:"Event",plural:"Events",pillar:"events",schema:"Event",icon:"calendar",lens:[s(1),{panel:"involved",title:"Who and what was involved",from:["involves","affects","related"],show:8},{panel:"followed",title:"What followed",source:"linked",types:["event","decision"],show:4},c]},{id:"decision",label:"Decision",plural:"Decisions",pillar:"decisions",schema:"ChooseAction",icon:"decision",lens:[s(1),{panel:"affects",title:"What it affects",from:["affects","creates","related"],show:6},{panel:"replaced",title:"Replaced by",from:["replaced_by"],show:2},c]},{id:"policy",label:"Policy",plural:"Policies",pillar:"decisions",schema:"LegalRuleML Obligation",icon:"decision",lens:[{panel:"rule",title:"Rule",from:["action","bearer","creates","created_by"],show:6},{panel:"affects",title:"What it affects",from:["affects","related"],show:6},s()]},{id:"procedure",label:"Procedure",plural:"Procedures",pillar:"procedures",schema:"HowTo",icon:"steps",lens:[s(1),{panel:"triggers",title:"What triggers it",from:["procedure","triggered_by","related"],show:5},{panel:"runs",title:"Last runs",source:"linked",types:["event"],show:4}]},{id:"topic",label:"Topic",plural:"Topics",pillar:"topics",schema:"skos:Concept",icon:"topic",lens:[s(1),{panel:"related",title:"Related",from:["related"],show:8},n(4)]}],u={version:1,pillars:[{id:"parties",label:"Parties",description:"People and organisations, and the roles between them",icon:"person"},{id:"places",label:"Places & Jurisdictions",description:"Where things are, and whose rules apply there",icon:"pin"},{id:"assets",label:"Assets",description:"What is owned or run: devices, servers, apps, domains, accounts, agents",icon:"server"},{id:"offerings",label:"Offerings & Projects",description:"What is sold, built or delivered",icon:"project"},{id:"agreements",label:"Agreements",description:"Contracts, subscriptions and their terms",icon:"contract"},{id:"law",label:"Law & Obligations",description:"Legal sources, the obligations they create, penalties, reliefs and due dates",icon:"law"},{id:"events",label:"Events",description:"What happened, by importance",icon:"calendar"},{id:"decisions",label:"Decisions & Policies",description:"Why things are the way they are",icon:"decision"},{id:"procedures",label:"Procedures",description:"How things are done",icon:"steps"},{id:"topics",label:"Topics",description:"Pages no type fits yet. A growing count means a type is missing.",icon:"topic",sidebar:!1}],types:v,properties:[{id:"related",label:"related to",inverse:"related to"},{id:"role_at",label:"role at",inverse:"people",wikidata:"P108",range:["organization"],domain:["person"]},{id:"member_of",label:"member of",inverse:"members",wikidata:"P463",range:["organization"],domain:["person","organization"]},{id:"founded",label:"founded",inverse:"founded by",wikidata:"P112",domain:["person","organization"]},{id:"works_with",label:"works with",inverse:"works with",domain:["person","organization"]},{id:"reports_to",label:"reports to",inverse:"manages",domain:["person"]},{id:"client_of",label:"client of",inverse:"clients",wikidata:"P1972",domain:["person","organization"]},{id:"client",label:"is for client",inverse:"projects",range:["organization","person"],domain:["project","offering","contract"]},{id:"works_on",label:"works on",inverse:"people",range:["project"],domain:["person","organization","agent"]},{id:"works_for",label:"works for",inverse:"agents",wikidata:"P108",domain:["agent","person"]},{id:"owns",label:"owns",inverse:"owned by",wikidata:"P1830"},{id:"uses",label:"uses",inverse:"used by",wikidata:"P2283"},{id:"located_in",label:"located in",inverse:"here",wikidata:"P276"},{id:"installed_on",label:"installed on",inverse:"installed apps",range:["device","server"]},{id:"runs_on",label:"runs on",inverse:"hosts"},{id:"registered_with",label:"registered with",inverse:"registered"},{id:"identifier",label:"identifier",wikidata:"P1448"},{id:"legal_form",label:"legal form",wikidata:"P1454"},{id:"registrar",label:"registrar"},{id:"licensed_by",label:"licensed by",inverse:"licences"},{id:"party_to",label:"party to",inverse:"parties"},{id:"starts",label:"starts"},{id:"renews",label:"renews"},{id:"notice",label:"notice period"},{id:"amount",label:"amount"},{id:"creates",label:"creates",inverse:"created by"},{id:"created_by",label:"created by",inverse:"creates"},{id:"changed_by",label:"changed by",inverse:"changes"},{id:"amends",label:"amends",inverse:"amended by",wikidata:"P144"},{id:"repeals",label:"repeals",inverse:"repealed by"},{id:"implements",label:"implements",inverse:"implemented by"},{id:"issued_by",label:"issued by",inverse:"issues"},{id:"published_in",label:"published in",wikidata:"P1433"},{id:"in_force_from",label:"in force from",wikidata:"P7588"},{id:"legal_force",label:"legal force"},{id:"applies_in",label:"applies in",inverse:"laws that apply",wikidata:"P1001"},{id:"jurisdiction_of",label:"authority in",inverse:"authorities"},{id:"subject_to",label:"subject to",inverse:"carried by"},{id:"action",label:"action"},{id:"bearer",label:"bearer"},{id:"due_rule",label:"due"},{id:"amount_rule",label:"amount"},{id:"authority",label:"authority",inverse:"collects"},{id:"status",label:"status"},{id:"penalty_for",label:"penalty for",inverse:"penalties"},{id:"relieves",label:"relieves",inverse:"reliefs"},{id:"condition",label:"condition"},{id:"kind",label:"kind"},{id:"procedure",label:"procedure",inverse:"carries out"},{id:"due_for",label:"due for",inverse:"due dates"},{id:"due",label:"due on"},{id:"fulfilled_by",label:"fulfilled by",inverse:"fulfils"},{id:"involves",label:"involves",inverse:"events",wikidata:"P710"},{id:"affects",label:"affects",inverse:"affected by"},{id:"replaced_by",label:"replaced by",inverse:"replaces",wikidata:"P1366"},{id:"triggered_by",label:"triggered by",inverse:"triggers"},{id:"mentions",label:"mentions",inverse:"discussed in"},{id:"reading",label:"reading"},{id:"importance_set",label:"importance set"}],importance:{default:"normal",major_set_by:"owner",rollup:{min:5,days:30},rules:[{level:"minor",title:"\\b(disk|storage) (is |was |almost |nearly )?(full|pressure|cleanup|clean-up|usage|space)\\b"},{level:"minor",title:"\\b(cache|logs?|temp files?) (was |were )?(cleared|cleaned|purged|rotated|pruned)\\b"},{level:"minor",title:"\\b(restart(ed)?|reboot(ed)?|health ?check|heartbeat)\\b"}]},sidebar:{pins_max:5,pins:[]},classify:[{type:"agent",legacy:["person","concept","project"],title:"\\bagents?\\b|\\bbot\\b"},{type:"server",legacy:["place","concept"],title:"\\b(server|vps|host|node)\\b"},{type:"device",legacy:["place","concept"],title:"\\b(laptop|macbook|desktop|phone|tablet|printer|router)\\b"},{type:"person",legacy:["person"]},{type:"event",legacy:["event"]},{type:"decision",legacy:["decision"]},{type:"procedure",legacy:["pattern"]},{type:"place",legacy:["place"]},{type:"project",legacy:["project"]},{type:"organization",path:["clients","customers","vendors","suppliers","organizations","orgs","companies"]},{type:"organization",tags:["organization","company","client","vendor","supplier","agency","bank"]},{type:"server",path:["servers","hosts","infrastructure"]},{type:"server",tags:["server","vps","host"]},{type:"device",path:["devices"]},{type:"device",tags:["device","laptop","phone","printer"]},{type:"agent",tags:["agent"],title:"\\bagent\\b"},{type:"app",path:["apps","systems","services"]},{type:"domain",tags:["domain","dns"]},{type:"contract",path:["contracts","agreements"]},{type:"contract",tags:["contract","agreement","subscription"]},{type:"legal_source",path:["laws","legislation"]},{type:"legal_source",tags:["law","legislation","decree"]},{type:"obligation",path:["obligations","compliance"]},{type:"obligation",tags:["obligation","compliance"]},{type:"policy",path:["policies"]},{type:"policy",tags:["policy"]},{type:"procedure",path:["runbooks","procedures"]},{type:"procedure",tags:["runbook","procedure","how-to"]}],fallback_type:"topic"};var m="ontology.yaml",y=new Map;function E(e){let i=g(e,m);if(!b(i))return{ontology:u,errors:[],file:null};let r=P(i).mtimeMs,a=y.get(i);if(a&&a.mtimeMs===r)return a.loaded;let l,t=[];try{l=h.load(k(i,"utf-8"))}catch(w){t.push(`${m} is not valid YAML: ${w.message}`),l={}}let o=A(u,f(l)?l:{},t);t.push(...j(o));let p={ontology:o,errors:t,file:i};return y.set(i,{mtimeMs:r,loaded:p}),p}function T(e){let i=g(e,m);if(b(i))throw new Error(`${i} already exists`);let r=["# Wiki ontology: pillars, types, typed relations, event importance and lenses.","# Edit any section; what you leave out falls back to the built-in defaults.","# Check it with: agentx wiki ontology check",""].join(`
2
+ `);return O(i,r+h.dump(u,{lineWidth:120,noRefs:!0})),i}function A(e,i,r=[]){let a=structuredClone(e);typeof i.version=="number"&&(a.version=i.version);for(let l of["pillars","types","properties"]){let t=i[l];if(t!==void 0){if(!Array.isArray(t)){r.push(`${l} must be a list`);continue}a[l]=L(a[l],t,l,r)}}return f(i.importance)&&(a.importance={...a.importance,...i.importance}),f(i.sidebar)&&(a.sidebar={...a.sidebar,...i.sidebar}),i.classify!==void 0&&(Array.isArray(i.classify)?a.classify=i.classify:r.push("classify must be a list")),typeof i.fallback_type=="string"&&(a.fallback_type=i.fallback_type),i.agent_names!==void 0&&(Array.isArray(i.agent_names)?a.agent_names=i.agent_names.filter(l=>typeof l=="string"&&!!l.trim()):r.push("agent_names must be a list")),a}function L(e,i,r,a){let l=e.map(t=>({...t}));for(let t of i){if(!f(t)||typeof t.id!="string"){a.push(`every item in ${r} needs an id`);continue}let o=l.findIndex(p=>p.id===t.id);o===-1?l.push(t):l[o]={...l[o],...t}}return l}function j(e){let i=[],r=new Set(e.pillars.map(t=>t.id)),a=new Set(e.types.map(t=>t.id)),l=new Set(e.properties.map(t=>t.id));for(let t of e.types){r.has(t.pillar)||i.push(`type ${t.id}: unknown pillar "${t.pillar}"`);for(let o of t.lens??[]){for(let p of $(o))l.has(p)||i.push(`type ${t.id}, panel ${o.panel}: unknown property "${p}"`);for(let p of o.types??[])a.has(p)||i.push(`type ${t.id}, panel ${o.panel}: unknown type "${p}"`);for(let p of o.importance??[])d.includes(p)||i.push(`type ${t.id}, panel ${o.panel}: unknown importance "${p}"`)}}for(let t of e.classify)if(a.has(t.type)||i.push(`classify: unknown type "${t.type}"`),t.title)try{new RegExp(t.title,"i")}catch{i.push(`classify: bad title pattern "${t.title}"`)}a.has(e.fallback_type)||i.push(`fallback_type: unknown type "${e.fallback_type}"`),d.includes(e.importance.default)||i.push(`importance.default: unknown level "${e.importance.default}"`);for(let t of e.importance.rules??[])if(d.includes(t.level)||i.push(`importance.rules: unknown level "${t.level}"`),!t.title&&!t.tags?.length&&i.push(`importance.rules: a rule for "${t.level}" needs a title or tags`),t.title)try{new RegExp(t.title,"i")}catch{i.push(`importance.rules: bad title pattern "${t.title}"`)}return e.sidebar.pins.length>e.sidebar.pins_max&&i.push(`sidebar.pins: ${e.sidebar.pins.length} pins, only the first ${e.sidebar.pins_max} are shown`),i}function $(e){return e.from?Array.isArray(e.from)?e.from:[e.from]:[]}function M(e){return e.source?e.source:e.panel==="history"||e.panel==="discussed"||e.panel==="notes"?e.panel:e.latest?"readings":e.from?"statements":"linked"}function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}export{m as a,E as b,T as c,A as d,j as e,$ as f,M as g};
3
+ //# sourceMappingURL=chunk-JTDUTCUE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/ontology/load.ts","../src/wiki/ontology/defaults.ts"],"sourcesContent":["// --- Load and check `ontology.yaml` (#811) ---\n//\n// The file is optional. Each section the owner writes is merged over the\n// defaults: pillars, types and properties by `id` (a listed id replaces\n// the fields it sets, a new id is added), `importance` and `sidebar`\n// field by field, and `classify` as a whole list. Problems are reported,\n// never thrown, so a typo in the file cannot take the wiki down.\n\nimport { existsSync, readFileSync, statSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport yaml from \"js-yaml\"\nimport { DEFAULT_ONTOLOGY } from \"./defaults\"\nimport { IMPORTANCE_LEVELS, type LensPanel, type Ontology, type PanelSource } from \"./types\"\n\nexport const ONTOLOGY_FILE = \"ontology.yaml\"\n\nexport interface LoadedOntology {\n ontology: Ontology\n /** Problems found in the file. The defaults are used where they apply. */\n errors: string[]\n /** Path of the file read, or null when the defaults were used as they are. */\n file: string | null\n}\n\nconst cache = new Map<string, { mtimeMs: number; loaded: LoadedOntology }>()\n\nexport function loadOntology(wikiDir: string): LoadedOntology {\n const file = resolve(wikiDir, ONTOLOGY_FILE)\n if (!existsSync(file)) return { ontology: DEFAULT_ONTOLOGY, errors: [], file: null }\n\n const mtimeMs = statSync(file).mtimeMs\n const hit = cache.get(file)\n if (hit && hit.mtimeMs === mtimeMs) return hit.loaded\n\n let raw: unknown\n const errors: string[] = []\n try {\n raw = yaml.load(readFileSync(file, \"utf-8\"))\n } catch (err) {\n errors.push(`${ONTOLOGY_FILE} is not valid YAML: ${(err as Error).message}`)\n raw = {}\n }\n const ontology = mergeOntology(DEFAULT_ONTOLOGY, isObject(raw) ? raw : {}, errors)\n errors.push(...checkOntology(ontology))\n const loaded = { ontology, errors, file }\n cache.set(file, { mtimeMs, loaded })\n return loaded\n}\n\n/** Write the defaults as a starting `ontology.yaml`. Refuses to overwrite. */\nexport function writeDefaultOntology(wikiDir: string): string {\n const file = resolve(wikiDir, ONTOLOGY_FILE)\n if (existsSync(file)) throw new Error(`${file} already exists`)\n const header = [\n \"# Wiki ontology: pillars, types, typed relations, event importance and lenses.\",\n \"# Edit any section; what you leave out falls back to the built-in defaults.\",\n \"# Check it with: agentx wiki ontology check\",\n \"\",\n ].join(\"\\n\")\n writeFileSync(file, header + yaml.dump(DEFAULT_ONTOLOGY, { lineWidth: 120, noRefs: true }))\n return file\n}\n\nexport function mergeOntology(base: Ontology, over: Record<string, unknown>, errors: string[] = []): Ontology {\n const out: Ontology = structuredClone(base)\n if (typeof over.version === \"number\") out.version = over.version\n for (const key of [\"pillars\", \"types\", \"properties\"] as const) {\n const list = over[key]\n if (list === undefined) continue\n if (!Array.isArray(list)) { errors.push(`${key} must be a list`); continue }\n out[key] = mergeById(out[key] as Array<{ id: string }>, list, key, errors) as never\n }\n if (isObject(over.importance)) out.importance = { ...out.importance, ...over.importance } as Ontology[\"importance\"]\n if (isObject(over.sidebar)) out.sidebar = { ...out.sidebar, ...over.sidebar } as Ontology[\"sidebar\"]\n if (over.classify !== undefined) {\n if (Array.isArray(over.classify)) out.classify = over.classify as Ontology[\"classify\"]\n else errors.push(\"classify must be a list\")\n }\n if (typeof over.fallback_type === \"string\") out.fallback_type = over.fallback_type\n if (over.agent_names !== undefined) {\n if (Array.isArray(over.agent_names)) out.agent_names = over.agent_names.filter((n): n is string => typeof n === \"string\" && !!n.trim())\n else errors.push(\"agent_names must be a list\")\n }\n return out\n}\n\nfunction mergeById(base: Array<{ id: string }>, list: unknown[], key: string, errors: string[]): Array<{ id: string }> {\n const out = base.map(x => ({ ...x }))\n for (const item of list) {\n if (!isObject(item) || typeof item.id !== \"string\") { errors.push(`every item in ${key} needs an id`); continue }\n const at = out.findIndex(x => x.id === item.id)\n if (at === -1) out.push(item as { id: string })\n else out[at] = { ...out[at], ...item }\n }\n return out\n}\n\n/** Problems that make part of the ontology unusable. */\nexport function checkOntology(o: Ontology): string[] {\n const errors: string[] = []\n const pillars = new Set(o.pillars.map(p => p.id))\n const types = new Set(o.types.map(t => t.id))\n const props = new Set(o.properties.map(p => p.id))\n for (const t of o.types) {\n if (!pillars.has(t.pillar)) errors.push(`type ${t.id}: unknown pillar \"${t.pillar}\"`)\n for (const p of t.lens ?? []) {\n for (const f of panelFrom(p)) if (!props.has(f)) errors.push(`type ${t.id}, panel ${p.panel}: unknown property \"${f}\"`)\n for (const ty of p.types ?? []) if (!types.has(ty)) errors.push(`type ${t.id}, panel ${p.panel}: unknown type \"${ty}\"`)\n for (const lv of p.importance ?? []) if (!IMPORTANCE_LEVELS.includes(lv)) errors.push(`type ${t.id}, panel ${p.panel}: unknown importance \"${lv}\"`)\n }\n }\n for (const r of o.classify) {\n if (!types.has(r.type)) errors.push(`classify: unknown type \"${r.type}\"`)\n if (r.title) {\n try { new RegExp(r.title, \"i\") } catch { errors.push(`classify: bad title pattern \"${r.title}\"`) }\n }\n }\n if (!types.has(o.fallback_type)) errors.push(`fallback_type: unknown type \"${o.fallback_type}\"`)\n if (!IMPORTANCE_LEVELS.includes(o.importance.default)) errors.push(`importance.default: unknown level \"${o.importance.default}\"`)\n for (const r of o.importance.rules ?? []) {\n if (!IMPORTANCE_LEVELS.includes(r.level)) errors.push(`importance.rules: unknown level \"${r.level}\"`)\n if (!r.title && !r.tags?.length) errors.push(`importance.rules: a rule for \"${r.level}\" needs a title or tags`)\n if (r.title) {\n try { new RegExp(r.title, \"i\") } catch { errors.push(`importance.rules: bad title pattern \"${r.title}\"`) }\n }\n }\n if (o.sidebar.pins.length > o.sidebar.pins_max) {\n errors.push(`sidebar.pins: ${o.sidebar.pins.length} pins, only the first ${o.sidebar.pins_max} are shown`)\n }\n return errors\n}\n\nexport function panelFrom(p: LensPanel): string[] {\n if (!p.from) return []\n return Array.isArray(p.from) ? p.from : [p.from]\n}\n\nexport function panelSource(p: LensPanel): PanelSource {\n if (p.source) return p.source\n if (p.panel === \"history\" || p.panel === \"discussed\" || p.panel === \"notes\") return p.panel\n if (p.latest) return \"readings\"\n if (p.from) return \"statements\"\n return \"linked\"\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n","// --- Default wiki ontology (#811) ---\n//\n// Generic starting point: nine pillars, the types inside them, the typed\n// relations between them and a lens for every type. An owner overrides\n// any section in `<wiki>/ontology.yaml`; `agentx wiki ontology init`\n// writes this file out as a starting point. Keep it free of any\n// particular organisation, person, country or product.\n\nimport type { LensPanel, Ontology, TypeDef } from \"./types\"\n\nconst history = (show = 5): LensPanel => ({\n panel: \"history\", title: \"History\", source: \"history\", show,\n importance: [\"major\", \"normal\"], fold: \"minor\", rollup: { min: 5, days: 30 },\n})\nconst discussed: LensPanel = { panel: \"discussed\", title: \"Discussed\", source: \"discussed\", show: 3, access: \"owner\" }\nconst notes = (show = 1): LensPanel => ({ panel: \"notes\", title: \"Notes\", source: \"notes\", show })\n\nconst ASSET_TYPES = [\"device\", \"server\", \"app\", \"domain\", \"account\", \"agent\"]\n\nconst types: TypeDef[] = [\n // Parties\n {\n id: \"person\", label: \"Person\", plural: \"People\", pillar: \"parties\", schema: \"Person\", icon: \"person\",\n lens: [\n { panel: \"roles\", title: \"Roles over time\", from: [\"role_at\", \"member_of\", \"founded\"], show: 6, display: \"timeline\" },\n { panel: \"relations\", title: \"Relations\", from: [\"works_with\", \"reports_to\", \"client_of\", \"works_on\", \"related\"], types: [\"person\", \"organization\", \"project\"], show: 5, group_by: \"role\" },\n // Agents are not a person's belongings or relations (#819).\n { panel: \"belongings\", title: \"Belongings\", from: [\"owns\", \"uses\", \"related\"], types: ASSET_TYPES.filter(t => t !== \"agent\"), show: 5 },\n { panel: \"obligations\", title: \"Obligations they carry\", from: [\"subject_to\"], show: 3 },\n history(),\n discussed,\n notes(),\n ],\n },\n {\n id: \"organization\", label: \"Organization\", plural: \"Organizations\", pillar: \"parties\", schema: \"Organization\", icon: \"org\",\n lens: [\n { panel: \"people\", title: \"People and roles\", from: [\"role_at\", \"member_of\", \"founded\"], show: 6, group_by: \"role\" },\n { panel: \"facts\", title: \"Key facts\", from: [\"registered_with\", \"located_in\", \"identifier\", \"legal_form\"], show: 6 },\n { panel: \"obligations\", title: \"Obligations and next due dates\", from: [\"subject_to\"], show: 4 },\n { panel: \"agreements\", title: \"Agreements\", source: \"linked\", types: [\"contract\"], show: 4 },\n { panel: \"decisions\", title: \"Decisions\", source: \"linked\", types: [\"decision\", \"policy\"], show: 4 },\n history(),\n discussed,\n notes(),\n ],\n },\n // Places & Jurisdictions\n {\n id: \"place\", label: \"Place\", plural: \"Places\", pillar: \"places\", schema: \"Place\", icon: \"pin\",\n lens: [\n { panel: \"here\", title: \"What is here\", from: [\"located_in\", \"related\"], show: 6 },\n { panel: \"laws\", title: \"Laws that apply here\", from: [\"applies_in\"], show: 5 },\n history(),\n notes(),\n ],\n },\n {\n id: \"jurisdiction\", label: \"Jurisdiction\", plural: \"Jurisdictions\", pillar: \"places\", schema: \"AdministrativeArea\", icon: \"pin\",\n lens: [\n { panel: \"laws\", title: \"Laws in force\", from: [\"applies_in\"], show: 6 },\n { panel: \"authorities\", title: \"Authorities with reach\", from: [\"jurisdiction_of\"], show: 5 },\n { panel: \"here\", title: \"What is here\", from: [\"located_in\"], show: 5 },\n notes(),\n ],\n },\n // Assets\n {\n id: \"device\", label: \"Device\", plural: \"Devices\", pillar: \"assets\", schema: \"Product\", icon: \"device\",\n lens: [\n { panel: \"state\", title: \"State now\", source: \"readings\", latest: true, show: 6 },\n history(),\n { panel: \"apps\", title: \"Installed apps\", from: [\"installed_on\"], show: 5 },\n discussed,\n { panel: \"parties\", title: \"Owner, user, location\", from: [\"owns\", \"uses\", \"located_in\", \"related\"], types: [\"person\", \"organization\", \"place\"], show: 5 },\n notes(),\n ],\n },\n {\n id: \"server\", label: \"Server\", plural: \"Servers\", pillar: \"assets\", schema: \"Product\", icon: \"server\",\n lens: [\n { panel: \"state\", title: \"State now\", source: \"readings\", latest: true, show: 6 },\n history(),\n { panel: \"hosts\", title: \"Hosted services\", from: [\"installed_on\", \"runs_on\"], show: 6 },\n discussed,\n { panel: \"parties\", title: \"Owner and location\", from: [\"owns\", \"uses\", \"located_in\"], show: 4 },\n notes(),\n ],\n },\n {\n id: \"app\", label: \"App or system\", plural: \"Apps\", pillar: \"assets\", schema: \"SoftwareApplication\", icon: \"app\",\n lens: [\n { panel: \"installs\", title: \"Where it runs\", from: [\"installed_on\", \"runs_on\"], show: 5 },\n { panel: \"licence\", title: \"Licence or subscription\", from: [\"party_to\", \"licensed_by\"], show: 3 },\n history(),\n discussed,\n notes(),\n ],\n },\n {\n id: \"domain\", label: \"Domain\", plural: \"Domains\", pillar: \"assets\", schema: \"WebSite\", icon: \"globe\",\n lens: [\n { panel: \"holder\", title: \"Holder\", from: [\"owns\", \"registrar\"], show: 3 },\n { panel: \"dues\", title: \"Renewal and due dates\", source: \"linked\", types: [\"due_date\"], show: 4 },\n { panel: \"services\", title: \"Linked services\", from: [\"related\"], show: 5 },\n history(),\n notes(),\n ],\n },\n {\n id: \"account\", label: \"Account\", plural: \"Accounts\", pillar: \"assets\", schema: \"Service\", icon: \"key\",\n lens: [\n { panel: \"holder\", title: \"Holder\", from: [\"owns\", \"uses\"], show: 3 },\n { panel: \"dues\", title: \"Renewal and due dates\", source: \"linked\", types: [\"due_date\"], show: 4 },\n history(),\n notes(),\n ],\n },\n {\n id: \"agent\", label: \"Agent\", plural: \"Agents\", pillar: \"assets\", schema: \"SoftwareApplication\", icon: \"agent\",\n lens: [\n { panel: \"runs\", title: \"Where it runs\", from: [\"runs_on\", \"installed_on\", \"related\"], types: [\"server\", \"device\"], show: 4 },\n { panel: \"works\", title: \"Works for\", from: [\"works_for\", \"uses\", \"related\"], types: [\"person\", \"organization\", \"project\"], show: 5 },\n history(),\n discussed,\n notes(),\n ],\n },\n // Offerings & Projects\n {\n id: \"project\", label: \"Project\", plural: \"Projects\", pillar: \"offerings\", schema: \"Project\", icon: \"project\",\n lens: [\n { panel: \"people\", title: \"Client and people\", from: [\"client\", \"client_of\", \"works_on\", \"related\"], types: [\"person\", \"organization\", \"agent\"], show: 6, group_by: \"role\" },\n { panel: \"agreements\", title: \"Agreements\", source: \"linked\", types: [\"contract\"], show: 3 },\n { panel: \"decisions\", title: \"Decisions\", source: \"linked\", types: [\"decision\", \"policy\"], show: 4 },\n history(6),\n discussed,\n notes(),\n ],\n },\n {\n id: \"offering\", label: \"Offering\", plural: \"Offerings\", pillar: \"offerings\", schema: \"Offer\", icon: \"project\",\n lens: [\n { panel: \"clients\", title: \"Clients\", from: [\"client_of\", \"related\"], types: [\"organization\", \"person\"], show: 5 },\n history(),\n notes(),\n ],\n },\n // Agreements\n {\n id: \"contract\", label: \"Agreement\", plural: \"Agreements\", pillar: \"agreements\", schema: \"Contract\", icon: \"contract\",\n lens: [\n { panel: \"parties\", title: \"Parties and roles\", from: [\"party_to\"], show: 5, group_by: \"role\" },\n { panel: \"terms\", title: \"Key terms and dates\", from: [\"starts\", \"renews\", \"notice\", \"amount\"], show: 6 },\n { panel: \"obligations\", title: \"Obligations it creates\", from: [\"creates\"], show: 5 },\n { panel: \"amendments\", title: \"Amendments\", from: [\"amends\"], show: 4 },\n history(),\n notes(),\n ],\n },\n // Law & Obligations\n {\n id: \"legal_source\", label: \"Legal source\", plural: \"Legal sources\", pillar: \"law\", schema: \"Legislation\", icon: \"law\",\n lens: [\n { panel: \"reference\", title: \"Gazette reference and dates\", from: [\"identifier\", \"published_in\", \"in_force_from\", \"legal_force\", \"issued_by\"], show: 6 },\n { panel: \"creates\", title: \"Obligations, penalties and reliefs it creates\", from: [\"creates\", \"created_by\"], show: 6 },\n { panel: \"amends\", title: \"Amends and amended by\", from: [\"amends\", \"repeals\", \"implements\"], show: 5 },\n { panel: \"applies\", title: \"Where it applies\", from: [\"applies_in\"], show: 3 },\n notes(),\n ],\n },\n {\n id: \"obligation\", label: \"Obligation\", plural: \"Obligations\", pillar: \"law\", schema: \"LegalRuleML Obligation\", icon: \"law\",\n lens: [\n { panel: \"rule\", title: \"Who must do what, by when\", from: [\"action\", \"bearer\", \"due_rule\", \"amount_rule\", \"authority\", \"status\"], show: 6 },\n { panel: \"dues\", title: \"Next due dates\", source: \"linked\", types: [\"due_date\"], show: 4 },\n { panel: \"sources\", title: \"Source articles\", from: [\"created_by\", \"changed_by\"], show: 4 },\n { panel: \"penalties\", title: \"Penalties and reliefs\", from: [\"penalty_for\", \"relieves\"], show: 4 },\n { panel: \"procedure\", title: \"Procedure\", from: [\"procedure\"], show: 2 },\n { panel: \"bearers\", title: \"Who carries it\", from: [\"subject_to\"], show: 5 },\n history(4),\n notes(),\n ],\n },\n {\n id: \"penalty\", label: \"Penalty\", plural: \"Penalties\", pillar: \"law\", schema: \"LegalRuleML Penalty\", icon: \"law\",\n lens: [\n { panel: \"rule\", title: \"For which failure, how much\", from: [\"penalty_for\", \"kind\", \"amount_rule\", \"created_by\"], show: 6 },\n notes(),\n ],\n },\n {\n id: \"relief\", label: \"Relief\", plural: \"Reliefs\", pillar: \"law\", schema: \"LegalRuleML Permission\", icon: \"law\",\n lens: [\n { panel: \"rule\", title: \"What it relieves, for whom, until when\", from: [\"relieves\", \"bearer\", \"condition\", \"created_by\"], show: 6 },\n notes(),\n ],\n },\n {\n id: \"due_date\", label: \"Due date\", plural: \"Due dates\", pillar: \"law\", schema: \"Event\", icon: \"calendar\",\n lens: [\n { panel: \"due\", title: \"Due\", from: [\"due_for\", \"bearer\", \"due\", \"status\", \"fulfilled_by\"], show: 6 },\n notes(),\n ],\n },\n // Events\n {\n id: \"event\", label: \"Event\", plural: \"Events\", pillar: \"events\", schema: \"Event\", icon: \"calendar\",\n lens: [\n notes(1),\n { panel: \"involved\", title: \"Who and what was involved\", from: [\"involves\", \"affects\", \"related\"], show: 8 },\n { panel: \"followed\", title: \"What followed\", source: \"linked\", types: [\"event\", \"decision\"], show: 4 },\n discussed,\n ],\n },\n // Decisions & Policies\n {\n id: \"decision\", label: \"Decision\", plural: \"Decisions\", pillar: \"decisions\", schema: \"ChooseAction\", icon: \"decision\",\n lens: [\n notes(1),\n { panel: \"affects\", title: \"What it affects\", from: [\"affects\", \"creates\", \"related\"], show: 6 },\n { panel: \"replaced\", title: \"Replaced by\", from: [\"replaced_by\"], show: 2 },\n discussed,\n ],\n },\n {\n id: \"policy\", label: \"Policy\", plural: \"Policies\", pillar: \"decisions\", schema: \"LegalRuleML Obligation\", icon: \"decision\",\n lens: [\n { panel: \"rule\", title: \"Rule\", from: [\"action\", \"bearer\", \"creates\", \"created_by\"], show: 6 },\n { panel: \"affects\", title: \"What it affects\", from: [\"affects\", \"related\"], show: 6 },\n notes(),\n ],\n },\n // Procedures\n {\n id: \"procedure\", label: \"Procedure\", plural: \"Procedures\", pillar: \"procedures\", schema: \"HowTo\", icon: \"steps\",\n lens: [\n notes(1),\n { panel: \"triggers\", title: \"What triggers it\", from: [\"procedure\", \"triggered_by\", \"related\"], show: 5 },\n { panel: \"runs\", title: \"Last runs\", source: \"linked\", types: [\"event\"], show: 4 },\n ],\n },\n // Topics (fallback, not in the sidebar)\n {\n id: \"topic\", label: \"Topic\", plural: \"Topics\", pillar: \"topics\", schema: \"skos:Concept\", icon: \"topic\",\n lens: [\n notes(1),\n { panel: \"related\", title: \"Related\", from: [\"related\"], show: 8 },\n history(4),\n ],\n },\n]\n\nexport const DEFAULT_ONTOLOGY: Ontology = {\n version: 1,\n pillars: [\n { id: \"parties\", label: \"Parties\", description: \"People and organisations, and the roles between them\", icon: \"person\" },\n { id: \"places\", label: \"Places & Jurisdictions\", description: \"Where things are, and whose rules apply there\", icon: \"pin\" },\n { id: \"assets\", label: \"Assets\", description: \"What is owned or run: devices, servers, apps, domains, accounts, agents\", icon: \"server\" },\n { id: \"offerings\", label: \"Offerings & Projects\", description: \"What is sold, built or delivered\", icon: \"project\" },\n { id: \"agreements\", label: \"Agreements\", description: \"Contracts, subscriptions and their terms\", icon: \"contract\" },\n { id: \"law\", label: \"Law & Obligations\", description: \"Legal sources, the obligations they create, penalties, reliefs and due dates\", icon: \"law\" },\n { id: \"events\", label: \"Events\", description: \"What happened, by importance\", icon: \"calendar\" },\n { id: \"decisions\", label: \"Decisions & Policies\", description: \"Why things are the way they are\", icon: \"decision\" },\n { id: \"procedures\", label: \"Procedures\", description: \"How things are done\", icon: \"steps\" },\n { id: \"topics\", label: \"Topics\", description: \"Pages no type fits yet. A growing count means a type is missing.\", icon: \"topic\", sidebar: false },\n ],\n types,\n properties: [\n { id: \"related\", label: \"related to\", inverse: \"related to\" },\n { id: \"role_at\", label: \"role at\", inverse: \"people\", wikidata: \"P108\", range: [\"organization\"], domain: [\"person\"] },\n { id: \"member_of\", label: \"member of\", inverse: \"members\", wikidata: \"P463\", range: [\"organization\"], domain: [\"person\", \"organization\"] },\n { id: \"founded\", label: \"founded\", inverse: \"founded by\", wikidata: \"P112\", domain: [\"person\", \"organization\"] },\n { id: \"works_with\", label: \"works with\", inverse: \"works with\", domain: [\"person\", \"organization\"] },\n { id: \"reports_to\", label: \"reports to\", inverse: \"manages\", domain: [\"person\"] },\n { id: \"client_of\", label: \"client of\", inverse: \"clients\", wikidata: \"P1972\", domain: [\"person\", \"organization\"] },\n { id: \"client\", label: \"is for client\", inverse: \"projects\", range: [\"organization\", \"person\"], domain: [\"project\", \"offering\", \"contract\"] },\n { id: \"works_on\", label: \"works on\", inverse: \"people\", range: [\"project\"], domain: [\"person\", \"organization\", \"agent\"] },\n { id: \"works_for\", label: \"works for\", inverse: \"agents\", wikidata: \"P108\", domain: [\"agent\", \"person\"] },\n { id: \"owns\", label: \"owns\", inverse: \"owned by\", wikidata: \"P1830\" },\n { id: \"uses\", label: \"uses\", inverse: \"used by\", wikidata: \"P2283\" },\n { id: \"located_in\", label: \"located in\", inverse: \"here\", wikidata: \"P276\" },\n { id: \"installed_on\", label: \"installed on\", inverse: \"installed apps\", range: [\"device\", \"server\"] },\n { id: \"runs_on\", label: \"runs on\", inverse: \"hosts\" },\n { id: \"registered_with\", label: \"registered with\", inverse: \"registered\" },\n { id: \"identifier\", label: \"identifier\", wikidata: \"P1448\" },\n { id: \"legal_form\", label: \"legal form\", wikidata: \"P1454\" },\n { id: \"registrar\", label: \"registrar\" },\n { id: \"licensed_by\", label: \"licensed by\", inverse: \"licences\" },\n { id: \"party_to\", label: \"party to\", inverse: \"parties\" },\n { id: \"starts\", label: \"starts\" },\n { id: \"renews\", label: \"renews\" },\n { id: \"notice\", label: \"notice period\" },\n { id: \"amount\", label: \"amount\" },\n { id: \"creates\", label: \"creates\", inverse: \"created by\" },\n { id: \"created_by\", label: \"created by\", inverse: \"creates\" },\n { id: \"changed_by\", label: \"changed by\", inverse: \"changes\" },\n { id: \"amends\", label: \"amends\", inverse: \"amended by\", wikidata: \"P144\" },\n { id: \"repeals\", label: \"repeals\", inverse: \"repealed by\" },\n { id: \"implements\", label: \"implements\", inverse: \"implemented by\" },\n { id: \"issued_by\", label: \"issued by\", inverse: \"issues\" },\n { id: \"published_in\", label: \"published in\", wikidata: \"P1433\" },\n { id: \"in_force_from\", label: \"in force from\", wikidata: \"P7588\" },\n { id: \"legal_force\", label: \"legal force\" },\n { id: \"applies_in\", label: \"applies in\", inverse: \"laws that apply\", wikidata: \"P1001\" },\n { id: \"jurisdiction_of\", label: \"authority in\", inverse: \"authorities\" },\n { id: \"subject_to\", label: \"subject to\", inverse: \"carried by\" },\n { id: \"action\", label: \"action\" },\n { id: \"bearer\", label: \"bearer\" },\n { id: \"due_rule\", label: \"due\" },\n { id: \"amount_rule\", label: \"amount\" },\n { id: \"authority\", label: \"authority\", inverse: \"collects\" },\n { id: \"status\", label: \"status\" },\n { id: \"penalty_for\", label: \"penalty for\", inverse: \"penalties\" },\n { id: \"relieves\", label: \"relieves\", inverse: \"reliefs\" },\n { id: \"condition\", label: \"condition\" },\n { id: \"kind\", label: \"kind\" },\n { id: \"procedure\", label: \"procedure\", inverse: \"carries out\" },\n { id: \"due_for\", label: \"due for\", inverse: \"due dates\" },\n { id: \"due\", label: \"due on\" },\n { id: \"fulfilled_by\", label: \"fulfilled by\", inverse: \"fulfils\" },\n { id: \"involves\", label: \"involves\", inverse: \"events\", wikidata: \"P710\" },\n { id: \"affects\", label: \"affects\", inverse: \"affected by\" },\n { id: \"replaced_by\", label: \"replaced by\", inverse: \"replaces\", wikidata: \"P1366\" },\n { id: \"triggered_by\", label: \"triggered by\", inverse: \"triggers\" },\n { id: \"mentions\", label: \"mentions\", inverse: \"discussed in\" },\n { id: \"reading\", label: \"reading\" },\n { id: \"importance_set\", label: \"importance set\" },\n ],\n importance: {\n default: \"normal\",\n major_set_by: \"owner\",\n rollup: { min: 5, days: 30 },\n // Routine machine upkeep: true for any fleet, so safe as a default.\n rules: [\n { level: \"minor\", title: \"\\\\b(disk|storage) (is |was |almost |nearly )?(full|pressure|cleanup|clean-up|usage|space)\\\\b\" },\n { level: \"minor\", title: \"\\\\b(cache|logs?|temp files?) (was |were )?(cleared|cleaned|purged|rotated|pruned)\\\\b\" },\n { level: \"minor\", title: \"\\\\b(restart(ed)?|reboot(ed)?|health ?check|heartbeat)\\\\b\" },\n ],\n },\n sidebar: { pins_max: 5, pins: [] },\n classify: [\n // Old pages filed agents as people and machines as places; the title\n // tells them apart until absorb writes `class` on the page.\n { type: \"agent\", legacy: [\"person\", \"concept\", \"project\"], title: \"\\\\bagents?\\\\b|\\\\bbot\\\\b\" },\n { type: \"server\", legacy: [\"place\", \"concept\"], title: \"\\\\b(server|vps|host|node)\\\\b\" },\n { type: \"device\", legacy: [\"place\", \"concept\"], title: \"\\\\b(laptop|macbook|desktop|phone|tablet|printer|router)\\\\b\" },\n { type: \"person\", legacy: [\"person\"] },\n { type: \"event\", legacy: [\"event\"] },\n { type: \"decision\", legacy: [\"decision\"] },\n { type: \"procedure\", legacy: [\"pattern\"] },\n { type: \"place\", legacy: [\"place\"] },\n // Folder and tag rules below refine untyped and concept pages only.\n { type: \"project\", legacy: [\"project\"] },\n { type: \"organization\", path: [\"clients\", \"customers\", \"vendors\", \"suppliers\", \"organizations\", \"orgs\", \"companies\"] },\n { type: \"organization\", tags: [\"organization\", \"company\", \"client\", \"vendor\", \"supplier\", \"agency\", \"bank\"] },\n { type: \"server\", path: [\"servers\", \"hosts\", \"infrastructure\"] },\n { type: \"server\", tags: [\"server\", \"vps\", \"host\"] },\n { type: \"device\", path: [\"devices\"] },\n { type: \"device\", tags: [\"device\", \"laptop\", \"phone\", \"printer\"] },\n { type: \"agent\", tags: [\"agent\"], title: \"\\\\bagent\\\\b\" },\n { type: \"app\", path: [\"apps\", \"systems\", \"services\"] },\n { type: \"domain\", tags: [\"domain\", \"dns\"] },\n { type: \"contract\", path: [\"contracts\", \"agreements\"] },\n { type: \"contract\", tags: [\"contract\", \"agreement\", \"subscription\"] },\n { type: \"legal_source\", path: [\"laws\", \"legislation\"] },\n { type: \"legal_source\", tags: [\"law\", \"legislation\", \"decree\"] },\n { type: \"obligation\", path: [\"obligations\", \"compliance\"] },\n { type: \"obligation\", tags: [\"obligation\", \"compliance\"] },\n { type: \"policy\", path: [\"policies\"] },\n { type: \"policy\", tags: [\"policy\"] },\n { type: \"procedure\", path: [\"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EAAM,IAAIH,EAAE,aAAa,GAAGtB,EAAO,KAAK,gCAAgCsB,EAAE,gBAAgB,EAC1FS,EAAkB,SAAST,EAAE,WAAW,OAAO,GAAGtB,EAAO,KAAK,sCAAsCsB,EAAE,WAAW,UAAU,EAChI,QAAWU,KAAKV,EAAE,WAAW,OAAS,CAAC,EAGrC,GAFKS,EAAkB,SAASC,EAAE,KAAK,GAAGhC,EAAO,KAAK,oCAAoCgC,EAAE,QAAQ,EAChG,CAACA,EAAE,OAAS,CAACA,EAAE,MAAM,QAAQhC,EAAO,KAAK,iCAAiCgC,EAAE,8BAA8B,EAC1GA,EAAE,MACJ,GAAI,CAAE,IAAI,OAAOA,EAAE,MAAO,GAAG,CAAE,MAAE,CAAQhC,EAAO,KAAK,wCAAwCgC,EAAE,QAAQ,CAAE,CAG7G,OAAIV,EAAE,QAAQ,KAAK,OAASA,EAAE,QAAQ,UACpCtB,EAAO,KAAK,iBAAiBsB,EAAE,QAAQ,KAAK,+BAA+BA,EAAE,QAAQ,oBAAoB,EAEpGtB,CACT,CAEO,SAAS4B,EAAUJ,EAAwB,CAChD,OAAKA,EAAE,KACA,MAAM,QAAQA,EAAE,IAAI,EAAIA,EAAE,KAAO,CAACA,EAAE,IAAI,EAD3B,CAAC,CAEvB,CAEO,SAASS,EAAYT,EAA2B,CACrD,OAAIA,EAAE,OAAeA,EAAE,OACnBA,EAAE,QAAU,WAAaA,EAAE,QAAU,aAAeA,EAAE,QAAU,QAAgBA,EAAE,MAClFA,EAAE,OAAe,WACjBA,EAAE,KAAa,aACZ,QACT,CAEA,SAASlB,EAAS4B,EAA0C,CAC1D,OAAO,OAAOA,GAAM,UAAYA,IAAM,MAAQ,CAAC,MAAM,QAAQA,CAAC,CAChE","names":["existsSync","readFileSync","statSync","writeFileSync","resolve","yaml","history","show","discussed","notes","ASSET_TYPES","types","t","DEFAULT_ONTOLOGY","ONTOLOGY_FILE","cache","loadOntology","wikiDir","file","resolve","existsSync","DEFAULT_ONTOLOGY","mtimeMs","statSync","hit","raw","errors","yaml","readFileSync","err","ontology","mergeOntology","isObject","checkOntology","loaded","writeDefaultOntology","header","writeFileSync","base","over","out","key","list","mergeById","n","x","item","at","o","pillars","p","types","props","f","panelFrom","ty","lv","IMPORTANCE_LEVELS","r","panelSource","v"]}
@@ -1,2 +1,2 @@
1
1
  var e=["person","project","place","concept","event","decision","pattern"];function i(t){return typeof t=="string"&&e.includes(t)}export{e as a,i as b};
2
- //# sourceMappingURL=chunk-4VVHGR7H.js.map
2
+ //# sourceMappingURL=chunk-KEXBEUSU.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/wiki/types.ts"],"sourcesContent":["// --- Wiki types ---\n//\n// Karpathy/Farzapedia pattern: plain files, LLM-chosen structure, articles\n// organized by `type` with wikilinks (`related`) as the primary navigation\n// surface. `_index.md` is the catalog; tags are a secondary hint, no longer\n// load-bearing. See blog/wiki-karpathy-review for the why.\n\nimport type { Importance, WikiStatement } from \"./ontology/types\"\n\nexport type WikiAccess = \"private\" | \"shared\" | \"public\"\n\n/**\n * Article type — the organizational spine. Matches Farzapedia's\n * `type: person | project | place | concept | event`, extended with\n * `decision` and `pattern` for workflow-heavy corpora.\n * Optional on legacy articles; Phase 2 migration backfills it.\n */\nexport type WikiArticleType =\n | \"person\"\n | \"project\"\n | \"place\"\n | \"concept\"\n | \"event\"\n | \"decision\"\n | \"pattern\"\n\n/** Runtime-iterable source of truth for the `type` enum. Use this for\n * write-side validation and CLI/prompt string interpolation. */\nexport const WIKI_ARTICLE_TYPES: readonly WikiArticleType[] = [\n \"person\",\n \"project\",\n \"place\",\n \"concept\",\n \"event\",\n \"decision\",\n \"pattern\",\n] as const\n\n/** True if `s` is a recognised article type. Use in the write path\n * to drop unknown values coming from upstream LLMs. */\nexport function isWikiArticleType(s: unknown): s is WikiArticleType {\n return typeof s === \"string\" && (WIKI_ARTICLE_TYPES as readonly string[]).includes(s)\n}\n\n/**\n * Article metadata. `type` + `related` are the primary retrieval surface;\n * tags remain as a secondary hint but are no longer central.\n */\nexport interface WikiArticleMeta {\n title: string\n /** Organizational spine — Phase 2 migration backfills any missing values. */\n type?: WikiArticleType\n /** Wikilink targets (by title) — persisted from `[[wikilinks]]` in body. */\n related?: string[]\n /** Secondary hint, no longer the retrieval spine. */\n tags: string[]\n owner: string // Agent ID\n access: WikiAccess\n sharedWith?: string[]\n created: string\n lastUpdated: string\n sources: string[] // Raw entry IDs\n /** Intent graph path (root → leaf node ids) when the article was authored\n * under an active intent graph. Empty for legacy articles — retrieval\n * falls back to pure BM25 for those. */\n graphPath?: string[]\n /** Ontology type (`organization`, `device`, `obligation`…), finer than\n * `type`. Unset, the ontology's classify rules decide (#811). */\n class?: string\n /** Event importance. Unset, the ontology default applies. */\n importance?: Importance\n /** When the event happened (YYYY-MM-DD). */\n date?: string\n /** Title of the event this minor event rolled up into. */\n rolledUpInto?: string\n /** Other names for the same thing; pages sharing a name merge. */\n aliases?: string[]\n /** Typed facts about this page's subject. */\n statements?: WikiStatement[]\n}\n\nexport interface WikiArticle {\n meta: WikiArticleMeta\n content: string // Markdown body — may contain section tags\n path: string // LLM-chosen path — structure emerges from data\n}\n\nexport interface WikiEntry {\n id: string\n date: string\n agentId: string\n source: string\n sourceContext?: string\n content: string\n meta?: Record<string, unknown>\n}\n\nexport interface WikiIndex {\n articles: Array<{\n path: string\n title: string\n type?: WikiArticleType\n related?: string[]\n tags: string[]\n owner: string\n access: WikiAccess\n sharedWith?: string[]\n aliases: string[]\n backlinks: number\n sources?: string[]\n lastUpdated?: string\n /** Intent-graph path the article's sources were classified under. */\n graphPath?: string[]\n }>\n lastRebuilt: string\n}\n"],"mappings":"AA4BO,IAAMA,EAAiD,CAC5D,SACA,UACA,QACA,UACA,QACA,WACA,SACF,EAIO,SAASC,EAAkBC,EAAkC,CAClE,OAAO,OAAOA,GAAM,UAAaF,EAAyC,SAASE,CAAC,CACtF","names":["WIKI_ARTICLE_TYPES","isWikiArticleType","s"]}
1
+ {"version":3,"sources":["../src/wiki/types.ts"],"sourcesContent":["// --- Wiki types ---\n//\n// Karpathy/Farzapedia pattern: plain files, LLM-chosen structure, articles\n// organized by `type` with wikilinks (`related`) as the primary navigation\n// surface. `_index.md` is the catalog; tags are a secondary hint, no longer\n// load-bearing. See blog/wiki-karpathy-review for the why.\n\nimport type { Importance, WikiStatement } from \"./ontology/types\"\n\nexport type WikiAccess = \"private\" | \"shared\" | \"public\"\n\n/**\n * Article type — the organizational spine. Matches Farzapedia's\n * `type: person | project | place | concept | event`, extended with\n * `decision` and `pattern` for workflow-heavy corpora.\n * Optional on legacy articles; Phase 2 migration backfills it.\n */\nexport type WikiArticleType =\n | \"person\"\n | \"project\"\n | \"place\"\n | \"concept\"\n | \"event\"\n | \"decision\"\n | \"pattern\"\n\n/** Runtime-iterable source of truth for the `type` enum. Use this for\n * write-side validation and CLI/prompt string interpolation. */\nexport const WIKI_ARTICLE_TYPES: readonly WikiArticleType[] = [\n \"person\",\n \"project\",\n \"place\",\n \"concept\",\n \"event\",\n \"decision\",\n \"pattern\",\n] as const\n\n/** True if `s` is a recognised article type. Use in the write path\n * to drop unknown values coming from upstream LLMs. */\nexport function isWikiArticleType(s: unknown): s is WikiArticleType {\n return typeof s === \"string\" && (WIKI_ARTICLE_TYPES as readonly string[]).includes(s)\n}\n\n/**\n * Article metadata. `type` + `related` are the primary retrieval surface;\n * tags remain as a secondary hint but are no longer central.\n */\nexport interface WikiArticleMeta {\n title: string\n /** Organizational spine — Phase 2 migration backfills any missing values. */\n type?: WikiArticleType\n /** Wikilink targets (by title) — persisted from `[[wikilinks]]` in body. */\n related?: string[]\n /** Secondary hint, no longer the retrieval spine. */\n tags: string[]\n owner: string // Agent ID\n access: WikiAccess\n sharedWith?: string[]\n created: string\n lastUpdated: string\n sources: string[] // Raw entry IDs\n /** Intent graph path (root → leaf node ids) when the article was authored\n * under an active intent graph. Empty for legacy articles — retrieval\n * falls back to pure BM25 for those. */\n graphPath?: string[]\n /** Ontology type (`organization`, `device`, `obligation`…), finer than\n * `type`. Unset, the ontology's classify rules decide (#811). */\n class?: string\n /** Event importance. Unset, the ontology default applies. */\n importance?: Importance\n /** A level a job suggests and only the owner may set (#811). */\n importanceProposed?: Importance\n /** When the event happened (YYYY-MM-DD). */\n date?: string\n /** Title of the event this minor event rolled up into. */\n rolledUpInto?: string\n /** Other names for the same thing; pages sharing a name merge. */\n aliases?: string[]\n /** Typed facts about this page's subject. */\n statements?: WikiStatement[]\n}\n\nexport interface WikiArticle {\n meta: WikiArticleMeta\n content: string // Markdown body — may contain section tags\n path: string // LLM-chosen path — structure emerges from data\n}\n\nexport interface WikiEntry {\n id: string\n date: string\n agentId: string\n source: string\n sourceContext?: string\n content: string\n meta?: Record<string, unknown>\n}\n\nexport interface WikiIndex {\n articles: Array<{\n path: string\n title: string\n type?: WikiArticleType\n related?: string[]\n tags: string[]\n owner: string\n access: WikiAccess\n sharedWith?: string[]\n aliases: string[]\n backlinks: number\n sources?: string[]\n lastUpdated?: string\n /** Intent-graph path the article's sources were classified under. */\n graphPath?: string[]\n }>\n lastRebuilt: string\n}\n"],"mappings":"AA4BO,IAAMA,EAAiD,CAC5D,SACA,UACA,QACA,UACA,QACA,WACA,SACF,EAIO,SAASC,EAAkBC,EAAkC,CAClE,OAAO,OAAOA,GAAM,UAAaF,EAAyC,SAASE,CAAC,CACtF","names":["WIKI_ARTICLE_TYPES","isWikiArticleType","s"]}