agentix-cli 0.125.0 → 0.125.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/{agent-IQV3P3CK.js → agent-YJFWFQ6A.js} +2 -2
  2. package/dist/{board-dashboard-H5CKFP4E.js → board-dashboard-SPYYHH54.js} +2 -2
  3. package/dist/{chunk-44A5JGRM.js → chunk-4WKBK7EQ.js} +2 -2
  4. package/dist/{chunk-LB4ZIQX3.js → chunk-5VWOK3GQ.js} +2 -2
  5. package/dist/{chunk-BSTIA4M6.js → chunk-BFCNSZHN.js} +2 -2
  6. package/dist/{chunk-ZTHSA7H3.js → chunk-IS4DA5CR.js} +4 -4
  7. package/dist/{chunk-326G2KKL.js → chunk-UOAJWNRF.js} +3 -3
  8. package/dist/{chunk-YSIRJZWF.js → chunk-WX47PYHL.js} +2 -2
  9. package/dist/{chunk-6PJ6XHG4.js → chunk-XSDUORMZ.js} +2 -2
  10. package/dist/chunk-XSDUORMZ.js.map +1 -0
  11. package/dist/{chunk-ZCUIBKKI.js → chunk-YKYMGIQ5.js} +2 -2
  12. package/dist/cli.js +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/{program-J2X6TR34.js → program-JNRKGK3U.js} +5 -5
  15. package/dist/{promote-W2BSSTRI.js → promote-GXZ7BLVG.js} +2 -2
  16. package/dist/{registry-5PMZ3ZCT.js → registry-PPJO5I6J.js} +2 -2
  17. package/dist/{wiki-VP4LSMR5.js → wiki-WJM5XNFS.js} +2 -2
  18. package/package.json +1 -1
  19. package/dist/chunk-6PJ6XHG4.js.map +0 -1
  20. /package/dist/{agent-IQV3P3CK.js.map → agent-YJFWFQ6A.js.map} +0 -0
  21. /package/dist/{board-dashboard-H5CKFP4E.js.map → board-dashboard-SPYYHH54.js.map} +0 -0
  22. /package/dist/{chunk-44A5JGRM.js.map → chunk-4WKBK7EQ.js.map} +0 -0
  23. /package/dist/{chunk-LB4ZIQX3.js.map → chunk-5VWOK3GQ.js.map} +0 -0
  24. /package/dist/{chunk-BSTIA4M6.js.map → chunk-BFCNSZHN.js.map} +0 -0
  25. /package/dist/{chunk-ZTHSA7H3.js.map → chunk-IS4DA5CR.js.map} +0 -0
  26. /package/dist/{chunk-326G2KKL.js.map → chunk-UOAJWNRF.js.map} +0 -0
  27. /package/dist/{chunk-YSIRJZWF.js.map → chunk-WX47PYHL.js.map} +0 -0
  28. /package/dist/{chunk-ZCUIBKKI.js.map → chunk-YKYMGIQ5.js.map} +0 -0
  29. /package/dist/{program-J2X6TR34.js.map → program-JNRKGK3U.js.map} +0 -0
  30. /package/dist/{promote-W2BSSTRI.js.map → promote-GXZ7BLVG.js.map} +0 -0
  31. /package/dist/{registry-5PMZ3ZCT.js.map → registry-PPJO5I6J.js.map} +0 -0
  32. /package/dist/{wiki-VP4LSMR5.js.map → wiki-WJM5XNFS.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as ug,b as nr,g as fg}from"./chunk-FHBPKMCF.js";import{A as Bi,B as mg,D as pg,a as lt,b as Hd,f as Rt,g as Vd,h as Kd,i as eg,j as tg,l as og,m as ng,n as sg,o as qi,p as rg,u as ig,v as ag,w as Wi,x as cg}from"./chunk-BSTIA4M6.js";import{a as lg,c as dg,d as gg}from"./chunk-5NTWGUSJ.js";import{a as zd,c as Yd}from"./chunk-6GLJIA25.js";import{d as Xd,e as Ui,h as Qd,i as Zd}from"./chunk-AD4QZZVN.js";import{a as Li}from"./chunk-LNY6N73E.js";import"./chunk-SCJ5ZXEN.js";import{a as ki,b as ul}from"./chunk-RKPAVWXF.js";import{$ as Ld,A as fd,B as Ci,C as hd,D as yd,E as wd,F as $d,G as bd,H as kd,I as vd,J as xd,K as Od,L as Xs,M as Ft,N as Xt,O as Zo,P as Qs,Q as Zs,R as Ni,S as Rd,T as jd,U as Nd,V as _d,W as Dd,X as Pd,Y as en,Z as tn,_ as Md,a as vl,aa as qe,b as xl,ba as er,ca as Yn,da as _i,ea as Fd,fa as Wd,ga as Mi,h as Ms,ha as Jd,i as Tl,ia as tr,j as Gn,ja as on,k as Ls,ka as or,l as Ol,la as Fi,m as Rl,ma as Gd,n as Bl,o as Jl,p as Js,q as Ei,r as Xl,s as sd,t as rd,u as ad,v as cd,w as gd,x as md,y as pd,z as ud}from"./chunk-ZTHSA7H3.js";import{$ as Vs,A as od,D as nd,E as Ys,I as id,Oa as Ud,Pa as Di,Qa as qd,Ra as Pi,X as Hn,_ as Ii,aa as Sd,db as Ot,fb as Bd,ha as Kt,ia as Ed,ja as Oi,la as Ri,na as Ad,oa as Td,pa as zn,ta as Ks,wa as Cd,x as td,xa as Id,ya as ji,z as Ti}from"./chunk-44A5JGRM.js";import"./chunk-GTJIKXDB.js";import{a as Sl,c as xi,e as El,f as Al}from"./chunk-5RE2B5YQ.js";import{a as Fs,b as Us,c as jl,d as Nl,e as _l,g as Dl,h as Pl,j as Ml,k as Ll,l as Fl,m as Ul,p as qs,s as ql,t as Wl}from"./chunk-S2GAEH2F.js";import"./chunk-BGG3ZSMW.js";import"./chunk-ZVP6GB4G.js";import{c as Gl}from"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import{b as Si}from"./chunk-GRMCAO3Q.js";import{c as Hl,e as Ws,g as Bs}from"./chunk-LQE73AZR.js";import{a as zl,b as Yl,c as Vl,d as Kl}from"./chunk-2D3RYIDU.js";import"./chunk-WEPON4FP.js";import{a as Ql,b as yo,c as Zl,d as Gs,e as ed,f as Ai,i as Hs,j as wo,k as zs}from"./chunk-AKLZ4YO2.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ld,b as dd}from"./chunk-EKJG63EJ.js";import{a as Cl,p as Il}from"./chunk-ZCUIBKKI.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as ct}from"./chunk-EMGB23H5.js";import"./chunk-JWDJMFU6.js";import"./chunk-KZKDVIOE.js";import{L as Vt,R as ll,ca as gl,g as zc,r as Yc,y as $i,z as Zc}from"./chunk-326G2KKL.js";import{E as cl,F as dl,b as Go,g as zo,h as _s,i as Ds,j as Yo,k as el,l as Yt,m as Vo}from"./chunk-ITATBKUL.js";import{e as il,f as ho,k as Xo}from"./chunk-GLQLCBJS.js";import{b as Ho}from"./chunk-6W74CHNW.js";import"./chunk-LB4ZIQX3.js";import"./chunk-SFQUP3BP.js";import{a as Lt}from"./chunk-Y4CYQV7G.js";import{b as Jn}from"./chunk-LLNPKE7H.js";import{a as ml,b as pl}from"./chunk-SHEUCITK.js";import{a as vi,e as fl,f as hl,h as yl,i as wl,k as $l,l as bl,m as kl}from"./chunk-QQYXYJOG.js";import{a as Ko}from"./chunk-GV7S5BAX.js";import{c as ol}from"./chunk-SZDACK6O.js";import{f as nl,g as sl,h as bi}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Xc,k as rl}from"./chunk-5DFUUYEA.js";import{a as Ps,b as re,c as je,d as Qo,e as al}from"./chunk-WMTGAVPW.js";import"./chunk-VWTBHLMX.js";import{a as yi}from"./chunk-YSIRJZWF.js";import"./chunk-6PJ6XHG4.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import{a as wi,b as Kc}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Qc}from"./chunk-X5C5W3E4.js";import{e as tl}from"./chunk-GSX4NK2N.js";import"./chunk-INLKJEEN.js";import"./chunk-MYVHVJWZ.js";import{n as Hc}from"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import{b as Vc}from"./chunk-NW7RVE57.js";import{g as zt,i as Ns}from"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import{c as Jo,e as Gc}from"./chunk-56KNKUFF.js";import{a as pi,b as Ec,c as Df,d as Is,e as Ac,f as Fc,g as qf,h as Uc,i as Wf,m as Bo,n as Wc,q as Bc,u as Jc,y as It,z as Bn}from"./chunk-BN5QMNON.js";import{a as Mt,b as Wo,e as Pc,f as Wn}from"./chunk-72SZI2UW.js";import{a as js,b as qc}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-2PJKGZWP.js";import{a as Ct,b as _f}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as jc,B as Mf,P as Nc,Q as ui,S as fi,Z as Lf,_ as hi,aa as _c,ba as Ff,h as Tc,i as Cc,j as Ic,k as Oc,l as Rc,m as Pf,ma as Dc,na as Os,oa as T,pa as Rs,ra as oe}from"./chunk-46JKX6CT.js";import{f as at,n as qn}from"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Mc,k as Lc,l as Uf}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Bf}from"commander";var hg=new Bf().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new xl({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});oe();import{Command as Jf}from"commander";import{execFileSync as ft}from"node:child_process";import{cpSync as yg,existsSync as Hi,mkdirSync as Ji,mkdtempSync as Gf,readdirSync as Hf,rmSync as wg,writeFileSync as $g}from"node:fs";import{dirname as bg,join as We}from"node:path";import{homedir as sr,release as zf,tmpdir as Yf}from"node:os";import{setTimeout as Vf}from"node:timers/promises";function rr(){let e=jl(process.platform,process.arch,zf());if(e)throw new Error(e)}function ir(){let e=We(sr(),"Library/LaunchAgents"),t=[];try{t=Hf(e).filter(Dl)}catch{}let o=t.flatMap(n=>{let s=We(e,n);try{return[{file:s,plist:ft("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Pl(e,o)}function Vn(e){return`gui/${process.getuid()}/${e.label}`}async function Gi(e){try{ft("launchctl",["bootout",Vn(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ft("launchctl",["print",Vn(e)],{stdio:"pipe"})}catch{return}await Vf(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function kg(e){if(!Hi(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ft("launchctl",["print",Vn(e)],{stdio:"pipe"})}catch{t=!1}t||ft("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ft("launchctl",["kickstart",Vn(e)],{stdio:"pipe"})}function Kf(){let e=Ul();if(e&&Hi(We(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var nn=new Jf("desktop").description("install and control the macOS desktop assistant");nn.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{rr();let t=T(),o=Nl(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=Kf(),i=We(sr(),"Applications"),{keep:a,remove:c}=ir();if(console.log(`Desktop assistant \u2192 ${We(i,Fs)}
1
+ import{a as ug,b as nr,g as fg}from"./chunk-FHBPKMCF.js";import{A as Bi,B as mg,D as pg,a as lt,b as Hd,f as Rt,g as Vd,h as Kd,i as eg,j as tg,l as og,m as ng,n as sg,o as qi,p as rg,u as ig,v as ag,w as Wi,x as cg}from"./chunk-BFCNSZHN.js";import{a as lg,c as dg,d as gg}from"./chunk-5NTWGUSJ.js";import{a as zd,c as Yd}from"./chunk-6GLJIA25.js";import{d as Xd,e as Ui,h as Qd,i as Zd}from"./chunk-AD4QZZVN.js";import{a as Li}from"./chunk-LNY6N73E.js";import"./chunk-SCJ5ZXEN.js";import{a as ki,b as ul}from"./chunk-RKPAVWXF.js";import{$ as Ld,A as fd,B as Ci,C as hd,D as yd,E as wd,F as $d,G as bd,H as kd,I as vd,J as xd,K as Od,L as Xs,M as Ft,N as Xt,O as Zo,P as Qs,Q as Zs,R as Ni,S as Rd,T as jd,U as Nd,V as _d,W as Dd,X as Pd,Y as en,Z as tn,_ as Md,a as vl,aa as qe,b as xl,ba as er,ca as Yn,da as _i,ea as Fd,fa as Wd,ga as Mi,h as Ms,ha as Jd,i as Tl,ia as tr,j as Gn,ja as on,k as Ls,ka as or,l as Ol,la as Fi,m as Rl,ma as Gd,n as Bl,o as Jl,p as Js,q as Ei,r as Xl,s as sd,t as rd,u as ad,v as cd,w as gd,x as md,y as pd,z as ud}from"./chunk-IS4DA5CR.js";import{$ as Vs,A as od,D as nd,E as Ys,I as id,Oa as Ud,Pa as Di,Qa as qd,Ra as Pi,X as Hn,_ as Ii,aa as Sd,db as Ot,fb as Bd,ha as Kt,ia as Ed,ja as Oi,la as Ri,na as Ad,oa as Td,pa as zn,ta as Ks,wa as Cd,x as td,xa as Id,ya as ji,z as Ti}from"./chunk-4WKBK7EQ.js";import"./chunk-GTJIKXDB.js";import{a as Sl,c as xi,e as El,f as Al}from"./chunk-5RE2B5YQ.js";import{a as Fs,b as Us,c as jl,d as Nl,e as _l,g as Dl,h as Pl,j as Ml,k as Ll,l as Fl,m as Ul,p as qs,s as ql,t as Wl}from"./chunk-S2GAEH2F.js";import"./chunk-BGG3ZSMW.js";import"./chunk-ZVP6GB4G.js";import{c as Gl}from"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import{b as Si}from"./chunk-GRMCAO3Q.js";import{c as Hl,e as Ws,g as Bs}from"./chunk-LQE73AZR.js";import{a as zl,b as Yl,c as Vl,d as Kl}from"./chunk-2D3RYIDU.js";import"./chunk-WEPON4FP.js";import{a as Ql,b as yo,c as Zl,d as Gs,e as ed,f as Ai,i as Hs,j as wo,k as zs}from"./chunk-AKLZ4YO2.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ld,b as dd}from"./chunk-EKJG63EJ.js";import{a as Cl,p as Il}from"./chunk-YKYMGIQ5.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as ct}from"./chunk-EMGB23H5.js";import"./chunk-JWDJMFU6.js";import"./chunk-KZKDVIOE.js";import{L as Vt,R as ll,ca as gl,g as zc,r as Yc,y as $i,z as Zc}from"./chunk-UOAJWNRF.js";import{E as cl,F as dl,b as Go,g as zo,h as _s,i as Ds,j as Yo,k as el,l as Yt,m as Vo}from"./chunk-ITATBKUL.js";import{e as il,f as ho,k as Xo}from"./chunk-GLQLCBJS.js";import{b as Ho}from"./chunk-6W74CHNW.js";import"./chunk-5VWOK3GQ.js";import"./chunk-SFQUP3BP.js";import{a as Lt}from"./chunk-Y4CYQV7G.js";import{b as Jn}from"./chunk-LLNPKE7H.js";import{a as ml,b as pl}from"./chunk-SHEUCITK.js";import{a as vi,e as fl,f as hl,h as yl,i as wl,k as $l,l as bl,m as kl}from"./chunk-QQYXYJOG.js";import{a as Ko}from"./chunk-GV7S5BAX.js";import{c as ol}from"./chunk-SZDACK6O.js";import{f as nl,g as sl,h as bi}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Xc,k as rl}from"./chunk-5DFUUYEA.js";import{a as Ps,b as re,c as je,d as Qo,e as al}from"./chunk-WMTGAVPW.js";import"./chunk-VWTBHLMX.js";import{a as yi}from"./chunk-WX47PYHL.js";import"./chunk-XSDUORMZ.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import{a as wi,b as Kc}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Qc}from"./chunk-X5C5W3E4.js";import{e as tl}from"./chunk-GSX4NK2N.js";import"./chunk-INLKJEEN.js";import"./chunk-MYVHVJWZ.js";import{n as Hc}from"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import{b as Vc}from"./chunk-NW7RVE57.js";import{g as zt,i as Ns}from"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import{c as Jo,e as Gc}from"./chunk-56KNKUFF.js";import{a as pi,b as Ec,c as Df,d as Is,e as Ac,f as Fc,g as qf,h as Uc,i as Wf,m as Bo,n as Wc,q as Bc,u as Jc,y as It,z as Bn}from"./chunk-BN5QMNON.js";import{a as Mt,b as Wo,e as Pc,f as Wn}from"./chunk-72SZI2UW.js";import{a as js,b as qc}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-2PJKGZWP.js";import{a as Ct,b as _f}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as jc,B as Mf,P as Nc,Q as ui,S as fi,Z as Lf,_ as hi,aa as _c,ba as Ff,h as Tc,i as Cc,j as Ic,k as Oc,l as Rc,m as Pf,ma as Dc,na as Os,oa as T,pa as Rs,ra as oe}from"./chunk-46JKX6CT.js";import{f as at,n as qn}from"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Mc,k as Lc,l as Uf}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Bf}from"commander";var hg=new Bf().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new xl({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});oe();import{Command as Jf}from"commander";import{execFileSync as ft}from"node:child_process";import{cpSync as yg,existsSync as Hi,mkdirSync as Ji,mkdtempSync as Gf,readdirSync as Hf,rmSync as wg,writeFileSync as $g}from"node:fs";import{dirname as bg,join as We}from"node:path";import{homedir as sr,release as zf,tmpdir as Yf}from"node:os";import{setTimeout as Vf}from"node:timers/promises";function rr(){let e=jl(process.platform,process.arch,zf());if(e)throw new Error(e)}function ir(){let e=We(sr(),"Library/LaunchAgents"),t=[];try{t=Hf(e).filter(Dl)}catch{}let o=t.flatMap(n=>{let s=We(e,n);try{return[{file:s,plist:ft("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Pl(e,o)}function Vn(e){return`gui/${process.getuid()}/${e.label}`}async function Gi(e){try{ft("launchctl",["bootout",Vn(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ft("launchctl",["print",Vn(e)],{stdio:"pipe"})}catch{return}await Vf(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function kg(e){if(!Hi(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ft("launchctl",["print",Vn(e)],{stdio:"pipe"})}catch{t=!1}t||ft("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ft("launchctl",["kickstart",Vn(e)],{stdio:"pipe"})}function Kf(){let e=Ul();if(e&&Hi(We(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var nn=new Jf("desktop").description("install and control the macOS desktop assistant");nn.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{rr();let t=T(),o=Nl(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=Kf(),i=We(sr(),"Applications"),{keep:a,remove:c}=ir();if(console.log(`Desktop assistant \u2192 ${We(i,Fs)}
2
2
  Computer-use helper \u2192 ${We(i,Us)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -488,7 +488,7 @@ return aid ?? null`}function R$(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
488
488
  Plan ${H.dim(`[${s.state}] by ${s.createdBy}, ${kn(s.createdAt)}`)}`),Qp(n.steps(e)),console.log(`
489
489
  Log`);for(let r of n.events(e))console.log(H.dim(` ${kn(r.at)} ${r.step?`step ${r.step} `:""}${r.kind}: ${r.detail}`))}});Do.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(c=>o[c]);if(n.length!==1){console.error(H.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=Wr();if(!s)return;let r=Xp();if(!r){process.exitCode=1;return}let i=Number(t),a=rd(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(H.red(` ${a}`)),process.exitCode=1;return}console.log(H.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+H.dim(" (the daemon goes on within a minute)")),Qp(r.steps(e))});function eu(e,t,o,n){Do.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,r)=>{let i=Wr();if(!i)return;let a=e==="done"?r.evidence:r.reason??"dropped by the owner";if(!a){console.error(H.red(` ${n}`)),process.exitCode=1;return}let c=i.get(s);if(!c||c.state==="candidate"){console.error(H.red(` no request "${s}"`)),process.exitCode=1;return}if(!i.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(H.red(` ${s} is already closed (${Kp[c.state]??c.state})`)),process.exitCode=1;return}console.log(H.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}eu("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");eu("drop","drop a request you no longer want","--reason <text>","");Do.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').action(async e=>{let t={};try{let s=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},r=(a,c)=>a===void 0?void 0:a===c?[]:a.split(",").map(l=>l.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}t.from=r(e.from,"none"),t.channels=r(e.channels,"all"),t.staleAfterHours=s("--stale-hours",e.staleHours),t.retentionDays=s("--retention-days",e.retentionDays);let i={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");i.enabled=e.plans==="on"}if(i.stallMinutes=s("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let a=Number(e.maxNudges);if(!Number.isInteger(a)||a<0)throw new Error("--max-nudges must be a whole number, 0 or more");i.maxNudges=a}i.approveKinds=r(e.approveKinds,"none"),i.disabledAgents=r(e.plansOffFor,"none"),Object.values(i).some(a=>a!==void 0)&&(t.plans=i)}catch(s){console.error(H.red(` ${s.message}`)),process.exitCode=1;return}if(Object.values(t).some(s=>s!==void 0)){let s=await od(t);if(!s.success){console.error(H.red(` ${s.error}`)),process.exitCode=1;return}console.log(H.green(" \u2713 saved")+(s.reloaded?H.dim(" (daemon reloaded)"):""))}let o=Ti();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`);let n=o.plans??sd;console.log(` Plans ${n.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${n.stallMinutes} minute(s), up to ${n.maxNudges} time(s)`),console.log(` You approve up front ${n.approveKinds.length?n.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${n.disabledAgents.length?n.disabledAgents.join(", "):"no agent"}`)});import{Command as Qb}from"commander";import vn from"chalk";oe();var tu=new Qb("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Wi.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(vn.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await re(r=>{n=cg(r,e,t==="on")});s.success||(console.error(vn.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(vn.green(`\u2713 ${n}`)),s.reloaded&&console.log(vn.dim(" daemon hot-reloaded"))}let o=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Wi)console.log(` ${n.padEnd(8)} ${o.includes(n)?vn.green("on"):vn.dim("off")}`)});import{Command as kk}from"commander";import xn from"chalk";import ge from"chalk";import hs from"prompts";import{readFileSync as Zb,writeFileSync as ek,existsSync as tk}from"fs";import{resolve as ou}from"path";var ok=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function nk(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Ha(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function nu(e=".env"){let t=ou(e);if(!tk(t))return[];let o=Zb(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let r=s.match(ok);r?n.push({kind:"kv",key:r[1],value:nk(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function sk(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Ha(t.value)}`:t.raw).join(`
490
490
  `)+`
491
- `}function fs(e,t,o=".env"){let n=ou(o),s=nu(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Ha(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Ha(t)}`})),ek(n,sk(s))}function za(e,t=".env"){return nu(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var su="https://t.me/BotFather";async function rk(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function ik(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function ru(e={}){console.log(),console.log(ge.bold(" Connect Telegram")),console.log(),console.log(ge.dim(` 1. Open ${su}`)),console.log(ge.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ge.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await hs({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&ko(su);let{token:o}=await hs({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(ge.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await rk(o.trim());n||(console.log(ge.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ge.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(ge.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ge.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await hs({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(ge.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await hs({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ge.red(" Aborted")),process.exit(1));let u=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;fs(u,o.trim()),process.env[u]=o.trim();let p=await re(b=>{je(b,"channels.telegram.enabled",!0),je(b,`channels.telegram.accounts.${f}`,{token:`\${${u}}`,agentBinding:g});let v=Qo(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),je(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(ge.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ge.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ge.dim(` Token stored in .env as ${u}`)),console.log(ge.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ge.dim(" Daemon hot-reloaded.")):console.log(ge.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await hs({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ge.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ge.dim(" Waiting up to 90s..."));let w=await ik(o.trim(),9e4);if(!w){console.log(ge.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ge.dim(" agentx config set notifications.destination.channel telegram")),console.log(ge.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ge.dim(` agentx config set notifications.destination.accountId ${f}`));return}let $=await re(b=>{je(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:f})},{configPath:e.configPath});if(!$.success){console.log(ge.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(ge.green(" \u2713 Default --notify target set")),console.log(ge.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ge.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(ge.dim(" Daemon hot-reloaded."))}import be from"chalk";import Ya from"prompts";import{existsSync as Ka,mkdirSync as ak,readdirSync as ck,readFileSync as iu}from"fs";import{resolve as Va}from"path";var lk=".agentx/whatsapp-sessions";function dk(){let e=Va(process.cwd(),".agentx/daemon.pid");if(!Ka(e))return!1;try{let t=parseInt(iu(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function gk(e){if(!Ka(e))return!1;try{return ck(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function mk(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;ak(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(u.qr,{small:!0})}catch{t(` QR: ${u.qr}`)}t("")}if(u.connection==="open"){clearTimeout(f),t(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function au(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),dk()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await Ya({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||Va(process.cwd(),"agentx.json");Ka(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(iu(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||lk,s=Va(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Ya({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(gk(s)&&a){let{keep:l}=await Ya({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await mk(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{je(l,"channels.whatsapp.enabled",!0),je(l,"channels.whatsapp.sessionDir",n),je(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(be.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as pk}from"crypto";import Ie from"chalk";import cu from"prompts";var Br="agentx-mesh:",Jr="//join/";function uk(e){return Buffer.from(e,"utf-8").toString("base64url")}function fk(e){return Buffer.from(e,"base64url").toString("utf-8")}function hk(e){return`${Br}${Jr}${uk(JSON.stringify(e))}`}function yk(e){if(!e.startsWith(`${Br}${Jr}`))throw new Error(`Not a mesh invite link \u2014 expected ${Br}${Jr}\u2026`);let t=e.slice(Br.length+Jr.length),o=JSON.parse(fk(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function wk(){return pk(32).toString("hex")}function $k(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function bk(e){return e?.node?.name||e?.node?.id||"node"}async function lu(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ie.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=za("MESH_TOKEN");i||(i=wk(),fs("MESH_TOKEN",i),console.log(Ie.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||$k(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await cu({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Ie.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ie.red(` \u2717 ${l.error}`)),process.exit(1));let g=hk({url:a,token:i,name:bk(r),version:1});console.log(),console.log(Ie.bold(" Mesh invite")),console.log(),console.log(` ${Ie.cyan(g)}`),console.log(),console.log(Ie.dim(" Run on the other node:")),console.log(Ie.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ie.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function du(e,t={}){let o;try{o=yk(e)}catch(r){console.log(Ie.red(` \u2717 ${r.message}`)),process.exit(1)}let n=za("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await cu({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ie.red(" Aborted (keeping existing .env)")),process.exit(1))}fs("MESH_TOKEN",o.token);let s=await re(r=>{je(r,"mesh.enabled",!0);let i=Qo(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),je(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ie.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ie.green(" \u2713 Joined mesh")),console.log(Ie.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ie.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ie.dim(" Daemon hot-reloaded.")):console.log(Ie.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ie.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ie.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ie.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Sn=new kk().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Sn.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await ru({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Sn.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await au({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var gu=Sn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");gu.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await lu({url:e.url,configPath:e.config})});gu.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await du(e,{configPath:t.config})});Sn.action(()=>{console.log(),console.log(xn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${xn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${xn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${xn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${xn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(xn.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as vk}from"commander";import K from"chalk";var Po=new vk().name("usage").description("token usage analysis and reporting");Po.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(K.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(K.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${K.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${K.red(String(s.totalErrors))}`),console.log(),console.log(K.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${K.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${K.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(K.red(" Daemon not running. Start with: agentx daemon start")):console.log(K.red(` ${e.message}`))}});Po.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=T(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:K.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(K.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(K.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,u=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?K.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[u,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(K.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(K.red(" Daemon not running. Start with: agentx daemon start")):console.log(K.red(` ${t.message}`))}});Po.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(K.red(` Script not found: ${s}`)),console.log(K.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(K.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(K.red(" Analysis failed. Is Python 3 installed?"))}});Po.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(K.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(p){console.log(K.red(` Cannot read baseline ${e.baseline}: ${p.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=p=>p===null?"-":`$${p.toFixed(p<10?3:2)}`,g=p=>`${(p/1e6).toFixed(1)}M`;console.log(),console.log(K.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(K.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(K.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let u=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(p=>[p,a.channels[p],c?.channels[p]]).sort((p,y)=>(y[1]?.cost||0)-(p[1]?.cost||0));u.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of u){let $=r(y),b=` ${p.padEnd(14)} ${String(y?.tasks||0).padStart(6)} ${g(y?.cacheRead||0).padStart(11)} ${g(y?.cacheCreate||0).padStart(11)} ${g(y?.output||0).padStart(8)} ${l(y?.cost||0).padStart(10)} ${l($).padStart(9)}`;if(c){let v=r(w),A=$!==null&&v?`${(($-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${A.padStart(7)}`}console.log(b)}console.log(),c&&console.log(K.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(K.dim(` Saved ${e.save}`)),console.log()});Po.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-WSY4SHHL.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-J2X6TR34.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let u of d.commands??[]){let p=f?`${f} ${u.name()}`:u.name();c.push(p),l(u,p)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(K.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${K.dim("\xB7")} ${d}`);console.log(),console.log(K.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(K.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(K.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(K.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(K.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(K.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=K.dim(`${r.days}d`);console.log(` ${K.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(K.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as xk}from"commander";import Te from"chalk";import{readFileSync as Sk}from"fs";import{resolve as Ek}from"path";oe();var go=new xk().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");go.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Gc(Ek(process.cwd(),".env"))}catch{}let t=Ak(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-H5CKFP4E.js");o(t)}catch(t){console.log(Te.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Te.dim(t.stack)),process.exit(1)}});function Ak(e,t){try{let o=T();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Te.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Te.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
491
+ `}function fs(e,t,o=".env"){let n=ou(o),s=nu(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Ha(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Ha(t)}`})),ek(n,sk(s))}function za(e,t=".env"){return nu(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var su="https://t.me/BotFather";async function rk(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function ik(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function ru(e={}){console.log(),console.log(ge.bold(" Connect Telegram")),console.log(),console.log(ge.dim(` 1. Open ${su}`)),console.log(ge.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ge.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await hs({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&ko(su);let{token:o}=await hs({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(ge.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await rk(o.trim());n||(console.log(ge.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ge.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(ge.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ge.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await hs({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(ge.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await hs({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ge.red(" Aborted")),process.exit(1));let u=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;fs(u,o.trim()),process.env[u]=o.trim();let p=await re(b=>{je(b,"channels.telegram.enabled",!0),je(b,`channels.telegram.accounts.${f}`,{token:`\${${u}}`,agentBinding:g});let v=Qo(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),je(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(ge.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ge.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ge.dim(` Token stored in .env as ${u}`)),console.log(ge.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ge.dim(" Daemon hot-reloaded.")):console.log(ge.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await hs({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ge.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ge.dim(" Waiting up to 90s..."));let w=await ik(o.trim(),9e4);if(!w){console.log(ge.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ge.dim(" agentx config set notifications.destination.channel telegram")),console.log(ge.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ge.dim(` agentx config set notifications.destination.accountId ${f}`));return}let $=await re(b=>{je(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:f})},{configPath:e.configPath});if(!$.success){console.log(ge.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(ge.green(" \u2713 Default --notify target set")),console.log(ge.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ge.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(ge.dim(" Daemon hot-reloaded."))}import be from"chalk";import Ya from"prompts";import{existsSync as Ka,mkdirSync as ak,readdirSync as ck,readFileSync as iu}from"fs";import{resolve as Va}from"path";var lk=".agentx/whatsapp-sessions";function dk(){let e=Va(process.cwd(),".agentx/daemon.pid");if(!Ka(e))return!1;try{let t=parseInt(iu(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function gk(e){if(!Ka(e))return!1;try{return ck(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function mk(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;ak(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(u.qr,{small:!0})}catch{t(` QR: ${u.qr}`)}t("")}if(u.connection==="open"){clearTimeout(f),t(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function au(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),dk()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await Ya({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||Va(process.cwd(),"agentx.json");Ka(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(iu(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||lk,s=Va(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Ya({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(gk(s)&&a){let{keep:l}=await Ya({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await mk(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{je(l,"channels.whatsapp.enabled",!0),je(l,"channels.whatsapp.sessionDir",n),je(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(be.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as pk}from"crypto";import Ie from"chalk";import cu from"prompts";var Br="agentx-mesh:",Jr="//join/";function uk(e){return Buffer.from(e,"utf-8").toString("base64url")}function fk(e){return Buffer.from(e,"base64url").toString("utf-8")}function hk(e){return`${Br}${Jr}${uk(JSON.stringify(e))}`}function yk(e){if(!e.startsWith(`${Br}${Jr}`))throw new Error(`Not a mesh invite link \u2014 expected ${Br}${Jr}\u2026`);let t=e.slice(Br.length+Jr.length),o=JSON.parse(fk(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function wk(){return pk(32).toString("hex")}function $k(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function bk(e){return e?.node?.name||e?.node?.id||"node"}async function lu(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ie.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=za("MESH_TOKEN");i||(i=wk(),fs("MESH_TOKEN",i),console.log(Ie.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||$k(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await cu({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Ie.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ie.red(` \u2717 ${l.error}`)),process.exit(1));let g=hk({url:a,token:i,name:bk(r),version:1});console.log(),console.log(Ie.bold(" Mesh invite")),console.log(),console.log(` ${Ie.cyan(g)}`),console.log(),console.log(Ie.dim(" Run on the other node:")),console.log(Ie.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ie.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function du(e,t={}){let o;try{o=yk(e)}catch(r){console.log(Ie.red(` \u2717 ${r.message}`)),process.exit(1)}let n=za("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await cu({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ie.red(" Aborted (keeping existing .env)")),process.exit(1))}fs("MESH_TOKEN",o.token);let s=await re(r=>{je(r,"mesh.enabled",!0);let i=Qo(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),je(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ie.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ie.green(" \u2713 Joined mesh")),console.log(Ie.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ie.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ie.dim(" Daemon hot-reloaded.")):console.log(Ie.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ie.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ie.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ie.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Sn=new kk().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Sn.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await ru({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Sn.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await au({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var gu=Sn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");gu.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await lu({url:e.url,configPath:e.config})});gu.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await du(e,{configPath:t.config})});Sn.action(()=>{console.log(),console.log(xn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${xn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${xn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${xn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${xn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(xn.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as vk}from"commander";import K from"chalk";var Po=new vk().name("usage").description("token usage analysis and reporting");Po.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(K.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(K.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${K.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${K.red(String(s.totalErrors))}`),console.log(),console.log(K.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${K.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${K.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(K.red(" Daemon not running. Start with: agentx daemon start")):console.log(K.red(` ${e.message}`))}});Po.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=T(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:K.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(K.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(K.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,u=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?K.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[u,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(K.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(K.red(" Daemon not running. Start with: agentx daemon start")):console.log(K.red(` ${t.message}`))}});Po.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(K.red(` Script not found: ${s}`)),console.log(K.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(K.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(K.red(" Analysis failed. Is Python 3 installed?"))}});Po.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(K.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(p){console.log(K.red(` Cannot read baseline ${e.baseline}: ${p.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=p=>p===null?"-":`$${p.toFixed(p<10?3:2)}`,g=p=>`${(p/1e6).toFixed(1)}M`;console.log(),console.log(K.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(K.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(K.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let u=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(p=>[p,a.channels[p],c?.channels[p]]).sort((p,y)=>(y[1]?.cost||0)-(p[1]?.cost||0));u.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of u){let $=r(y),b=` ${p.padEnd(14)} ${String(y?.tasks||0).padStart(6)} ${g(y?.cacheRead||0).padStart(11)} ${g(y?.cacheCreate||0).padStart(11)} ${g(y?.output||0).padStart(8)} ${l(y?.cost||0).padStart(10)} ${l($).padStart(9)}`;if(c){let v=r(w),A=$!==null&&v?`${(($-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${A.padStart(7)}`}console.log(b)}console.log(),c&&console.log(K.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(K.dim(` Saved ${e.save}`)),console.log()});Po.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-WSY4SHHL.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-JNRKGK3U.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let u of d.commands??[]){let p=f?`${f} ${u.name()}`:u.name();c.push(p),l(u,p)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(K.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${K.dim("\xB7")} ${d}`);console.log(),console.log(K.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(K.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(K.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(K.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(K.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(K.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=K.dim(`${r.days}d`);console.log(` ${K.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(K.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as xk}from"commander";import Te from"chalk";import{readFileSync as Sk}from"fs";import{resolve as Ek}from"path";oe();var go=new xk().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");go.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Gc(Ek(process.cwd(),".env"))}catch{}let t=Ak(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-SPYYHH54.js");o(t)}catch(t){console.log(Te.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Te.dim(t.stack)),process.exit(1)}});function Ak(e,t){try{let o=T();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Te.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Te.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
492
492
  `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}go.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(Te.dim(`
493
493
  No boards configured.
494
494
  `));return}console.log();for(let t of e.boards){console.log(` ${Te.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Te.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Te.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Te.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Te.red(` ${e.message}`)),process.exit(1)}});go.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{ys(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(Te.red(` ${o.message}`)),process.exit(1)}});go.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{ys(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(Te.red(` ${o.message}`)),process.exit(1)}});var Xa=go.command("column").description("manage a board's columns (add / remove / edit / list)");Xa.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(Sk("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(Te.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${Te.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Te.dim(r)}`)}}catch(t){console.log(Te.red(` ${t.message}`)),process.exit(1)}});Xa.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{ys(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(Te.red(` ${n.message}`)),process.exit(1)}});Xa.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{ys(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(Te.red(` ${o.message}`)),process.exit(1)}});go.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{ys(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(Te.red(` ${t.message}`)),process.exit(1)}});function ys(e){let{summary:t,backupPath:o}=lt(n=>e(n));console.log(Te.green(`
@@ -516,7 +516,7 @@ ${j.content}
516
516
 
517
517
  `),k="";if(e.facts!==!1){let{extractHints:j,resolveFacts:U,mergeRecords:V,renderFactsBlock:ke,installPrompts:se,defaultSources:Le,recordsFromEntries:Re}=await import("./facts-ROUMKS7I.js");if(!l){let Se=new Set;for(let Qe of n.listAgents())for(let I of n.getAgentWiki(Qe).listArticles(Qe))I.meta.type==="person"&&Se.add(I.meta.title);l=[...Se]}let F=j($.map(Se=>({context:Se.sourceContext,content:Se.content,sender:typeof Se.meta?.sender=="string"?Se.meta.sender:void 0})),{known:l}),ve=Re($);if(F.length>0||ve.length>0){let Se=Le(),{records:Qe,results:I}=F.length>0?await U(F,{sources:Se}):{records:[],results:[]},fe=V([...ve,...Qe]);k=ke(fe);let Ue=[...ve.length>0?[`entries:${ve.length}`]:[],...I.filter(Ye=>Ye.records.length>0).map(Ye=>`${Ye.source}:${Ye.records.length}`)];console.log(m.dim(` Facts: ${F.length} entities \u2192 ${fe.length} resolved${Ue.length?` (${Ue.join(" ")})`:""}`));for(let Ye of se(I,Se))console.log(m.yellow(` ! ${Ye.source} ${Ye.kind} \u2014 would supply ${Ye.provides.join(", ")}`)),console.log(m.dim(` ${Ye.hint}`))}}let x=v.articles.filter(j=>j.path&&!j.path.includes("/_versions/")),D=await $u($,b,p,x);D.length>0&&console.log(m.dim(` Existing: ${D.map(j=>j.path).join(", ")}`));let N=Cl(t,p,A,v.articles,S,$.length,k,bu(D));console.log(m.dim(` Mode: ${Za(t)}`));let R=W(b.baseDir,"_tmp");Jt(R,{recursive:!0});let L=W(R,"absorb-prompt.txt");Lo(L,N),console.log(m.dim(` Compiling with Claude (${o})...`));try{let j,U=!1;try{j=Mo(`cat '${L}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Jo(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(F){if(j=F.stdout||"",!j)throw F;U=!0}let V=j;try{let F=JSON.parse(j);F.is_error===!0&&(U=!0),V=F.result||F.content||"",V||(console.log(m.dim(` Claude envelope keys: ${Object.keys(F).join(", ")}`)),console.log(m.dim(` is_error: ${F.is_error}, stop_reason: ${F.stop_reason}`)))}catch{}let ke=mu(V);if("error"in ke){console.log(m.red(` ${ke.error}`)),console.log(m.dim(` First 500 chars: ${V.slice(0,500)}`));continue}let{articles:se,gaps:Le}=ke,Re=new Set;for(let F of se){let ve=new Date().toISOString().slice(0,10),Se=Array.isArray(F.sources)?F.sources:[],Qe=vu(F,x);Qe!==F.path&&(console.log(m.dim(` ~ ${F.path} \u2192 ${Qe} (an article with this title exists)`)),F.path=Qe);let I=b.readArticle(F.path);if(I){let Tt=ku(I.content,String(F.content??""));if(Tt.length>0){console.log(m.yellow(` ! refused ${F.path}: the rewrite drops ${Tt.length} fact(s) the article has`)),console.log(m.dim(` ${Tt.slice(0,8).join("; ")}${Tt.length>8?"; \u2026":""}`));for(let Un of Se)Re.add(Un);continue}}let fe=d(Se,$)??I?.meta.graphPath;b.writeArticle(F.path,{title:F.title,type:F.type,related:Array.isArray(F.related)?F.related:void 0,tags:F.tags||[],owner:p,access:I?.meta.access??"public",sharedWith:I?.meta.sharedWith?.length?I.meta.sharedWith:void 0,created:I?.meta.created||ve,lastUpdated:ve,sources:[...new Set([...I?.meta.sources??[],...Se])],graphPath:fe},F.content,p);let Ue=F.type?m.magenta(`[${F.type}]`)+" ":"",Ye=Array.isArray(F.related)&&F.related.length?` \u2192 ${F.related.slice(0,3).join(", ")}${F.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(I?"~":"+")} ${Ue}${F.path}: ${F.title}${m.dim(Ye)}`);let ut=(F.tags||[]).slice(0,4).join(", ");ut&&console.log(m.dim(` tags: ${ut}`)),fe?.length&&(console.log(m.dim(` graphPath: ${fe.join(" \u203A ")}`)),u++),f++}if(U)console.log(m.yellow(` Run reported an error \u2014 ${$.length} entries stay queued`));else{let F=$.map(ve=>ve.id).filter(ve=>!Re.has(ve));Re.size>0&&console.log(m.yellow(` ${$.length-F.length} entries stay queued behind refused saves`)),n.markProcessed(p,F,se.flatMap(ve=>ve.sources||[]).filter(ve=>!Re.has(ve)))}if(Le.length>0){console.log(),console.log(m.yellow(` Gaps detected (${Le.length} missing pieces):`));for(let F of Le)console.log(m.yellow(` ? ${F}`));try{let{QuestionStore:F}=await import("./questions-ZATLU5AW.js"),ve=new F(Fo(e.dir)).add(Le.map(Se=>({kind:"article",agentId:p,path:"",subject:String(Se).slice(0,120),question:`No article yet for: ${String(Se).slice(0,160)}`})));ve.added>0&&console.log(m.dim(` queued ${ve.added} for follow-up (agentx wiki questions)`))}catch{}}b.rebuildIndex()}catch(j){console.log(m.red(` Absorb failed: ${j.message?.slice(0,200)}`)),j.stderr&&console.log(m.dim(String(j.stderr).slice(0,300))),j.stdout&&console.log(m.dim("stdout: "+String(j.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(f>0&&(console.log(m.green(` ${f} articles compiled across ${r.length} agent(s)`)),a)){let p=f>0?Math.round(u/f*100):0;console.log(m.dim(` ${u}/${f} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ae.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=Dk(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let r=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-S34UICQD.js"),{default:c}=await import("better-sqlite3"),l=W(process.cwd(),".agentx/db.sqlite");if(!it(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(t??6048e5));r=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let f=r.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${r.length} candidate finding(s), ${f} seen in more than one session`));let u=r[0];u&&(u.occurrences??1)>1&&console.log(m.dim(` most recurrent (${u.occurrences} sessions): ${u.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-JNGUVBDG.js"),{default:g}=await import("better-sqlite3"),d=W(process.cwd(),".agentx/db.sqlite");if(!it(d))console.log(m.yellow(` --failures: no ${d}`));else{let f=new g(d,{readonly:!0});try{let u=c(f,{since:Date.now()-(t??6048e5)}),p=l(u,{minSessions:a});console.log(m.dim(` ${u.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let y=p[0];y&&console.log(m.dim(` most recurrent (${y.occurrences} sessions, ${y.failure.runs} runs): ${y.memory.description.slice(0,84)}`)),r=[...r,...p]}finally{f.close()}}}let i=await Il({extraCandidates:r,wikiDir:e.dir?W(e.dir):void 0,memoryRoot:e.memoryDir?W(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(i.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${i.candidates.length} candidate(s) in ${i.clusters.length} cluster(s):`);for(let a of i.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),i.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of i.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of i.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(i.gaps.length){console.log(),console.log(m.yellow(` Gaps (${i.gaps.length}):`));for(let a of i.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of i.warnings)console.log(m.dim(` ! ${a}`));for(let a of i.errors)console.log(m.red(` x ${a}`));console.log(),console.log(i.errors.length?m.red(` ${i.proposed.length} proposed, ${i.errors.length} error(s)`):m.green(` ${i.proposed.length} proposed, ${i.skipped.length} skipped`)),i.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),i.errors.length&&process.exit(1)});var Yr=ae.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Vr(e){return e?W(e):W(process.cwd(),".agentx","wiki")}Yr.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:t}=await import("./proposals-O4B5LD5T.js"),o=t(Vr(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){let s=n.evidence,r=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",i=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${r}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${i}`))}});Yr.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(Vr(t.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
518
518
  `).map(s=>` ${s}`).join(`
519
- `)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let r=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,i=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${r}, ${s.updatedAt.slice(0,10)}${i})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Yr.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-W2BSSTRI.js"),n=o(Vr(t.dir),e,{force:t.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});Yr.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{rejectProposal:o}=await import("./promote-W2BSSTRI.js"),n=o(Vr(t.dir),e,{reason:t.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Dk(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ae.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",W(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:t}=await import("./query-RV6SHTRN.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=Oe(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=r(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let f=[],u=o(d).sort().reverse();for(let w of u){let $=i(d,w),b=[];try{b=o($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(f.length>=g)break;try{let A=JSON.parse(n(i($,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&f.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||w})}catch{}}if(f.length>=g)break}if(f.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${f.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${f.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<f.length;w++){let $=f[w];process.stdout.write(m.dim(` [${w+1}/${f.length}] querying... `));let v=l.findRelevant($.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
519
+ `)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let r=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,i=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${r}, ${s.updatedAt.slice(0,10)}${i})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Yr.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-GXZ7BLVG.js"),n=o(Vr(t.dir),e,{force:t.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});Yr.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{rejectProposal:o}=await import("./promote-GXZ7BLVG.js"),n=o(Vr(t.dir),e,{reason:t.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Dk(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ae.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",W(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:t}=await import("./query-RV6SHTRN.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=Oe(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=r(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let f=[],u=o(d).sort().reverse();for(let w of u){let $=i(d,w),b=[];try{b=o($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(f.length>=g)break;try{let A=JSON.parse(n(i($,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&f.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||w})}catch{}}if(f.length>=g)break}if(f.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${f.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${f.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<f.length;w++){let $=f[w];process.stdout.write(m.dim(` [${w+1}/${f.length}] querying... `));let v=l.findRelevant($.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
520
520
  `)||"_(none returned)_",A;try{let S=await t($.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let k=S.citations.map(x=>`\`${x.title}\` [${x.type||"?"}]`).join(", ");A=`**Answer:**
521
521
 
522
522
  ${S.answer}
@@ -731,7 +731,7 @@ Restart the daemon to activate.
731
731
  dist/
732
732
  *.log
733
733
  .env
734
- `}import{Command as xx}from"commander";import Me from"chalk";import{writeFileSync as Sx,mkdirSync as Ex,existsSync as di,readFileSync as vf,appendFileSync as xf}from"fs";import{resolve as Mn,dirname as Af}from"path";import{homedir as $c}from"os";var Tf=new xx().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-J2X6TR34.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Cx(o);break;case"bash":s=Nx(o);break;case"fish":s=_x(o);break;default:console.error(Me.red(`unsupported shell: ${n}`)),console.error(Me.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Mn(String(e.output)):Ax(n);Ex(Af(r),{recursive:!0}),Sx(r,s),console.log(Me.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),Tx(n,r,!!e.yes)});function Ax(e){let t=$c();switch(e){case"zsh":return Mn(t,".zsh","completions","_agentx");case"bash":return Mn(t,".bash_completion.d","agentx.bash");case"fish":return Mn(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Tx(e,t,o){if(e==="zsh"){let n=Mn($c(),".zshrc"),s=Af(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=di(n)?vf(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Me.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&di(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),xf(n,g.join(`
734
+ `}import{Command as xx}from"commander";import Me from"chalk";import{writeFileSync as Sx,mkdirSync as Ex,existsSync as di,readFileSync as vf,appendFileSync as xf}from"fs";import{resolve as Mn,dirname as Af}from"path";import{homedir as $c}from"os";var Tf=new xx().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-JNRKGK3U.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Cx(o);break;case"bash":s=Nx(o);break;case"fish":s=_x(o);break;default:console.error(Me.red(`unsupported shell: ${n}`)),console.error(Me.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Mn(String(e.output)):Ax(n);Ex(Af(r),{recursive:!0}),Sx(r,s),console.log(Me.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),Tx(n,r,!!e.yes)});function Ax(e){let t=$c();switch(e){case"zsh":return Mn(t,".zsh","completions","_agentx");case"bash":return Mn(t,".bash_completion.d","agentx.bash");case"fish":return Mn(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Tx(e,t,o){if(e==="zsh"){let n=Mn($c(),".zshrc"),s=Af(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=di(n)?vf(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Me.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&di(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),xf(n,g.join(`
735
735
  `)+`
736
736
  `),console.log(Me.green("\u2713 Patched ~/.zshrc")),console.log(Me.dim("Reload your shell: exec zsh"));return}console.log(Me.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Me.cyan(` ${r}`)),l&&console.log(Me.cyan(` ${i}`)),console.log(),console.log(Me.dim("Then reload: exec zsh")),console.log(Me.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Mn($c(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((di(n)?vf(n,"utf-8"):"").includes(t)){console.log(Me.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&di(n)){xf(n,`
737
737
  # agentx completion
@@ -747,4 +747,4 @@ ${Dx({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
747
747
  ${o.url}`)}catch(t){console.error(Fn.red(` ${t.message}`)),process.exitCode=1}});Cs.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",kc).action(async(e,t)=>{try{let o=await Sc(t.models);if(!vc(t.model,o)){console.log(xc(t.model,o)),process.exitCode=1;return}let n=e==="-"?await Lx():await Mx(e,"utf8"),s=JSON.parse(n),{version:r}=await Ms(),i=Rf({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(Fn.red(` ${o.message}`)),process.exitCode=1}});async function Lx(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function uD(){let e=await Ms(),t=new Fx().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=dg(n);gg(s)&&lg("cli",s)});for(let o of[qg,Ug,Sn,nn,vo,ht,Yd,xo,mr,qt,Bt,Do,tu,lo,gr,Qu,ro,Tm,Cm,Mm,ms,Ym,Qm,Em,tp,op,$p,xp,Sp,pt,Po,nf,es,eo,Tf,Cs])t.addCommand(o);for(let o of Nf)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Nf.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Ux(o,74," "),""].join(`
748
748
  `)}),t}var Nf=[ae,Tn,uo,At,ns,wn,Ge,Gt,go,No,Rn,jn,no,Ze,dn,Er,Ur,Vu,Ku,Ut,dt,hg,Eo,As,sa,po,st,cn,ra,ni,Pt,Ht,hf,yf,of];function Ux(e,t,o){let n=[],s="";for(let r of e)s&&s.length+r.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+r;return s&&n.push(o+s),n.join(`
749
749
  `)}export{uD as buildProgram};
750
- //# sourceMappingURL=program-J2X6TR34.js.map
750
+ //# sourceMappingURL=program-JNRKGK3U.js.map
@@ -1,2 +1,2 @@
1
- import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-ZCUIBKKI.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-6W74CHNW.js";import"./chunk-6PJ6XHG4.js";import"./chunk-CECHWYJ2.js";import"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import"./chunk-BN5QMNON.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-46JKX6CT.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_PROMOTE_TYPES,a as PROMOTER_OWNER,c as PROMOTION_LEDGER_FILE,j as appendPromotionLedger,s as approveProposal,n as callPromotionLlm,p as estimateTokens,r as evidenceFor,m as getUnpromotedMemories,k as groupCandidates,h as listAllAgentMemories,d as memoryKey,e as memoryStamp,g as mergeSources,f as parseMemoryStamp,l as parsePromotionResponse,i as readPromotionLedger,t as rejectProposal,o as runPromotion,q as sourceKind};
2
- //# sourceMappingURL=promote-W2BSSTRI.js.map
1
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-YKYMGIQ5.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-6W74CHNW.js";import"./chunk-XSDUORMZ.js";import"./chunk-CECHWYJ2.js";import"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import"./chunk-BN5QMNON.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-46JKX6CT.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_PROMOTE_TYPES,a as PROMOTER_OWNER,c as PROMOTION_LEDGER_FILE,j as appendPromotionLedger,s as approveProposal,n as callPromotionLlm,p as estimateTokens,r as evidenceFor,m as getUnpromotedMemories,k as groupCandidates,h as listAllAgentMemories,d as memoryKey,e as memoryStamp,g as mergeSources,f as parseMemoryStamp,l as parsePromotionResponse,i as readPromotionLedger,t as rejectProposal,o as runPromotion,q as sourceKind};
2
+ //# sourceMappingURL=promote-GXZ7BLVG.js.map
@@ -1,2 +1,2 @@
1
- import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l,ca as m,da as n}from"./chunk-326G2KKL.js";import"./chunk-ITATBKUL.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-5DFUUYEA.js";import"./chunk-WMTGAVPW.js";import"./chunk-VWTBHLMX.js";import"./chunk-YSIRJZWF.js";import"./chunk-6PJ6XHG4.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-INLKJEEN.js";import"./chunk-MYVHVJWZ.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-NW7RVE57.js";import"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-BN5QMNON.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-46JKX6CT.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{m as AgentRegistry,a as EDIT_TOOL_INSTRUCTION,h as TRACE_STEP_SUMMARY_BYTES,e as buildEntryMeta,f as buildEventDigest,g as buildWikiContext,i as clipForTrace,b as codingInstructions,l as emitTraceStepsFromStreamEvent,k as firstMissingRequiredTool,d as getGlobalRegistry,n as richReplyPrompt,c as setGlobalRegistry,j as tallyToolUses};
2
- //# sourceMappingURL=registry-5PMZ3ZCT.js.map
1
+ import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l,ca as m,da as n}from"./chunk-UOAJWNRF.js";import"./chunk-ITATBKUL.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-5DFUUYEA.js";import"./chunk-WMTGAVPW.js";import"./chunk-VWTBHLMX.js";import"./chunk-WX47PYHL.js";import"./chunk-XSDUORMZ.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-INLKJEEN.js";import"./chunk-MYVHVJWZ.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-NW7RVE57.js";import"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-BN5QMNON.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-46JKX6CT.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{m as AgentRegistry,a as EDIT_TOOL_INSTRUCTION,h as TRACE_STEP_SUMMARY_BYTES,e as buildEntryMeta,f as buildEventDigest,g as buildWikiContext,i as clipForTrace,b as codingInstructions,l as emitTraceStepsFromStreamEvent,k as firstMissingRequiredTool,d as getGlobalRegistry,n as richReplyPrompt,c as setGlobalRegistry,j as tallyToolUses};
2
+ //# sourceMappingURL=registry-PPJO5I6J.js.map
@@ -1,2 +1,2 @@
1
- import"./chunk-VWTBHLMX.js";import{a as b}from"./chunk-YSIRJZWF.js";import{a}from"./chunk-6PJ6XHG4.js";import"./chunk-CECHWYJ2.js";import{a as c}from"./chunk-NW7RVE57.js";import"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-BN5QMNON.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-46JKX6CT.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as WikiHub,a as WikiStore,c as agenticQuery};
2
- //# sourceMappingURL=wiki-VP4LSMR5.js.map
1
+ import"./chunk-VWTBHLMX.js";import{a as b}from"./chunk-WX47PYHL.js";import{a}from"./chunk-XSDUORMZ.js";import"./chunk-CECHWYJ2.js";import{a as c}from"./chunk-NW7RVE57.js";import"./chunk-VHT7HESZ.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-BN5QMNON.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-46JKX6CT.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as WikiHub,a as WikiStore,c as agenticQuery};
2
+ //# sourceMappingURL=wiki-WJM5XNFS.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentix-cli",
3
- "version": "0.125.0",
3
+ "version": "0.125.1",
4
4
  "description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/wiki/store.ts"],"sourcesContent":["import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync, readdirSync, statSync, type Stats } from \"fs\"\nimport { resolve, join, relative, dirname } from \"path\"\nimport { isWikiArticleType } from \"./types\"\nimport type { WikiArticle, WikiArticleMeta, WikiEntry, WikiIndex, WikiAccess } from \"./types\"\nimport { buildIndex, buildIndexCached, scoreAll } from \"../memory/bm25\"\nimport { askSeat } from \"../decisions/seat\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"../decisions/seats/wiki-rerank\"\nimport { ancestryScore as ancestryOf } from \"@/graph\"\n\n// --- Wiki Store: filesystem-based knowledge base with permissions ---\n//\n// Structure:\n// .agentx/wiki/\n// _index.md # Master index with aliases\n// _backlinks.json # Reverse link index\n// raw/entries/ # One .md per ingested entry\n// {directories}/ # Articles organized by type\n//\n// Permission model:\n// - private: only owner agent reads/writes\n// - shared: owner writes, listed agents read\n// - public: owner writes, all agents read\n\nexport class WikiStore {\n readonly baseDir: string\n private rawDir: string\n private log: (...args: unknown[]) => void\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki]\"),\n ) {\n this.baseDir = baseDir\n this.rawDir = resolve(baseDir, \"raw/entries\")\n this.log = log\n\n mkdirSync(this.rawDir, { recursive: true })\n mkdirSync(resolve(baseDir, \"raw\"), { recursive: true })\n\n // Initialize schema if missing\n this.ensureSchema()\n }\n\n // --- Permission checks ---\n\n /**\n * Check if an agent can read an article.\n */\n canRead(article: WikiArticleMeta, agentId?: string): boolean {\n if (article.access === \"public\") return true\n if (!agentId) return false\n if (article.owner === agentId) return true\n if (article.access === \"shared\" && article.sharedWith?.includes(agentId)) return true\n return false\n }\n\n /**\n * Check if an agent can write an article.\n */\n canWrite(article: WikiArticleMeta, agentId: string): boolean {\n return article.owner === agentId\n }\n\n // --- Raw entries (ingestion) ---\n\n /**\n * Add a raw entry (from a conversation, cron result, etc.)\n */\n addEntry(entry: WikiEntry): string {\n const filename = `${entry.date}_${entry.id}.md`\n const filepath = resolve(this.rawDir, filename)\n\n const frontmatter = [\n \"---\",\n `id: ${entry.id}`,\n `date: ${entry.date}`,\n `agent: ${entry.agentId}`,\n `source: ${entry.source}`,\n ]\n if (entry.sourceContext) frontmatter.push(`context: ${entry.sourceContext}`)\n if (entry.meta) {\n for (const [k, v] of Object.entries(entry.meta)) {\n frontmatter.push(`${k}: ${JSON.stringify(v)}`)\n }\n }\n frontmatter.push(\"---\", \"\", entry.content)\n\n writeFileSync(filepath, frontmatter.join(\"\\n\"))\n this.appendLog(\"ingest\", `${entry.id} from ${entry.agentId} via ${entry.source}`)\n return filename\n }\n\n /**\n * List raw entries, optionally filtered by agent or date range.\n */\n listEntries(filter?: { agentId?: string; after?: string; before?: string }): WikiEntry[] {\n if (!existsSync(this.rawDir)) return []\n\n const files = readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).sort()\n const entries: WikiEntry[] = []\n\n for (const file of files) {\n const content = readFileSync(resolve(this.rawDir, file), \"utf-8\")\n const entry = this.parseEntry(content, file)\n if (!entry) continue\n\n if (filter?.agentId && entry.agentId !== filter.agentId) continue\n if (filter?.after && entry.date < filter.after) continue\n if (filter?.before && entry.date > filter.before) continue\n\n entries.push(entry)\n }\n\n return entries\n }\n\n private parseEntry(content: string, filename: string): WikiEntry | null {\n const fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n if (!fmMatch) return null\n\n const fm = fmMatch[1]\n const body = fmMatch[2].trim()\n\n const get = (key: string): string => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"))\n return m?.[1]?.trim() || \"\"\n }\n\n // Everything addEntry wrote that is not one of the five named keys is\n // `meta`, JSON-encoded one key per line. Dropping it here is what made\n // graphPath 0%: the capture path stamps intentPath onto every entry,\n // `wiki absorb` reads entry.meta.intentPath to propagate it onto the\n // article, and this parser never returned a meta at all — so absorb\n // always fell through to a fingerprint lookup its own comment calls\n // unreliable, and the retrieval scorer multiplied the graph weight\n // (0.6 of the hybrid score) by zero for every article ever compiled.\n const KNOWN = new Set([\"id\", \"date\", \"agent\", \"source\", \"context\"])\n const meta: Record<string, unknown> = {}\n for (const line of fm.split(\"\\n\")) {\n const m = line.match(/^(\\w+):\\s*(.+)$/)\n if (!m || KNOWN.has(m[1])) continue\n try {\n meta[m[1]] = JSON.parse(m[2])\n } catch {\n meta[m[1]] = m[2].trim()\n }\n }\n\n return {\n id: get(\"id\") || filename.replace(\".md\", \"\"),\n date: get(\"date\"),\n agentId: get(\"agent\"),\n source: get(\"source\"),\n sourceContext: get(\"context\") || undefined,\n content: body,\n meta: Object.keys(meta).length > 0 ? meta : undefined,\n }\n }\n\n // --- Articles (compiled knowledge) ---\n\n /**\n * Write or update a wiki article.\n */\n writeArticle(\n path: string,\n meta: WikiArticleMeta,\n content: string,\n agentId: string,\n ): boolean {\n // LLM picks the path. We just write the file.\n const existing = this.readArticle(path)\n if (existing && !this.canWrite(existing.meta, agentId)) {\n this.log(`Permission denied: \"${agentId}\" cannot write \"${path}\" (owner: ${existing.meta.owner})`)\n return false\n }\n\n // Drop invalid `type` at write time. The parser already rejects invalid\n // values on read (returns type=undefined), so silently serialising a\n // stray value would cause the round-trip to look fine but the article\n // to render as \"untyped\" in the catalog. Log + drop beats surprise.\n if (meta.type && !isWikiArticleType(meta.type)) {\n this.log(`Dropping invalid article type \"${meta.type}\" for \"${path}\" — enum is [person, project, place, concept, event, decision, pattern]`)\n meta = { ...meta, type: undefined }\n }\n\n const fullPath = resolve(this.baseDir, path)\n\n // Version the previous content before overwriting (immutable history)\n if (existing) {\n this.saveVersion(path, fullPath)\n }\n\n mkdirSync(dirname(fullPath), { recursive: true })\n\n const frontmatter = [\n \"---\",\n `title: \"${meta.title}\"`,\n ]\n if (meta.type) frontmatter.push(`type: ${meta.type}`)\n if (meta.related?.length) {\n frontmatter.push(`related: [${meta.related.map(t => `\"${t}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `tags: [${(meta.tags || []).map(t => `\"${t}\"`).join(\", \")}]`,\n `owner: ${meta.owner}`,\n `access: ${meta.access}`,\n )\n if (meta.sharedWith?.length) {\n frontmatter.push(`shared_with: [${meta.sharedWith.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `created: ${meta.created}`,\n `last_updated: ${meta.lastUpdated}`,\n `sources: [${meta.sources.map(s => `\"${s}\"`).join(\", \")}]`,\n )\n if (meta.graphPath?.length) {\n frontmatter.push(`graph_path: [${meta.graphPath.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n frontmatter.push(\"---\", \"\", content)\n\n writeFileSync(fullPath, frontmatter.join(\"\\n\"))\n const action = existing ? \"update\" : \"create\"\n this.appendLog(action, `${meta.title} [${(meta.tags || []).slice(0, 5).join(\", \")}] by ${agentId} at ${path}`)\n return true\n }\n\n // --- Article Versioning ---\n\n /**\n * Save current article content as an immutable version before overwriting.\n * Versions stored in _versions/{article-path}/{timestamp}.md\n */\n private saveVersion(articlePath: string, fullPath: string): void {\n try {\n if (!existsSync(fullPath)) return\n const content = readFileSync(fullPath, \"utf-8\")\n const ts = new Date().toISOString().replace(/[:.]/g, \"-\")\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n mkdirSync(versionDir, { recursive: true })\n writeFileSync(resolve(versionDir, `${ts}.md`), content)\n } catch {\n // Version save is best-effort\n }\n }\n\n /**\n * List all versions of an article (newest first).\n */\n getVersions(articlePath: string): Array<{ timestamp: string; path: string }> {\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n if (!existsSync(versionDir)) return []\n\n try {\n return readdirSync(versionDir)\n .filter(f => f.endsWith(\".md\"))\n .sort()\n .reverse()\n .map(f => ({\n timestamp: f.replace(/\\.md$/, \"\").replace(/-/g, (m, i) => i < 19 ? (i === 10 ? \"T\" : i === 13 || i === 16 ? \":\" : \"-\") : m),\n path: resolve(versionDir, f),\n }))\n } catch {\n return []\n }\n }\n\n /**\n * Restore a specific version of an article.\n */\n restoreVersion(articlePath: string, versionTimestamp: string): boolean {\n const versions = this.getVersions(articlePath)\n const version = versions.find(v => v.timestamp.startsWith(versionTimestamp))\n if (!version) return false\n\n try {\n const content = readFileSync(version.path, \"utf-8\")\n const fullPath = resolve(this.baseDir, articlePath)\n // Save current as a version too before restoring\n this.saveVersion(articlePath, fullPath)\n writeFileSync(fullPath, content)\n this.appendLog(\"restore\", `${articlePath} restored to ${versionTimestamp}`)\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Read an article. Returns null if not found.\n */\n readArticle(path: string): WikiArticle | null {\n const fullPath = resolve(this.baseDir, path)\n if (!existsSync(fullPath)) return null\n\n const raw = readFileSync(fullPath, \"utf-8\")\n return this.parseArticle(raw, path)\n }\n\n /**\n * Read an article with permission check.\n */\n readArticleAs(path: string, agentId: string): WikiArticle | null {\n const article = this.readArticle(path)\n if (!article) return null\n if (!this.canRead(article.meta, agentId)) return null\n return article\n }\n\n private parseArticle(raw: string, path: string): WikiArticle | null {\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n if (!fmMatch) return null\n\n const fm = fmMatch[1]\n const content = fmMatch[2].trim()\n\n const get = (key: string): string => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"))\n return m?.[1]?.trim().replace(/^\"(.*)\"$/, \"$1\") || \"\"\n }\n\n const getArray = (key: string): string[] => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*\\\\[(.*)\\\\]$`, \"m\"))\n if (!m) return []\n return m[1].split(\",\").map(s => s.trim().replace(/^\"(.*)\"$/, \"$1\")).filter(Boolean)\n }\n\n // `type` and `kind` are the new structural spine; no longer stuffed into tags.\n // Legacy articles may have a `kind:` field; we promote it to `type` on read so\n // the migration (Phase 2) can patch it in place.\n const rawType = get(\"type\") || get(\"kind\")\n const validTypes = new Set([\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\",\n ])\n const type = validTypes.has(rawType) ? (rawType as WikiArticleMeta[\"type\"]) : undefined\n\n const tags = getArray(\"tags\").filter((v, i, a) => v && a.indexOf(v) === i)\n const related = getArray(\"related\")\n const graphPath = getArray(\"graph_path\")\n return {\n meta: {\n title: get(\"title\"),\n type,\n related: related.length ? related : undefined,\n tags,\n owner: get(\"owner\"),\n access: (get(\"access\") as WikiAccess) || \"public\",\n sharedWith: getArray(\"shared_with\"),\n created: get(\"created\"),\n lastUpdated: get(\"last_updated\"),\n sources: getArray(\"sources\"),\n graphPath: graphPath.length ? graphPath : undefined,\n },\n content,\n path,\n }\n }\n\n // --- Index and discovery ---\n\n /**\n * List all articles accessible to an agent.\n */\n /** Catalog per agent, valid while no article file changed. The walk is\n * repeated (names, mtimes, sizes) but the frontmatter parse of every\n * article is not; on a wiki of ten thousand files that parse was the\n * cost of every fresh session. */\n private listCache = new Map<string, { signature: string; articles: WikiArticle[] }>()\n\n listArticles(agentId: string): WikiArticle[] {\n const relPaths: string[] = []\n const sig: string[] = []\n this.walkDir(this.baseDir, (filePath, stat) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n relPaths.push(relPath)\n sig.push(`${relPath}:${stat?.mtimeMs ?? \"?\"}:${stat?.size ?? \"?\"}`)\n })\n const signature = sig.join(\"|\")\n const hit = this.listCache.get(agentId)\n if (hit && hit.signature === signature) return hit.articles.slice()\n\n const articles: WikiArticle[] = []\n for (const relPath of relPaths) {\n const article = this.readArticle(relPath)\n if (article && this.canRead(article.meta, agentId)) {\n articles.push(article)\n }\n }\n this.listCache.set(agentId, { signature, articles })\n return articles.slice()\n }\n\n /**\n * Search articles by keyword. Returns articles the agent can read.\n */\n search(query: string, agentId: string, maxResults: number = 10): WikiArticle[] {\n const queryLower = query.toLowerCase()\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n // BM25 over article content (cached to disk)\n const docs = articles.map((a) => a.content)\n const cachePath = resolve(this.baseDir, \"_bm25_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(query, index)\n const scoreMap = new Map(bm25Scores.map((r) => [r.docIndex, r.score]))\n\n const results = articles.map((article, i) => {\n let score = scoreMap.get(i) ?? 0\n // Additive bonuses for title and tag matches\n if (article.meta.title.toLowerCase().includes(queryLower)) score += 10\n if (article.meta.tags?.some(t => t.toLowerCase().includes(queryLower))) score += 5\n return { article, score }\n })\n\n return results\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxResults)\n .map((r) => r.article)\n }\n\n /**\n * findRelevant, then re-ranked by the wiki-rerank seat.\n *\n * Recall comes from findRelevant rather than search() because\n * findRelevant is the function everything actually calls — search()\n * turned out to have no callers at all. Additive on purpose: the\n * synchronous findRelevant is untouched and its existing callers stay\n * as they are. Measured on the 12-query eval against this\n * wiki, re-ranking moves R@1 from 33.3% to 50.0% and R@3 from 41.7% to\n * 66.7%, for about $0.0005 and 550ms a query.\n *\n * Fail-open in every direction. Seat off, backend down, no key, fewer\n * than two candidates — all return BM25's own order, which is what the\n * caller would have got anyway.\n *\n * Note what this cannot do: it only reorders what BM25 shortlisted. In\n * the eval R@3 sat exactly on that ceiling, so every remaining miss was\n * an article BM25 never returned. Widening the shortlist does not fix\n * that — past 30 the extra candidates measurably diluted the ranking.\n */\n async findRelevantReranked(\n query: string,\n agentId?: string,\n maxResults = 10,\n opts: { shortlist?: number; excerptChars?: number } = {},\n ): Promise<WikiArticle[]> {\n const shortlist = Math.max(maxResults, opts.shortlist ?? DEFAULT_SHORTLIST)\n const pool = this.findRelevant(query, agentId, shortlist)\n if (pool.length < 2) return pool.slice(0, maxResults)\n\n const candidates: RerankCandidate[] = pool.map((article, i) => ({\n // Index, not title: titles are not unique across a wiki and a\n // Choice needs distinct keys.\n id: `c${i}`,\n title: article.meta.title || `(untitled ${i})`,\n tags: article.meta.tags,\n excerpt: article.content,\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query, candidates, excerptChars: opts.excerptChars }),\n rerankQuestions(candidates),\n { incumbent: { best: candidates[0].id }, features: { agent: agentId ?? \"unknown\" } },\n )\n if (!result || result.mode !== \"active\") return pool.slice(0, maxResults)\n\n const ranking = toRanking(result.answers as never, candidates)\n return ranking.ranked\n .map((id) => pool[Number(id.slice(1))])\n .filter((a): a is WikiArticle => Boolean(a))\n .slice(0, maxResults)\n }\n\n /**\n * Find articles relevant to a message (for context injection).\n *\n * Scoring:\n * - BM25 over title+tags+content (always)\n * - + ancestry bonus if the caller classified the message through the\n * intent graph and articles carry `graphPath` from a previous classification\n *\n * `weights.graph` is scaled against `weights.bm25`. When the caller omits\n * `messagePath`, retrieval collapses to pure BM25 and matches legacy behavior.\n */\n findRelevant(\n message: string,\n agentId?: string,\n maxArticles: number = 3,\n messagePath?: string[],\n weights: { graph: number; bm25: number } = { graph: 0.6, bm25: 0.4 },\n ): WikiArticle[] {\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n const docs = articles.map(\n (a) => `${a.meta.title} ${(a.meta.tags || []).join(\" \")} ${a.content}`,\n )\n const cachePath = resolve(this.baseDir, \"_bm25_relevance_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(message, index)\n\n // Normalize BM25 so the two signals live on [0,1] before the weighted sum.\n const maxBm25 = bm25Scores.reduce((m, s) => Math.max(m, s.score), 0) || 1\n const bm25Map = new Map(bm25Scores.map((s) => [s.docIndex, s.score / maxBm25]))\n\n const hasGraph = !!(messagePath && messagePath.length > 0)\n const scored = articles.map((article, i) => {\n const bm25 = bm25Map.get(i) ?? 0\n let ancestry = 0\n if (hasGraph && article.meta.graphPath?.length) {\n ancestry = ancestryOf(messagePath!, article.meta.graphPath)\n }\n // When the caller passed no path, BM25 gets the full weight.\n const combined = hasGraph\n ? weights.graph * ancestry + weights.bm25 * bm25\n : bm25\n return { article, score: combined }\n })\n\n return scored\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxArticles)\n .map((r) => r.article)\n }\n\n /**\n * Build context string from relevant wiki articles for prompt injection.\n * Token-efficient: includes title + first ~500 chars of each article.\n */\n buildContext(articles: WikiArticle[], maxChars: number = 4000): string {\n if (articles.length === 0) return \"\"\n\n const lines: string[] = [\"[Wiki Knowledge]\"]\n\n let totalChars = 0\n for (const article of articles) {\n const header = `\\n## ${article.meta.title} [${(article.meta.tags || []).slice(0, 3).join(\", \")}]`\n const body = article.content.length > 600\n ? article.content.slice(0, 600) + \"...\"\n : article.content\n\n const chunk = header + \"\\n\" + body\n if (totalChars + chunk.length > maxChars) break\n\n lines.push(chunk)\n totalChars += chunk.length\n }\n\n lines.push(\"\\n[End Wiki Knowledge]\")\n return lines.join(\"\\n\")\n }\n\n /**\n * Rebuild the master index.\n */\n rebuildIndex(): WikiIndex {\n const articles: WikiIndex[\"articles\"] = []\n const backlinks = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n // Count wikilinks for backlinks\n const links = article.content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n for (const link of links) {\n const target = link.replace(/\\[\\[|\\]\\]/g, \"\")\n backlinks.set(target, (backlinks.get(target) || 0) + 1)\n }\n\n // Extract aliases from title and tags\n const aliases = [article.meta.title.toLowerCase()]\n if (article.meta.tags) {\n aliases.push(...article.meta.tags.map(t => t.toLowerCase()))\n }\n\n articles.push({\n path: relPath,\n title: article.meta.title,\n type: article.meta.type,\n related: article.meta.related,\n tags: article.meta.tags || [],\n owner: article.meta.owner,\n access: article.meta.access,\n sharedWith: article.meta.sharedWith,\n aliases,\n backlinks: backlinks.get(article.meta.title) || 0,\n sources: article.meta.sources,\n lastUpdated: article.meta.lastUpdated,\n graphPath: article.meta.graphPath,\n })\n })\n\n const index: WikiIndex = {\n articles,\n lastRebuilt: new Date().toISOString(),\n }\n\n // Machine-readable index\n writeFileSync(\n resolve(this.baseDir, \"_index.json\"),\n JSON.stringify(index, null, 2),\n )\n\n // Farzapedia-style content catalog at _index.md — the one file the\n // agentic query reads to pick candidate articles by `type` + title.\n // Load-bearing in Phase 3; grouped by type, alphabetical within group.\n this.writeCatalog(articles, index.lastRebuilt)\n\n // Human-readable WIKI.md — legacy view, grouped by access level.\n const md = [\"# Wiki Index\", \"\", `Last rebuilt: ${index.lastRebuilt}`, \"\"]\n const byAccess = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.access || \"public\"\n const list = byAccess.get(bucket) || []\n list.push(a)\n byAccess.set(bucket, list)\n }\n for (const [bucket, list] of Array.from(byAccess.entries()).sort()) {\n md.push(`## ${bucket}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const t = a.type ? ` [${a.type}]` : \"\"\n md.push(`- [${a.title}](${a.path})${t} — owner: ${a.owner}`)\n }\n md.push(\"\")\n }\n writeFileSync(resolve(this.baseDir, \"WIKI.md\"), md.join(\"\\n\"))\n\n this.log(`Index rebuilt: ${articles.length} articles`)\n this.appendLog(\"rebuild-index\", `${articles.length} articles indexed`)\n return index\n }\n\n /**\n * Write `_index.md` — the Farzapedia-style content catalog grouped by\n * article `type`. This is the one file the agentic query (Phase 3) reads\n * to pick candidate articles before walking the wikilink subgraph.\n *\n * Articles without a `type` land in \"Untyped\" at the bottom; the Phase 2\n * migration backfills those.\n */\n private writeCatalog(\n articles: WikiIndex[\"articles\"],\n lastRebuilt: string,\n ): void {\n const typeOrder: Array<NonNullable<WikiArticleMeta[\"type\"]> | \"untyped\"> = [\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\", \"untyped\",\n ]\n const typeHeaders: Record<string, string> = {\n person: \"## People\",\n project: \"## Projects\",\n place: \"## Places\",\n concept: \"## Concepts\",\n event: \"## Events\",\n decision: \"## Decisions\",\n pattern: \"## Patterns\",\n untyped: \"## Untyped (needs migration)\",\n }\n\n const byType = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.type || \"untyped\"\n const list = byType.get(bucket) || []\n list.push(a)\n byType.set(bucket, list)\n }\n\n const lines: string[] = [\n \"# Wiki Content Catalog\",\n \"\",\n `_Last rebuilt: ${lastRebuilt}_`,\n \"\",\n \"Articles grouped by type. Agentic query walks this file first to pick candidates.\",\n \"\",\n ]\n\n for (const type of typeOrder) {\n const list = byType.get(type)\n if (!list || list.length === 0) continue\n lines.push(typeHeaders[type] || `## ${type}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const access = a.access === \"private\" ? \" (private)\" : a.access === \"shared\" ? \" (shared)\" : \"\"\n const related = a.related?.length ? ` → [[${a.related.slice(0, 3).join(\"]], [[\")}]]${a.related.length > 3 ? \", …\" : \"\"}` : \"\"\n lines.push(`- [${a.title}](${a.path})${access}${related}`)\n }\n lines.push(\"\")\n }\n\n writeFileSync(resolve(this.baseDir, \"_index.md\"), lines.join(\"\\n\"))\n }\n\n /**\n * Get wiki stats.\n */\n stats(): {\n totalArticles: number\n totalEntries: number\n articlesByType: Record<string, number>\n articlesByAccess: Record<string, number>\n articlesByOwner: Record<string, number>\n } {\n let totalArticles = 0\n const byType: Record<string, number> = {}\n const byAccess: Record<string, number> = {}\n const byOwner: Record<string, number> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n totalArticles++\n for (const tag of (article.meta.tags || [])) {\n byType[tag] = (byType[tag] || 0) + 1\n }\n byAccess[article.meta.access] = (byAccess[article.meta.access] || 0) + 1\n byOwner[article.meta.owner] = (byOwner[article.meta.owner] || 0) + 1\n })\n\n const entryFiles = existsSync(this.rawDir)\n ? readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).length\n : 0\n\n return {\n totalArticles,\n totalEntries: entryFiles,\n articlesByType: byType,\n articlesByAccess: byAccess,\n articlesByOwner: byOwner,\n }\n }\n\n // --- Helpers ---\n\n // --- Log (chronological, append-only) ---\n\n /**\n * Append an entry to log.md.\n * Format: ## [YYYY-MM-DD HH:MM] action | details\n */\n appendLog(action: string, details: string): void {\n const logPath = resolve(this.baseDir, \"log.md\")\n const timestamp = new Date().toISOString().replace(\"T\", \" \").slice(0, 16)\n const entry = `## [${timestamp}] ${action} | ${details}\\n\\n`\n\n if (!existsSync(logPath)) {\n writeFileSync(logPath, \"# Wiki Log\\n\\nChronological record of all wiki operations.\\n\\n\")\n }\n\n appendFileSync(logPath, entry)\n }\n\n /**\n * Get recent log entries.\n */\n getLog(limit: number = 20): string[] {\n const logPath = resolve(this.baseDir, \"log.md\")\n if (!existsSync(logPath)) return []\n\n const content = readFileSync(logPath, \"utf-8\")\n const entries = content.split(/^## /m).filter(e => e.startsWith(\"[\")).slice(-limit)\n return entries.map(e => e.trim())\n }\n\n // --- Schema ---\n\n /**\n * Create _schema.md if it doesn't exist.\n * This tells the LLM how to operate on the wiki.\n */\n private ensureSchema(): void {\n const schemaPath = resolve(this.baseDir, \"_schema.md\")\n if (existsSync(schemaPath)) return\n\n const schema = `# Wiki Schema\n\nA personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,\nstructure emerges from data. The wiki is a compounding artifact.\n\n## Structure\n\n\\`\\`\\`\nwiki/\n _schema.md # This file\n worldview.md # YOUR mental model — the LLM reads this during absorb\n raw/entries/ # Immutable raw sources (conversations, imports, anything)\n [LLM-chosen dirs] # Structure emerges from data — the LLM picks paths\n\\`\\`\\`\n\nThe LLM decides how to organize articles. You describe YOUR world in worldview.md.\n\n## Article Format\n\n\\`\\`\\`yaml\n---\ntitle: \"Staging Deployment Process\"\ntags: [\"deploy\", \"staging\", \"devops\", \"process\", \"2026-04-06\"]\nowner: devops-agent\naccess: public\ncreated: 2026-04-06\nlast_updated: 2026-04-06\nsources: [\"entry-id-1\", \"entry-id-2\"]\n---\n\nArticle content with [[wikilinks]] and section tags.\n\n## Deploy Steps\n<!-- tags: process, runbook, staging -->\nContent specific to this section...\n\\`\\`\\`\n\n## Tags\n\nTags are the primary context-narrowing mechanism. The more tags, the better.\n\nTag aggressively:\n- **Who**: people, agents, teams involved\n- **What**: project, client, topic, technology\n- **When**: dates, periods, milestones\n- **Where**: server, environment, channel\n- **How**: process, decision, pattern\n- **Your terms**: whatever vocabulary makes sense in YOUR world\n\nSection tags (\\`<!-- tags: ... -->\\`) let different parts of an article\nmatch different queries. A deploy article might have sections tagged\n\"runbook\" and \"incident\" separately.\n\n## Operations\n\n### Absorb\nRead raw entries → read worldview.md → tag aggressively → create/update articles.\nAlso identify GAPS: \"We mention X but have no article for it.\"\n\n### Query\nMatch by tags first → then keyword within matched articles → synthesize.\nIf agent is working on a specific project, only send content tagged for that project.\n\n### Lint\nCheck for: orphan articles, broken [[wikilinks]], untagged articles,\narticles over 100 lines that should split, mentioned-but-missing topics.\n\n## Worldview\n\nEdit \\`worldview.md\\` to describe YOUR world. This is not a schema — it's your\nmental model. The LLM reads it during absorb to understand where things go.\n\nExample worldview.md:\n\\`\\`\\`\nI'm the founder of Acme Corp.\nWe build software products.\nOur agents: Marketing Bot, DevOps Bot, Coordinator.\nClients: ClientA (enterprise), ClientB (startup).\nInfrastructure: local dev machine, cloud server.\nWe use GitLab for version control.\n\\`\\`\\`\n`\n\n writeFileSync(schemaPath, schema)\n this.log(\"Created _schema.md\")\n }\n\n // --- Wikilinks and Backlinks ---\n\n /**\n * Extract all [[wikilinks]] from article content.\n */\n extractWikilinks(content: string): string[] {\n const matches = content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n return matches.map(m => m.replace(/\\[\\[|\\]\\]/g, \"\"))\n }\n\n /**\n * Build backlinks index: for each article, which other articles link to it.\n */\n buildBacklinks(): Record<string, string[]> {\n const backlinks: Record<string, string[]> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const content = readFileSync(filePath, \"utf-8\")\n const links = this.extractWikilinks(content)\n\n for (const link of links) {\n if (!backlinks[link]) backlinks[link] = []\n backlinks[link].push(relPath)\n }\n })\n\n // Save\n writeFileSync(\n resolve(this.baseDir, \"_backlinks.json\"),\n JSON.stringify(backlinks, null, 2),\n )\n\n return backlinks\n }\n\n /**\n * Get backlinks for a specific article title.\n */\n getBacklinks(title: string): string[] {\n const path = resolve(this.baseDir, \"_backlinks.json\")\n if (!existsSync(path)) return []\n try {\n const data = JSON.parse(readFileSync(path, \"utf-8\"))\n return data[title] || []\n } catch {\n return []\n }\n }\n\n // --- Tag-based filtering (Karpathy: tags are the context narrowing mechanism) ---\n\n /**\n * Find articles matching ANY of the given tags.\n * This is how agents get relevant context — only articles tagged with\n * the client/project/topic they're working on.\n */\n findByTags(tags: string[], agentId?: string, limit: number = 10): WikiArticle[] {\n const lowerTags = tags.map(t => t.toLowerCase())\n const results: Array<{ article: WikiArticle; score: number }> = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n if (agentId && !this.canRead(article.meta, agentId)) return\n\n // Score: how many of the requested tags match?\n const articleTags = (article.meta.tags || []).map(t => t.toLowerCase())\n // Also check section tags: <!-- tags: foo, bar -->\n const sectionTags = (article.content.match(/<!--\\s*tags?:\\s*([^>]+)\\s*-->/gi) || [])\n .flatMap(m => m.replace(/<!--\\s*tags?:\\s*|\\s*-->/gi, \"\").split(\",\").map(t => t.trim().toLowerCase()))\n\n const allTags = [...articleTags, ...sectionTags]\n const score = lowerTags.filter(t => allTags.includes(t)).length\n\n if (score > 0) {\n results.push({ article, score })\n }\n })\n\n return results\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map(r => r.article)\n }\n\n /**\n * Get all unique tags across all articles.\n */\n getAllTags(): Map<string, number> {\n const tagCounts = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article?.meta.tags) return\n\n for (const tag of article.meta.tags) {\n tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1)\n }\n })\n\n return tagCounts\n }\n\n // --- Worldview (user's mental model — input to absorb) ---\n\n /**\n * Get the worldview file. This is the user's description of their world —\n * the LLM uses it during absorb to know where things go.\n * Returns null if not set.\n */\n getWorldview(): string | null {\n const path = resolve(this.baseDir, \"worldview.md\")\n if (!existsSync(path)) return null\n return readFileSync(path, \"utf-8\")\n }\n\n /**\n * Set the worldview. The user describes their world: companies, clients,\n * projects, team, processes. The LLM uses this as context during absorb.\n */\n setWorldview(content: string): void {\n writeFileSync(resolve(this.baseDir, \"worldview.md\"), content)\n this.appendLog(\"worldview\", \"Updated worldview\")\n }\n\n // --- Lint ---\n\n /**\n * Run a lint pass on the wiki. Returns issues found.\n */\n lint(): Array<{ type: string; article: string; message: string }> {\n const issues: Array<{ type: string; article: string; message: string }> = []\n const allTitles = new Set<string>()\n const allLinks = new Map<string, string[]>() // article -> outbound links\n const articlePaths = new Map<string, string>() // title -> path\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n allTitles.add(article.meta.title)\n articlePaths.set(article.meta.title, relPath)\n\n const links = this.extractWikilinks(article.content)\n allLinks.set(relPath, links)\n\n // Check: article too long\n const lines = article.content.split(\"\\n\").length\n if (lines > 100) {\n issues.push({\n type: \"bloated\",\n article: relPath,\n message: `${lines} lines — consider splitting`,\n })\n }\n\n // Check: no sources\n if (!article.meta.sources?.length) {\n issues.push({\n type: \"unsourced\",\n article: relPath,\n message: \"No sources listed in frontmatter\",\n })\n }\n\n // Check: stub (too short)\n if (lines < 10 && article.content.trim().length < 100) {\n issues.push({\n type: \"stub\",\n article: relPath,\n message: \"Very short article — needs enrichment\",\n })\n }\n })\n\n // Check: broken wikilinks\n for (const [articlePath, links] of allLinks) {\n for (const link of links) {\n if (!allTitles.has(link)) {\n issues.push({\n type: \"broken-link\",\n article: articlePath,\n message: `[[${link}]] — target article not found`,\n })\n }\n }\n }\n\n // Check: orphan articles (no inbound links)\n const backlinks = this.buildBacklinks()\n for (const [title, path] of articlePaths) {\n if (!backlinks[title] || backlinks[title].length === 0) {\n issues.push({\n type: \"orphan\",\n article: path,\n message: `No other articles link to \"${title}\"`,\n })\n }\n }\n\n this.appendLog(\"lint\", `Found ${issues.length} issues`)\n return issues\n }\n\n // --- Absorb summary (for automated cron) ---\n\n /**\n * Get unabsorbed entries (entries not referenced by any article's sources field).\n */\n getUnabsorbedEntries(): WikiEntry[] {\n const allSources = new Set<string>()\n\n // Collect all source IDs referenced by articles\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (article?.meta.sources) {\n for (const s of article.meta.sources) allSources.add(s)\n }\n })\n\n // Find entries not in any article's sources\n const entries = this.listEntries()\n return entries.filter(e => !allSources.has(e.id))\n }\n\n /**\n * Build an absorb prompt for unprocessed entries.\n * Returns a prompt string an agent can execute to compile entries into articles.\n */\n buildAbsorbPrompt(maxEntries: number = 20): string | null {\n const unabsorbed = this.getUnabsorbedEntries().slice(0, maxEntries)\n if (unabsorbed.length === 0) return null\n\n const entrySummaries = unabsorbed.map(e =>\n `[${e.date} ${e.agentId} via ${e.source}] ${e.content.slice(0, 200)}`\n ).join(\"\\n\\n\")\n\n return `/wiki absorb\\n\\nThere are ${unabsorbed.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.\\n\\n${entrySummaries}`\n }\n\n private walkDir(dir: string, callback: (filePath: string, stat?: Stats) => void): void {\n if (!existsSync(dir)) return\n for (const entry of readdirSync(dir)) {\n const full = join(dir, entry)\n const stat = statSync(full)\n if (stat.isDirectory()) {\n this.walkDir(full, callback)\n } else {\n callback(full, stat)\n }\n }\n }\n}\n"],"mappings":"iNAAA,OAAS,gBAAAA,EAAc,iBAAAC,EAAe,kBAAAC,EAAgB,cAAAC,EAAY,aAAAC,EAAW,eAAAC,EAAa,YAAAC,MAA4B,KACtH,OAAS,WAA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,QAAQA,EAAE,eAAeA,EAAE,WAAWA,EAAE,QAAQ,MAAM,EAAG,GAAG,GACpE,EAAE,KAAK;AAAA;AAAA,CAAM,EAEb,MAAO;AAAA;AAAA,YAA6Be,EAAW;AAAA;AAAA,EAA2GC,GAC5J,CAEQ,QAAQC,EAAaC,EAA0D,CACrF,GAAKnI,EAAWkI,CAAG,EACnB,QAAW1I,KAASU,EAAYgI,CAAG,EAAG,CACpC,IAAME,EAAOC,EAAKH,EAAK1I,CAAK,EACtBkD,EAAO4F,EAASF,CAAI,EACtB1F,EAAK,YAAY,EACnB,KAAK,QAAQ0F,EAAMD,CAAQ,EAE3BA,EAASC,EAAM1F,CAAI,EAGzB,CACF","names":["readFileSync","writeFileSync","appendFileSync","existsSync","mkdirSync","readdirSync","statSync","resolve","join","relative","dirname","init_seat","WikiStore","baseDir","resolve","log","mkdirSync","article","agentId","entry","filename","filepath","frontmatter","k","v","writeFileSync","filter","existsSync","files","readdirSync","f","entries","file","content","readFileSync","fmMatch","fm","body","get","key","KNOWN","meta","line","m","path","existing","isWikiArticleType","fullPath","dirname","t","s","action","articlePath","ts","versionDir","i","versionTimestamp","version","raw","getArray","rawType","type","tags","a","related","graphPath","relPaths","sig","filePath","stat","relPath","relative","signature","hit","articles","query","maxResults","queryLower","docs","cachePath","index","buildIndexCached","bm25Scores","scoreAll","scoreMap","r","score","b","opts","shortlist","DEFAULT_SHORTLIST","pool","candidates","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","toRanking","id","message","maxArticles","messagePath","weights","maxBm25","bm25Map","hasGraph","bm25","ancestry","ancestryScore","combined","maxChars","lines","totalChars","header","chunk","backlinks","links","link","target","aliases","md","byAccess","bucket","list","x","y","lastRebuilt","typeOrder","typeHeaders","byType","access","totalArticles","byOwner","tag","entryFiles","details","logPath","appendFileSync","limit","e","schemaPath","title","lowerTags","results","articleTags","sectionTags","allTags","tagCounts","issues","allTitles","allLinks","articlePaths","allSources","maxEntries","unabsorbed","entrySummaries","dir","callback","full","join","statSync"]}