agentix-cli 0.113.0 → 0.114.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.
- package/apps/mac-helper/Resources/AppIcon.png +0 -0
- package/apps/mac-voice/Resources/AppIcon.png +0 -0
- package/apps/mac-voice/Resources/Info.plist +1 -0
- package/apps/mac-voice/build.sh +10 -0
- package/dist/{App-5ZI475WY.js → App-Q4UAYL2V.js} +2 -2
- package/dist/{ChatApp-PLR7J5D3.js → ChatApp-6KGP57OP.js} +2 -2
- package/dist/{agent-GRX75ANW.js → agent-NGCPRTBH.js} +2 -2
- package/dist/{board-dashboard-EKJHQKPH.js → board-dashboard-7B2B564A.js} +553 -327
- package/dist/board-dashboard-7B2B564A.js.map +1 -0
- package/dist/{chunk-QAIYUMHW.js → chunk-4VDA4UM7.js} +2 -2
- package/dist/{chunk-74CQWVHE.js → chunk-A35RTVMM.js} +2 -2
- package/dist/{chunk-DG5I6PPM.js → chunk-BGG3ZSMW.js} +4 -2
- package/dist/chunk-BGG3ZSMW.js.map +1 -0
- package/dist/{chunk-X7E27RYS.js → chunk-C4S5XQKD.js} +2 -2
- package/dist/{chunk-RXQ2XCKP.js → chunk-CSLVHAYV.js} +2 -2
- package/dist/{chunk-A6B5JRUG.js → chunk-CYKPDILL.js} +2 -2
- package/dist/{chunk-B37WAFT5.js → chunk-DOQ6Y7GZ.js} +160 -160
- package/dist/chunk-DOQ6Y7GZ.js.map +1 -0
- package/dist/{chunk-QWI3FM5R.js → chunk-EVB23EHN.js} +2 -2
- package/dist/{chunk-XG2XVGSL.js → chunk-FDCTFT2Q.js} +2 -2
- package/dist/{chunk-MEXXGNNN.js → chunk-HG6QA6EU.js} +2 -2
- package/dist/{chunk-THRWE4Y3.js → chunk-J3GXZQXY.js} +2 -2
- package/dist/chunk-JVSTKXMI.js +6 -0
- package/dist/chunk-JVSTKXMI.js.map +1 -0
- package/dist/{chunk-V3C2BOYR.js → chunk-LP227A6L.js} +2 -2
- package/dist/{chunk-37EDS7SZ.js → chunk-QBWJGDKE.js} +5 -5
- package/dist/{chunk-N7HKIMMR.js → chunk-SCJ5ZXEN.js} +2 -2
- package/dist/{chunk-R43TE2XX.js → chunk-TZIPWZY6.js} +2 -2
- package/dist/{chunk-6FJ44HYY.js → chunk-UMFFIUU6.js} +2 -2
- package/dist/{chunk-QF377BDS.js → chunk-UZB5UO35.js} +2 -2
- package/dist/{chunk-4QCYSKPD.js → chunk-VGI4EZTP.js} +2 -2
- package/dist/{chunk-EEOQ5C5N.js → chunk-VTWSW4KB.js} +2 -2
- package/dist/{chunk-TXX5W3SH.js → chunk-Y5HBYSJW.js} +2 -2
- package/dist/{chunk-TXX5W3SH.js.map → chunk-Y5HBYSJW.js.map} +1 -1
- package/dist/{chunk-22LO3GBP.js → chunk-YLKCFW2R.js} +2 -2
- package/dist/{chunk-DVJW3IWI.js → chunk-Z6OPM7EH.js} +2 -2
- package/dist/{chunk-OZDSQVHU.js → chunk-ZXQYOSHP.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-DBQ5QNJJ.js → client-QTXWO46T.js} +2 -2
- package/dist/{config-4T62LT27.js → config-4XGZYYQP.js} +2 -2
- package/dist/config-mutator-QLSA6JOY.js +2 -0
- package/dist/{doctor-M32NIOZH.js → doctor-DO262COW.js} +2 -2
- package/dist/index.d.ts +49 -0
- package/dist/index.js +1 -1
- package/dist/processes-5MP32QZT.js +2 -0
- package/dist/{program-7MG42JKO.js → program-4IMJEMDM.js} +14 -14
- package/dist/{promote-DAEKJVWN.js → promote-4VTXBVUC.js} +2 -2
- package/dist/{query-MCJYD66I.js → query-B32UDQJS.js} +2 -2
- package/dist/{registry-AYPPHZ3Z.js → registry-GY4X2GZX.js} +2 -2
- package/dist/{request-planner-7NKKLY7C.js → request-planner-RYWFGBGK.js} +2 -2
- package/dist/{review-candidates-QG2U5YID.js → review-candidates-TXX532LY.js} +2 -2
- package/dist/{routing-HBNYDAGE.js → routing-IT4YS6X3.js} +2 -2
- package/dist/schedule-tool-FJKH2ERY.js +2 -0
- package/dist/scheduler-ALPDUE4H.js +2 -0
- package/dist/{seat-PQ7AMPMT.js → seat-LK45MTVI.js} +2 -2
- package/dist/{select-J6TO7RED.js → select-4LAHUZ74.js} +2 -2
- package/dist/{set-enabled-WXRUHFWW.js → set-enabled-F2K56HQZ.js} +2 -2
- package/dist/{tool-I3OGQKAD.js → tool-J4VHHZWN.js} +2 -2
- package/dist/{tool-KN2QEPDO.js → tool-W3ODKQM2.js} +2 -2
- package/dist/wiki-LVYHDK2R.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-EKJHQKPH.js.map +0 -1
- package/dist/chunk-B37WAFT5.js.map +0 -1
- package/dist/chunk-DG5I6PPM.js.map +0 -1
- package/dist/chunk-JBE4H7PL.js +0 -6
- package/dist/chunk-JBE4H7PL.js.map +0 -1
- package/dist/config-mutator-ARUEJ6V5.js +0 -2
- package/dist/processes-W5VHBP7T.js +0 -2
- package/dist/schedule-tool-6S35TPJJ.js +0 -2
- package/dist/scheduler-KZ6VVZZA.js +0 -2
- package/dist/wiki-2IKLQ6PO.js +0 -2
- /package/dist/{App-5ZI475WY.js.map → App-Q4UAYL2V.js.map} +0 -0
- /package/dist/{ChatApp-PLR7J5D3.js.map → ChatApp-6KGP57OP.js.map} +0 -0
- /package/dist/{agent-GRX75ANW.js.map → agent-NGCPRTBH.js.map} +0 -0
- /package/dist/{chunk-QAIYUMHW.js.map → chunk-4VDA4UM7.js.map} +0 -0
- /package/dist/{chunk-74CQWVHE.js.map → chunk-A35RTVMM.js.map} +0 -0
- /package/dist/{chunk-X7E27RYS.js.map → chunk-C4S5XQKD.js.map} +0 -0
- /package/dist/{chunk-RXQ2XCKP.js.map → chunk-CSLVHAYV.js.map} +0 -0
- /package/dist/{chunk-A6B5JRUG.js.map → chunk-CYKPDILL.js.map} +0 -0
- /package/dist/{chunk-QWI3FM5R.js.map → chunk-EVB23EHN.js.map} +0 -0
- /package/dist/{chunk-XG2XVGSL.js.map → chunk-FDCTFT2Q.js.map} +0 -0
- /package/dist/{chunk-MEXXGNNN.js.map → chunk-HG6QA6EU.js.map} +0 -0
- /package/dist/{chunk-THRWE4Y3.js.map → chunk-J3GXZQXY.js.map} +0 -0
- /package/dist/{chunk-V3C2BOYR.js.map → chunk-LP227A6L.js.map} +0 -0
- /package/dist/{chunk-37EDS7SZ.js.map → chunk-QBWJGDKE.js.map} +0 -0
- /package/dist/{chunk-N7HKIMMR.js.map → chunk-SCJ5ZXEN.js.map} +0 -0
- /package/dist/{chunk-R43TE2XX.js.map → chunk-TZIPWZY6.js.map} +0 -0
- /package/dist/{chunk-6FJ44HYY.js.map → chunk-UMFFIUU6.js.map} +0 -0
- /package/dist/{chunk-QF377BDS.js.map → chunk-UZB5UO35.js.map} +0 -0
- /package/dist/{chunk-4QCYSKPD.js.map → chunk-VGI4EZTP.js.map} +0 -0
- /package/dist/{chunk-EEOQ5C5N.js.map → chunk-VTWSW4KB.js.map} +0 -0
- /package/dist/{chunk-22LO3GBP.js.map → chunk-YLKCFW2R.js.map} +0 -0
- /package/dist/{chunk-DVJW3IWI.js.map → chunk-Z6OPM7EH.js.map} +0 -0
- /package/dist/{chunk-OZDSQVHU.js.map → chunk-ZXQYOSHP.js.map} +0 -0
- /package/dist/{client-DBQ5QNJJ.js.map → client-QTXWO46T.js.map} +0 -0
- /package/dist/{config-4T62LT27.js.map → config-4XGZYYQP.js.map} +0 -0
- /package/dist/{config-mutator-ARUEJ6V5.js.map → config-mutator-QLSA6JOY.js.map} +0 -0
- /package/dist/{doctor-M32NIOZH.js.map → doctor-DO262COW.js.map} +0 -0
- /package/dist/{processes-W5VHBP7T.js.map → processes-5MP32QZT.js.map} +0 -0
- /package/dist/{program-7MG42JKO.js.map → program-4IMJEMDM.js.map} +0 -0
- /package/dist/{promote-DAEKJVWN.js.map → promote-4VTXBVUC.js.map} +0 -0
- /package/dist/{query-MCJYD66I.js.map → query-B32UDQJS.js.map} +0 -0
- /package/dist/{registry-AYPPHZ3Z.js.map → registry-GY4X2GZX.js.map} +0 -0
- /package/dist/{request-planner-7NKKLY7C.js.map → request-planner-RYWFGBGK.js.map} +0 -0
- /package/dist/{review-candidates-QG2U5YID.js.map → review-candidates-TXX532LY.js.map} +0 -0
- /package/dist/{routing-HBNYDAGE.js.map → routing-IT4YS6X3.js.map} +0 -0
- /package/dist/{schedule-tool-6S35TPJJ.js.map → schedule-tool-FJKH2ERY.js.map} +0 -0
- /package/dist/{scheduler-KZ6VVZZA.js.map → scheduler-ALPDUE4H.js.map} +0 -0
- /package/dist/{seat-PQ7AMPMT.js.map → seat-LK45MTVI.js.map} +0 -0
- /package/dist/{select-J6TO7RED.js.map → select-4LAHUZ74.js.map} +0 -0
- /package/dist/{set-enabled-WXRUHFWW.js.map → set-enabled-F2K56HQZ.js.map} +0 -0
- /package/dist/{tool-I3OGQKAD.js.map → tool-J4VHHZWN.js.map} +0 -0
- /package/dist/{tool-KN2QEPDO.js.map → tool-W3ODKQM2.js.map} +0 -0
- /package/dist/{wiki-2IKLQ6PO.js.map → wiki-LVYHDK2R.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as fd,b as Ps,g as hd}from"./chunk-
|
|
1
|
+
import{a as fd,b as Ps,g as hd}from"./chunk-C4S5XQKD.js";import{a as Kl,c as Ql}from"./chunk-LP227A6L.js";import{A as ar,B as pd,D as ud,a as so,b as Xl,f as Bt,g as Zl,h as ed,i as od,j as td,l as nd,m as sd,n as id,o as ir,p as rd,u as ad,v as cd,w as rr,x as ld}from"./chunk-UMFFIUU6.js";import{a as dd,c as gd,d as md}from"./chunk-4FU4BFCH.js";import"./chunk-SCJ5ZXEN.js";import{a as Ji,b as xc}from"./chunk-RKPAVWXF.js";import{$ as Dn,A as kl,B as vl,C as xl,D as Sl,E as El,F as Al,G as Tl,H as _l,I as Cs,J as Co,K as Bo,L as qt,M as Is,N as Ns,O as Zi,P as Dl,Q as Pl,R as Ml,S as Ll,T as ql,U as Fl,V as Ft,W as Ut,X as Ul,Y as Wl,Z as Le,_ as Rs,a as Ic,aa as er,b as Nc,ba as Bl,ca as Gl,da as nr,ea as Yl,fa as _s,ga as Wt,h as $s,ha as Ds,i as Pc,ia as sr,j as Nn,ja as Vl,k as bs,l as qc,m as Fc,n as Qc,o as Zc,p as As,q as Gi,r as il,s as ml,t as pl,u as hl,v as yl,w as wl,x as $l,y as bl,z as Yi}from"./chunk-DOQ6Y7GZ.js";import{A as Ts,G as gl,Ma as Jl,Na as or,Oa as Hl,Pa as tr,V as Rn,Y as Vi,Z as js,_ as jl,bb as vo,db as zl,fa as Wo,ga as Ol,ha as Xi,ja as Ki,la as Cl,ma as Il,na as _n,ra as Os,ua as Nl,va as Rl,w as zi,wa as Qi,x as ll,z as dl}from"./chunk-ZXQYOSHP.js";import{a as Rc,d as _c,e as Dc}from"./chunk-VTWSW4KB.js";import{a as ks,b as vs,c as Uc,d as Wc,e as Bc,g as Jc,h as Hc,j as Gc,k as zc,l as Yc,m as Vc,p as xs,s as Xc,t as Kc}from"./chunk-S2GAEH2F.js";import"./chunk-GTJIKXDB.js";import"./chunk-BGG3ZSMW.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ul,b as fl}from"./chunk-EKJG63EJ.js";import{a as Mc,p as Lc}from"./chunk-EVB23EHN.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as no}from"./chunk-ACFQBLPX.js";import{c as el,e as Ss,g as Es}from"./chunk-LQE73AZR.js";import{a as ol,b as tl,c as nl,d as sl}from"./chunk-2D3RYIDU.js";import"./chunk-QLWGLRT5.js";import{a as rl,e as al,g as cl}from"./chunk-JIT5GPTX.js";import{L as Uo,R as wc,ca as bc,g as tc,r as nc,y as Ui,z as ac}from"./chunk-QBWJGDKE.js";import{b as Rt,g as Dt,h as ys,i as ws,j as Pt,k as cc,l as ct,m as Cn,u as $c}from"./chunk-J3GXZQXY.js";import{e as uc,f as Bi,k as fc}from"./chunk-GLQLCBJS.js";import{b as _t}from"./chunk-6W74CHNW.js";import"./chunk-UZB5UO35.js";import"./chunk-SFQUP3BP.js";import{b as In}from"./chunk-LLNPKE7H.js";import{a as kc,b as vc}from"./chunk-SHEUCITK.js";import"./chunk-Y4CYQV7G.js";import{a as Hi,e as Sc,f as Ec,h as Ac,i as Tc,k as jc,l as Oc,m as Cc}from"./chunk-YLKCFW2R.js";import{a as Mt}from"./chunk-GV7S5BAX.js";import{c as dc}from"./chunk-SZDACK6O.js";import{f as gc,g as mc,h as Wi}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as ic,k as pc}from"./chunk-VGI4EZTP.js";import{a as hc,b as re,c as Ie,d as Lt,e as yc}from"./chunk-CYKPDILL.js";import"./chunk-VWTBHLMX.js";import{a as qi}from"./chunk-Z6OPM7EH.js";import"./chunk-TZIPWZY6.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import{a as Fi,b as sc}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as rc}from"./chunk-X5C5W3E4.js";import{e as lc}from"./chunk-GSX4NK2N.js";import"./chunk-HG6QA6EU.js";import"./chunk-MYVHVJWZ.js";import{n as oc}from"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-CSLVHAYV.js";import{g as Fo,i as hs}from"./chunk-JVSTKXMI.js";import"./chunk-WPNRDEHW.js";import{b as Nt,d as ec}from"./chunk-2GIDVZ4H.js";import{a as Pi,b as _a,c as tu,d as ps,e as Da,f as Ya,g as au,h as Va,i as cu,m as It,n as Ka,q as Qa,u as Za,y as ko,z as On}from"./chunk-A35RTVMM.js";import{a as Oo,b as Ct,e as Ha,f as jn}from"./chunk-72SZI2UW.js";import{a as Xa,b as lu}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-2PJKGZWP.js";import{a as jo,b as ou}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as su,O as Wa,P as Mi,R as Li,Y as iu,h as Pa,ha as Ba,i as Ma,ia as Ja,j as La,ja as T,k as qa,ka as fs,l as Fa,m as nu,ma as te,z as Ua}from"./chunk-Y5HBYSJW.js";import{f as qo,n as us}from"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Ga,k as za,l as ru}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as du}from"commander";var yd=new du().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 Nc({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()});te();import{Command as gu}from"commander";import{execFileSync as co}from"node:child_process";import{cpSync as wd,existsSync as dr,mkdirSync as cr,mkdtempSync as mu,readdirSync as pu,rmSync as $d,writeFileSync as bd}from"node:fs";import{dirname as kd,join as qe}from"node:path";import{homedir as Ms,release as uu,tmpdir as fu}from"node:os";import{setTimeout as hu}from"node:timers/promises";function Ls(){let e=Uc(process.platform,process.arch,uu());if(e)throw new Error(e)}function qs(){let e=qe(Ms(),"Library/LaunchAgents"),o=[];try{o=pu(e).filter(Jc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:co("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Hc(e,t)}function Pn(e){return`gui/${process.getuid()}/${e.label}`}async function lr(e){try{co("launchctl",["bootout",Pn(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{co("launchctl",["print",Pn(e)],{stdio:"pipe"})}catch{return}await hu(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function vd(e){if(!dr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{co("launchctl",["print",Pn(e)],{stdio:"pipe"})}catch{o=!1}o||co("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),co("launchctl",["kickstart",Pn(e)],{stdio:"pipe"})}function yu(){let e=Vc();if(e&&dr(qe(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 Jt=new gu("desktop").description("install and control the macOS desktop assistant");Jt.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=>{Ls();let o=T(),t=Wc(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=yu(),r=qe(Ms(),"Applications"),{keep:a,remove:c}=qs();if(console.log(`Desktop assistant \u2192 ${qe(r,ks)}
|
|
2
2
|
Computer-use helper \u2192 ${qe(r,vs)}
|
|
3
3
|
Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -27,7 +27,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
27
27
|
`))});function tf(e){let o=Math.round(el/6e4),t=[` Pairing code: ${Te.bold.cyan(Ss(e.code))}`,Te.dim(` Open the app from the phone's home screen and type this code. It works once, for ${o} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Te.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Te.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||t.push(Te.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),t}function hr(){let e;try{e=JSON.parse(Jd("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let o=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!o)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${o}`}var nf=new Set(["/app","/api/app","/member","/api/member"]);function yr(e,o){let t=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of t)for(let[i,r]of Object.entries(s?.Web??{}))for(let[a,c]of Object.entries(r?.Handlers??{})){let l=String(c?.Proxy??"").match(/^(?:https?:\/\/)?(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/),g=a.replace(/\/+$/,"")||"/";l&&Number(l[1])===o&&!nf.has(g)&&n.push(`${i}${a}`)}return n}function wr(){try{return JSON.parse(Jd("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Wn(){try{return T().dashboard.port||4202}catch{return 4202}}te();import{Command as So}from"commander";import h from"chalk";import Me from"prompts";import{readFileSync as Ho,writeFileSync as Yt,existsSync as we,mkdirSync as xo,cpSync as $r,readdirSync as kr}from"fs";import{resolve as z,join as Jo,dirname as sf}from"path";import{fileURLToPath as rf}from"url";function me(){let e=z(process.cwd(),"agentx.json");if(!we(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ho(e,"utf-8"))}function Je(e){return re(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var mt=new So().name("agent").description("manage agents \u2014 add, list, remove");mt.command("list").alias("ls").description("list configured agents").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});mt.command("add").description("add a new agent interactively").action(async()=>{let e=me(),o=await Me([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:z(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:Jo(o.workspace,o.id);xo(z(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-HAV4CQV7.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=z(process.cwd(),"src/wiki/SKILL.md"),a=z(sf(rf(import.meta.url)),"../wiki/SKILL.md"),c=we(r)?r:a;we(c)&&(xo(z(t,".claude/skills/wiki"),{recursive:!0}),$r(c,z(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Je(e),console.log(h.green(`
|
|
28
28
|
Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});mt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=me();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Je(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});mt.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=me(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Je(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Bn=new So().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Bn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=me().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
|
|
29
29
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
30
|
-
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Bn.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=me();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-4T62LT27.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Me({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Me({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Me({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});u.scheme==="tokenEnv"?a=((await Me({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await Me({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Me({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...y]=f.split("=");p&&(g[p.trim()]=y.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Je(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Bn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=me(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Je(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Bn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=me().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});mt.addCommand(Bn);var Hs=new So().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Hs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=me();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Hs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=me(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Me({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Me([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Je(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Me([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Me([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Je(e),xo(z(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Me([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Me([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Je(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Vt=new So().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Vt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Vt.command("add").description("add a cron job").action(async()=>{let e=me(),o=Object.keys(e.agents||{}),t=await Me([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Je(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Vt.command("enable <id>").description("enable a cron job").action(async e=>{let o=me();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Je(o),console.log(h.green(` Cron "${e}" enabled`))});Vt.command("disable <id>").description("disable a cron job").action(async e=>{let o=me();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Je(o),console.log(h.green(` Cron "${e}" disabled`))});var io=new So().name("mesh").description("manage mesh peers \u2014 add, list, remove");io.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=me();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});io.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=me(),o=await Me([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Je(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});io.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=me();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Je(o),console.log(h.green(` Peer "${e}" removed`)))});io.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=me();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Je(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});io.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,o)=>{let t=o.node||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var Hd=e=>{let o=e||"";if(!o)try{o=T().dashboard?.daemonUrl||""}catch{}return(o||"http://localhost:18800").replace(/\/+$/,"")};async function Gs(e,o,t={}){let n=Hd(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let i=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${o}`,{method:"POST",headers:s,body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` ${r.error||`HTTP ${i.status}`}`)),process.exit(1));let a=r.grant;console.log(h.green(` \u2713 ${a?.name??e}: ${a?.state}${r.stopped?`, ${r.stopped} running turn(s) stopped`:""}`))}catch(i){console.log(h.red(` Could not reach the daemon at ${n}: ${i?.message||i}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var pt=io.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");pt.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:o}=await import("./token-store-YBSU2DTV.js"),{PairCodeStore:t,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:i}=await import("./grants-BRAVOGBP.js"),r=T(),a=i({tokens:new o,codes:new t,guests:new s,hasAgent:l=>!!r.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log(h.red(` ${a.error}`)),process.exit(1));let c=(e.url||Hd()).replace(/\/+$/,"");console.log(),console.log(` Grant ${h.bold(a.grant.name)} for ${h.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(h.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${h.cyan(c)}`),console.log(` ${h.bold(n(a.code))}`),console.log(),console.log(` They run: ${h.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});pt.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:o}=await import("./store-7W2AP5H4.js"),t=new o().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(h.dim(`
|
|
30
|
+
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Bn.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=me();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-4XGZYYQP.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Me({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Me({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Me({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});u.scheme==="tokenEnv"?a=((await Me({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await Me({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Me({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...y]=f.split("=");p&&(g[p.trim()]=y.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Je(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Bn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=me(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Je(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Bn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=me().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});mt.addCommand(Bn);var Hs=new So().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Hs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=me();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Hs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=me(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Me({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Me([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Je(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Me([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Me([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Je(e),xo(z(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Me([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Me([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Je(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Vt=new So().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Vt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Vt.command("add").description("add a cron job").action(async()=>{let e=me(),o=Object.keys(e.agents||{}),t=await Me([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Je(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Vt.command("enable <id>").description("enable a cron job").action(async e=>{let o=me();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Je(o),console.log(h.green(` Cron "${e}" enabled`))});Vt.command("disable <id>").description("disable a cron job").action(async e=>{let o=me();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Je(o),console.log(h.green(` Cron "${e}" disabled`))});var io=new So().name("mesh").description("manage mesh peers \u2014 add, list, remove");io.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=me();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});io.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=me(),o=await Me([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Je(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});io.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=me();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Je(o),console.log(h.green(` Peer "${e}" removed`)))});io.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=me();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Je(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});io.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,o)=>{let t=o.node||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var Hd=e=>{let o=e||"";if(!o)try{o=T().dashboard?.daemonUrl||""}catch{}return(o||"http://localhost:18800").replace(/\/+$/,"")};async function Gs(e,o,t={}){let n=Hd(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let i=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${o}`,{method:"POST",headers:s,body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` ${r.error||`HTTP ${i.status}`}`)),process.exit(1));let a=r.grant;console.log(h.green(` \u2713 ${a?.name??e}: ${a?.state}${r.stopped?`, ${r.stopped} running turn(s) stopped`:""}`))}catch(i){console.log(h.red(` Could not reach the daemon at ${n}: ${i?.message||i}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var pt=io.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");pt.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:o}=await import("./token-store-YBSU2DTV.js"),{PairCodeStore:t,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:i}=await import("./grants-BRAVOGBP.js"),r=T(),a=i({tokens:new o,codes:new t,guests:new s,hasAgent:l=>!!r.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log(h.red(` ${a.error}`)),process.exit(1));let c=(e.url||Hd()).replace(/\/+$/,"");console.log(),console.log(` Grant ${h.bold(a.grant.name)} for ${h.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(h.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${h.cyan(c)}`),console.log(` ${h.bold(n(a.code))}`),console.log(),console.log(` They run: ${h.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});pt.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:o}=await import("./store-7W2AP5H4.js"),t=new o().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(h.dim(`
|
|
31
31
|
No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
|
|
32
32
|
`));return}console.log();for(let n of t){let s=n.state==="active"?h.green("active"):n.state==="pending"?h.yellow(n.guestNode?"waiting for your approval":"not joined yet"):n.state==="paused"?h.yellow("paused"):h.red(`ended${n.endedReason?`: ${n.endedReason}`:""}`);console.log(` ${h.cyan(n.id)} ${h.bold(n.name)} ${n.guest} \u2192 ${n.agentId} ${n.level} ${s}`),console.log(h.dim(` until ${n.expiresAt.slice(0,10)} \xB7 ${n.usage.turns} turn(s), ${n.usage.tokens} tokens${n.usage.lastAt?` \xB7 last ${n.usage.lastAt.slice(0,16).replace("T"," ")} UTC`:""}${n.guestNode?.name?` \xB7 node ${n.guestNode.name}`:""}`))}console.log()});pt.command("show <id>").description("one grant, what it opens and what the guest did").action(async e=>{let{GuestStore:o}=await import("./store-7W2AP5H4.js"),t=new o,n=t.get(e);n||(console.log(h.red(` No grant "${e}". See \`agentx mesh guests\`.`)),process.exit(1)),console.log(),console.log(` ${h.bold(n.name)} (${n.id}) \xB7 ${n.state}`),console.log(` guest: ${n.guest}${n.guestNode?` \xB7 node ${n.guestNode.name??n.guestNode.id??"?"} at ${n.guestNode.address??"?"}`:""}`),console.log(` agent: ${n.agentId} \xB7 level: ${n.level} \xB7 until ${n.expiresAt.slice(0,10)}`),console.log(` folders: ${n.folders.join(", ")||"none"}
|
|
33
33
|
skills: ${n.skills.join(", ")||"none"}
|
|
@@ -38,7 +38,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
38
38
|
Not a guest anywhere. Join with: agentx mesh join <url> --code \u2026 --name \u2026
|
|
39
39
|
`));return}console.log();for(let n of t){let s=await o(n),i=s.ok?s.grant.state==="active"?h.green("active"):h.yellow(String(s.grant.state)):s.status===403?h.yellow(s.error):h.red(s.error);console.log(` ${h.cyan(n.name)} ${h.dim(n.url)} ${n.agentId} until ${n.expiresAt.slice(0,10)} ${i}`)}console.log()});io.command("ask <host> <message...>").description("ask the host's agent something, inside the grant").action(async(e,o)=>{let{GuestHostStore:t,askHost:n}=await import("./hosts-NFNCYKGY.js"),s=new t().get(e);s||(console.log(h.red(` No host "${e}". See \`agentx mesh hosts\`.`)),process.exit(1));let i=await n(s,o.join(" "));i.error&&(console.log(h.red(` ${i.error}`)),process.exit(1)),console.log(`
|
|
40
40
|
${i.content}
|
|
41
|
-
`)});io.command("leave <host>").description("forget a host you joined as a guest (the host can also end it on its side)").action(async e=>{let{GuestHostStore:o}=await import("./hosts-NFNCYKGY.js");new o().remove(e)||(console.log(h.red(` No host "${e}".`)),process.exit(1)),console.log(h.green(` \u2713 Left ${e}`))});var ut=new So().name("skill").description("manage skills \u2014 add to agent(s), list");ut.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=me(),n=z(e);if(!we(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=we(Jo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Me({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=z(a.workspace,".claude/skills",s);xo(c,{recursive:!0}),we(Jo(n,"SKILL.md"))?$r(n,c,{recursive:!0}):n.endsWith(".md")&&$r(n,Jo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});ut.command("list").alias("ls").description("list skills per agent").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=z(t.workspace,".claude/skills"),s=we(n)?kr(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});ut.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[z(n,"src",e,"SKILL.md"),z(n,"skills",e,"SKILL.md")],i=s.find(b=>we(b));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(h.dim(` ${b}`));return}let r=Ho(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=T()}catch(b){console.log(h.red(` Can't load agentx.json: ${b.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([b])=>b===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,y=0;for(let[b,k]of d){let $=k.workspace;if(!$||!we($)){console.log(` ${h.yellow("\u2717")} ${b.padEnd(22)} ${h.dim("(workspace missing: "+($||"undefined")+")")}`),y++;continue}let E=z($,".claude/skills",e),S=z(E,"SKILL.md");if(!we(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${b.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||(xo(E,{recursive:!0}),Yt(S,r)),console.log(` ${h.green("+")} ${b.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let v=Ho(S,"utf-8");if(t("sha256").update(v).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${b.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Yt(S,r),console.log(` ${h.yellow("\u21BB")} ${b.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${y} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});ut.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-YFVSSYSL.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=me().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(z(f.workspace))}else if(e.allWorkspaces){let u=me();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(z(f.workspace))}else i.push(z(e.cwd));let r=z(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let y of f.reasons)console.log(` ${h.dim("\xB7")} ${y}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});ut.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=me(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-
|
|
41
|
+
`)});io.command("leave <host>").description("forget a host you joined as a guest (the host can also end it on its side)").action(async e=>{let{GuestHostStore:o}=await import("./hosts-NFNCYKGY.js");new o().remove(e)||(console.log(h.red(` No host "${e}".`)),process.exit(1)),console.log(h.green(` \u2713 Left ${e}`))});var ut=new So().name("skill").description("manage skills \u2014 add to agent(s), list");ut.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=me(),n=z(e);if(!we(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=we(Jo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Me({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=z(a.workspace,".claude/skills",s);xo(c,{recursive:!0}),we(Jo(n,"SKILL.md"))?$r(n,c,{recursive:!0}):n.endsWith(".md")&&$r(n,Jo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});ut.command("list").alias("ls").description("list skills per agent").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=z(t.workspace,".claude/skills"),s=we(n)?kr(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});ut.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[z(n,"src",e,"SKILL.md"),z(n,"skills",e,"SKILL.md")],i=s.find(b=>we(b));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(h.dim(` ${b}`));return}let r=Ho(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=T()}catch(b){console.log(h.red(` Can't load agentx.json: ${b.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([b])=>b===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,y=0;for(let[b,k]of d){let $=k.workspace;if(!$||!we($)){console.log(` ${h.yellow("\u2717")} ${b.padEnd(22)} ${h.dim("(workspace missing: "+($||"undefined")+")")}`),y++;continue}let E=z($,".claude/skills",e),S=z(E,"SKILL.md");if(!we(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${b.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||(xo(E,{recursive:!0}),Yt(S,r)),console.log(` ${h.green("+")} ${b.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let v=Ho(S,"utf-8");if(t("sha256").update(v).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${b.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Yt(S,r),console.log(` ${h.yellow("\u21BB")} ${b.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${y} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});ut.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-YFVSSYSL.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=me().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(z(f.workspace))}else if(e.allWorkspaces){let u=me();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(z(f.workspace))}else i.push(z(e.cwd));let r=z(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let y of f.reasons)console.log(` ${h.dim("\xB7")} ${y}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});ut.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=me(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-4LAHUZ74.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
|
|
42
42
|
shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(h.dim(`
|
|
43
43
|
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Jn=new So().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Jn.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=z(o.cwd),n=z(t,"references/example"),s=z(t,"references/recipes/example.yaml");we(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=z(t,".agentx/references",e),r=z(t,".agentx/references/recipes");xo(i,{recursive:!0}),xo(r,{recursive:!0});let a=kr(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Jo(i,d);if(we(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=Ho(Jo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Yt(u,p),console.log(h.green(` + ${u}`)),c++}let g=Jo(r,`${e}.yaml`);if(we(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(we(s)){let d=Ho(s,"utf-8").replaceAll("example.",`${e}.`);Yt(g,d),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Jn.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=z(o.cwd),r=o.from?String(o.from).split(",").map(y=>y.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([y,w])=>[y,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=z(o.referencesCwd||o.cwd),u=z(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[y,w]of Object.entries(g))console.log(h.cyan(`
|
|
44
44
|
--- ${y} ---`)),console.log(w.split(`
|
|
@@ -47,7 +47,7 @@ ${i.content}
|
|
|
47
47
|
`).length>30&&console.log(h.dim(` \u2026 (${w.split(`
|
|
48
48
|
`).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}xo(u,{recursive:!0});let f=0,p=0;for(let[y,w]of Object.entries(g)){let b=Jo(u,y);if(we(b)&&!o.force){console.log(h.dim(` skip ${b} (exists; --force to overwrite)`)),p++;continue}Yt(b,w),console.log(h.green(` + ${b}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Jn.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-KKMG24O5.js"),t=await o(z(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var vr=new So().name("hook").description("manage hooks \u2014 add to agent workspace");vr.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=me().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=z(t.workspace,".claude/settings.json"),s=we(n)?JSON.parse(Ho(n,"utf-8")):{},i=await Me([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),xo(z(t.workspace,".claude"),{recursive:!0}),Yt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var xr=new So().name("migrate").description("import configuration from OpenClaw or other tools");xr.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,z(process.env.HOME||"",".openclaw/openclaw.json"),z(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&we(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(Ho(n,"utf-8")),i=we(z(process.cwd(),"agentx.json"))?me():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),y=f.groupChat?.mentionPatterns||[];if(y.some(w=>w===p)||y.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:y,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){xo(z(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-HAV4CQV7.js");w(p,i.agents[p])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,p]of Object.entries(g)){if(!p.botToken)continue;let w=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:w},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let u=z(n,"../cron/jobs.json");if(we(u)){let f=JSON.parse(Ho(u,"utf-8")),p=0;for(let y of f.jobs||[]){let w=y.name||y.id,b=y.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[w]={enabled:y.enabled||!1,schedule:y.schedule?.expr||"0 9 * * *",timezone:y.schedule?.tz||"UTC",agent:b,prompt:y.payload?.message||"",timeout:y.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
|
|
49
49
|
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Je(i),console.log(h.green(`
|
|
50
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Go=new So().name("config").description("validate and inspect configuration");Go.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=T(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=fs(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=we(z(r,".claude")),c=we(z(r,"CLAUDE.md")),l=we(z(r,".claude/settings.json")),g=we(z(r,".claude/skills"))?kr(z(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Go.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=T(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function af(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function br(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Go.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-
|
|
50
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Go=new So().name("config").description("validate and inspect configuration");Go.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=T(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=fs(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=we(z(r,".claude")),c=we(z(r,"CLAUDE.md")),l=we(z(r,".claude/settings.json")),g=we(z(r,".claude/skills"))?kr(z(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Go.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=T(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function af(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function br(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Go.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-QLSA6JOY.js"),{expandEnvVars:r}=await import("./config-4XGZYYQP.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(br(g))});Go.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-QLSA6JOY.js"),r=af(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${br(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${br(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Go.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-QLSA6JOY.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});Go.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let d=T(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});us();import{Command as cf}from"commander";import zo from"chalk";import{resolve as Yo}from"path";import{existsSync as lf}from"fs";var Io=new cf().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function ft(e){let o=Yo(e,".agentx/db.sqlite");lf(o)||(console.log(zo.red(` No SQLite at ${o}`)),console.log(zo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=qo({path:o});return t||(console.log(zo.red(` Could not open ${o}`)),console.log(zo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function ht(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(zo.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}Io.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=ft(Yo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
|
|
51
51
|
SELECT agent_id, channel, status, duration_ms,
|
|
52
52
|
input_tokens, output_tokens,
|
|
53
53
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -453,7 +453,7 @@ return aid ?? null`}function py(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
453
453
|
Latest runs (${s.length})`),s.length===0&&console.log(F.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?F.green("ok"):r.status==="in-flight"?F.yellow("running"):F.red(r.status);console.log(` ${F.dim(Om(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${Cm(r.messagePreview)}`)}console.log()});us();su();import{Command as Iw}from"commander";import{existsSync as Nw}from"fs";import ye from"chalk";var cn=new Iw("requests").description("what you asked agents for that is not finished, oldest first"),Dm={in_progress:"in progress",waiting_owner:"waiting on you",waiting_other:"waiting on another agent",needs_attention:"needs attention",done:"done",declined:"declined",dropped:"dropped"};function Zr(){if(!Nw(hc()))return console.error(ye.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=qo();return e?new Ua(e):(process.exitCode=1,null)}var mi=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function Pm(e){let o=e.state==="needs_attention"?ye.red:e.state==="waiting_owner"?ye.yellow:ye.dim;console.log(` ${ye.cyan(e.id)} ${o(`[${Dm[e.state]??e.state}]`)} ${ye.dim(`${mi(e.createdAt)} \xB7 ${e.channel} \xB7 ${e.agentId}`)}`),console.log(` ${e.text.replace(/\s+/g," ").trim().slice(0,240)}`),e.state==="waiting_owner"&&e.question&&console.log(ye.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(ye.red(` ${e.attentionReason}`)),e.evidence&&console.log(ye.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(ye.dim(` Reason: ${e.closeReason}`))}cn.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=Zr();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(zi().enabled||console.log(ye.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(ye.dim(" no open requests"));return}for(let n of t)Pm(n);console.log(ye.dim(`
|
|
454
454
|
${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});cn.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=Zr();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(ye.red(` no request "${e}"`)),process.exitCode=1;return}Pm(t),console.log(ye.dim(` Last activity ${mi(t.updatedAt)}${t.closedAt?` \xB7 closed ${mi(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(ye.dim(` ${n.kind} ${n.ref} (${mi(n.at)})`))});function Mm(e,o,t,n){cn.command(`${e} <id>`).description(o).option(t,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,i)=>{let r=Zr();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(ye.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(ye.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(ye.red(` ${s} is already closed (${Dm[c.state]??c.state})`)),process.exitCode=1;return}console.log(ye.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}Mm("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");Mm("drop","drop a request you no longer want","--reason <text>","");cn.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").action(async e=>{let o={};try{let n=(i,r)=>{if(r===void 0)return;let a=Number(r);if(!(a>0))throw new Error(`${i} must be a positive number`);return a},s=(i,r)=>i===void 0?void 0:i===r?[]:i.split(",").map(a=>a.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");o.enabled=e.enabled==="on"}o.from=s(e.from,"none"),o.channels=s(e.channels,"all"),o.staleAfterHours=n("--stale-hours",e.staleHours),o.retentionDays=n("--retention-days",e.retentionDays)}catch(n){console.error(ye.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await ll(o);if(!n.success){console.error(ye.red(` ${n.error}`)),process.exitCode=1;return}console.log(ye.green(" \u2713 saved")+(n.reloaded?ye.dim(" (daemon reloaded)"):""))}let t=zi();console.log(` Requests ${t.enabled?"on":"off"}`),console.log(` Channels ${t.channels.length?t.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${t.from.length?t.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${t.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${t.retentionDays} day(s)`)});import{Command as Rw}from"commander";import ln from"chalk";te();var Lm=new Rw("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",rr.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(ln.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await re(i=>{n=ld(i,e,o==="on")});s.success||(console.error(ln.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(ln.green(`\u2713 ${n}`)),s.reloaded&&console.log(ln.dim(" daemon hot-reloaded"))}let t=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of rr)console.log(` ${n.padEnd(8)} ${t.includes(n)?ln.green("on"):ln.dim("off")}`)});import{Command as t$}from"commander";import dn from"chalk";import ce from"chalk";import es from"prompts";import{readFileSync as _w,writeFileSync as Dw,existsSync as Pw}from"fs";import{resolve as qm}from"path";var Mw=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Lw(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function ea(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Fm(e=".env"){let o=qm(e);if(!Pw(o))return[];let t=_w(o,"utf-8"),n=[];for(let s of t.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 i=s.match(Mw);i?n.push({kind:"kv",key:i[1],value:Lw(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function qw(e){return e.map(o=>o.kind==="kv"?`${o.key}=${ea(o.value)}`:o.raw).join(`
|
|
455
455
|
`)+`
|
|
456
|
-
`}function Zn(e,o,t=".env"){let n=qm(t),s=Fm(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${ea(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${ea(o)}`})),Dw(n,qw(s))}function oa(e,o=".env"){return Fm(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Um="https://t.me/BotFather";async function Fw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function Uw(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.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 Wm(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${Um}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await es({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&>(Um);let{token:t}=await es({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:k=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(k.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Fw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.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(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await es({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await es({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Zn(f,t.trim()),process.env[f]=t.trim();let p=await re(k=>{Ie(k,"channels.telegram.enabled",!0),Ie(k,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=Lt(k,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(k,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await es({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(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await Uw(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let b=await re(k=>{Ie(k,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!b.success){console.log(ce.red(` \u2717 failed to save destination: ${b.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),b.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import ta from"prompts";import{existsSync as sa,mkdirSync as Ww,readdirSync as Bw,readFileSync as Bm}from"fs";import{resolve as na}from"path";var Jw=".agentx/whatsapp-sessions";function Hw(){let e=na(process.cwd(),".agentx/daemon.pid");if(!sa(e))return!1;try{let o=parseInt(Bm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Gw(e){if(!sa(e))return!1;try{return Bw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function zw(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Ww(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Jm(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),Hw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await ta({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||na(process.cwd(),"agentx.json");sa(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Bm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Jw,s=na(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await ta({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Gw(s)&&a){let{keep:l}=await ta({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(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await zw(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Yw}from"crypto";import je from"chalk";import Hm from"prompts";var pi="agentx-mesh:",ui="//join/";function Vw(e){return Buffer.from(e,"utf-8").toString("base64url")}function Xw(e){return Buffer.from(e,"base64url").toString("utf-8")}function Kw(e){return`${pi}${ui}${Vw(JSON.stringify(e))}`}function Qw(e){if(!e.startsWith(`${pi}${ui}`))throw new Error(`Not a mesh invite link \u2014 expected ${pi}${ui}\u2026`);let o=e.slice(pi.length+ui.length),t=JSON.parse(Xw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Zw(){return Yw(32).toString("hex")}function e$(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function o$(e){return e?.node?.name||e?.node?.id||"node"}async function Gm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=oa("MESH_TOKEN");r||(r=Zw(),Zn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||e$(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Hm({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=Kw({url:a,token:r,name:o$(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function zm(e,o={}){let t;try{t=Qw(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=oa("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Hm({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Zn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=Lt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var gn=new t$().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");gn.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 Wm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});gn.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 Jm({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Ym=gn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Ym.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 Gm({url:e.url,configPath:e.config})});Ym.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await zm(e,{configPath:o.config})});gn.action(()=>{console.log(),console.log(dn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${dn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${dn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${dn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${dn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(dn.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as n$}from"commander";import X from"chalk";var St=new n$().name("usage").description("token usage analysis and reporting");St.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(X.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(X.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${X.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${X.red(String(s.totalErrors))}`),console.log(),console.log(X.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${X.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${X.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${e.message}`))}});St.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 o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:X.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(X.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(X.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=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)?X.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(X.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${o.message}`))}});St.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(X.red(` Script not found: ${s}`)),console.log(X.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(X.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(X.red(" Analysis failed. Is Python 3 installed?"))}});St.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:o,writeFileSync:t}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:i}=await import("./usage-channels-KBLEC4NE.js"),r=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!r(e.from)||!r(e.to)||e.from>e.to){console.log(X.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&&t(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(o(e.baseline,"utf-8"))}catch(p){console.log(X.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(X.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(X.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(X.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...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));f.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of f){let b=i(y),k=` ${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(b).padStart(9)}`;if(c){let $=i(w),E=b!==null&&$?`${((b-$)/$*100).toFixed(0)}%`:"-";k+=` ${l($).padStart(9)} ${E.padStart(7)}`}console.log(k)}console.log(),c&&console.log(X.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(X.dim(` Saved ${e.save}`)),console.log()});St.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:o}=await import("./surface-usage-HCJTUS6Z.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-7MG42JKO.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");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(X.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${X.dim("\xB7")} ${d}`);console.log(),console.log(X.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(X.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(X.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(X.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(X.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(X.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=X.dim(`${i.days}d`);console.log(` ${X.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(X.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as s$}from"commander";import xe from"chalk";import{readFileSync as i$}from"fs";import{resolve as r$}from"path";te();var tt=new s$().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");tt.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{ec(r$(process.cwd(),".env"))}catch{}let o=a$(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-EKJHQKPH.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function a$(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
456
|
+
`}function Zn(e,o,t=".env"){let n=qm(t),s=Fm(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${ea(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${ea(o)}`})),Dw(n,qw(s))}function oa(e,o=".env"){return Fm(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Um="https://t.me/BotFather";async function Fw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function Uw(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.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 Wm(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${Um}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await es({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&>(Um);let{token:t}=await es({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:k=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(k.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Fw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.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(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await es({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await es({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Zn(f,t.trim()),process.env[f]=t.trim();let p=await re(k=>{Ie(k,"channels.telegram.enabled",!0),Ie(k,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=Lt(k,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(k,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await es({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(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await Uw(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let b=await re(k=>{Ie(k,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!b.success){console.log(ce.red(` \u2717 failed to save destination: ${b.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),b.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import ta from"prompts";import{existsSync as sa,mkdirSync as Ww,readdirSync as Bw,readFileSync as Bm}from"fs";import{resolve as na}from"path";var Jw=".agentx/whatsapp-sessions";function Hw(){let e=na(process.cwd(),".agentx/daemon.pid");if(!sa(e))return!1;try{let o=parseInt(Bm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Gw(e){if(!sa(e))return!1;try{return Bw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function zw(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Ww(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Jm(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),Hw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await ta({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||na(process.cwd(),"agentx.json");sa(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Bm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Jw,s=na(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await ta({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Gw(s)&&a){let{keep:l}=await ta({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(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await zw(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Yw}from"crypto";import je from"chalk";import Hm from"prompts";var pi="agentx-mesh:",ui="//join/";function Vw(e){return Buffer.from(e,"utf-8").toString("base64url")}function Xw(e){return Buffer.from(e,"base64url").toString("utf-8")}function Kw(e){return`${pi}${ui}${Vw(JSON.stringify(e))}`}function Qw(e){if(!e.startsWith(`${pi}${ui}`))throw new Error(`Not a mesh invite link \u2014 expected ${pi}${ui}\u2026`);let o=e.slice(pi.length+ui.length),t=JSON.parse(Xw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Zw(){return Yw(32).toString("hex")}function e$(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function o$(e){return e?.node?.name||e?.node?.id||"node"}async function Gm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=oa("MESH_TOKEN");r||(r=Zw(),Zn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||e$(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Hm({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=Kw({url:a,token:r,name:o$(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function zm(e,o={}){let t;try{t=Qw(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=oa("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Hm({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Zn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=Lt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var gn=new t$().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");gn.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 Wm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});gn.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 Jm({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Ym=gn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Ym.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 Gm({url:e.url,configPath:e.config})});Ym.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await zm(e,{configPath:o.config})});gn.action(()=>{console.log(),console.log(dn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${dn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${dn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${dn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${dn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(dn.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as n$}from"commander";import X from"chalk";var St=new n$().name("usage").description("token usage analysis and reporting");St.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(X.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(X.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${X.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${X.red(String(s.totalErrors))}`),console.log(),console.log(X.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${X.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${X.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${e.message}`))}});St.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 o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:X.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(X.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(X.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=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)?X.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(X.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${o.message}`))}});St.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(X.red(` Script not found: ${s}`)),console.log(X.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(X.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(X.red(" Analysis failed. Is Python 3 installed?"))}});St.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:o,writeFileSync:t}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:i}=await import("./usage-channels-KBLEC4NE.js"),r=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!r(e.from)||!r(e.to)||e.from>e.to){console.log(X.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&&t(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(o(e.baseline,"utf-8"))}catch(p){console.log(X.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(X.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(X.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(X.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...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));f.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of f){let b=i(y),k=` ${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(b).padStart(9)}`;if(c){let $=i(w),E=b!==null&&$?`${((b-$)/$*100).toFixed(0)}%`:"-";k+=` ${l($).padStart(9)} ${E.padStart(7)}`}console.log(k)}console.log(),c&&console.log(X.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(X.dim(` Saved ${e.save}`)),console.log()});St.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:o}=await import("./surface-usage-HCJTUS6Z.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-4IMJEMDM.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");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(X.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${X.dim("\xB7")} ${d}`);console.log(),console.log(X.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(X.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(X.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(X.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(X.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(X.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=X.dim(`${i.days}d`);console.log(` ${X.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(X.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as s$}from"commander";import xe from"chalk";import{readFileSync as i$}from"fs";import{resolve as r$}from"path";te();var tt=new s$().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");tt.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{ec(r$(process.cwd(),".env"))}catch{}let o=a$(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-7B2B564A.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function a$(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
457
457
|
`)),{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:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}tt.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(xe.dim(`
|
|
458
458
|
No boards configured.
|
|
459
459
|
`));return}console.log();for(let o of e.boards){console.log(` ${xe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(xe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(xe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(xe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});tt.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,o)=>{try{os(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});tt.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,o)=>{try{os(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});var ia=tt.command("column").description("manage a board's columns (add / remove / edit / list)");ia.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(i$("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(xe.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${xe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${xe.dim(i)}`)}}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});ia.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,o,t)=>{try{os(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(xe.red(` ${n.message}`)),process.exit(1)}});ia.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{os(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});tt.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{os(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});function os(e){let{summary:o,backupPath:t}=so(n=>e(n));console.log(xe.green(`
|
|
@@ -464,9 +464,9 @@ return aid ?? null`}function py(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
464
464
|
${x.content}
|
|
465
465
|
--- END ENTRY ---`).join(`
|
|
466
466
|
|
|
467
|
-
`),$="";if(e.facts!==!1){let{extractHints:x,resolveFacts:R,mergeRecords:I,renderFactsBlock:C,installPrompts:M,defaultSources:H,recordsFromEntries:q}=await import("./facts-ROUMKS7I.js");if(!a){let G=new Set;for(let Ce of t.listAgents())for(let Se of t.getAgentWiki(Ce).listArticles(Ce))Se.meta.type==="person"&&G.add(Se.meta.title);a=[...G]}let Y=x(p.map(G=>({context:G.sourceContext,content:G.content,sender:typeof G.meta?.sender=="string"?G.meta.sender:void 0})),{known:a}),fe=q(p);if(Y.length>0||fe.length>0){let G=H(),{records:Ce,results:Se}=Y.length>0?await R(Y,{sources:G}):{records:[],results:[]},L=I([...fe,...Ce]);$=C(L);let oo=[...fe.length>0?[`entries:${fe.length}`]:[],...Se.filter(Ee=>Ee.records.length>0).map(Ee=>`${Ee.source}:${Ee.records.length}`)];console.log(m.dim(` Facts: ${Y.length} entities \u2192 ${L.length} resolved${oo.length?` (${oo.join(" ")})`:""}`));for(let Ee of M(Se,G))console.log(m.yellow(` ! ${Ee.source} ${Ee.kind} \u2014 would supply ${Ee.provides.join(", ")}`)),console.log(m.dim(` ${Ee.hint}`))}}let E=Mc(o,u,b,w.articles,k,p.length,$);console.log(m.dim(` Mode: ${aa(o)}`));let S=U(y.baseDir,"_tmp");Do(S,{recursive:!0});let v=U(S,"absorb-prompt.txt");At(v,E),console.log(m.dim(" Compiling with Claude..."));try{let x;try{x=Et(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Nt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(L){if(x=L.stdout||"",!x)throw L}let R=x;try{let L=JSON.parse(x);R=L.result||L.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(L).join(", ")}`)),console.log(m.dim(` is_error: ${L.is_error}, stop_reason: ${L.stop_reason}`)))}catch{}let I,C=[],M=R.indexOf("{"),H=R.indexOf("["),q=M>=0&&(H<0||M<H)?M:H;if(q===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let Y=R[q],fe=Y==="{"?"}":"]",G=0,Ce=-1;for(let L=q;L<R.length;L++)if(R[L]===Y)G++;else if(R[L]===fe&&(G--,G===0)){Ce=L+1;break}if(Ce===-1){console.log(m.red(" Unbalanced JSON"));continue}let Se=R.slice(q,Ce);try{let L=JSON.parse(Se);Array.isArray(L)?I=L:(I=L.articles||[],C=L.gaps||[])}catch(L){console.log(m.red(` JSON parse error: ${L.message}`)),console.log(m.dim(` First 300 chars: ${Se.slice(0,300)}`));continue}for(let L of I){let oo=new Date().toISOString().slice(0,10),Ee=l(L.sources||[],p);y.writeArticle(L.path,{title:L.title,type:L.type,related:Array.isArray(L.related)?L.related:void 0,tags:L.tags||[],owner:u,access:"public",created:oo,lastUpdated:oo,sources:L.sources||[],graphPath:Ee},L.content,u);let at=L.type?m.magenta(`[${L.type}]`)+" ":"",_=Array.isArray(L.related)&&L.related.length?` \u2192 ${L.related.slice(0,3).join(", ")}${L.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${at}${L.path}: ${L.title}${m.dim(_)}`);let $e=(L.tags||[]).slice(0,4).join(", ");$e&&console.log(m.dim(` tags: ${$e}`)),Ee?.length&&(console.log(m.dim(` graphPath: ${Ee.join(" \u203A ")}`)),d++),g++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let L of C)console.log(m.yellow(` ? ${L}`));try{let{QuestionStore:L}=await import("./questions-ZATLU5AW.js"),oo=new L(Tt(e.dir)).add(C.map(Ee=>({kind:"article",agentId:u,path:"",subject:String(Ee).slice(0,120),question:`No article yet for: ${String(Ee).slice(0,160)}`})));oo.added>0&&console.log(m.dim(` queued ${oo.added} for follow-up (agentx wiki questions)`))}catch{}}y.rebuildIndex()}catch(x){console.log(m.red(` Absorb failed: ${x.message?.slice(0,200)}`)),x.stderr&&console.log(m.dim(String(x.stderr).slice(0,300))),x.stdout&&console.log(m.dim("stdout: "+String(x.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ne.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 o=p$(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.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 i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-QG2U5YID.js"),{default:c}=await import("better-sqlite3"),l=U(process.cwd(),".agentx/db.sqlite");if(!to(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()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.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-PBPF45GN.js"),{default:g}=await import("better-sqlite3"),d=U(process.cwd(),".agentx/db.sqlite");if(!to(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(o??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.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)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Lc({extraCandidates:i,wikiDir:e.dir?U(e.dir):void 0,memoryRoot:e.memoryDir?U(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,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(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.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(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.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 r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var hi=ne.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function yi(e){return e?U(e):U(process.cwd(),".agentx","wiki")}hi.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:o}=await import("./proposals-O4B5LD5T.js"),t=o(yi(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,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(` ${r}`))}});hi.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,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(yi(o.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(`
|
|
467
|
+
`),$="";if(e.facts!==!1){let{extractHints:x,resolveFacts:R,mergeRecords:I,renderFactsBlock:C,installPrompts:M,defaultSources:H,recordsFromEntries:q}=await import("./facts-ROUMKS7I.js");if(!a){let G=new Set;for(let Ce of t.listAgents())for(let Se of t.getAgentWiki(Ce).listArticles(Ce))Se.meta.type==="person"&&G.add(Se.meta.title);a=[...G]}let Y=x(p.map(G=>({context:G.sourceContext,content:G.content,sender:typeof G.meta?.sender=="string"?G.meta.sender:void 0})),{known:a}),fe=q(p);if(Y.length>0||fe.length>0){let G=H(),{records:Ce,results:Se}=Y.length>0?await R(Y,{sources:G}):{records:[],results:[]},L=I([...fe,...Ce]);$=C(L);let oo=[...fe.length>0?[`entries:${fe.length}`]:[],...Se.filter(Ee=>Ee.records.length>0).map(Ee=>`${Ee.source}:${Ee.records.length}`)];console.log(m.dim(` Facts: ${Y.length} entities \u2192 ${L.length} resolved${oo.length?` (${oo.join(" ")})`:""}`));for(let Ee of M(Se,G))console.log(m.yellow(` ! ${Ee.source} ${Ee.kind} \u2014 would supply ${Ee.provides.join(", ")}`)),console.log(m.dim(` ${Ee.hint}`))}}let E=Mc(o,u,b,w.articles,k,p.length,$);console.log(m.dim(` Mode: ${aa(o)}`));let S=U(y.baseDir,"_tmp");Do(S,{recursive:!0});let v=U(S,"absorb-prompt.txt");At(v,E),console.log(m.dim(" Compiling with Claude..."));try{let x;try{x=Et(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Nt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(L){if(x=L.stdout||"",!x)throw L}let R=x;try{let L=JSON.parse(x);R=L.result||L.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(L).join(", ")}`)),console.log(m.dim(` is_error: ${L.is_error}, stop_reason: ${L.stop_reason}`)))}catch{}let I,C=[],M=R.indexOf("{"),H=R.indexOf("["),q=M>=0&&(H<0||M<H)?M:H;if(q===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let Y=R[q],fe=Y==="{"?"}":"]",G=0,Ce=-1;for(let L=q;L<R.length;L++)if(R[L]===Y)G++;else if(R[L]===fe&&(G--,G===0)){Ce=L+1;break}if(Ce===-1){console.log(m.red(" Unbalanced JSON"));continue}let Se=R.slice(q,Ce);try{let L=JSON.parse(Se);Array.isArray(L)?I=L:(I=L.articles||[],C=L.gaps||[])}catch(L){console.log(m.red(` JSON parse error: ${L.message}`)),console.log(m.dim(` First 300 chars: ${Se.slice(0,300)}`));continue}for(let L of I){let oo=new Date().toISOString().slice(0,10),Ee=l(L.sources||[],p);y.writeArticle(L.path,{title:L.title,type:L.type,related:Array.isArray(L.related)?L.related:void 0,tags:L.tags||[],owner:u,access:"public",created:oo,lastUpdated:oo,sources:L.sources||[],graphPath:Ee},L.content,u);let at=L.type?m.magenta(`[${L.type}]`)+" ":"",_=Array.isArray(L.related)&&L.related.length?` \u2192 ${L.related.slice(0,3).join(", ")}${L.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${at}${L.path}: ${L.title}${m.dim(_)}`);let $e=(L.tags||[]).slice(0,4).join(", ");$e&&console.log(m.dim(` tags: ${$e}`)),Ee?.length&&(console.log(m.dim(` graphPath: ${Ee.join(" \u203A ")}`)),d++),g++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let L of C)console.log(m.yellow(` ? ${L}`));try{let{QuestionStore:L}=await import("./questions-ZATLU5AW.js"),oo=new L(Tt(e.dir)).add(C.map(Ee=>({kind:"article",agentId:u,path:"",subject:String(Ee).slice(0,120),question:`No article yet for: ${String(Ee).slice(0,160)}`})));oo.added>0&&console.log(m.dim(` queued ${oo.added} for follow-up (agentx wiki questions)`))}catch{}}y.rebuildIndex()}catch(x){console.log(m.red(` Absorb failed: ${x.message?.slice(0,200)}`)),x.stderr&&console.log(m.dim(String(x.stderr).slice(0,300))),x.stdout&&console.log(m.dim("stdout: "+String(x.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ne.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 o=p$(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.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 i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-TXX532LY.js"),{default:c}=await import("better-sqlite3"),l=U(process.cwd(),".agentx/db.sqlite");if(!to(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()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.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-PBPF45GN.js"),{default:g}=await import("better-sqlite3"),d=U(process.cwd(),".agentx/db.sqlite");if(!to(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(o??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.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)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Lc({extraCandidates:i,wikiDir:e.dir?U(e.dir):void 0,memoryRoot:e.memoryDir?U(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,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(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.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(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.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 r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var hi=ne.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function yi(e){return e?U(e):U(process.cwd(),".agentx","wiki")}hi.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:o}=await import("./proposals-O4B5LD5T.js"),t=o(yi(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,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(` ${r}`))}});hi.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,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(yi(o.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(`
|
|
468
468
|
`).map(s=>` ${s}`).join(`
|
|
469
|
-
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),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>)`))}});hi.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,o)=>{let{approveProposal:t}=await import("./promote-
|
|
469
|
+
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),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>)`))}});hi.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,o)=>{let{approveProposal:t}=await import("./promote-4VTXBVUC.js"),n=t(yi(o.dir),e,{force:o.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`))});hi.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,o)=>{let{rejectProposal:t}=await import("./promote-4VTXBVUC.js"),n=t(yi(o.dir),e,{reason:o.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function p$(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ne.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",U(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:o}=await import("./query-B32UDQJS.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=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=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=t(d).sort().reverse();for(let w of f){let b=r(d,w),k=[];try{k=t(b).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of k){if(u.length>=g)break;try{let E=JSON.parse(n(r(b,$),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||$.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.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 ${u.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<u.length;w++){let b=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(b.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
470
470
|
`)||"_(none returned)_",E;try{let S=await o(b.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")E=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let v=S.citations.map(x=>`\`${x.title}\` [${x.type||"?"}]`).join(", ");E=`**Answer:**
|
|
471
471
|
|
|
472
472
|
${S.answer}
|
|
@@ -483,7 +483,7 @@ Q: ${_.q}
|
|
|
483
483
|
A: ${_.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",k||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
|
|
484
484
|
`),E=U(a.baseDir,"_tmp");Do(E,{recursive:!0});let S=U(E,`interview-${t().slice(0,8)}.txt`);At(S,$),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let v="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$e=Et(_,{env:Nt({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let ao=JSON.parse($e);v=String(ao.result||ao.content||"")}catch{v=$e}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}v=v.trim();let x=v.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);x&&(v=x[1].trim());let R=v.indexOf("---");R>0&&(v=v.slice(R));let I=v.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!I){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(v.slice(0,600)),c?.close();return}let C={};for(let _ of I[1].split(`
|
|
485
485
|
`)){let $e=_.match(/^(\w+):\s*(.+)$/);$e&&(C[$e[1]]=$e[2].trim().replace(/^"(.*)"$/,"$1"))}let M=I[2],H=C.title||g,q=H.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),fe=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${q}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${fe}`)),console.log(),console.log(v),console.log();let G=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),G==="scrap"||G==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let Ce=M,Se={title:H,type:C.type||d,related:C.related?C.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:C.tags?C.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:C.access||"public",created:C.created||new Date().toISOString().slice(0,10),lastUpdated:C.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(G==="edit"){let _=process.env.EDITOR||"vi",$e=U(E,`draft-${t().slice(0,8)}.md`);At($e,v);try{Et(`${_} '${$e}'`,{stdio:"inherit"});let _i=ts($e,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(_i){let Lo={};for(let Tn of _i[1].split(`
|
|
486
|
-
`)){let Di=Tn.match(/^(\w+):\s*(.+)$/);Di&&(Lo[Di[1]]=Di[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=_i[2],Se={...Se,title:Lo.title||Se.title,type:Lo.type||Se.type,access:Lo.access||Se.access,related:Lo.related?Lo.related.replace(/^\[|\]$/g,"").split(",").map(Tn=>Tn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.related,tags:Lo.tags?Lo.tags.replace(/^\[|\]$/g,"").split(",").map(Tn=>Tn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.tags}}}catch(ao){console.log(m.red(` editor failed: ${ao.message}`));return}}if(!a.writeArticle(fe,Se,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${fe} saved.`));let oo=a.extractWikilinks(Ce),Ee=new Map;for(let _ of a.listArticles(e.agent))Ee.set(_.meta.title.toLowerCase(),!0);let at=oo.filter(_=>!Ee.has(_.toLowerCase()));if(at.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of at.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ne.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-
|
|
486
|
+
`)){let Di=Tn.match(/^(\w+):\s*(.+)$/);Di&&(Lo[Di[1]]=Di[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=_i[2],Se={...Se,title:Lo.title||Se.title,type:Lo.type||Se.type,access:Lo.access||Se.access,related:Lo.related?Lo.related.replace(/^\[|\]$/g,"").split(",").map(Tn=>Tn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.related,tags:Lo.tags?Lo.tags.replace(/^\[|\]$/g,"").split(",").map(Tn=>Tn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.tags}}}catch(ao){console.log(m.red(` editor failed: ${ao.message}`));return}}if(!a.writeArticle(fe,Se,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${fe} saved.`));let oo=a.extractWikilinks(Ce),Ee=new Map;for(let _ of a.listArticles(e.agent))Ee.set(_.meta.title.toLowerCase(),!0);let at=oo.filter(_=>!Ee.has(_.toLowerCase()));if(at.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of at.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ne.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-B32UDQJS.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Oe(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=ts(e.script,"utf-8").split(/\n\s*\n/).map(y=>y.trim()).filter(Boolean);r=[];for(let y of p){let w=y.split(/\r?\n/).filter($=>$.trim());if(w.length<2)continue;let b=w[0].replace(/^Q:\s*/i,"").trim(),k=w.slice(1).join(" ").trim();b&&k&&r.push({q:b,verdict:k})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,y;if(r){let Y=r[f];if(!Y)break;p=Y.q,y=Y.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;y=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(Y){console.log(m.red(`failed: ${Y.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let Y=w.citations.map(fe=>`${fe.title} [${fe.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
|
|
487
487
|
`)),console.log(m.dim(" citations: "+Y))}r||(y=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+y);let b={q:p,answer:w.answer,citations:w.citations,verdict:y},k=y.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!k){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(b);continue}let $=k[1].toLowerCase(),E=(k[2]||"").trim();if(d.push(b),$==="/ok"||$==="/skip")continue;if(!E){console.log(m.yellow(` ${$} without note \u2014 skipping.`));continue}let S=w.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let v=i.readArticle(S.path);if(!v){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let x=f$(v.content,$,E,v.meta.title,v.meta.type),R=U(i.baseDir,"_tmp");Do(R,{recursive:!0});let I=U(R,`quiz-patch-${t().slice(0,8)}.txt`);At(I,x);let C="";try{let Y=`cat '${I}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,fe=Et(Y,{env:Nt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ce=JSON.parse(fe);C=String(Ce.result||Ce.content||"")}catch{C=fe}let G=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);G&&(C=G[1].trim()),C=C.trim()}catch(Y){console.log(m.red(` patch failed: ${Y.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let M=v.content.split(`
|
|
488
488
|
`).length,H=C.split(`
|
|
489
489
|
`).length;if(console.log(m.dim(` diff: ${M} \u2192 ${H} lines (${H-M>=0?"+":""}${H-M})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),b.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...v.meta,lastUpdated:new Date().toISOString().slice(0,10)},C,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,b.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let y=d[p];f.push(`## ${p+1}. Q: ${y.q}`,"",`**A:** ${y.answer}`,"",`**Citations:** ${y.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${y.verdict}\``+(y.patched?` \u2192 patched \`${y.patched}\``:""),"")}At(e.out,f.join(`
|
|
@@ -544,14 +544,14 @@ Output (JSON array, one entry per input article, same order):
|
|
|
544
544
|
[
|
|
545
545
|
{"path": "path/to/article.md", "type": "project"},
|
|
546
546
|
...
|
|
547
|
-
]`}ne.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Oe(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ne.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||U(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-
|
|
547
|
+
]`}ne.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Oe(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ne.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||U(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-4XGZYYQP.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),ud(o,t,e.agent,n,e.mode)});ne.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-LK45MTVI.js"),c=Oe(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let b=c.getAgentWiki(w);for(let k of b.listArticles(w)){if(u.length>=g)break e;let $=b.readArticle(k.path);if(!$||e.type&&$.meta.type!==e.type)continue;let E={...o($.meta.type),...e.fields?i($.meta.type):{}},S=await a(s,t({path:k.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:k.path}],features:{agent:w,type:$.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let v=n(S.answers),x=e.fields?r($.meta.type,S.answers):null;v.completeness>=d&&!(x&&!x.fit)||u.push({agent:w,type:$.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...x?{missing:x.missingCritical.join(",")||"-",cov:`${Math.round(x.coverage*100)}%`}:{},title:$.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((w,b)=>parseFloat(w.score)-parseFloat(b.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(b=>String(b[w]).length))),y=w=>w.map((b,k)=>String(b).padEnd(p[k])).join(" ");console.log(),console.log(m.bold(y(f)));for(let w of u)console.log(y(f.map(b=>w[b])));if(e.fields){let w=u.filter(b=>b.missing!=="-").length;console.log(m.dim(`
|
|
548
548
|
${u.length} article(s) flagged; ${w} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
|
|
549
|
-
${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ne.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-MCJYD66I.js"),n=Oe(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=U(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});ne.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=Oe(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ne.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=U(process.cwd(),".agentx/graph");if(!to(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Fo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),y=new Map(p.map($=>[$.id,$])),w=0,b=0,k=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let v of $.meta.sources){let x=y.get(v);if(!x)continue;let R=String(x.meta?.sender??""),I=s.fingerprint({text:x.content,channel:x.source,sender:R}),C=r.get(I);if(!C?.length)continue;let M=C.join("/"),H=E.get(M);H?H.n++:E.set(M,{path:C,n:1})}if(E.size===0)continue;b++,l++;let S;for(let v of E.values())(!S||v.n>S.n)&&(S=v);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),k++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${b} matched \xB7 ${m.green(k)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ne.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Oe(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-4T62LT27.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ne.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||U(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new qi(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,y=0,w=new Set;for(let k of d.articles){for(let $ of k.tags||[])p.add($);y+=k.tags?.length||0;for(let $ of k.sources||[])w.add($)}let b=new Set(d.articles.map(k=>k.path.includes("/")?k.path.split("/")[0]:"/"));return{mode:c,label:aa(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(y/d.articles.length).toFixed(1):"0",dirs:b.size,coverage:w.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ne.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?U(process.cwd(),o.dir):U(process.cwd(),".agentx/wiki");to(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?U(process.cwd(),e):U(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=U(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=to(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${w$(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ne.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-PQ7AMPMT.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Oe(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let v of d){let x=l.getAgentWiki(v);for(let R of x.listArticles(v)){if(f>=u)break e;let I=x.readArticle(R.path);if(!I||e.type&&I.meta.type!==e.type)continue;f++;let C=await a(r,n({title:I.meta.title,type:I.meta.type,body:I.content}),o(I.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:v,type:I.meta.type??"?"}});if(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let M=t(I.meta.type,C.answers);for(let H of s(M,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&H.needsHuman||(e.ask&&H.needsHuman&&g.push({kind:"field",agentId:v,path:R.path,subject:I.meta.title,field:H.field,tier:H.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${H.label}?`}),p.push({tier:H.tier,need:H.field,how:H.needsHuman?m.yellow("ask"):H.sources.join("/"),uncertain:H.uncertain?"?":"",agent:v,article:I.meta.title.slice(0,40)}))}}let y={added:0,skipped:0};if(e.ask&&g.length>0&&(y=new c(Tt(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],b=v=>String(v).replace(/\u001b\[[0-9;]*m/g,""),k=w.map(v=>Math.max(v.length,...p.map(x=>b(x[v]).length))),$=(v,x)=>String(v)+" ".repeat(Math.max(0,k[x]-b(v).length));console.log(),console.log(m.bold(w.map((v,x)=>$(v,x)).join(" ")));for(let v of p)console.log(w.map((x,R)=>$(v[x],R)).join(" "));let E=p.filter(v=>v.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${y.added} question(s) for a person (${y.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&y.added>0){let{TIER_RANK:v}=await import("./article-fields-PITN4NHA.js"),x=v[e.notifyTier]??v.pillar,R=g.filter(I=>(v[I.tier??"furniture"]??9)<=x);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:I}=await import("./config-4T62LT27.js"),C=I(),M=C?.notifications?.destination;if(!M?.channel||!M?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let H=R.slice(0,10).map(G=>`\u2022 ${G.question}`).join(`
|
|
549
|
+
${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ne.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-B32UDQJS.js"),n=Oe(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=U(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});ne.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=Oe(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ne.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=U(process.cwd(),".agentx/graph");if(!to(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Fo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),y=new Map(p.map($=>[$.id,$])),w=0,b=0,k=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let v of $.meta.sources){let x=y.get(v);if(!x)continue;let R=String(x.meta?.sender??""),I=s.fingerprint({text:x.content,channel:x.source,sender:R}),C=r.get(I);if(!C?.length)continue;let M=C.join("/"),H=E.get(M);H?H.n++:E.set(M,{path:C,n:1})}if(E.size===0)continue;b++,l++;let S;for(let v of E.values())(!S||v.n>S.n)&&(S=v);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),k++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${b} matched \xB7 ${m.green(k)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ne.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Oe(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-4XGZYYQP.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ne.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||U(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new qi(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,y=0,w=new Set;for(let k of d.articles){for(let $ of k.tags||[])p.add($);y+=k.tags?.length||0;for(let $ of k.sources||[])w.add($)}let b=new Set(d.articles.map(k=>k.path.includes("/")?k.path.split("/")[0]:"/"));return{mode:c,label:aa(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(y/d.articles.length).toFixed(1):"0",dirs:b.size,coverage:w.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ne.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?U(process.cwd(),o.dir):U(process.cwd(),".agentx/wiki");to(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?U(process.cwd(),e):U(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=U(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=to(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${w$(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ne.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-LK45MTVI.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Oe(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let v of d){let x=l.getAgentWiki(v);for(let R of x.listArticles(v)){if(f>=u)break e;let I=x.readArticle(R.path);if(!I||e.type&&I.meta.type!==e.type)continue;f++;let C=await a(r,n({title:I.meta.title,type:I.meta.type,body:I.content}),o(I.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:v,type:I.meta.type??"?"}});if(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let M=t(I.meta.type,C.answers);for(let H of s(M,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&H.needsHuman||(e.ask&&H.needsHuman&&g.push({kind:"field",agentId:v,path:R.path,subject:I.meta.title,field:H.field,tier:H.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${H.label}?`}),p.push({tier:H.tier,need:H.field,how:H.needsHuman?m.yellow("ask"):H.sources.join("/"),uncertain:H.uncertain?"?":"",agent:v,article:I.meta.title.slice(0,40)}))}}let y={added:0,skipped:0};if(e.ask&&g.length>0&&(y=new c(Tt(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],b=v=>String(v).replace(/\u001b\[[0-9;]*m/g,""),k=w.map(v=>Math.max(v.length,...p.map(x=>b(x[v]).length))),$=(v,x)=>String(v)+" ".repeat(Math.max(0,k[x]-b(v).length));console.log(),console.log(m.bold(w.map((v,x)=>$(v,x)).join(" ")));for(let v of p)console.log(w.map((x,R)=>$(v[x],R)).join(" "));let E=p.filter(v=>v.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${y.added} question(s) for a person (${y.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&y.added>0){let{TIER_RANK:v}=await import("./article-fields-PITN4NHA.js"),x=v[e.notifyTier]??v.pillar,R=g.filter(I=>(v[I.tier??"furniture"]??9)<=x);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:I}=await import("./config-4XGZYYQP.js"),C=I(),M=C?.notifications?.destination;if(!M?.channel||!M?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let H=R.slice(0,10).map(G=>`\u2022 ${G.question}`).join(`
|
|
550
550
|
`),q=R.length>10?`
|
|
551
551
|
\u2026and ${R.length-10} more`:"",Y=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
552
552
|
${H}${q}
|
|
553
553
|
|
|
554
|
-
agentx wiki questions`,fe=C?.daemon?.port??C?.port??18800;try{let G=await fetch(`http://127.0.0.1:${fe}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:M.channel,chatId:M.chatId,accountId:M.accountId,text:Y})});console.log(G.ok?m.cyan(` Pushed ${R.length} question(s) to ${M.channel}.`):m.yellow(` Push failed (${G.status}) \u2014 questions are still queued.`))}catch(G){console.log(m.yellow(` Push failed (${String(G?.message??G).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ne.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-PQ7AMPMT.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Oe(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),y=parseInt(e.limit),w=g(),b=c(d(f.getSharedStore().listEntries())),k=new Map(b.map(C=>[C.name.toLowerCase().trim(),C])),$=0,E=0,S=[],v=!1;e:for(let C of p){let M=f.getAgentWiki(C);for(let H of M.listArticles(C)){if($>=y)break e;if(H.meta.type!=="person")continue;let q=M.readArticle(H.path);if(!q)continue;$++;let Y=await r(s,n({title:q.meta.title,type:q.meta.type,body:q.content}),o(q.meta.type),{links:[{kind:"article",id:H.path}],features:{agent:C,op:"backfill"}});if(!Y){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let G=t(q.meta.type,Y.answers).missing.filter(_=>i.includes(_));if(G.length===0)continue;let{records:Ce,results:Se}=await a([{name:q.meta.title,type:"person"}],{sources:w}),L=k.get(q.meta.title.toLowerCase().trim());if(!v){for(let _ of l(Se,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));v=!0}let oo=c([...L?[{name:L.name,source:"entries",fields:Object.fromEntries(Object.entries(L.fields).map(([_,$e])=>[_,$e.value]))}]:[],...Ce]);if(oo.length===0)continue;let{content:Ee,edits:at}=u(q.content,oo[0],G);if(at.length!==0){for(let _ of at)S.push({agent:C,article:q.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(M.writeArticle(H.path,q.meta,Ee,C)?E++:console.log(m.red(` could not write ${H.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let x=["agent","article","field","action","got"],R=x.map(C=>Math.max(C.length,...S.map(M=>String(M[C]).length))),I=C=>C.map((M,H)=>String(M).padEnd(R[H])).join(" ");console.log(),console.log(m.bold(I(x)));for(let C of S)console.log(I(x.map(M=>C[M])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ne.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(Tt(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});ne.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(Tt(t.dir)),a=r.list().find(y=>(y.id===e||y.id.startsWith(e))&&y.status!=="open"&&y.kind==="contradiction");if(a&&!r.list("open").some(y=>y.id===e||y.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let y=r.resolve(e,"dismissed");console.log(y?m.dim(` dismissed: ${y.question}`):m.red(` no question matching "${e}"`))}catch(y){console.log(m.red(` ${y?.message??y}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(y=>y.id===e||y.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:y}=await import("./ledger-CH7R756S.js"),w=new y(Tt(t.dir));try{let b=w.get(c.factId);if(b){let k=w.write({subject:b.subject,attribute:b.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:b.volatility},{confirmedBy:"operator"});console.log(m.green(` ${k.status}: ${b.id} ${b.subject} \xB7 ${b.attribute}: ${k.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(b){b?.name!=="LedgerCorruptError"&&console.log(m.red(` ${b?.message??b}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",o),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",o)}catch(y){console.log(m.red(` ${y?.message??y}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Oe(t.dir,t.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${o} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});ne.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-PQ7AMPMT.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Oe(e.dir,"graph").getSharedStore(),p=f.listEntries(),y=new Set(f.getUnabsorbedEntries().map(q=>q.id)),{labeled:w,backlog:b}=r(p,y),k=a(w,q=>q.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,v=Date.now();if(e.load){let{readFileSync:q}=await import("fs");E.push(...JSON.parse(q(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${b} in backlog) \u2014 grading ${k.length}`));for(let q of e.load?[]:k){let Y=await i(o,n(q),t,{features:{source:q.source??"",absorbed:q.absorbed}});if(!Y){S++;continue}let fe=Y.answers;E.push({entry:q,verdict:s(Y.answers,$),citeWorthy:fe.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:q}=await import("fs");q(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let x=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),C=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:x,calibration:I,failures:S,elapsed:C},null,2));return}let M=q=>`${(q*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${x.n} (${x.positives} kept by absorb, ${x.negatives} passed over)`),console.log(` recall ${M(x.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${M(x.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${M(x.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${x.lostPositives>0?m.yellow(`lost ${x.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in I)||!I.insufficient)&&console.log(` ECE ${I.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),x.lostPositives>0){let q=x.droppedBy;console.log(m.dim(` dropped by: type ${q.type} \xB7 worth ${q.worth} \xB7 durability ${q.durability} (a positive can fail several)`))}let H=x.positiveMeans;if(console.log(m.dim(` positives avg: worth ${H.worth.toFixed(2)} \xB7 durability ${H.durability.toFixed(2)} \xB7 typeConf ${H.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${C}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let q=parseFloat(e.minRecall),{best:Y,points:fe}=g(E,{minRecall:q});if(console.log(),console.log(m.bold(` threshold sweep (${fe.length} policies, recall floor ${M(q)})`)),Y)console.log(` best: ${Y.requireTyped?`typed & type>=${Y.minType}`:"type gate OFF"} worth>=${Y.minWorth} durability>=${Y.minDurability}`),console.log(` recall ${M(Y.recall)} \xB7 filtered ${M(Y.filtered)} \xB7 precision ${M(Y.precision)} \xB7 lost ${Y.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${M(q)} recall \u2014 not even keeping everything typed.`));let G=fe.slice().sort((Ce,Se)=>Se.recall-Ce.recall)[0];G&&console.log(m.dim(` Best recall available: ${M(G.recall)} at ${G.requireTyped?`type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} dur>=${G.minDurability}, filtering ${M(G.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ne.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=U(process.cwd(),e);to(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?U(process.cwd(),o.dir):U(process.cwd(),".agentx/wiki");to(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=U(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function w$(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}lu();import{Command as $$}from"commander";import D from"chalk";import{resolve as wi}from"path";import{existsSync as b$}from"fs";te();var un=new $$().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");un.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=T();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new Fo({baseDir:wi(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let y=r[p],w=hs(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(y.msgHash.slice(0,8))} ${D.dim(w)} ... `);let b=k$(y,a,c),k=null;try{k=await v$(n,t,b,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!k||!k.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(k.decision).toLowerCase().trim(),E=(k.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{x$(i,y,a,c,t),i.updateClassificationStatus(y.msgHash,{status:"approved",reviewer:t,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(y.msgHash,{status:"rejected",reviewer:t,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});un.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=T();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=wi(process.cwd(),o.graph.baseDir);if(!b$(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Fo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});un.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=T();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new Fo({baseDir:wi(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(x=>x.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let x=await fetch(`${t}/graph/schema`,{headers:s});if(!x.ok)throw new Error(`schema HTTP ${x.status}`);l=(await x.json()).schema;let I=await fetch(`${t}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);g=(await I.json()).nodes||[];let C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);d=(await C.json()).classifications||[]}catch(x){console.log(D.red(` fetch failed: ${x.message}`));return}let u=r.levels.map(x=>x.id).join(","),f=l?.levels?.map(x=>x.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let y=p?r:l,w=new Map;y.levels.forEach((x,R)=>w.set(x.id,R));let b=[...g].sort((x,R)=>(w.get(x.level)??99)-(w.get(R.level)??99)),k=0,$=0,E=0;for(let x of b){if(c.has(x.id)){$++;continue}if(e.dryRun){k++,c.add(x.id);continue}try{i.addNode({...x,createdBy:x.createdBy?`${x.createdBy} (sync)`:`sync:${t}`}),c.add(x.id),k++}catch(R){E++,console.log(D.yellow(` skip node ${x.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${k} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,v=0;for(let x of d)if(!(!x.msgHash||!Array.isArray(x.path))){if(i.getFingerprint(x.msgHash)){v++;continue}if(e.dryRun){S++;continue}i.setFingerprint(x.msgHash,{path:x.path,leaf:x.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${v} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function k$(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
554
|
+
agentx wiki questions`,fe=C?.daemon?.port??C?.port??18800;try{let G=await fetch(`http://127.0.0.1:${fe}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:M.channel,chatId:M.chatId,accountId:M.accountId,text:Y})});console.log(G.ok?m.cyan(` Pushed ${R.length} question(s) to ${M.channel}.`):m.yellow(` Push failed (${G.status}) \u2014 questions are still queued.`))}catch(G){console.log(m.yellow(` Push failed (${String(G?.message??G).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ne.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-LK45MTVI.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Oe(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),y=parseInt(e.limit),w=g(),b=c(d(f.getSharedStore().listEntries())),k=new Map(b.map(C=>[C.name.toLowerCase().trim(),C])),$=0,E=0,S=[],v=!1;e:for(let C of p){let M=f.getAgentWiki(C);for(let H of M.listArticles(C)){if($>=y)break e;if(H.meta.type!=="person")continue;let q=M.readArticle(H.path);if(!q)continue;$++;let Y=await r(s,n({title:q.meta.title,type:q.meta.type,body:q.content}),o(q.meta.type),{links:[{kind:"article",id:H.path}],features:{agent:C,op:"backfill"}});if(!Y){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let G=t(q.meta.type,Y.answers).missing.filter(_=>i.includes(_));if(G.length===0)continue;let{records:Ce,results:Se}=await a([{name:q.meta.title,type:"person"}],{sources:w}),L=k.get(q.meta.title.toLowerCase().trim());if(!v){for(let _ of l(Se,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));v=!0}let oo=c([...L?[{name:L.name,source:"entries",fields:Object.fromEntries(Object.entries(L.fields).map(([_,$e])=>[_,$e.value]))}]:[],...Ce]);if(oo.length===0)continue;let{content:Ee,edits:at}=u(q.content,oo[0],G);if(at.length!==0){for(let _ of at)S.push({agent:C,article:q.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(M.writeArticle(H.path,q.meta,Ee,C)?E++:console.log(m.red(` could not write ${H.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let x=["agent","article","field","action","got"],R=x.map(C=>Math.max(C.length,...S.map(M=>String(M[C]).length))),I=C=>C.map((M,H)=>String(M).padEnd(R[H])).join(" ");console.log(),console.log(m.bold(I(x)));for(let C of S)console.log(I(x.map(M=>C[M])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ne.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(Tt(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});ne.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(Tt(t.dir)),a=r.list().find(y=>(y.id===e||y.id.startsWith(e))&&y.status!=="open"&&y.kind==="contradiction");if(a&&!r.list("open").some(y=>y.id===e||y.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let y=r.resolve(e,"dismissed");console.log(y?m.dim(` dismissed: ${y.question}`):m.red(` no question matching "${e}"`))}catch(y){console.log(m.red(` ${y?.message??y}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(y=>y.id===e||y.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:y}=await import("./ledger-CH7R756S.js"),w=new y(Tt(t.dir));try{let b=w.get(c.factId);if(b){let k=w.write({subject:b.subject,attribute:b.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:b.volatility},{confirmedBy:"operator"});console.log(m.green(` ${k.status}: ${b.id} ${b.subject} \xB7 ${b.attribute}: ${k.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(b){b?.name!=="LedgerCorruptError"&&console.log(m.red(` ${b?.message??b}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",o),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",o)}catch(y){console.log(m.red(` ${y?.message??y}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Oe(t.dir,t.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${o} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});ne.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-LK45MTVI.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Oe(e.dir,"graph").getSharedStore(),p=f.listEntries(),y=new Set(f.getUnabsorbedEntries().map(q=>q.id)),{labeled:w,backlog:b}=r(p,y),k=a(w,q=>q.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,v=Date.now();if(e.load){let{readFileSync:q}=await import("fs");E.push(...JSON.parse(q(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${b} in backlog) \u2014 grading ${k.length}`));for(let q of e.load?[]:k){let Y=await i(o,n(q),t,{features:{source:q.source??"",absorbed:q.absorbed}});if(!Y){S++;continue}let fe=Y.answers;E.push({entry:q,verdict:s(Y.answers,$),citeWorthy:fe.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:q}=await import("fs");q(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let x=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),C=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:x,calibration:I,failures:S,elapsed:C},null,2));return}let M=q=>`${(q*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${x.n} (${x.positives} kept by absorb, ${x.negatives} passed over)`),console.log(` recall ${M(x.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${M(x.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${M(x.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${x.lostPositives>0?m.yellow(`lost ${x.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in I)||!I.insufficient)&&console.log(` ECE ${I.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),x.lostPositives>0){let q=x.droppedBy;console.log(m.dim(` dropped by: type ${q.type} \xB7 worth ${q.worth} \xB7 durability ${q.durability} (a positive can fail several)`))}let H=x.positiveMeans;if(console.log(m.dim(` positives avg: worth ${H.worth.toFixed(2)} \xB7 durability ${H.durability.toFixed(2)} \xB7 typeConf ${H.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${C}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let q=parseFloat(e.minRecall),{best:Y,points:fe}=g(E,{minRecall:q});if(console.log(),console.log(m.bold(` threshold sweep (${fe.length} policies, recall floor ${M(q)})`)),Y)console.log(` best: ${Y.requireTyped?`typed & type>=${Y.minType}`:"type gate OFF"} worth>=${Y.minWorth} durability>=${Y.minDurability}`),console.log(` recall ${M(Y.recall)} \xB7 filtered ${M(Y.filtered)} \xB7 precision ${M(Y.precision)} \xB7 lost ${Y.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${M(q)} recall \u2014 not even keeping everything typed.`));let G=fe.slice().sort((Ce,Se)=>Se.recall-Ce.recall)[0];G&&console.log(m.dim(` Best recall available: ${M(G.recall)} at ${G.requireTyped?`type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} dur>=${G.minDurability}, filtering ${M(G.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ne.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=U(process.cwd(),e);to(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?U(process.cwd(),o.dir):U(process.cwd(),".agentx/wiki");to(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=U(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function w$(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}lu();import{Command as $$}from"commander";import D from"chalk";import{resolve as wi}from"path";import{existsSync as b$}from"fs";te();var un=new $$().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");un.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=T();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new Fo({baseDir:wi(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let y=r[p],w=hs(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(y.msgHash.slice(0,8))} ${D.dim(w)} ... `);let b=k$(y,a,c),k=null;try{k=await v$(n,t,b,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!k||!k.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(k.decision).toLowerCase().trim(),E=(k.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{x$(i,y,a,c,t),i.updateClassificationStatus(y.msgHash,{status:"approved",reviewer:t,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(y.msgHash,{status:"rejected",reviewer:t,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});un.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=T();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=wi(process.cwd(),o.graph.baseDir);if(!b$(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Fo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});un.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=T();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new Fo({baseDir:wi(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(x=>x.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let x=await fetch(`${t}/graph/schema`,{headers:s});if(!x.ok)throw new Error(`schema HTTP ${x.status}`);l=(await x.json()).schema;let I=await fetch(`${t}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);g=(await I.json()).nodes||[];let C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);d=(await C.json()).classifications||[]}catch(x){console.log(D.red(` fetch failed: ${x.message}`));return}let u=r.levels.map(x=>x.id).join(","),f=l?.levels?.map(x=>x.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let y=p?r:l,w=new Map;y.levels.forEach((x,R)=>w.set(x.id,R));let b=[...g].sort((x,R)=>(w.get(x.level)??99)-(w.get(R.level)??99)),k=0,$=0,E=0;for(let x of b){if(c.has(x.id)){$++;continue}if(e.dryRun){k++,c.add(x.id);continue}try{i.addNode({...x,createdBy:x.createdBy?`${x.createdBy} (sync)`:`sync:${t}`}),c.add(x.id),k++}catch(R){E++,console.log(D.yellow(` skip node ${x.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${k} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,v=0;for(let x of d)if(!(!x.msgHash||!Array.isArray(x.path))){if(i.getFingerprint(x.msgHash)){v++;continue}if(e.dryRun){S++;continue}i.setFingerprint(x.msgHash,{path:x.path,leaf:x.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${v} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function k$(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
555
555
|
`),i=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",i,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
|
|
556
556
|
`)}async function v$(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return Xa((c?.content||"").toString())}finally{clearTimeout(r)}}function x$(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function ca(){let e=T();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=wi(process.cwd(),e.graph.baseDir);return{store:new Fo({baseDir:o}),baseDir:o}}var la=un.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");la.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let o=ca();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(D.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(hs(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(D.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(D.dim(` ${r.length} to check (${e.strategy}).`)),console.log(D.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});la.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){console.log(D.red(" verdict must be correct | wrong | unsure"));return}let n=ca();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(D.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(D.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(D.green(` ${o}: ${hs(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});la.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=ca();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${D.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(D.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?D.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(D.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(D.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as O$}from"commander";import Q from"chalk";import{Command as tp}from"commander";import pe from"chalk";import{existsSync as S$}from"fs";import{resolve as E$}from"path";import A$ from"better-sqlite3";function T$(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(pe.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function j$(e){let o=E$(process.cwd(),e);return S$(o)||(console.log(pe.red(` No db at ${o}`)),process.exit(1)),new A$(o,{readonly:!0})}var np=new tp().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Nn)).option("--max <n>","max clusters distilled per run",String(bs)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(pe.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=j$(e.path),t=await qc(o,{since:T$(e.since),agentId:e.agent,sessions:new nc(process.cwd()),minOccurrences:Number(e.minOccurrences)||Nn,max:Number(e.max)||bs,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(pe.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${pe.cyan(n.key)} ${pe.bold(`\xD7${n.count}`)} ${pe.dim(n.status)}`),n.sampleMessage&&console.log(pe.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(pe.dim(`
|
|
557
557
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(pe.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(pe.green(` \u2713 draft written: ${n.id}`)+pe.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(pe.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(pe.yellow(` \u26A0 ${n}`));t.dryRun?console.log(pe.dim(`
|
|
@@ -587,7 +587,7 @@ agentx wiki questions`,fe=C?.daemon?.port??C?.port??18800;try{let G=await fetch(
|
|
|
587
587
|
|
|
588
588
|
`))>=0;){let f=l.slice(0,u);l=l.slice(u+2),Z$(f)}}}catch(r){console.error(ie.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Z$(e){let o="message",t="";for(let i of e.split(`
|
|
589
589
|
`))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ie.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ie.cyan(n.phase?.padEnd(9)??"run"),r=ie.bold(n.workflowId??""),a=ie.dim((n.runId??"").slice(0,8)),c=n.nodeId?ie.yellow(n.nodeId):"",l=n.note?ie.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ie.magenta(`task.${n.phase}`.padEnd(14)),r=ie.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ie.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ie.cyan(a)} ${c}`);break}case"signal":{let i=ie.green("signal".padEnd(9)),r=ie.bold(n.name),a=ie.dim(`(${n.scope})`),c=n.workflowId?ie.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ie.blue("mesh".padEnd(9)),r=ie.bold(n.peer),a=n.healthy?ie.green("\u2713 healthy"):ie.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ie.dim(n.delta??"")}`);break}case"channel":{let i=ie.yellow("channel".padEnd(9)),r=n.direction==="in"?ie.cyan("\u2190"):ie.magenta("\u2192"),a=ie.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ie.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ie.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}te();import{Command as eb}from"commander";import kn from"chalk";function ob(e,o){let t=e.replace(/\/+$/,""),n=new URLSearchParams;if(o.since&&n.set("since",o.since),o.limit&&n.set("limit",o.limit),o.agent){let s=n.toString();return`${t}/agents/${encodeURIComponent(o.agent)}/events${s?`?${s}`:""}`}return o.kind&&n.set("kind",o.kind),o.limit||n.set("limit","50"),`${t}/events/recent?${n}`}var bp=new eb().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let a=T(e.config);o||(o=a.dashboard?.daemonUrl||""),t||(t=a.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n={};t&&(n.Authorization=`Bearer ${t}`);let s;try{let a=await fetch(ob(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(kn.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(kn.red(` daemon unreachable at ${o}: ${a?.message||a}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(s,null,2));return}let i=s.events??[];if(e.agent&&!s.subscriptions){console.log(kn.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(kn.dim(" no events"));return}for(let a of i)console.log(` ${rc(a)} ${kn.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(kn.dim(`
|
|
590
|
-
${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as nb}from"commander";import is from"chalk";import{spawn as sb}from"node:child_process";import{execFileSync as tb}from"node:child_process";function kp(e=()=>tb("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var vp=new nb().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(is.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-
|
|
590
|
+
${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as nb}from"commander";import is from"chalk";import{spawn as sb}from"node:child_process";import{execFileSync as tb}from"node:child_process";function kp(e=()=>tb("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var vp=new nb().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(is.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-QTXWO46T.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:kp();if(n?.ok){let{fetchAgents:l}=await import("./client-QTXWO46T.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(b=>b.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(b=>[b.id,{name:`AgentX ${b.name||b.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(is.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:y}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:p,cwd:process.cwd(),pool:y,spawnImpl:sb,log:b=>console.error(is.dim(b))});return}n&&!n.ok&&(console.error(is.yellow(n.reason)),console.error(is.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-Q4UAYL2V.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as ib}from"commander";import Z from"chalk";import{randomUUID as Ep}from"crypto";import{createInterface as rb}from"node:readline/promises";import ab from"ora";import Ei from"chalk";function xp(e){console.error(),console.error(Ei.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Ei.dim(` ${e.why}`)),console.error(),console.error(` Use ${Ei.cyan(e.instead)} instead.`),e.note&&console.error(Ei.dim(` ${e.note}`)),console.error()}var Sp={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var Ap=new ib().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{xp({what:"agentx chat",...Sp});let t=fd({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Ep().slice(0,12)}`,r=[];try{r=await Ps(t)}catch(g){console.error(Z.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(Z.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(Z.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(Z.red(` unknown agent: @${n}`)),console.error(Z.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(Z.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-6KGP57OP.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}lb(t.baseUrl,n,i,s);let a=rb({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(Z.dim(`
|
|
591
591
|
bye`)),process.exit(0)});;){let g;try{g=(await a.question(Z.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(Z.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Ep().slice(0,12)}`,console.log(Z.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await Ps(t);for(let y of p){let w=y.id===n?Z.green("\u25CF"):Z.dim("\u25CB");console.log(` ${w} @${y.id} ${Z.dim(y.tier)} ${y.model??""}`)}}catch(p){console.error(Z.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(Z.red(" usage: /agent <id>"));continue}try{if(!(await Ps(t)).find(w=>w.id===p)){console.log(Z.red(` unknown agent: @${p}`));continue}n=p,console.log(Z.dim(` now talking to @${n}`))}catch(y){console.error(Z.red(` failed to switch agent: ${y?.message||y}`))}continue}if(g.startsWith("/")){console.log(Z.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(Z.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=ab({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=cb(n);try{let p=await hd(t,n,g,{channel:s,chatId:i,onText:w=>{d.stop(),f.text(w)},onThinking:()=>{},onTool:w=>{d.stop(),f.tool(w)}});d.stop();let y=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(y,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(Z.dim(" bye"));return}}});function cb(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${Z.green(`@${e}`)}
|
|
592
592
|
`),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
|
|
593
593
|
`&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
|
|
@@ -680,7 +680,7 @@ Restart the daemon to activate.
|
|
|
680
680
|
dist/
|
|
681
681
|
*.log
|
|
682
682
|
.env
|
|
683
|
-
`}import{Command as Qb}from"commander";import Pe from"chalk";import{writeFileSync as Zb,mkdirSync as ek,existsSync as Ii,readFileSync as Bp,appendFileSync as Jp}from"fs";import{resolve as Sn,dirname as zp}from"path";import{homedir as ja}from"os";var Yp=new Qb().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:o}=await import("./program-
|
|
683
|
+
`}import{Command as Qb}from"commander";import Pe from"chalk";import{writeFileSync as Zb,mkdirSync as ek,existsSync as Ii,readFileSync as Bp,appendFileSync as Jp}from"fs";import{resolve as Sn,dirname as zp}from"path";import{homedir as ja}from"os";var Yp=new Qb().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:o}=await import("./program-4IMJEMDM.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=nk(t);break;case"bash":s=ck(t);break;case"fish":s=lk(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Sn(String(e.output)):ok(n);ek(zp(i),{recursive:!0}),Zb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),tk(n,i,!!e.yes)});function ok(e){let o=ja();switch(e){case"zsh":return Sn(o,".zsh","completions","_agentx");case"bash":return Sn(o,".bash_completion.d","agentx.bash");case"fish":return Sn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function tk(e,o,t){if(e==="zsh"){let n=Sn(ja(),".zshrc"),s=zp(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ii(n)?Bp(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ii(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Jp(n,g.join(`
|
|
684
684
|
`)+`
|
|
685
685
|
`),console.log(Pe.green("\u2713 Patched ~/.zshrc")),console.log(Pe.dim("Reload your shell: exec zsh"));return}console.log(Pe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Pe.cyan(` ${i}`)),l&&console.log(Pe.cyan(` ${r}`)),console.log(),console.log(Pe.dim("Then reload: exec zsh")),console.log(Pe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Sn(ja(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ii(n)?Bp(n,"utf-8"):"").includes(o)){console.log(Pe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ii(n)){Jp(n,`
|
|
686
686
|
# agentx completion
|
|
@@ -696,4 +696,4 @@ ${dk({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
696
696
|
${t.url}`)}catch(o){console.error(An.red(` ${o.message}`)),process.exitCode=1}});ms.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",Ca).action(async(e,o)=>{try{let t=await Ra(o.models);if(!Ia(o.model,t)){console.log(Na(o.model,t)),process.exitCode=1;return}let n=e==="-"?await pk():await mk(e,"utf8"),s=JSON.parse(n),{version:i}=await $s(),r=Qp({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(An.red(` ${t.message}`)),process.exitCode=1}});async function pk(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function YI(){let e=await $s(),o=new uk().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");o.hook("preAction",(t,n)=>{let s=gd(n);md(s)&&dd("cli",s)});for(let t of[Wd,Ud,gn,Jt,zt,lo,Ql,mt,Hs,No,_o,cn,Lm,ot,Js,vp,Ko,mg,pg,vg,Xn,Rg,Mg,dg,Fg,Ug,sm,cm,lm,ro,St,Tp,Un,Go,Yp,ms])o.addCommand(t);for(let t of eu)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=eu.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,fk(t,74," "),""].join(`
|
|
697
697
|
`)}),o}var eu=[ne,un,it,bo,Jn,sn,Ze,Po,tt,vt,wn,$n,Vo,ze,Kt,di,$p,bp,Io,io,yd,ut,ds,vr,st,Qe,Vt,xr,Si,To,Mo,Mp,Lp,Ap];function fk(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
|
|
698
698
|
`)}export{YI as buildProgram};
|
|
699
|
-
//# sourceMappingURL=program-
|
|
699
|
+
//# sourceMappingURL=program-4IMJEMDM.js.map
|